How to write a loop in C?
There are three ways for writing loops in C or C++.
for
loop:
The for
loop has three parameters (initialization, test, iteration):
for ( initialization ; test ; iteration)
{
// Repeated code
}
More details about the syntax of a for loop on this page.
while
loop:
The while
loop repeat a block of code while the test is true:
do
{
// Repeated code
}
while (test);
do...while
loop:
The do...while loop is similar to the while loop, except that the instruction block will necessarily be executed at least once:
do
{
// Repeated code
}
while (test);
Be careful, the do...while loop ends with a semicolon.
Examples :
The examples below shows how to count from 0 to 9 with the three loops:
int i;
// for loop
for (i=0;i<10;i++) printf ("%d ",i);
putchar ('\n');
// while
i=0;
while (i<10) printf ("%d ",i++);
putchar ('\n');
// do...while
i=0;
do
printf ("%d ",i++);
while (i<10);
putchar ('\n');
Try online on repl.it.
See also:
There are three ways for writing loops in C or C++.
for
loop:
The for
loop has three parameters (initialization, test, iteration):
for ( initialization ; test ; iteration)
{
// Repeated code
}
More details about the syntax of a for loop on this page.
while
loop:
The while
loop repeat a block of code while the test is true:
do
{
// Repeated code
}
while (test);
do...while
loop:
The do...while loop is similar to the while loop, except that the instruction block will necessarily be executed at least once:
do
{
// Repeated code
}
while (test);
Be careful, the do...while loop ends with a semicolon.
Examples :
The examples below shows how to count from 0 to 9 with the three loops:
int i;
// for loop
for (i=0;i<10;i++) printf ("%d ",i);
putchar ('\n');
// while
i=0;
while (i<10) printf ("%d ",i++);
putchar ('\n');
// do...while
i=0;
do
printf ("%d ",i++);
while (i<10);
putchar ('\n');
Try online on repl.it.
See also:
# | ID | Query | URL | Count |
---|