C Program Learning Part-7
DECISION MAKING AND LOOPING
Looping:
When we
know in advance exactly how many times the loop will be executed, we use a
counter controlled loop. We use a control variable known as counter. The
counter must be initialized, tested and updated properly for the desired loop
operations. Sentinel Loops: In a sentinel controlled loop, a special value
called a sentinel value is used to change the loop control from true to false.
For example when reading data we may indicate the “ end of data” by a special
value, like -1 and 999. The control variable is called sentinel variable. A
sentinel controlled loop is often called indefinite repetition loop because the
number of repetitions is not known before the loop begins executing.
THE WHILE STATEMENT:
The basic
format of the while statement is:
n = 1;
while ( n
<=10)
{
sum
= sum + n * n;
n
= n + 1;
}
printf(“sum
= %d”, sum);
Write a program to evaluate the equation: y =xn .
#include<stdio.h>
main()
{
int count, n;
float x,y;
printf(“Enter the values of x and
n.\n”);
scanf(“%f %d”, &x, &n);
y = 1.0;
count = 1;
while( count <= n);
{
y = y * n;
count++;
}
printf(“x = %f; n= %d; x to power
n = %f”, x,n,y);
}
THE DO STATEMENT:
The basic format of do statement is:
do
{
body of the loop
}
while(test condition);
do....while Example
#define colmax 10
#define rowmax 12
main()
{
int row, column, y;
row = 1;
printf(" MULTIPLICATION
TABLE\n");
printf("-----------------------------------------------\n");
do
{
column = 1;
do
{
y= row * column;
printf("%4d",y);
column = column +1;
}
while(column <= colmax);
{
printf("\n");
row = row + 1;
}
}
while(row <= rowmax);
printf("--------------------------------------------");
}
THE FOR STATEMENT
for( initialization; test condition; increment)
{
body of the loop;
}
For loop example:
main()
{
int sum;
for(n=1; n<=10; i++)
{
sum = sum + n;
}
printf(“Sum = %d”, sum);
}