C Programs always execute in sequential order. But sometimes we need to perform some code statements repeatedly. That time we can use the loop concept. Both loop and iterative statements can use for this concept.
Syntax
while (condition) {
// statement
}
For example, you want to print some message more than one times. You have two choices: first, to write a print statement n time and another, to use the loop — a better solution for that.
int i = 0;
while (i < 4) {
printf("Bye"); // ByeByeByeBye
i++;
}
In C programming language, three types of a loop are available.
- while
- for
- do while
Components of iterative statements
Iterative statements have 3 components –
Initial point All types of loop should have initial point where we can start.
Statement Inside the loop, we need repeated statements.
Final point Final point to stop the loop.
While Statement
int i = 0;
while (i < 5) {
printf("%2d", i); // 0 1 2 3 4
i++;
}
Here i = 0 is the initial point of the statement, i < 5 is the final statement where loop will stops and printf is the statement part.
For Statement
for (int i = 0; i < 5; i++) {
printf("%2d", i); // 0 1 2 3 4
}
Do While Statement
int i = 0;
do {
printf("%2d", i); // 0 1 2 3 4
i++;
} while (i < 5);
do while loop executes the statement first then the condition.
Continue
Continue to exit the current iteration in a loop.
int i = 0;
while (++i < 5) {
if (i % 2 == 0) continue;
printf("%2d", i); // 1 3
i++;
}
Break
Break exits the loop completely.
int i = 0;
while (++i < 5) {
if (i % 3 == 0) break;
printf("%2d", i); // 1
i++;
}
Notes: Be aware of an infinite loop lot of times when we miss the loop stopping conditions then our loop run infinite times.
while (1) {
printf("Bye"); // ByeByeByeByeBye upto infinite
}