|< C & C++ Program Controls 2 | Main | C & C++ Program Controls 4 >| Site Index | Download |


 

 

 

MODULE 6a

MORE ON C/C++ PROGRAM CONTROLS/LOOPS 3

 

 

 

 

 

 

 

 

My Training Period: xx hours

 

A continuation from previous Module. The source code for this Module is: C/C++ loops source codes. The lab worksheets for your practice are: C/C++ program control repetition 1, C/C++ program control repetition 2, C/C++ program control selection 1, C/C++ program control selection 2 and C/C++ program control selection 3.

 

The C and C++ programming abilities should be:

 

Able to understand and use:

  • The while statement.

  • The do-while loop.

  • The nested loop.

  • Other program controls such as goto, continue, exit, atexit and return statement.

 

6.4    The while Statement – Repetition Control Structure, Iteration

  • Also called the while loop, executes a block of statements as long as a specified condition is true.

  • The general form:

while(condition)

     statement(s);

next_statement;

  • The (condition) may be any C/C++ valid expression.

  • The statement(s) may be either a single or a compound (a block) C/C++ statement.

  • When program execution reaches a while statement, the following events occur:

  1. The (condition) is evaluated.

  2. If (condition) evaluates as false (that is zero), the while statement terminates and execution passes to the first statement following statement(s) that is the next_statement.

  3. If (condition) evaluates as true (that is non zero), the C/C++ statement(s) are executed.

  4. Then, the execution returns to step number 1.

  • The while statement flow chart is shown below.

C++ program control while statement loop repetition

// demonstrates a simple while statement

#include <stdio.h>

 

int main()

{

       int  calculate;

       // print the numbers 1 through 12, set the initial value...

       calculate = 1;

       // set the while condition...

       while(calculate <= 12)

       {

              // display...

              printf("%d  ", calculate);

              // increment by 1...repeats

              calculate++;

       }

       printf("\n");

       return 0;

}

 

Output:

 

C++ program control while statement loop repetition example

for( ; condition; )  vs    while(condition)

// a nested while statements

#include <stdio.h>

 

// this program have some array that you will learn in another module...

void main()

{

   // array variable...

   int  arrange[5];

   int  count = 0,

   number = 0;

   printf("\nPrompting you for 5 numbers\n");

   printf("Each number should be from 1 to 10\n");

   // while condition is true

   while(count<5)

   {

          // set the initial condition...

          number = 0;

          // another while condition...

          while((number < 1) || (number > 10))

          {

                printf("Enter number %d of 5: ", count + 1);

                scanf("%d", &number);

          }

          // inner while loop stop here...  

          arrange[count] = number;

          count++;

   }

   // outer while loop stop here, start for loop for printing the result...

   for (count = 0; count < 5; count++)

       printf("\nValue %d is %d", count + 1, arrange[count]);

   printf("\n");

}

 

Output:

 

C C++ loops program control while statement loop repetition another example

6.5    Repetition: The do-while Loop, Iteration

do

  statement(s);

while(condition);

next_statement;

  1. The statement(s) are executed.

  2. The condition is evaluated.  If it is true, execution returns to step number 1.  If it is false, the loop terminates and the next_statement is executed.

C++ loops program control do...while statement loop repetition

// a program to illustrate a do-while loop

#include <iostream>

using namespace std;

 

int main()

{

   int   selection;

   do

   {

          // true for 1, 2 and 3 ONLY, then repeat

          // false for other numbers including 0, then stop...

          // the do loop is repeated if the while expression is true.

          cout<<"\n     Menu"<<"\n";

          cout<<"\n   0.    Exit";

          cout<<"\n   1.    Append";

          cout<<"\n   2.    Delete";

          cout<<"\n   3.    Modify";

          cout<<"\n\n      Enter selection: ";

          cin>>selection;

   }while((selection > 0) && (selection < 4));

   return 0;

}

 

Output:

 

C C++ loops program control do...while statement loop repetition example

// another do…while statement example

#include <stdio.h>

 

int get_menu_choice(void);

 

void main()

{

   int   choice;

   choice = get_menu_choice();

   printf("You have chosen Menu #%d\n", choice);

   printf("\n");

}

 

int get_menu_choice(void)

{

   int selection = 0;

   do

   {

          printf("1   -  Add a record");

          printf("\n2   -  Change a record");

          printf("\n3   -  Delete a record");

          printf("\n4   -  Quit");

          printf("\nEnter a selection:  ");

          scanf("%d", &selection );

   } while ((selection < 1) || (selection > 4));

   return selection;

}

               

Output:

 

C C++ loops program control do...while statement loop repetition another example

 

6.6    Other Program Controls

  • The continue statement can only be used inside a loop (for, do-while and while) and not inside a switch.  When executed, it transfers control to the test condition (the expression part) in a while or do-while loop, and to the increment expression in a for loop.

  • It forces the next iteration to take place immediately, skipping any instructions that may follow it.

  • Unlike the break statement, continue does not force the termination of a loop, it merely transfers control to the next iteration.

  • Let consider the following example:

for(i=1, sum=0; i<100; i++)

{

    if (i%2) // test value, 0 or non-zero

        continue;     // executed if the test value is non-zero and repeat the for statement

     sum = sum + i;  // executed if the test value is zero and then, also repeat the for statement

}

  • This loop sums up the even numbers 2, 4, 6, ... , 98 and stores the value in the variable sum.  If the expression i % 2 (the remainder when i is divided by 2) yields a non-zero value (i.e., if i is odd), the continue statement is executed and the iteration repeated (i incremented and tested).

  • If it yields a zero value (i.e., if i is even), the statement sum = sum + i;  is executed and the iteration continued.

  • When a continue statement executes, the next iteration of the enclosing loop begins.  The enclosing loop means the statements between the continue statement and the end of the loop are not executed.

  • Another program example:

            // continue example

#include <stdio.h>

 

void main()

{

       // declare storage for input, an array and counter variable

       char buffer[81];

       int ctr;

       // input and read a line of text using

       // puts() and gets() are pre defined functions in stdio.h

       puts("Enter a line of text and press Enter key,");

       puts("all the vowels will be discarded!:\n");

       gets(buffer);

       // go through the string, displaying only those

       // characters that are not lowercase vowels

       for(ctr=0; buffer[ctr] != '\0'; ctr++)

       {

         // if the character is a lowercase vowel, loop back without displaying it

         if((buffer[ctr]=='a')||(buffer[ctr]=='e')|| (buffer[ctr]=='i')||(buffer[ctr]=='o')||(buffer[ctr]=='u'))

              continue;

          // if not a vowel, display it

          putchar(buffer[ctr]);

       }

       printf("\n");

 }

 

 Output:

 

C C++ program control continue

// demonstrates the goto statement

#include <stdio.h>

 

void main()

{

   int   n;

   start: ;

   puts("Enter a number between 0 and 10: ");

   scanf("%d", &n);

   if ((n < 0) || (n > 10))

   goto  start;

   else if (n == 0)

          goto location0;

   else if (n == 1)

          goto location1;

   else

          goto location2;

   location0:  ;

   {

          puts("You entered 0.");

   }

   goto   end;

   location1: ;

   {

          puts("You entered 1.");

   }

   goto  end;

   location2: ;

   {

          puts("You entered something between 2 and 10.");

   }

   end: ;

}

 

Output:

 

C C++ Program control goto

Function

Description

abort()

Abort current process and return error code defined in stdlib.h

terminate()

Used when a handler for an exception cannot be found.  The default action by terminate is to call abort() and causes immediate program termination.  It is defined in except.h.

 

Table 6.2:  Termination functions.

exit(status);

 

Status

Description

0

The program terminated normally.

1

Indicates that the program terminated with some sort of error.  The return value is usually ignored.  Other implementation may use other than 1 (non-zero) for termination with error.

 

Table 6.3:  exit() status

#define  EXIT_SUCCESS  0

#define  EXIT_FAILURE  1

exit(EXIT_SUCCESS);

 

Or

 

exit(EXIT_FAILURE);

int    atexit(void(*)(void));

#include <stdlib.h>

#include <stdio.h>

 

// function prototypes...

void cleanup1(void);

void cleanup2(void);

 

void main()

{

       atexit(cleanup2);

       atexit(cleanup1);

       // end of main

}

 

void cleanup1(void)

{

       // dummy cleanup.....

       printf("\nThis is the demonstration...\n");

       printf("cleanup....\n");

       printf("You computer is SHUTTING DOWN!!!");

       getchar();

}

 

void cleanup2(void)

{

       // another dummy cleanup...

       printf("\nAnother cleanup...");

       printf("\nWINDOWS 20000 is closing the entire program...");

       printf("\nPlease WAIT...");

       printf("\nSHUTTING DOWN IN PROGRESS...\n");

       getchar();

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C C++ program control atexit()

// demonstrates the exit() and atexit() functions

#include <stdio.h>

#include <time.h>

#include <stdlib.h>

#define  DELAY  1500000

 

// function prototypes

void  cleanup(void);

void  delay(void);

 

void main()

{

   // register the function to be called at exit

   int  reply;

   atexit(cleanup);

   puts("Enter 1 to exit, any other to continue.");

   scanf("%d", &reply);

   if(reply == 1)

          exit(EXIT_SUCCESS);

   // pretend to do some work

   for(reply = 0; reply < 5; reply++)

   {

          puts("WORKING...");

          delay();

   }

} // end of main

 

// function definition...

void  cleanup(void)

{

   puts("\nPreparing for exit");

   delay();

}

 

// function definition

void  delay(void)

{

   long  x;

   for(x = 0; x < DELAY; x++)

   ;

}

 

Output if user presses other than 1:

 

C C++ program control exit() and atexit()

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C/C++ related reading:

 

  1. Check the best selling C / C++ books at Amazon.com.
  2. The source code for this Module is: C/C++ loops source codes.
  3. The lab worksheets for your practice are: C/C++ program control repetition 1, C/C++ program control repetition 2, C/C++ program control selection 1, C/C++ program control selection 2 and C/C++ program control selection 3.

 

 

 

 

 

 

 

 

|< C & C++ Program Controls 2 | Main | C & C++ Program Controls 4 >| Site Index | Download |


C Formatted Input/Output:  Part 1 | Part 2 | Part 3 | Part 4 |