Professional Documents
Culture Documents
While Loop Is Used When You Want To Execute A Block of Statements Repeatedly With Checked
While Loop Is Used When You Want To Execute A Block of Statements Repeatedly With Checked
While Loop Is Used When You Want To Execute A Block of Statements Repeatedly With Checked
A loop statement allows you to execute a statement or block of statements repeatedly. The
while loop is used when you want to execute a block of statements repeatedly with checked
condition before making an iteration. Here is syntax of while loop statement:
while (expression) {
// statements
This loop executes as long as the given logical expression between parentheses after while is
true. When expression is false, execution continues with the statement following the loop
block. The expression is checked at the beginning of the loop, so if it is initially false, the loop
statement block will not be executed at all. And it is necessary to update loop conditions in loop
body to avoid loop forever. If you want to escape loop body when a certain condition meet, you
can use break statement
#include <stdio.h>
void main(){
int x = 10;
int i = 0;
while(i < x)
{
i++;
printf("%d\n",i);
int numberFound= 5;
int j = 1;
if(j == numberFound){
printf("number found\n");
break;
printf("%d...keep finding\n",j);
j++;
1
2
3
4
5
6
7
8
9
10
1...keep finding
2...keep finding
3...keep finding
4...keep finding
number found
DO-WHILE
do while loop statement allows you to execute code block in loop body at least one. Here is do
while loop syntax:
do {
// statements
} while (expression);
#include <stdio.h>
void main(){
int x = 5;
int i = 0;
// using do while loop statement
do{
i++;
printf("%d\n",i);
}while(i < x);
}
The program above print exactly 5 times as indicated in do while loop body
1
2
3
4
5
FOR
or (initialization_expression;loop_condition;increment_expression){
// statements
}
There are three parts that are separated by semi-colons in control block of the C for loop.
#include <stdio.h>
void main(){
// using for loop statement
int max = 5;
int i;
for(i = 0; i < max;i++){
printf("%d\n",i);
}
}
0
1
2
3
4
BREAK
break statement is used to break any type of loop such as while, do while an for loop. break
statement terminates the loop body immediately. continue statement is used to break current
iteration. After continue statement the control returns to the top of the loop test conditions.
#include <stdio.h>
#define SIZE 10
void main(){
if(items[i] == number_found)
{
if(items[i] != number_found){
break;
}
finding at position 0
finding at position 1
finding at position 2
number found at position 3
finding at position 0
finding at position 1
finding at position 2
number found at position 3