Loop For, While and Do-While in C Language

All loops have the same function, which is to repeat an instruction a certain or undetermined number of times.

The structure of the FOR loop is as follows:


for(inicialização; condição; incremento)
comandos;

For example:

#include

voi main()
{
int x;

for(x = 0; x <= 100; x++) printf("%d", x); } 

The program above displays numbers from 0 to 100 on the screen. The FOR loop is usually also used to make infinite loops since its fields are not mandatory, but this is just a custom, which does not prevent you from using the WHILE loop instead of FOR.

Example of an infinite loop with FOR:

#include

void main()
{
int x;
for(x = 0; ; x++)
printf("%d", x);
}

Structure of the While loop:

while(condição)
comando;

Example:

include

void main()
{
int x;
while(x != 0)
{
printf("Insira um valor para X: ");
scanf("%d", x);
}
}

The WHILE loop is repeated until the user enters the value zero.

Structure of the Do-While loop:

do{
comando1;
comando2;
}
while(condição);

The Do-While loop, unlike the FOR and WHILE loops, tests the condition at the end of execution, i.e. the commands inside the ‘Do’ keys:

do{
command1;
command2;
}

are executed, then the condition inside the WHILE is tested, if true the commands inside the ‘Do’ braces are executed again, if false the program exits the loop.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *