Loops in C language #2

 Loops in C language  
       Previous tutorial we studied about for loop. Now in this tutorial we will study while loop and do while loop.



 
2. While loop:-
                       Also known as entry controlled loop i.e if the condition is true then the program inside the loop execute.

Syntax of while loop 

while(condition)
{
  statement program
  ...............................
  ...............................
}

Program using while loop. 

#include<stdio.h>
#include<conio.h>
int main()
{
  int n, ch=1, sum=0;
  clrscr();
  while(ch==1)
 {
   printf("Enter a number :");
   scanf("%d",&n);
   sum=sum+n;
   printf("\nDo you want to add more number type 1:");
   scanf("%d",&ch);
  }
  printf("\nsum=%d",sum);  
  return0;
}

Output:-
Enter a number:2
Do you want to add more number type 1:1
Enter a number:3
Do you want to add more number type 1:0
sum=5 

Explanation:-
                      In this program initial value of ch is 1. the condition of while loop is ch==1 and is true and the program inside the loop is execute.

3. do while loop:-
                            Also known as exit controlled loop i.e If the condition is true then the program inside the loop will stop executing.

Syntax of do while loop:- 

do
{
  statement program
  ...............................
  ...............................
}while(condition); 

Example:-

#include<stdio.h>
#include<conio.h>
int main()
{
  int n, ch, sum=0;
  clrscr();
  do
 {
   printf("Enter a number :");
   scanf("%d",&n);
   sum=sum+n;
   printf("\nDo you want to add more number type 1:");
   scanf("%d",&ch);
  }while(ch==0)
  printf("\nsum=%d",sum);  
  return0;
}

Output:-

Enter a number:2
Do you want to add more number type 1:1
Enter a number:3
Do you want to add more number type 1:0
sum=5
         


If any doubt or query comment below......
In next blog we will learn conditional statement. 

Keynote:-While loop and do while loop are almost same but with the difference is that do while loop executes if the condition is false and while loop executes if the condition is true.
     

No comments

Powered by Blogger.