Loops in C

By | February 21, 2023

Loops are a fundamental control structure in programming that allow a section of code to be executed repeatedly. In the C programming language, there are three types of loops: the for loop, the while loop, and the do-while loop.

1. for loop: The for loop is used to execute a block of code a specific number of times. It has the following syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

Here, initialization is the code that is executed before the loop starts, condition is the condition that is checked before each iteration of the loop, and increment/decrement is the code that is executed after each iteration of the loop. The loop continues as long as the condition is true.

For example, the following for loop prints the numbers from 1 to 10:

for (int i = 1; i <= 10; i++) {
    printf("%d ", i);
}

2. while loop: The while loop is used to execute a block of code as long as a certain condition is true. It has the following syntax:

while (condition) {
    // code to be executed
}

Here, condition is the condition that is checked before each iteration of the loop. The loop continues as long as the condition is true.

For example, the following while loop prints the numbers from 1 to 10:

int i = 1;
while (i <= 10) {
    printf("%d ", i);
    i++;
}

3. do-while loop: The do-while loop is similar to the while loop, but the condition is checked at the end of the loop instead of the beginning. This means that the loop is guaranteed to be executed at least once. It has the following syntax:

do {
    // code to be executed
} while (condition);

Here, condition is the condition that is checked at the end of each iteration of the loop. The loop continues as long as the condition is true.

For example, the following do-while loop prints the numbers from 1 to 10:

int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 10);

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.