C programming
COMPILED BY ARUP ROY CHOUDHURY, ASSOCIATE PROFESSOR, DEPARTMENT OF MATHEMATICS, MALDA COLLEGE, MALDA
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.
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.
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 */
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
{
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*/
LOOPING
do
{
printf(“\n %d”, x);
x=x+1;/* increment*/
}
while(x<=4);
printf(“\n End of the program.”);
getch( );
}
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()
{
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.