c do-while loop


do-while LOOP Construct
In a real time situation, while an iteration is taking place, if the condition
needs to be evaluated at the end of each iteration, then do-while Loop is
proposed.
Syntax:
do
{
program statements;
}while(condition);
The Program statement is executed first.
The Condition is evaluated to check TRUE or FALSE.
If TRUE loop continues executing program statement once again.
If FALSE loop terminates handling remaining tasks.


Program to calculate average of N numbers
Program
#include<stdio.h>
void main()
{
int n, count = 1;
float x, avg, sum = 0;
printf("\nHow many Numbers to Average : ");
scanf("%d", &n);
do
{
printf("\nEnter Value for X = ");
scanf("%f", &x);
sum += x;
++count;
}while(count <= n);
avg = sum / n;
printf("\nThe Average is %0.2f", avg);
}
for – loop Construct
The ‘for’ loop construct has the fallowing properties:
It includes an EXPRESSION that specifies an INITIAL VALUE for an INDEX.
The SECOND EXPRESSION determines whether or not the LOOP SHOULD
CONTINUE or TERMINATE.
The THIRD EXPRESSION allows the INDEX to be MODIFIED at the END OF
EACH PASS.
Syntax:
For(exp1; expr2; expr3)
{
Programming Statements;
}
1. Expr1: It is used to INITIALIZE some parameter for LOOP.
2. Expr2: It represents a CONDITION that must be TRUE for the LOOP to
CONTINUE
3. Expr3: It represents the EVOLUTION at the END of EACH PASS.
‘for’ LOOP is mostly used when we want to execute a loop for a fixed
number of times.
The control variable need not be initialized and incremented separately
inside or outside the loop body.
All the three expressions in the for loop are separated by semi-colon.

No comments: