C Programming language

Loops in C
Previous Home Next

Lop control structure

The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times until particular condition is being satisfied. there are methods by way of which we can repeat a part of program.

Types of loop

  1. Using a for statement
  2. Using a while statement
  3. Using a do while statement

While loop

This is the case when you want to do something a fixed number of times.

For example-- if we want to calculate the gross salary of 10 people then the while loop is best suited for that process.

The general form of the while loop is given below:

initialize loop counter;

while(test loop counter using a condition)

{

do this;

and this;

increment loop counter;

}

 

Some conditions for while loop

  1. The statement within the while loop would keep on getting executed till condition being tested remains true.
  2. If condition becomes falls the control passes to the first statement that follows the body of the while loop.
  3. The condition being tested may use may use relational or logical operators. for example--
    while(i<=10)
    while(i>=10&&j<=5)
    
  4. The statement within the loop may be a single line or a block of statement.
    for example--while ( i <= 10 )
    i = i + 1;
    is same as
    while ( i <= 10)
    {
    i = i + 1 ;
    }
    
  5. It is not necessary that a loop counter must be an int. it can be float also.
    main( )
    {
    float a=10.0;
    while(float a<=10.5)
    {
    printf("raindrops on roses");
    a=A+0.1;
    }
    }
    

For loop

The 'for' allows us to specify three things about a loop in a single line.

  1. Setting a loop counter to an initial value.
  2. Testing the loop counter to determine whether it's value has reached the number of repetition desired.
  3. increasing the value of loop counter each time the program segment with in the loop has been executed. the general form of 'for' statement is as follows:
    for(initialize counter;test counter;increment counter)
    {
    do this;
    and this;
    and this;
    }
    

Example

/* Calculation of simple interest for 3 sets of p, n and r */
main ( )
{
int p, n, count ;
float r, si ;
for ( count = 1 ; count <= 3 ; count = count + 1 )
{
printf ( "Enter values of p, n, and r " ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%f\n", si ) ;
}
}

The execution process for the above program is given as follows:

  1. When the for statement is executed for the first time, the value of count is set to an initial value 1.
  2. Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time.
  3. Upon reaching the closing brace of for, control is sent back to the for statement, where the value of count gets incremented by 1.
  4. Again the test is performed to check whether the new value of count exceeds 3.
  5. If the value of count is still within the range 1 to 3, the statements within the braces of for are executed again.
  6. The body of the for loop continues to get executed till count doesn’t exceed the final value 3.
  7. When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for.

Multiple initialization in For loop

one statement separated by a comma. For example:

for ( i = 1, j = 2 ; j <= 10 ; j++ )

Multiple statements can also be used in the incrementation expression of for loop; i.e., you can increment (or decrement) two or more variables at the same time. However, only one expression is allowed in the test expression. This expression may contain several conditions linked together using logical operators. Use of multiple statements in the initialisation expression also demonstrates why semicolons are used to separate the three expressions in the for loop. If commas had been used, they could not also have been used to separate multiple statements in the initialisation expression, without confusing the compiler.

The 'do while' code

The do-while loop looks like this:

do
{
this ;
and this ;
and this ;
and this ;
} while ( this condition is true ) ;

The major difference between the while loop and dowhile loop is that The while tests the condition before executing any of the statements within the while loop. As against this, the do-while tests the condition after having executed the statements within the loop.

Example

main( )
{
do
{
printf ( "Hello there \n") ;
} while ( 4 < 1 ) ;
}

In this program the printf( ) would be executed once, since first the body of the loop is executed and then the condition is tested.

break and continue are used with do-while just as they would be in a while or a for loop. A break takes you out of the do-while bypassing the conditional test. A continue sends you straight to the test at the end of the loop.

Nesting of Loops

The way if statements can be nested, similarly whiles and fors can also be nested. To understand how nested loops work, look at the program given below:

/* Demonstration of nested loops */
main( )
{
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
{
sum = r + c ;
printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
}
}
}

When you run this program you will get the following output:
r = 1 c = 1 sum = 2
r = 1 c = 2 sum = 3
r = 2 c = 1 sum = 3
r = 2 c = 2 sum = 4
r = 3 c = 1 sum = 4
r = 3 c = 2 sum = 5

Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2. The inner loop terminates when the value of c exceeds 2, and the outer loop terminates when the value of r exceeds 3.

As you can see, the body of the outer for loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the program easier to understand. Instead of using two statements, one to calculate sum and another to print it out, we can compact this into one single statement by saying:

printf ( "r = %d c = %d sum = %d\n", r, c, r + c ) ;

The way for loops have been nested here, similarly, two while loops can also be nested. Not only this, a for loop can occur within a while loop, or a while within a for.

The odd loop

The loops that we have used so far executed the statements within them a finite number of times.

Example

/* Execution of a loop an unknown number of times */
main( )
{
char another ;
int num ;
do
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
} while ( another == 'y' ) ;
}

And here is the sample output...
Enter a number 5
square of 5 is 25
Want to enter another number y/n y
Enter a number 7
square of 7 is 49

In this program the do-while loop would keep getting executed till the user continues to answer y. The moment he answers n, the loop terminates, since the condition ( another == 'y' ) fails. Note that this loop ensures that statements within it are executed at least once even if n is supplied first time itself.

Though it is simpler to program such a requirement using a do while loop, the same functionality if required, can also be accomplished using for and while loops as shown below:

/* odd loop using a for loop */
main( )
{
char another = 'y' ;
int num ;
for ( ; another == 'y' ; )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\nWant to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
}
}
/* odd loop using a while loop */
main( )
{
char another = 'y' ;
int num ;
while ( another == 'y' )
{
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
printf ( "square of %d is %d", num, num * num ) ;
printf ( "\want to enter another number y/n " ) ;
scanf ( " %c", &another ) ;
}
}

The break statement

when we want to jump out of a loop instantly, with out waiting to get back to the conditional test then we use the 'break' keyword. when 'break' encountered inside any loop, control automatically passes to the first statement after the loop. a 'break' is usually associated with an 'if'.

Example

Write a program to determine whether a number is prime or not. A prime number is one, which is divisible only by 1 or itself.

main( )
{
int num, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i = 2 ;
while ( i <= num - 1 )
{
if ( num % i == 0 )
{
printf ( "Not a prime number" ) ;
break ;
}
i++ ;
}
if ( i == num )
printf ( "Prime number" ) ;
}

In this program the moment num % i turns out to be zero, (i.e.num is exactly divisible by i) the message “Not a prime number” is printed and the control breaks out of the while loop. Why does the program require the if statement after the while loop at all? Well, there are two ways the control could have reached outside the while loop:

  1. It jumped out because the number proved to be not a prime .The loop came to an end because the value of i became equal to num.
  2. When the loop terminates in the second case, it means that there was no number between 2 to num - 1 that could exactly divide num. That is, num is indeed a prime. If this is true, the program should print out the message “Prime number”.

Continue statement

At the time of making the program when we want to take the control to the beginning of the loop, bypassing the statement inside the loop which has not been executed then the keyword 'continue' allows us to do so.

A continue is usually associated with an if. As an example, let's consider the following program.

main( )
{
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j )
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}

The output of the above program would be...
1 2
2 1

Case control structure

C provides a special control statement that allows us to handle the difficult programming and to make a decision from the number of choices.

The "Goto" keyword

In a difficult programming situation it seems so easy to use a goto to take the control where you want.

By the following example we can understand the use of goto keyword:

main( )
{
int goals ;
printf ( "Enter the number of goals scored against India" ) ;
scanf ( "%d", &goals ) ;
if ( goals <= 5 )
goto sos ;
else
{
printf ( "About time soccer players learnt C\n" ) ;
printf ( "and said goodbye! adieu! to soccer" ) ;
exit( ) ; /* terminates program execution */
}
sos :
printf ( "To err is human!" )
}

About the program

If the condition is satisfied the goto statement transfers control to the label ‘sos’, causing printf( ) following sos to be executed.

  1. The label can be on a separate line or on the same line as the statement following it, as in
     sos : printf ( "To err is human!" ) ;
    
  2. Any number of gotos can take the control to the same label.
  3. The exit( ) function is a standard library function which terminates the execution of the program. It is necessary to use this function since we don't want the statement
    printf ( "To err is human!" ) to get executed after execution of the else block.
  4. The only programming situation in favour of using goto is when we want to take the control out of the loop that is contained in several other loops.
Previous Home Next