More C

Declaring and using variables

int i;    // declare a variable 'i' to hold integer numbers
i=5;      // the variable 'i' now has the value 5

int j=3;  // equivalent to the 2 statements: int j; j=3;
j=j+1;    // j now has the value 4;
j++;      // increment j by 1, it now has the value 5
j--;      // j is back to 4.

float pi; //float = 'floating point' = real number
pi=3.14159;
float radius=2.0;
float area;
area = pi * radius^2;

Conditional (if ... then ... else)

Carrying on with the variable declarations and assignments above:

if (area > 10.0) {
   // Do something for larger circles
} else {
   // Do something for smaller circles,
   //    that have areas less than or equal to 10.0
}

if (j==4){
   // Do something if j is tested
   //   and found to be equal to 4
}


if ( j ){  // any non-zero value is the same as "true"
   // Do something if j is not zero
}

if ( !j ){  // !j means "not" j
  // Do something if j *is* zero:
  //   0 means "false"
  //   and "not false" = true
}

The statement in parenthesis, (), is considered 'boolean'. If it evaluates to true, then the following code block is executed.

Looping

int k = 1;
while(  k  ) { // As long as the conditional is 'true', execute the code block
   // Just keep doing something *forever*, if k is never modified...
}
With a partner...
  1. How could you set things up to execute the contents of the loop above exactly 7 times?
  2. Look up the syntax for a for(.....) loop. Using this, set up a loop that executes exactly 7 times.
  3. The break; command immediately exits a loop, and execution continues after the loop. Set up a loop that executes exactly 7 times using the break command

There is also a do{...} while ([condition]); with a test at the end of the code block.