C language tutorial loops(for loop,while loop,do while loop,custom loops)
First of all we'll look at why loops are required in any programming language.Suppose you are making program to print table of 5,and you are doing it like below,
#include<stdio.h>main()
{
printf("5*1=%d",5*1);
printf("5*2=%d",5*2);
printf("5*3=%d",5*3);
printf("5*4=%d",5*4);
printf("5*5=%d",5*5);
printf("5*6=%d",5*6);
printf("5*7=%d",5*7);
printf("5*8=%d",5*8);
printf("5*9=%d",5*9);
printf("5*10=%d",5*10);
}
Phewwww...I tired writing above code..And you probably will...So what we can do to avoid writing above long code(yes, you can copy and paste,but you have to make changes though).So the ultimate solution is to make loop...See the below diagram to understand loops batter...
So ,loops does some specific task written in it's structure until the condition which we put don't stop it.Below I have written the C code for "for" loop to print the table of five.
for loop:
#include<stdio.h>
main()
{
int i; //i works as counter which will help us to control loop
for(i=1;i<=10;i++) //i=1 initializes i as 1 , i<=10 checking condition when to exit
// i++ increments counter by +1
{
printf("5*%d=%d",i,5*i); // 5*i will give us multiplication of 5 and i
}
}
See the easiness loops provide us.. You can do the same with other loops also, see below codes...
do...while loop:
#include<stdio.h>
main()
{ int i; //i works as counter which will help us to control loop
i=1; //i=1 initializes i as 1
do
{
printf("5*%d=%d",i,5*i); // 5*i will give us multiplication of 5 and i
i++; // i++ increments counter by +1
}while(i<=10) ; //i<=10 checking condition when to exit
}
while loop:
#include<stdio.h>
main()
{ int i; //i works as counter which will help us to control loop
i=1; //i=1 initializes i as 1
while(i<=10) //i<=10 checking condition when to exit
{
printf("5*%d=%d",i,5*i); // 5*i will give us multiplication of 5 and i
i++; // i++ increments counter by +1
}
}
Custom loop with goto :
#include<stdio.h>
main()
{ int i; //i works as counter which will help us to control loop
i=1; //i=1 initializes i as 1
start: if(i>10) //i<=10 checking condition when to exit
{
goto end;
}
else
{ printf("5*%d=%d",i,5*i); // 5*i will give us multiplication of 5 and i
i++; // i++ increments counter by +1
goto start;
}
end:
}
Start and end are the labels which tells the compiler where to jump.When you write goto end; then compiler finds end:and jump program execution to there.