top of page

Loops in c programming

Sometimes we want to do a task for a certain number of times. Let’s say we want to write the same statement multiple times on the screen. One approach will be that we can use the print statement several times, or another will be we can use loops.

Loops, as the name suggests, iterate multiple times according to the condition and execute the code we want.

In C programming we basically have 3 loops that we can use to write our program:

  1. For loops

  2. While loops

  3. Do-while loops

Let’s understand each of them one by one.

  1. For loop

For loop starts with a declaration of a variable followed by the condition up to which the loop will run, followed by increment or decrement of the variable.

It has syntax something like this:


ree

Now inside the curly braces you can write your code. The loop will run n times as it starts from zero and increases by one every time the body of the loop runs.

Quick tip: For loop is useful when you know how many times a loop should run.

  1. While loop

While loop is useful when you don’t know how many times the code is to be run, but you know the condition up to which it has to be run.

Its syntax is as follows:


ree

Inside curly braces you can now code whatever you want.

While loop will execute only when the condition is true.

  1. Do-while loop

Do-while loop is similar to while loop but it has a specialty: it runs at least once, whether the condition is true or not.

Its syntax is as follows:


ree

It will first execute the block of code and then check the condition to decide whether to run it again or not.

Comments


bottom of page