Loops 1: While
Basically, loops are repetition statements. We use repetition statements to execute some code consecutively.
While loops are one of the repetition statements.
Structure of a while loop:
while(condition)
{//1. do something;
//2. do something about condition;
}
In first line we write some code to run. IT can be a printf function that helps us to print same thing repeatedly. After that we need to make some changes to conditional variable. To explain better, here's an example:
#include <stdio.h>
int main()
{//a program to print 100 lines with line numbers.
int counter;
counter = 1;
while(counter<101)
{ printf("Line %d:\n",counter);counter++;
}
return 0;
}
This small program prints 100 lines with line numbers on console screen. As you see, there are not 100 printfs, just one in the while statements brackets which is going to run 100 times.
Another example:
#include <stdio.h>
//factorial calculation
int main()
{int number,counter=1,factor=1;
printf("Enter a number and see its factorial: "); scanf("%d",&number);while(counter<=number)
{factor = factor * counter;
counter++;
}
printf("Factorial of %d is %d\n",number,factor);return 0;
}
In this program, we used while loop to multiply factorial with the integer counter and increase the counter by one every turn.
Using while loop is easy and enjoyable. Write some code by yourself as exercise.
