C Loops

Learn the fundamentals of C loops.

C Loops

In C programming, loops are used to execute a block of code repeatedly as long as a certain condition is met. There are three main types of loops in C:

  1. for Loop
  2. while Loop
  3. do-while Loop

for Loop:

The for loop is typically used when you know how many times you want to iterate. It consists of three parts: initialization, condition, and increment/decrement.

The basic syntax of a switch statement in C looks like this:

for (initialization; condition; increment/decrement) {
    // Code to be repeated
}

while Loop:

The while loop is used when you want to execute a block of code as long as a certain condition is true.

The basic syntax of a switch statement in C looks like this:

while (condition) {
    // Code to be repeated
}

do-while Loop:

The 'do-while' loop is similar to the 'while' loop, but it guarantees that the code block is executed at least once because it checks the condition after the code block is executed.

do {
    // Code to be repeated
} while (condition);

Loop Comparison

Each type of loop has its own use cases and advantages, so the choice of which loop to use depends on the specific requirements of your program. Here's a comparison of these loop constructs in C:

*** Turn your screen into landscape mode to show the do-while table.

for Loop while Loop do-while Loop
A for loop is used to execute and repeat a statement block depending on a condition which is evaluated at the beginning of the loop.
Example:

for(i=1; i<=10; i++)
{
s = s + i;
p = p * i;
}
A while loop is used to execute and repeat a statement block depending on a condition which is evaluated at the beginning of the loop.
Example:

i = 1;
while(i <= 10)
{
s = s + i;
p = p * i;
i++;
}
A do-while loop is used to execute and repeat a statement block depending on a condition which is evaluated at the end of the loop.
Example:

i = 1;
do
{
s = s + i;
p = p * i;
i++;
}
while(i <= 10 )
A variable value is initialized at the beginning of the loop and is used in the condition. A variable value is initialized at the beginning or before the loop and is used in the condition. A variable value is initialized at the before the loop or assigned inside the loop and is used in the condition.
A statement to change the value of the condition or to increment the value of the variable is given at the beginning of the loop. A statement to change the value of the condition or to increment the value of the variable is given inside the loop. A statement to change the value of the condition or to increment the value of the variable is given inside the loop.

What is New?

We have just updated this website & still working on adding new content & updating existing features.