Skip to main content Skip to navigation

2.5 Conditionals and loops

1. Statement blocks

Statement blocks are a useful way of grouping statements together. This grouping can be achieved by enclosing your set of statements with curly braces {}. The statements itself are usually (manually) indented for the sake of clarity. Block statements are very useful, since you can use them, say in loops, wherever you could use a single statement.

Example:

Below is an example of a simple statement block
{
  x = 3;
  y = 2.0*x+2;
}

There's nothing to stop you including conditional statements and/or loops in a statement block, so this makes it conventient for nesting of loops and conditionals.

Back to top

2. if / else

These conditional structures allow you to control the flow of your code. The if statement allows you to control if a program enters a section of code or not, based on whether a given condition is true or false. There are three basic variations on if, with general syntax given below:

if (expression == true)
  Execute the next statement

or you could use a statement block

if (expression == true) {
  Execute a block statement
}

Both of these structures will only execute the statement(s) that follow if the statement is true. If you want to execute other code in the situation when the statement is false, you can use the if/else construct:

if (expression == true) {
   Execute these statements if expression is true
}
else {
   Execute these statements if expression is false
}

Finally, if you have several conditions you wish to test to, use the if/else if/else construct:

if ( expression1 == true ) {
   Execute these statements if expression1 is true
}
else if ( expression2 == true ) {
   Execute these statements if expression2 is true
}
else {
   Execute these statements if both expressions are false
}

Putting it into Practice:

Code up the statements below to see how this kind of construct works.
#include<stdio.h>	

int main()                            
{
  int age;
  char line[100];                            
  
  printf("Please enter your age \n");
  fgets(line,sizeof(line),stdin);
  sscanf(line,"%d",&age);
    if ( age < 50 ) {                  
       printf("You are pretty young!\n"); 
    } 
    else if ( age == 50 ) {            
       printf("You are old!\n");           
    } 
    else {
       printf("You are really old!\n");     
    } 
    return 0;
}
Compile and run this code. Try writing some variations on this code.

Back to top

3. while

This construct is useful for running a particular statement or block of statements many many times, in the case when you don't have a pre-defined idea of how many times you need to execute your statement blocks in a loop. In this case the loop executes while a conditional statement remains true. The general syntax is:

while (expression is true) {
    Execute these statements 
}

Putting it into Practice:

Code up the statements below to see how this construct works.
#include<stdio.h>	

int main()                            
{
  int count=0;

  while (count < 101) {
    printf("Count has value %d \n",count);
    count++;
  }
  return 0;
}
Compile and run this code. Try writing some variations on this code.

A variation on this construct is the do/while construct. This loop construct also executes so long as a conditional statement is true, but this conditional test is made inside the loop rather than at the top of the loop. This means your block statements will always be executed at least once. The general syntax is:

do {
    Execute these statements
} while (expression is true);

Back to top

for

On the other hand, if you have a pre-defined idea of how many times you need to run statements in a loop, the for construct is useful. The general syntax is:

for (initializations; test conditions; actions)
{
   Execute these statements 
}

Putting it into Practice:

Code up the statements below to see how this construct works.
#include<stdio.h>	
int main() {

  int count;

  for (count = 1; count <= 10; count++)
  {
    printf("%d\n",count);
  } 
  return 0;
}
Compile and run this code. Try writing some variations on this code.

Example:

Initialising the loop in an option, although you still need the first semicolon, e.g., see code fragment below
printf("Enter a number to start the count: ");
fgets(line,sizeof(line),stdin);
sscanf(line,"%d",&count);
for ( ; count < 100 ; count++)
{
    printf("%d\n",count);
}
You can also have many initialisations and actions, e.g. see code fragment below to that finds the midpoint between 0 an 100<
for (i = 0, j = 100; j != i; i++, j--)
{
    printf("i = %d, j = %d\n",i,j);
}
printf("i = %d, j = %d\n",i,j);

Back to top

5. break & continue

break

A loop will terminate when the test condition(s) are no longer true, and this typically happens at the start or the end of a loop structure. The break statement allows a loop to terminate in the middle of the construct. The general syntax is

while (condition1==true) {
    executing_statements1();
if (condition2==true) {
break; }
executing_statements2();
}

If condition2 equals true, then the executing_statements2() will not be executed, and the while loop will be exited.

continue

A related statement is continue. Consider the following example

int i;

for (i=0; i<20; i++) {
if (i==13) {
continue;
}
printf("i=%d\n",i);
}

This will loop from 0 to 20. However, when it arrives at the unlucky number 13, it will continue to the next iteration of the for loop (i=14) without executing the statements after it. Hence upon executing this code all the numbers from 0 to 19 will be printed to the screen, except number 13.

6. Indenting

With the statement blocks and flow control statements the code can look quite complicated. One strategy is to properly indent your code. Then you can immediately see if brackets are not matching. For C there are two main styles for indenting

  • The opening and closing curly brace are the only symbols on a line and match up each other by starting at the same column; code in between is indentented; each statement starts on a seperate line
  • The conditional keyword matches up with the closing curly brace, and the opening curly brace is on the same line as the conditional keyword; code in between is indented;each statement starts on a seperate line

Look at the examples above to see which style has been used. It is also common practise to start each statement on a new line.

Putting it into Practice:

Properly indent the following code according both styles
#include<stdio.h>	
int main(){int count;for(count=1;count<=10;count++){printf("%d\n",count);} return 0;}
 


Back to top