[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here

Do/Do-While/For Loops

Created: Monday, 12 August 2013 Written by Ehab Eldeeb

There are generally three types of loops in C

you can use either of them depending on the situation

Note: This is a rough and fast explanation

For Loop: You know where to start  (start value) and where to end (final value) and increment/decrement value

While Loop: You start (initial value) but you don't know where to end, so you put a condition for stopping
example: while (n > 0) ...

Do-While Loop: Similar to While loop  with just one difference, which is... you get to process the code once before checking the condition
example: do { ....... } while ( n > 0); // notice there's a semicolon here

  Syntax

For Loop:

for ( initial ; condition ; increment/decrement){
code statements;
}

 

Example:
for(int i = 0; i < 10; i++){
printf("Ehab Eldeeb is awesome \n");
}

This for loop will be repeated 10 times..
The statement says Ehab Eldeeb is awesome, so it will print out that sentence 10 times :)

While Loop:

while(condition){
statements;
}

 


Example:
int x = 10;
while(x > 5){
printf("Ehab Eldeeb is awesome");
i--;
}

 

this while loop will print out Ehab Eldeeb is awesome until the value of x gets changed and becomes <= 5

 Do-While Loop:

Do-While is similar to while loop but the statement will be processed once even if the condition is false.