Lec8 Loops
Lec8 Loops
Lec8 Loops
LOOPS
• A Loop executes the sequence of statements
many times until the stated condition
becomes false. A loop consists of two parts, a
body of a loop and a control statement.
• C programming has three types of loops:
• for loop
• while loop
• do...while loop
while loop
variable initialization;
while(condition)
{ statements;
variable increment or decrement; }
• Example: Program to print first 10 natural
numbers
#include<stdio.h>
void main( )
{ int x; x = 1;
while(x <= 10)
{ printf("%d\t", x); /* below statement means,
do x = x+1, increment x by 1*/
x++; } }
#include<stdio.h>
int main(){
int i=1,number=0,b=9;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10){
printf("%d \n",(number*i));
i++;
}
return 0;
}
#include<stdio.h>
void main ()
{
int j = 1;
while(j+=2,j<=10)
{
printf("%d ",j);
}
printf("%d",j);
}
#include<stdio.h>
void main ()
{
while()
{
printf("hello Javatpoint");
}
}
Output
compile time error: while loop can't be empty
Example 3
#include<stdio.h>
void main ()
{
int x = 10, y = 2;
while(x+y-1)
{
printf("%d %d",x--,y--);
}
}
Output
infinite loop
do...while loop