Looping Statements ( For loop ,while loop ,do while)


                     Looping Statements 

Executing a statement (or a group of statements) a number of times is called looping, and there are four statements for looping and iteration in C#.
loops are used to repeat a lick of code being able to have your program repeatedly execute a block of code is one of the most basic but useful talks in programming.Al loops can do nesting(loops in loops )there are 3 loops in c#. 

  1. For loop
  2. while loop
  3. do while
For loop:- The for loop is used when the number of loops is known.



 



 Syntax:-

for(i=1;i>1;i++)
    { printf("ankit c guru");     } 
for(<variable> = <equals to example 1,x,a> ; <identifier> > <comparison with>;<identifier<increment/decrement>>)
{
\\statements;
}

Example:-print 1 to 100 numbers by for loop.

#include<stdio.h>
void main()
{int i;
for(i=0;i<=100;i++)
    {
      printf("\n%d",i); 
    } 
getch();
} 
while Loop:- With the for loop we know in advance how many iterations we need.Sometimes we need similar behavior; we need to loop through a series of statements until something happens -- maybe the user wants to exit the program, or the user entered invalid data.


Syntax:-

while(boolean expression) 
{ 
//statement 1; 
//statement 2; 
//statement 3; 
//increment/decrement;
} 



Example:- print 1 to 10 numbers by while loop.


#include<stdio.h>
void main()
{int i=1;
 while(i<=100)
{
printf("\n%d",i);
} 
getch();
}

Do while loop:-The C do while loop statement consists of a block of code and a Boolean condition. First the code block is executed, and then the condition is evaluated. If the condition is true, the code block is executed again until the condition becomes false.
Syntax:-

do{

//statements;

}
while(boolean condition)

Example:-C program to continue the program by pressing 'y' exiting by pressing 'n'. 

#include<stdio.h>
void main()
{int a,b,c;
char choice;
do {
printf"enter first value");
scanf("%d",&a);
printf"enter Second value");
scanf("%d",&b);
c=a+b;
printf("%d",c);
printf("\ndo you want to continue press 'y' or to exit program press 'n'");
scanf("%c",&choice);
}while(choice=='y'||choice=='Y')  \\ capital Y is used if user enter capital Y
getch();
}

Comments

Popular posts from this blog