[rps-include post=6557]
Loops are used to loop and iterate through sequential data or similar serial output. Sequential data will be generally an array. For example to search in a array for a specific value while loop can be used. We will look 3 main loop mechanism provided by C programming language.
While
While runs repeatedly if given condition is true. Here is the syntax of while .
while(condition) { statemens; }
In while syntax condition can be a boolean value like true
or false
.
In this example we will count up to 10. For each step the a<10
will be evaluated. a=a+1
will run in each step and a
will increment one by one. When a
reached 10 the a<10
will be false and the while loop end. In each step the value of the a
will be printed with printf
function.
#include <stdio.h> int main() { int a=0; while(a<10){ a = a + 1; printf("%d\n",a); } return 0; }
Here our condition is a<10
which is met for the first 10 steps but in each step we increment a
and print it to the console with printf("%d\n",a)
Infinite While Loop
While loop is the simplest and easiest way to create infinite loop. Infinite loop will run forever if the application is not stopped externally. We will put 1
into condition of the while which is equivalent of true
boolean in C.
while(1){ a = a + 1; printf("%d\n",a); }
OR we will use 1=1
which will evaluate boolean true
while(1=1){ a = a + 1; printf("%d\n",a); }
OR we will use 1>0
which is always true
while(1>0){ a = a + 1; printf("%d\n",a); }
Do While
Do While mechanism is very similar to While but the difference is that While code block is executed after condition check. In Do While mechanism code block is executed first and then condition is checked. If condition is not met which is not true the Do While mechanism ends. Here is the syntax.
do{ statement; }while(condition);
In the example below we print some message to the console and then check the number.
[rps-include post=6557]