Professional Documents
Culture Documents
Objectives:
Theory:
The while statement is also a looping statement. The while loop evaluates the test expression before every loop, so it can
execute zero times if the condition is initially false. It has the following syntax.
while (expression)
Statement 1;
Statement 2;
…………...
Statement n;
Here the initialization of a loop control variable is generally done before the loop separately. The testing of the
condition is done in while by evaluating the expression within the parenthesis. If the evaluation result is true value, the
block of statement within calibrates is executed. If the evaluation result is false value the block of statements within the
body of loop is skipped and the loop execution get terminated with the control passing to the statement immediately
following the while construct. The increment or decrement of the loop control variable is generally done within the body
of the loop.
statement/s to be executed. }
The while loop checks whether the test expression is true or not. If it is true, code/s inside the body of while loop is
executed,that is, code/s inside the braces { } are executed. Then again the test expression is checked whether test
expression is true or not. This process continues until the test expression becomes false.
Example of while loop
Write a C program to find the factorial of a number, where the number is entered by user. (Hints: factorial of n =
1*2*3*...*n
#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition number>0 is true */
factorial=factorial*number;
--number;
printf("Factorial=%d",factorial);
return 0;
}
Problem: Write a program to determine and print the sum of the following harmonic series for a given value of n
1+2+3+4+5+……………….n
Coding:
#include <stdio.h>
#include<conio.h>
main ()
{
int n, sum;
printf("Enter an integer: \n");
scanf("%d", &n);
i=0;
sum=0;
while (i<=n)
{
sum= sum+i;
i=i+1;
}
Printf(“sum=%d”,sum);
getch ();
}
Exercise:
12+22+32+42+………………. +.n2