Computersnyou

C Programming – Looping

Posted on  3/26/2012
image
Like any other programming language c program also supports looping.Looping gives your code more power to do a particular program.With loops you can execute any code finite or infinte number of times.
Looping in C are of three types:
i) For Loop
ii) While Loop
iii) Do-While Loop

For Loop
Among these three looping for loop is the simplest among all,both in implementation and use.
For loop consist of three fields separated by “;”
for(initialization;condition_checking;incrementation)
{

/*Your Looping Code */

}
If the condition is true then looping code will be executed,otherwise,not.
While Loop
It is also known as Entry Control loop because it checks the condition before entering inside the loop.
while(condition_checking)
{

/*Your Looping Code*/

}
If the condition is true then it will execute the looping code, otherwise, not.
Do-While Loop
It is also known as Exit Control loop because it checks the condition after the looping code.
do
{

/*Looping Code*/

}while(condition_checking);
Remember: Even if the condition is false the looping code will execute once that’s make do-while loop a little different from other loops
Observe:”;” smi-colon after while in do-while loop
Illustration with Examples
For Loop
#include
int main()
{

for(int i=1;i<=3;i++)
{
       printf(“i = %d n”,i);
}
return 0;

}
Output
i = 1
i = 2
i = 3

While Loop
#include
int main()
{

int i=5;

while(i<=3)
{
printf(“i = %d n”,i);
i++;
}
printf(“No Output”);
return 0;

}
Output
No Output

Do-While Loop
#include
int main()
{

int i=5;

do
{
printf(“i = %d n”,i);
i++;
}while(i<=2);
return 0;

}
Output
i = 5

If you have any queries or any questions in any part then do leave us a comment.


  • Home
  • About