Loop Control Structure / Looping in C language / How to make loops in C language / Using for, while and do while in C language

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 if times or until a particular condition is being satisfied . This repetitive operation is done through a loop control instruction.

There are three methods by way of which we can repeat a part of a program. They are:

a) Using a for loop.

b) Using a while loop.

c) Using a do-while loop


For loop

The format of for loop:

For (initializing variable; testing variable; increment variable)

{

Statements; //what the loop will do

}

 

Now making a simple C program in which we will print a name 3 times.

int i;  // initialing looping variable

for ( i=1; i<=3; i++ )

{

printf(“www.programmingdoctors.wordpress.com”);

printf(“\n”);

}

Here is the output:

http://www.programmingdoctors.wordpress.com

http://www.programmingdoctors.wordpress.com

http://www.programmingdoctors.wordpress.com

Let us now examine how the for statement gets executed:

1.      When the for statement is executed for the first time, the value of i is set to an initial value 1.

2.      Now the condition i <= 3 is tested. Since i 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 i gets                             incremented by 1(i.e i++ means i=i+1).

4.      Again the test is performed to check whether the new value of i exceeds 3.

5.      If the value of i 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 i doesn’t exceed the final value 3.

7.      When i reaches the value 4 the control exits from the loop.

The diagram further illustrates the concept:

For is concerned with three things:

1.      Tell the compiler where to start.

2.      Tell the compiler when to stop

3.      Increment the loop.

The loop in the same way can be decrement as well by making few changes:

for ( i=3; i >=1; i– )

{

printf(“www.nediangurus.webs.com”);

printf(“\n”);

}

Here i is initialize to 3 and the condition is given that until i is greater than or equal to 1 the loop will proceed in the similar way as explain above, this is the way we can move the loop by decrementing.

While loop:

The format of while loop is:

initialize loop variable;

while(condition)

{

statements;

increment loop variable;

}

The statements keep on executed till the condition being tested remains true.

When the condition found false the loop terminates.

Let’s check out the simple example with a while loop :

int i=1;

while(i<=3)

{

printf(“www.nediangurus.webs.com”);

printf(“\n”);

i++;

}

Let us now examine how the while statement gets executed:

1.      When the while statement is executed for the first time, the value of i is set to an initial value 1.

2.      Now the condition i <= 3 is tested. Since i is 1 the condition is satisfied and the body of the loop is executed for the first time.

3.      After the statements are executed, the increment is done within the braces of the whileand the value of i is incremented (i.e.  i++ means i=i+1)

4.      Again the test is performed to check whether the new value of i exceeds 3.

5.      If the value of i is still within the range 1 to 3, the statements within the braces of whileare executed again.

6.      The body of the while loop continues to get executed till i doesn’t exceed the final value 3.

7.      When i reaches the value 4 the control exits from the loop.

The diagram further illustrates the concept:

There may be multiple or single statement, when there is a single statement parentheses are optional:

while ( i <= 10 )

i = i + 1

is same as:

while ( i <= 1)

{

i=i+1;

}

Instead of incrementing we can execute the loop by decrementing also :

void main(void)

{

int i = 5 ;

while (i>=1)

{

printf (“\nMake the computer literate!” ) ;

i=i–1;

}

}

♦  In place of the condition there can be any other valid expression. So long as the expression evaluates to a non-zero value the statements within the loop would get executed. The condition being tested may use relational or logical operators as shown in the following examples

while ( i <= 10 )

while ( i >= 10 && j <= 15 )

while ( j > 10 &&( b < 15 || c < 20 ) )

♦  As a rule the while must test a condition that will eventually become false, otherwise the loop would be executed forever,

main()

{

int i=1;

while(i<=10)

{

printf(“\n”);

}

}

This loop will execute forever hence i is not incremented and will remain 1 and the condition is always remain true.

Do-while loop

The format of  do-while loop:

do

{

statements;

increment loop variable;

} while(condition);

There is a minor difference between the working of while and do-while loops. This difference is the place where the condition is tested. The while tests the condition before executing any of the statements within the while loop. Instead, the do-while tests the condition after having executed the statements within the loop..

The diagram further illustrates:

This means that do-while would execute its statements at least once, even if the condition fails for the first time. The while, on the other hand will not execute its statements if the condition fails for the first time. This difference is brought about more clearly by the following program.

void main( void )

{

while(4<1)

printf(“Hello http://www.programmingdoctors.wordpress.com\n”);

}

Here, since the condition fails the first time itself, the printf( ) will not get executed at all. Let’s now write the same program using a do-while loop.

void main( void )

{

do

{

printf ( “Hello http://www.programmingdoctors.wordpress.com\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.

Nested-loop

1.  What a nested loop is a loop within a loop, i.e an inner loop and and outer loop.

2.  There is no restriction for the limit of nested loop, a large number of loops can be nested.

3.  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:

Nested-for loop:

int i,j;

for ( i=1 ; i<=3 ;i++)

{

for( j=1; j<=3; j++)

{

printf(“i=%d , j=%d\t”,i,j);

}

printf(“\n”);

}

Here is the output:

i=1 , j=1                  i=1 , j=2            i=1 , j=3

i=2 , j=1                  i=2 , j=2            i=2 , j=3

i=3 , j=1                  i=3 , j=2            i=3 , j=3

confused? let me elaborate,

Now what we have done here is make an outer loop and an inner loop. For each outer loop the inner loop will executes three times. Lets make make some points to made it clear,

♦  For the first time the value of i (i.e the looping variable of the outer loop)

is 1,the condition is tested it satisfied the test so the body of the outer executed.

♦  When the inner for statement is executed for the first time, the value of j is set to an initial value 1.

♦  Now the condition j <= 3 is tested. Since j is 1 the condition is satisfied and the body of the inner loop is executed for the first time and value of i and j is printed.

♦  \t is used as tab between values.

♦  Upon reaching the closing braces of inner for, control is sent back to the inner for statement, where the value of j gets incremented by 1(i.e j++ means j=j+1).

♦  Again the test is performed to check whether the new value of j exceeds 3.

♦   If the value of j is still within the range 1 to 3, the statements within the braces of inner for are executed again and the value of i and j are printed.

♦  The body of the inner for loop continues to get executed till j doesn’t exceed the final value 3.

♦  When j reaches the value 4 the control exits from the inner loop and move to next statement after the closing braces of the for inner loop and a new line is printed(due to printf(“\n”);).

♦  Similarly upon reaching the closing brace of outer for, control is sent back to the outer forstatement, where the value of i gets incremented by 1(i.e i++ means i=i+1).

♦  The body of the outer for loop continues to get executed till j doesn’t exceed the final value 3.

♦  When i reaches the value 4 the control exits from the outer loop, and the program ends.

Well that was the nested-for loop, hope it clears the concept.

Nested-while loop:

lets make a same program with a while loop.

int i=1,j=1;

while(i<=3)

{

While(j<=3)

{

printf(“i=%d , j=%d\t”,i,j);

j++;

}

printf(“\n”);

i++;

}

◊  Now same as the for loop the while loop executes in the same way, for each outer loopthe inner loop will executes 3 times.

◊  The inner loop will executes till the inner while loop condition remains true, for eachouter while loop.

\t is used as tab between values.

◊  The outer while loop will reach the value of 4 and the condition becomes false.

It’s a simple program and hope that nested while loop can easily be understand.

Here is the output of the program:

i=1 , j=1                  i=1 , j=2            i=1 , j=3

i=2 , j=1                  i=2 , j=2            i=2 , j=3

i=3 , j=1                  i=3 , j=2            i=3 , j=3

that’s all about the nested-while loop.

Multiple Initializations in the for Loop

The initialization expression of the for loop can contain more than 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 initialization 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 initialization expression, without confusing the compiler.

The multiple inialization can also be done by decrementing one value with incrementing  the other.

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

{

}

In multiple initialization the loop will terminates when each of the one condition becomes false.

Well that’s all about the loop, I hope it clears the concept about the loops, if there is any query please ask question to clear the concept at the forum of our website.

Do practice different programs, “Because every thing is difficult until tried”.

Best of luck!

Regards,

Shehroz Ahmed Khan

http://www.programmingdoctors.wordpress.com

Advertisements
  1. No trackbacks yet.

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

%d bloggers like this: