Loop
Suppose you’re a class teacher and your college organized a tour for somewhere so you have assigned a task to fill up tour fee form. Total 200 hundred students in your class, in this situation you need to reach each student seat and collect fees. If we analysis from computer point of view for this scenario then you need to take total 200 step for achieve this.
This was real life an example which creates a basic idea of repetitive task. This type of task needs some automatic process which minimizes our effort then loop is your solution. Following are some example of task where you need loop.
- Printing all numbers between 1 to 100
- Printing your name a number of times
- Accessing some continuous item like arrays
C language gives you three types of loops to accomplished repetitive task.
- While
- For
- Do-while
While Loop
Syntax:
As you can see in while loop syntax a condition is being check at entry point of loop if condition is true then control goes to loop body and after running last statement control return top to loop and again check condition this process continue until condition goes false.
While loop is easy to understand and use. You should be master of while loop before jump to other loop s because it make your looping basic knowledge more strong.
void main()
{
int number=1;
while(number<=10)
{
printf("\n\t%d",number);
number+=1;
}
}
For Loop
Next category of looping is for loop which is more powerful than other category of loops because it decreases number of lines from your program. This is little bit complicated for beginner but ones you understand it then it implement complicated logic in few line of code.
Syntax:
Rules of for loop
- First step is to initialize variable
- Second step check condition
- After check condition if it is true then control goes to loop body otherwise outside and stop loop
- After running all statement of loop control goes to increment and decrement section through step 4 then move to condition check
- Step 2, 3 and 4 run till condition remain true.
For Loop Flow Chart
void main()
{
int number;
for(number=1;number<=10;number++)
{
printf("\n\t%d",number);
}
}Do-while Loop
An exit control loops because condition is being check on bottom side of loop So this will run at least one time when condition is false.
Syntax :
void main()
{
int number=1;
do
{
printf("\n\t%d",number);
number++;
}while(number<=10);
}
No comments:
Post a Comment