C Loops: For, While, Do While, Looping Statements with Example
A loop allows one to execute a statement or block of statements repeatedly. There are mainly two types of iterations or loops – unbounded iteration or unbounded loop and bounded iteration or bounded loop. A loop can either be a pre-test loop or be a post-test loop as illustrated in the diagram.
int main()
{
int c;
c=5; // Initialization
while(c>0)
{ // Test Expression
printf(“ \n %d”,c);
c=c-1; // Updating
}
return 0;
}
Testing for floating-point ‘equality’
float x;
x = 0.0;
while(x != 1.1)
{
x = x + 0.1;
printf(“1.1 minus %f equals %.20g\n”, x, 1.1 -x);
}
The above loop never terminates on many computers, because 0.1
cannot be accurately represented using binary numbers.
Never test floating point numbers for exact equality, especially in
loops.
The correct way to make the test is to see if the two numbers are
‘approximately equal’.
“for” Construct
The general form of the for statement is as
follows:
for(initialization; TestExpr; updating)
stmT;
for construct
flow chart
“do-while” Construct
The C do-while loop
The form of this loop
construct is as
follows:
do
{
stmT; /* body of
statements would be
placed here*/
}while(TestExpr)
Example - do loop
// Program to add numbers until user enters zero
#include <stdio.h>
int main()
{ double number, sum = 0;
// loop body is executed at least once
do
{ printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Point to Note
With a do-while statement, the body of the loop is executed first and the test expression is checked after the loop body is executed. Thus, the do-while statement always executes the loop body at least once.
Which loop should be used???
When to use which loop
For, while loops are pre test loops. Do while is
post test loop.
For loop is usually when the number of iterations
are known in advance. Like o to 75 etc.
While and do while are for unknown iterations.
While – when you don’t even want to execute the
body even once.
Do – while when you want to execute the body
You can Practice question on this Topic in Practice and Learn section on Menu Bar with questions and their answers ..Kindly check out there.
ConversionConversion EmoticonEmoticon