Professional Documents
Culture Documents
While Loop in C: Department of Computer Science and Engineering
While Loop in C: Department of Computer Science and Engineering
By:
Prof. Melwin D souza
HOD,
Department of computer Science and Engineering
MOODLAKATTE INSTITUTE OF TECHNOLOGY, KUNDAPURA
Loops in C program
• Loops are used to execute a set of statements repeatedly
• Statements executes until the condition is satisfied (true)
Syntax :
while (expression)
{
statements;
}
First, The test expression/condition is evaluated.
If condition is true, statements in body of the loop gets executed.
statements of the body will execute repeatedly till the test condition returns true.
The control will be transferred out of the loop when test condition returns false
while loop
C program to display the name five times
without loop with while loop
#include <stdio.h>
#include <stdio.h>
int main()
{ int main()
Rajesh Rajesh
printf(“Rajesh\n”); Rajesh { Rajesh
printf(“Rajesh\n”); Rajesh int i=0; Rajesh
Rajesh while (i<10) Rajesh
printf(“Rajesh\n”);
Rajesh { Rajesh
printf(“Rajesh\n”); Rajesh
Rajesh printf(“ Rajesh\n”);
printf(“Rajesh\n”); Rajesh
Rajesh
printf(“Rajesh\n”); i++; Rajesh
Rajesh
printf(“Rajesh\n”); Rajesh } Rajesh
printf(“Rajesh\n”); Rajesh } Rajesh
printf(“Rajesh\n”);
printf(“Rajesh\n”);
}
Programming Examples
sum=0, i=1
#include <stdio.h> Iteration 1: i=1, 1<=5 => true
void main() sum=1,
i++ => 2
{ Iteration 2: i=2, 2<=5 => true
int sum=0, i=1; sum=3,
i++ => 3
while(i<=5) Iteration 3: i=3, 3<=5 => true
{ sum=6,
Sum=15 i++ => 4
sum=sum+i; Iteration 4: i=4, 4<=5 => true
sum=10
i++;
i++ => 5
} Iteration 5: i=5, 5<=5 => true
sum=15
printf(“\nSum=%d”,sum); i++ => 6
} Iteration 6: i=6, 6<=5 => false
Example 3: C program to reverse the digits of a given number
#include <stdio.h> digit=? rev=0, num=?
void main() Num=123
{
int digit,rev=0,num; Iteration 1: num=123, 123!=0 , => true
printf("Enter the number:\n"); digit=3
scanf("%d",&num); rev=3
while(num!=0) num=12
{ Iteration 2: num=12, 12!=0 => true
digit=num%10; digit=2
rev=rev*10+digit; rev=32
num=num/10; num=1
Iteration 3: num=1, 1!=0 => true
}
digit=1
printf("The reversed number is = %d\n”, rev);
rev=321
}
Enter the number num=0
123 Iteration 4: num=0, 0!=0 => false
The reversed number is = 321
Example 4: C program to check whether the number is palindrome or not
#include <stdio.h> digit=? rev=0, num=?
void main() num=121
{ origin=121
int digit,rev=0,num, origin; Iteration 1: num=121, 123!=0 , => true
printf("Enter the number:\n");
digit=1
scanf("%d",&num);
Enter the number rev=1
origin=num;
121 num=12
while(num!=0)
The number is palindrome Iteration 2: num=12, 12!=0 => true
{
digit=num%10; digit=2
rev=rev*10+digit; rev=12
num=num/10; num=1
} Iteration 3: num=1, 1!=0 => true
if (origin==rev) digit=1
printf("The number is a palindrome\n”); rev=121
Else num=0
printf("The number is not a palindrome\n”); Iteration 4: num=0, 0!=0 => false
}