1 of 8

C programming

COMPILED BY ARUP ROY CHOUDHURY, ASSOCIATE PROFESSOR, DEPARTMENT OF MATHEMATICS, MALDA COLLEGE, MALDA

2 of 8

LOOPING

In C, one may have repeated execution of a statement block. This can be done by using the statements: (1) while statement, (2) do-while statement and (3) for statement.

  1. while statement: The general form of the while statement is

while(condition)

{

statement block;

increment/decrement;

}

This is an entry controlled statement. At first test condition is verified. If it is true the statement block is executed, otherwise the control goes outside the loop.

3 of 8

LOOPING

Example: Find the sum of first hundred natural numbers.

Solution: /* Sum of first hundred natural numbers */

#include<stdio.h>

#include<conio.h>

main( )

{

int i, s;/* declaration of data type */

s=0;

i=1;/* initialization */

while(i<=100)/* testing */

4 of 8

LOOPING

{

s = s+i;

i = i+1;/* increment */

}

printf(“\n The required sum is %d”, s);

getch( );

}

(2) do-while statement: The general form of the do-while statement is

initialization;

do

{

5 of 8

LOOPING

statement block;

increment/decrement;

}

while(condition);

It is an exit controlled loop. At least once the statement block will be executed.

Example: #include<stdio.h>

#include<conio.h>

main( )

{

int x=6;/* initialization*/

6 of 8

LOOPING

do

{

printf(“\n %d”, x);

x=x+1;/* increment*/

}

while(x<=4);

printf(“\n End of the program.”);

getch( );

}

7 of 8

LOOPING

3) for statement: The general form of for statement is

for(initialization; test condition; increment/decrement)

{

statement block;

}

Example: Find the sum of first twenty natural number.

Solution: /*Sum of first twenty natural numbers*/

#include<stdio.h>

#include<conio.h>

main()

{

8 of 8

LOOPING

int i, s=0;

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

{

s=s+i;

}

printf(“\n The required sum = %d”,s);

getch();

}

The sum of first twenty natural numbers in the above program will be 210.