Decision Making – Looping-C Programming


C Programming – Decision Making – Looping

In this tutorial you will learn about C Programming – Decision Making – Looping, The While Statement, The Do while statement, The Break Statement, Continue statement and For Loop.

 During looping a set of statements are executed until some conditions for termination of the loop is encountered. A program loop therefore consists of two segments one known as body of the loop and other is the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.

In looping process in general would include the following four steps
1. Setting and initialization of a counter
2. Exertion of the statements in the loop
3. Test for a specified conditions for the execution of the loop
4. Incrementing the counter

The test may be either to determine whether the loop has repeated the specified number of times or to determine whether the particular condition has been met.

The test may be either to determine whether the loop has repeated the specified  number of times or to determine whether the particular condition has been met.

The While Statement:

The simplest of all looping structure in C is the while statement. The general format of the while statement is:

while (test condition)
{
body of the loop
}

Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statements immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contained two are more statements.

Example program for generating ‘N’ Natural numbers using while loop:

# include < stdio.h > //include the stdio.h file
void main() // Start of your program
{
int n, i=0; //Declare and initialize the variables
printf(“Enter the upper limit number”); //Message to the user
scanf(“%d”, &n); //read and store the number
while(I < = n) // While statement with condition
{ // Body of the loop
printf(“\t%d”,I); // print the value of i
I++; increment I to the next natural number.
}
}

In the above program the looping concept is used to generate n natural numbers. Here n and I are declared as integer variables and I is initialized to value zero. A message is given to the user to enter the natural number till where he wants to generate the numbers. The entered number is read and stored by the scanf statement. The while loop then checks whether the value of I is less than n i.e., the user entered number if it is true then the control enters the loop body and prints the value of I using the printf statement and increments the value of I to the next natural number this process repeats till the value of I becomes equal to or greater than the number given by the user.

The Do while statement:

The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once.

The syntax of the do while loop is:

Do
{
statement;
}
while(expression);

Here the statement is executed, then expression is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false. When the expression becomes false. When the expression becomes false the loop terminates.

 To realize the usefulness of the do while construct consider the following problem. The user must be prompted to press Y or N. In reality the user can press any key other than y or n. IN such case the message must be shown again and the user should be allowed to enter one of the two keys, clearly this is a loop construct. Also it has to be executed at least once. The following program illustrates the solution.

/* Program to illustrate the do while loop*/
#include < stdio.h > //include stdio.h file to your program
void main() // start of your program
{
char inchar; // declaration of the character
do // start of the do loop
{
printf(“Input Y or N”); //message for the user
scanf(“%c”, &inchar); // read and store the character
}
while(inchar!=’y’ && inchar != ‘n’); //while loop ends
if(inchar==’y’) // checks whther entered character is y
printf(“you pressed u\n”); // message for the user
else
printf(“You pressed n\n”);
} //end of for loop

The Break Statement:

Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately.

Example program to illustrate the use of break statement.

/* A program to find the average of the marks*/
#include < stdio.h > //include the stdio.h file to your program
void main() // Start of the program
{
int I, num=0; //declare the variables and initialize
float sum=0,average; //declare the variables and initialize
printf(“Input the marks, -1 to end\n”); // Message to the user
while(1) // While loop starts
{
scanf(“%d”,&I); // read and store the input number
if(I==-1) // check whether input number is -1
break; //if number –1 is input skip the loop
sum+=I; //else add the value of I to sum
num++ // increment num value by 1
}} end of the program
 

Continue statement:

During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued with the next iteration after skipping any statement in between. The continue with the next iteration the format of the continue statement is simply:

Continue;

Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement.

#include < stdio.h > //Include stdio.h file
void main() //start of the program
{
int I=1, num, sum=0; // declare and initialize the variables
for (I = 0; I < 5; I++) // for loop
{
printf(“Enter the integer”); //Message to the user
scanf(“%I”, &num); //read and store the number
if(num < 0) //check whether the number is less than zero
{
printf(“You have entered a negative number”); // message to the user
continue; // starts with the beginning of the loop
} // end of for loop
sum+=num; // add and store sum to num
}
printf(“The sum of positive numbers entered = %d”,sum); // print thte sum.
} // end of the program.
 

For Loop:

The for loop provides a more concise loop control structure. The general form of the for loop is: 

for (initialization; test condition; increment)
{
body of the loop

When the control enters for loop the variables used in for loop is initialized with the starting value such as I=0,count=0. The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition. 

Additional features of the for loop: 

We can include multiple expressions in any of the fields of for loop provided that we separate such expressions by commas. For example in the for statement that begins 

For( I = 0; j = 0; I < 10, j=j-10)  

Sets up two index variables I and j the former initialized to zero and the latter to 100 before the loop begins. Each time after the body of the loop is executed, the value of I will be incremented by 1 while the value of j is decremented by 10. 

Just as the need may arise to include more than one expression in a particular field of the for statement, so too may the need arise to omit on or more fields from the for statement. This can be done simply by omitting the desired filed, but by marking its place with a semicolon. The init_expression field can simply be “left blank” in such a case as long as the semicolon is still included: 

For(;j!=100;++j)

The above statement might be used if j were already set to some initial value before the loop was entered. A for loop that has its looping condition field omitted effectively sets up an infinite loop, that is a loop that theoretically will be executed for ever.

For loop example program:

/* The following is an example that finds the sum of the first fifteen positive natural numbers*/
#include < stdio.h > //Include stdio.h file
void main() //start main program
{
int I; //declare variable
int sum=0,sum_of_squares=0; //declare and initialize variable.
for(I=0;I < = 30; I+=2) //for loop
{
sum+=I; //add the value of I and store it to sum
sum_of_squares+=I*I; //find the square value and add it to sum_of_squares
} //end of for loop
printf(“Sum of first 15 positive even numbers=%d\n”,sum); //Print sum
printf(“Sum of their squares=%d\n”,sum_of_squares); //print sum_of_square
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s