Question #6883   Submitted by Answiki on 10/12/2022 at 01:25:35 PM UTC

How to write a loop in C?

Answer   Submitted by Answiki on 10/12/2022 at 01:35:45 PM UTC

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:



2 events in history
Answer by Answiki on 10/12/2022 at 01:35:45 PM

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:



Question by Answiki 10/12/2022 at 01:25:35 PM
How to write a loop in C?
# ID Query URL Count

Icons proudly provided by Friconix.