Loops in C
What are loops ? Sometimes you will want to do something a lot of times. An example would be printing a character at the beginning of each ...
https://things-for-students.blogspot.com/2012/01/loops-in-c.html
What are loops?
Sometimes you will want to do something a lot of times. An example would be printing a character at the beginning of each line on the screen. To do this you would have to type out 24 printf commands because there are 25 rows on the screen and the 25th row will be left blank. We can use a loop to do this for us and only have to type 1 printf command. There are 3 basic types of loops which are the for loop, while loop and do while loop.The for loop
The for loop lets you loop from one number to another number and increases by a specified number each time. This loop is best suited for the above problem because we know exactly how many times we need to loop for. The for loop uses the following structure:for (starting number;loop condition;increase variable)
command;
#include<stdio.h>
int main()
{
int i;
for (i = 1;i <= 24;i++)
printf("H\n");
return 0;
}
The while loop
The while loop is different from the for loop because it is used when you don't know how many times you want the loop to run. You also have to always make sure you initialize the loop variable before you enter the loop. Another thing you have to do is increment the variable inside the loop. Here is an example of a while loop that runs the amount of times that the user enters:
#include<stdio.h>
int main()
{
int i,times;
scanf("%d",×);
i = 0;
while (i <= times)
{
i++;
printf("%d\n",i);
}
return 0;
}
The do while loop
The do while loop is the same as the while loop except that it tests the condition at the bottom of the loop.
#include<stdio.h>
int main()
{
int i,times;
scanf("%d",×);
i = 0;
do
{
i++;
printf("%d\n",i);
}
while (i <= times);
return 0;
}
Break and continue
You can exit out of a loop at any time using the break statement. This is useful when you want a loop to stop running because a condition has been met other than the loop end condition.
#include<stdio.h>
int main()
{
int i;
while (i < 10)
{
i++;
if (i == 5)
break;
}
return 0;
}
#include<stdio.h>
int main()
{
int i;
while (i < 10)
{
i++;
continue;
printf("Hello\n");
}
return 0;
}