T223 C Tutorial. How to Branch and Loop, using if, if ( ) ... else, do ... while, while, for, switch, break, continue, default

John McGuinn's C Tutorial

ICRA This site does not contain Adult material

Up to 80% off for Students from Adobe. 

 

Back to School! Adobe Student Editions

T223 'C' Tutorial - How to Branch and Loop

Results per page:

Match: any search words all search words

C Home page | ' C ' Books | Student Software | Tutorial 2. Outputting text | Tutorial 3. Variables | Tutorial 5. Controlling program flow in plain English | Tutorial 6 Branching & Looping | Tutorial 90.' C ' Error Messages | Tutorial 99. Quick reference | ASCII Codes | Download files |

Updated 3 Mar 03

Contents

 Introduction Conditions
 Testing - Boundary Values Function Quick Comparison
 Branching if ( )
if ( ) ... else
 Looping do ... while ( )
while ( )
for ( )
switch ( )
Jump statements case
break
default
continue
Divide by zero error     Semicolon ;     braces { }     nesting constructs     nested example

Introduction

Unless you already understand the basics of “branching and looping” you should read The previous tutorial Controlling Program Flow in Plain English.

You have arrived at the point where programming becomes more challenging and if you have a programmers mind" far more interesting, so enjoy.

This is the stage where you have to start thinking, how can I code a particular aspect of my project.

This is the point where you start to develop your personel style.

Up to this tutorial your programs have been sequential or linear statements being executed one after the other. Now you are going to be introduced to constructs that alter that linear progression.

The new functions that are in this tutorial allow either branching or looping.

You will note that a pair braces { } are used with these constructs.

The { denotes the start of the first statement within the construct.
The } denotes the end of the last statement in the construct.

Tip: Take particular note of how braces { } are used.

Tip: Note where ; is NOT used in these constructs.

Tip: As you read my tutorials, books, course material etc., copy a few samples of each construct showing the use of braces and where ; is used or not used, for future reference. Pay particular note of the if ( ) ... else construct, and where constructs are nested. That it where a construct is placed within the braces of another construct. You can have several layers of nesting. A nested example is given later on this page.

Top of Page

Branching

Branching statements allow different sections of code to be executed, or not executed depending on some condition being either true or false.
The following constructs contain branching.

From the previous tutorial, “Do you require sugar” is an example

.

if, if ... else, while, do, switch, and for constructs.

All these construct contain a test. Think of test as a question. Example “Is the number less than 3”

All tests contain a comparison / conditional operator such as equal to, less than, or greater than. These comparison or conditional operators are listed below.

Top of Page

Looping

Looping constructs are used to repeat a section of code a number of times, depending on some condition being either true or false.

To take the previous lesson a little further, if somebody wanted 3 teaspoon full of sugar the you could repeat adding 1 spoonful of sugar 3 times.

Iteration is the correct term to use for this looping process

The looping constructs are while, do, for constructs.

Again these contructs contain a test and a a comparison / conditional operator

Top of Page


True or False

In C the value of true is nonzero, and false 0. See Conditions below

Function Quick Comparison

This table compare how the different contructs compare in what they do. At the moment you may not understand this comparison, refer back to this table as you gain experience.

The actual test is always carried out, and depending on the test result, the following section(s) code will be or will not be exectuted, this is listed in the Times executed column.

Construct Times executed A section of code executed
if 0 or 1 Section 1 Not executed or executed
if ... else 1 Section 1 or Section 2 executed
switch ... case 0 or 1 Not executed or 1 or more section(s) executed,
see break from a multi choice of alternative sections.
A default option available
while 0,1 or more Section 1 Not executed, executed once, or executed more times
do ... while 1 or more Section 1 executed at least once or more times
for 0,1 or more Section 1 Not executed or executed 1 or more times

Top of Page


Jump Statements

These statements transfer control to a different location within the code.
Statement Where used
break Only within while, do, for, and switch constructs.
continue Only within while, do, for constructs.
goto Transfers control to a label within the same function. Note this contruct is frowned upon, because it makes the code hard to understand.
return Normally at the end of functions

Top of Page

Conditions

In C a condition is any expression that generates a zero (false) or nonzero (true).
The operators in the table below are used in conditions.

Operator
Meaning
Comment
Equality Operators == Equal A common error is to confuse the
equals == operator

with the
assignment operator =
!= Not equal
Relational Operators < Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Example

x == y
a! = 5

Is X equal to Y
Is a not equal to 5

 
String example strcmp(str1,str2) == 0 Is str1 equal to str2  

Top of Page

Testing - Boundary Values

Pay particular attention to boundary values. Use them when testing.

For the following condition
if (count <= 50) count++;

The boundary values that you would use in testing are 49, 50 and 51.

Top of Page

if ( )

Use

Depending on the result of a condition the program will either
  • branch and execute some code, then continue with the rest of the program.
OR
  • continue with the rest of the program.

Syntax

if ( condition ) statement 1; 

if ( condition ) 
      statement 1; 

This is perhaps a more popular way of writing the code. The additional line is white space, therefore there is no ; after if ( condition )
Warning: Inserting a ; may be accepted by the compiler but will produce unexpected results.

Although not required for single statement if constructs, I recommend that braces are used as follows, so that there is no confusion to what is included within the construct.

if ( condition )
    {
      statement 1;
    } 

When more than 1 statement is used then braces MUST be used.

If ( condition )
    {
      statement 1;
      statement 2;
    } 


Description

Use if to implement a conditional statement.
When condition evaluates to be nonzero, statement 1 executes.
If condition is false (0), statement 2 executes.

Example

if (count < 50) count++;
This code will add 1 to the value of count is < (less than) 50
Thus
Value of count at start   Value of count at end
 35  36
 49  50
 50  50 (No change)
 54  54 (No change)

Top of Page

if ( ) ... else

Use

Depending on the result of a condition the program will either
  • branch and execute some code, then continue with the rest of the program.

OR
  • branch and execute some different code, then continue with the rest of the program.
If three choices are required then an additional if ... else pair is required.
If several choices are required see the switch construct
if ( condition ) 
    {
       statement 1; 
    }
   else 
    {
       statement 2;
    }

Description

Use if to implement a conditional statement. When condition evaluates to be nonzero, statement 1 executes. If condition is false (0), statement 2 executes.

Else is optional, but no statements can come between an if statement and an else.

The #if and #else pre-processor statements (directives) look similar to the if and else statements, but have very different effects. They control which source file lines are compiled and which are ignored.

Example

if (x < y)
    {   
      z = x;
    }
else
    {
       z = y;
    }

Explanation

If the value of x is     less than the value of y   then  z is assigned the value of x
If the value of x is NOT less than the value of y   then  z is assigned the value of y

Top of Page

do ... while

Use

  1. The code within a do ... while loop will execute at least once, because the condition is at the end of the loop. Then depending on the result of a condition the program will either
  2. repeat the loop code step 1.
  3. OR
  4. continue with the rest of the program.

Syntax

do
      { 
      statement(s)
      }while (condition );

Description

The do statement implements a do ... while loop.
Statement is executed repeatedly as long as the value of condition remains non-zero. Since the condition tests after each the loop executes the statement , the loop will execute at least once.
Normally within the loop is code that will modify one, or more, of the variables in the condition so that the loop will eventually end. This modification may take they form of incrementing or decrementing to a variable.

Example. File do01.c

/* This example prompts users for a password     */
/* and continued to prompt them until they       */
/* enter one that matches the value stored in    */
/* checkword.                                    */


#include <stdio.h>
#include <string.h> 
int main ()
{
  char checkword [80] = "password" ;     /*  Declare variable and initialize with string "password" */  
  char password [80]  = "" ;             /*  Declare variable and initialize with string "" */   
  do                                     /*  Loop start  */
    {
       printf ("Enter password: ") ;     /*  User input  prompt  */ 
       scanf ("%s", password) ;          /*  Store user input in string variable  */
    }  while (strcmp (password, checkword)) ;  /*  Compare password & checkword, goto Loop start if not equal */
  return 0;
}

Explanation

See comments in code

Top of Page

while ( )

Use

Very similar to the do ... while construct, but with the condition at the start of the construct. Therefore depending on the condition the loop may not execute.

Syntax

while ( condition ) statement

Description

Use the while keyword to implement a while loop. statement executes repeatedly until the value of condition is zero. The test takes place before statement executes. Thus, if condition evaluates to zero on the first pass, the loop does not execute.

Example

while (p < 6) p++;
statement(s)
If the value of p is 4 when the loop is entered then the statement(s) in the loop will execute twice.

Top of Page

for ( )

Use

This construct is known as looping because the execution loops back and repeats some code a number of times.

Syntax

for ( [initialization] ; [condition] ; [increment] )  statement

Description


The for statement implements a for loop.
<Statement> is executed repeatedly UNTIL the value of <condition> is FALSE.
  • Before the first iteration of the loop, <initialization> initializes variables for the loop.
  • After each iteration of the loop, <increments> increments a loop counter. (Consequently, j++ is functionally the same as ++j.)

Examples

total = 0
for (i = 0; i < 100; i++)
   total += x[i];

Explanation

Total up the first 100 values (index 0-99) held in array x[].
Code Explanation  
total = 0
The variable total is set to 0 before the start of the loop.  
i = 0
Initialises i the start value for the loop. The usual settings are either 0 or 1 but any number can be used.  
i < 100
The loop will continue while the value of i is less than 100. To make code easier to read, try to show the number of times the loop will operate.
If the start value was 1 and you still required 100 loops, then i <= 100 would be better than using i < 101, although both will work.
 
i++
The value of i is incremented by 1. Decrements can also be used, but thing about what will then be required for the start initialisation, and the condition  
total += x[i]
Adds the value of the array contents for the array elements 0 to 99, storing the sum in the variable total.  

 

Top of Page

switch ( )

Use

Switch allows multi choice branching.
Suitable where several choices are required.
Ideal to use to construct a menus.

Syntax

switch ( switch variable ) 
    { 
      case constant expression :statement; [break;] 
      . 
      . 
      . 
      default : statement; 
    } 

Description

Use the switch statement to pass control to a case which matches the switch variable. At which point the statements following the matching case evaluate.

If no case satisfies the condition the default case evaluates.

To avoid evaluating any other cases and relinquish control from the switch, terminate each case with break;.


Further information See case break default

Example

switch (operand) 
     {
       case MULTIPLY:   x *= y ; break ;
       case DIVIDE:     x /= y ; break ;
       case ADD:        x += y ; break ;
       case SUBTRACT:   x -= y ; break ;
       case INCREMENT2: x++ ;            /* execution continues to next case */
       case INCREMENT1: x++ ;    break ;
       case EXPONENT:
       case ROOT:
       case MOD:        printf("Not done\n") ; break ;
       default:         printf("Bug!\n") ;  /* Often used for user warnings */
       exit(1) ;
      }

Top of Page


break

Use

Used within loops

Syntax

break ;

Description

Use the break statement within loops to pass control to the first statement following the innermost enclosing brace.
Further information See case switch ( ) default

Example

switch (time)
	  {
	    case 12: printf ( "Time for lunch!\n" ) ;       break;
	    case 1:  printf ( "Meet with manager.\n" ) ; 	break;
	  }
Further example see switch ( )

Top of Page

case

Use

Is a vital part of the switch ( ) construct

Syntax

switch ( switch variable ) 
    { 
      case constant expression :statement; [break;] 
      . 
      . 
      . 
      default : statement; 
    } 

Description

Use the case statement in conjunction with switches to determine which statements evaluate.

The list of possible branch points within statement is determined by preceding substatements with

case constant expression : statement;
where constant expression must be an int and must be unique.

The constant expression values are searched for a match for the switch variable.

If a match is found, execution continues after the matching case statement until a break statement is encountered or the end of the switch statement is reached.

If no match is found, control is passed to the default case.

Note: It is illegal to have duplicate case constants in the same switch statement.
Further information. Seeswitch ( ) break default

Example

See switch ( ) break

Top of Page

default

Use

Used within a switch ( ) construct, as a catch all!
Usually the programmer will code in checks to prevent the default code being executed.
Often warns the user of inappropriate data entry, and sets a flag so that the user can re-enter data.

Syntax

switch ( switch variable ) 
    { 
      case constant expression :statement; [break;] 
      . 
      . 
      . 
      default : statement; 
    } 

Description

Use the default statement in switch statement blocks.
  • If a case match is not found and the default statement is found within the switch statement, the execution continues at this point.
  • If no default is defined in the switch statement, control passes to the next statement that follows the switch.
  • Can be used to initiate an error message, possibly stating that the user input was not acceptable.
See case switch ( ) break

Example

See switch ( ) break

Top of Page

continue

Use

Syntax

continue ;

Description

Use the continue statement within loops to pass control to the end of the innermost enclosing brace; at which point the loop continuation condition is re-evaluated.

Example

This example sets the value of the first 20 array element to the value of, 1 divided by the value of the array element. Zero values are left unchanged and a divide by zero error avoided.

Note the nested if construct within the for construct.

void main ()
   {
       for (i = 0; i < 20; i++) 
          {
            if (array[i] == 0) 
                {
                    continue;
                }  
            array[i] = 1/array[i];
          }
   }

 

Tip:

  • When writing nested or complicated constructs, start by entering the the name of the constructs, parenthesis and the braces.
  • Vertically align the braces.
  • Add any helpful comment if required.
  • Count that the number of left braces equals the number of right braces.
  • Count that the number of left brackets equals the number of right brackets.
  • Enter the semi colons in the required positions. You may need to re-read the above, and to collect a few examples to help in doing this.
Void main ()
   {
       for (    )        /* Repeat 20 times */
          {
            if ( )       /* Check if array value is 0 */  
                {
                    ;   /* Prevent a divide by zero error and miss the following line */
                }        /* End of the if construct */
          ;   /* Set the array */
          }              /* End of the for construct */
   }                     /* End of the main function */

This example is only to give you an idea, of setting out the nested constructs, before adding the code that does the actual work. If you are attempting an exercise or Open University TMA you can incorporate the actual wording into the comment.


| Previous Tutorial 5. Controlling program flow in plain English| | Next Tutorial | Top of Page |

 

| Top of Page |

More courses for Open University students by John McGuinn.
HTML and Web Design tutorial suitable for Beginers and students of Open University Courses for T171, TT

Smalltalk  suitable for Beginers and students of Open University Courses an Object-Oriented Approach M885
and discontinued Object-oriented courses M878 and M206

Other Sites to Visit

Leeds guide my home town City of Leeds information

 

Relax in the sun

Benidorm and Costa Blanca   Gran Canaria  Malta and Gozo   Resorts in Spain   Tenerife

 

 

AireWeb Web Site Designers


Leeds Web Design Web Designers Hosting Domain names Web site Promotion

Leeds my home town

Relax in the sun.

Benidorm   Tenerife   San Marino apartments to rent

Copyright © John G McGuinn 2001-03