Control flow and logic in C and the structured program theorem

If-Then-Else

If-then-else

if () x else y

can group multiple with block

if () {} else {}

block curly counts as single command

can pass varibales to logical evaluation

int x = 1;
if (x)

evaluating ints and longs. seems to be if >= 1 then true otherwise false? does something on char too?

Conditional operator

If we want to set the value of something based on a conditional, eg:

if (a > b) {
    result = x;
}
else {
    result = y;
}

We can instead do the following

result = a > b ? x : y;

If we have something of the form:

if (a) {
    result = a;
}
else {
    result = y;
}

We can write the following in some implementations of C.

result = a ? : y;

Known as the Elvis operator (because of "?:").

While loops

While

while (n<10) {;
  n++;
}

Do-While

do while in addition to while. do while means the loop is run at least once

do {
  // the body of the loop
}
while (testExpression);

For loops

For loops

int a = 1;
for (int n=10; n>0; n--) {
    a = a + 5;
}

Continue in for loops

int a = 1;
for (int n=10; n>0; n--) {
    if (n==5) continue;
    a = a + 2;
}

Break in for loops

int a = 1;
for (int n=10; n>0; n--) {
    if (n==5) break;
    a = a + 1;
}

Using multiple variables

for loops like this. can do multiple variables like below.


for (int n=0, i=100 ; n!=i ; n++, i--)
{
   // whatever here...
}

Structured program theorem

Introduction

Can do without gotos, and use structured loops instead.