Home Icon Home Resource Centre Understanding Looping Statements In C [With Examples]

Understanding Looping Statements In C [With Examples]

Looping is a fundamental concept in programming that allows you to execute a block of code repeatedly. The article below covers all the key topics in looping statements in C with relevant examples.
Shreeya Thakur
Schedule Icon 0 min read
Understanding Looping Statements In C [With Examples]
Schedule Icon 0 min read

Table of content: 

  • What Are Loops In C?
  • Why use Loops in C?
  • Classification Of Loops In C
  • How do Loops in C work?
  • Types of Loops in C
  • Nested Loop in C
  • Infinite Loops in C
  • Loop Control Statements in C
  • Which Loop to Select?
  • Difference between Conditional and Looping Statement
  • Advantages of Loops in C
  • Conclusion
  • Frequently Asked Questions
expand icon

Looping statements are a fundamental aspect of programming languages that provide a way to execute a block of code repeatedly. In the C programming language, several types of loops are commonly used, each serving specific purposes and catering to different programming scenarios. In this article, we'll explore the various looping statements in C, their syntax, and how these loop statements can be effectively applied in C programs.

What Are Loops In C?

What are Loops in C?

Loops are control structures used in C programming that let you run a block of code repeatedly up until a predetermined condition is met. They offer a mechanism to carry out repetitive tasks or take action on a set of data. Loops reduce repetition, allowing for the creation of code that is clear and effective.

C provides three types of loops:

  1. For loop
  2. While loop
  3. Do-while loop

Why use Loops in C?

The repetitive execution of code using loops increases efficiency by automating tedious processes. They are necessary for doing computations, executing algorithms, processing user input, dynamically managing program flow, iterating over data structures, and creating patterns. Loops offer flexibility, allow for code reuse, and promote clear and organized programming. They are a key component of C programming and are used to manage repetitive tasks and regulate program behavior according to runtime circumstances.

Add C to your skills! Check out this course on Unstop

Classification Of Loops In C

Types of looping statements in C, i.e., entry and exit controlled.

Loop statements in C programming fall into one of two kinds depending on how the loop condition is evaluated. 

Entry-controlled Loop Statements

In an entry-controlled loop, the condition is checked before moving on to the loop body/ block of statement to be executed. If the condition expression first evaluates to false, the loop is never executed. The for and while loops are two types of entry-controlled loops.

Example of a For Loop

for (int i = 0; i < 5; i++) {
// Code to be executed
}
// Example of a while loop
int i = 0;
while (i < 5) {
// Code to be executed
i++;
}

The condition expression, i.e., i <5, is verified in the aforementioned cases before proceeding to the loop body. The loop is not run at all if the condition is false.

Code Example:

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Explanation:

  • The code prints a count using a while loop.
  • An integer variable cnt is initialized to 0.
  • The while loop condition checks if cnt is less than 5.
  • Inside the loop, the program prints the value of cnt using printf.
  • After printing, cnt is incremented by 1 (cnt++).
  • The loop continues to execute as long as the condition (cnt < 5) is true.
  • The loop prints the values of cnt (0, 1, 2, 3, 4) and increments cnt in each iteration.
  • Once cnt becomes 5, the loop exits.
  • The program returns 0, indicating successful execution after the loop completes.

2. Exit-controlled Loop Statements:

In an exit-control loop, also known as a post-checking loop, the condition is checked after the body of the loop (or block of statement) has been executed. In other words, at least one execution of the loop body must have taken place before the control condition is assessed. An illustration of an exit-controlled loop is the while loop.

Example of a Do-While Loop

int i = 0;
do {
// Code to be executed
i++;
} while (i < 5);

The code inside the loop is executed first in the aforementioned example, and then the condition expression, i.e., i <5, is verified/ checked. If the loop test condition is true, the loop is continued; if not, it is broken.

Code Example:

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Explanation:

  • The code prints a count using a do-while loop.
  • An integer variable cnt is initialized to 0.
  • The do block contains the code to be executed, which prints the current value of cnt using printf.
  • After printing, cnt is incremented by 1 (cnt++).
  • The while condition checks if cnt is less than 5.
  • The loop continues to execute as long as the condition (cnt < 5) is true.
  • The loop prints the values of cnt (0, 1, 2, 3, 4) and increments cnt in each iteration.
  • Once cnt becomes 5, the loop exits.
  • The program returns 0, indicating successful execution after the loop completes.

How do Loops in C work?

Loops in C typically operate by continually running a piece of code until a specific condition is met. Here is a step-by-step explanation of how C loops work:

  • Initialization of the loop: All required initialization operations are carried out before entering the loop. Any necessary preparation, such as establishing initial values for initial variables in loop control variables, may fall under this category.
  • Condition verification: An assessment of the loop condition. If the condition is satisfied, the body of the loop is run. The program moves on to the statement that comes after the loop if the condition is false and the loop is terminated.
  • Loop body execution: The loop body's code is run. Calculations, variable manipulation, printing output, and any other needed actions may be included in this. Multiple statements are allowed in the loop's body.
  • Update or increment: After the loop body has been completed, an update or increment step is carried out. This can entail changing loop control variables or making any other necessary modifications.
  • Repeat steps 2-4: The condition is checked once again after the update step. If the condition is still true, the loop body and update step are repeated. This procedure keeps going until the condition is no longer true.
  • Exit the loop: When the condition evaluates to false, the loop is broken, and the program moves on to the sentence that comes after it.

It's vital to remember that the loop condition/ conditional expression is verified before each iteration, and the loop is not run at all if the condition is verified as false in the beginning. In order to prevent an infinite loop, the loop body must also have a mechanism to alter the loop control variables or conditions. This is where the update expression, or increment/ decrement condition, comes into play.

Here is a flowchart that illustrates how a loop in C works generally:

How do loops in C work

  • The process of performing a loop is shown in the flowchart.
  • Initialization comes first, and then comes the condition check.
  • The loop is ended if the condition is false.
  • The loop body and update step are both executed if the condition is true.
  • Once the condition is no longer true, the process is repeated, testing the condition one more to end the loop.

Types of Loops in C

Types of Loops in C

Loops are used in computer programming to repeatedly run a certain block of code up until a predetermined condition is satisfied. In programming languages, loops come in a variety of forms. Here are the main categories:

For Loop

For Loop in C

When iterating over a set of values a certain number of times, a for loop is employed. It typically comprises of an iteration statement, a block of code to be executed once for each iteration, a condition, and an initialization step. Up till the condition expression is false, the loop is in motion.

For Loop has the following syntax:

for (initialization; condition; increment/decrement) {

// code to be executed

}

Program Example:

Output:

Cnt: 0
Cnt: 1
Cnt: 2
Cnt: 3

Explanation:

  • The code prints a count using a for loop.
  • An integer variable z is initialized to 0.
  • The for loop has three parts: initialization (z = 0), condition (z < 4), and update (z++).
  • The loop iterates as long as the condition z < 4 is true.
  • Inside the loop, the program prints the current value of z using printf.
  • After printing, z is incremented by 1 in each iteration (z++).
  • The loop prints the values of z (0, 1, 2, 3) and increments z until the condition is no longer true.
  • Once z becomes 4, the loop exits.
  • The program returns 0, indicating successful execution after the loop completes.

While Loop

While Loop

The while loop is appropriate when the number of iterations depends on a certain condition expression being met but is not known beforehand. As long as the conditional expression evaluates to true, the body of the loop is repeatedly executed. A while loop has the following syntax:

while (condition) {

// code to be executed

// increment/decrement

}

Program Example:

Output:

ans: 0
ans: 1
ans: 2
ans: 3
ans: 4

Explanation:

  • The code prints values of i in a while loop.
  • An integer variable i is initialized to 0.
  • The while loop condition checks if i is less than 5.
  • Inside the loop, the program prints the value of i using printf.
  • After printing, i is incremented by 1 (i++).
  • The loop continues to execute as long as the condition (i < 5) is true.
  • The loop prints the values of i (0, 1, 2, 3, 4) and increments i in each iteration.
  • Once i becomes 5, the loop exits.
  • The program returns 0, indicating successful execution after the loop completes.

Do-While Loop

Do-While Loop

The do-while loop is comparable to the while loop in that it ensures that the loop body will run at least once before testing the condition. As long as the condition evaluates to true it keeps running the body of the loop. A do-while loop is written as follows:

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

Program:

Output:

Count: 0
Count: 1
Count: 2

Explanation:

  • The code prints a count using a do-while loop.
  • An integer variable z is initialized to 0.
  • The do block contains the code to be executed, which prints the current value of z using printf.
  • After printing, z is incremented by 1 (z++).
  • The while condition checks if z is less than 3.
  • If the condition is true, the loop continues to execute.
  • The loop repeats the printing and incrementing steps until z is no longer less than 3.
  • The program returns 0, indicating successful execution after the loop completes.

Nested Loop in C

Nested Loop in C

The idea of nesting loops refers to the arrangement of one loop inside another. Multiple levels or dimensions of data can be iterated as a result. With nested loops, you can repeatedly run a section of code inside the outer loop each time the inner loop is iterated.

Program:

Output:

(1, 1) (1, 2) (1, 3) (1, 4)
(2, 1) (2, 2) (2, 3) (2, 4)

Explanation:

  • The code prints coordinates in a grid pattern.
  • Two integer variables, row and column, are initialized to 2 and 4, respectively.
  • Two nested for loops are used to iterate through rows (i) and columns (j) in the grid.
  • The outer loop (i) runs from 1 to the value of row (2 in this case).
  • The inner loop (j) runs from 1 to the value of column (4 in this case).
  • Inside the inner loop, the program prints the coordinates in the format "(i, j)".
  • After each row is printed, a newline character (\n) is used to move to the next line.
  • The loops repeat until all combinations of i and j are covered.
  • The program returns 0, indicating successful execution.

Infinite Loops in C

Loops that run eternally without a condition that can end them are known as infinite loops. These loops could make the program unresponsive or produce undesirable behaviour. It's critical to either prevent the creation of infinite loops or make sure that they have a way to be broken.

Output:

Infinite loop.
Infinite loop.
Infinite loop.
...

Explanation:

  • The code creates an infinite loop using a while statement.
  • The loop condition is while (1), which means the loop will run as long as the condition is true (1 is always true).
  • Inside the loop, the program prints the message "Infinite loop." using printf.
  • Since the loop condition is always true, the loop will continue to execute indefinitely.
  • To break out of the infinite loop, the program needs to be terminated manually (e.g., by pressing Ctrl+C).
  • After the loop, the program returns 0, indicating successful execution (although in practice, the program will likely not reach this point due to the infinite endless loop).

Loop Control Statements in C

Several loop control statements exist in the C programming language that let you change how loops behave. With the use of these statements, loops execution sequences can be managed. The statements that govern loops in C are listed below:

Break Statement in C

Break Statement in C

The break statement is used to end a loop in an instantaneous manner when it is encountered. When the break command is used, the program exits the loop and moves on to the statement that follows the loop. It is frequently used to leave a loop early based on specific circumstances.

Syntax:

break;

  • The break statement is written as a standalone keyword.
  • When encountered, it causes the immediate termination of the nearest enclosing

Code:

Output:

1 2 3 4

Explanation:

  • The code prints numbers from 1 to 10.
  • The loop counter variable i is initialized to 1 and increments by 1 in each iteration of the for loop.
  • The loop runs as long as i is less than or equal to 10.
  • Inside the loop, there is an if statement checking if the current value of i is equal to 5.
  • If i is equal to 5, the break statement is executed, causing an immediate exit from the loop.
  • If i is not equal to 5, the program prints the value of i using printf("%d ", i);.
  • The loop terminates when i becomes 5 due to the break statement.
  • The program returns 0, indicating successful execution.

Continue Statement in C

Continue Statement in C

The continue statement is used to go to the next iteration while skipping the remainder of the loop's body for the current iteration. When the keyword continue is found, the program restarts the loop and checks the loop condition to see if it should continue or end. It is frequently used to implement conditional processing inside of a loop or skip particular iterations.

Syntax:

continue;

  • The continue statement is written as a standalone keyword.
  • When encountered, it immediately transfers the control to the next iteration of the nearest enclosing loop.

Program:

Output:

1 3 5 7 9

Explanation:

  • The code prints odd numbers from 1 to 10.
  • A loop counter variable i is declared and initialized outside the loop.
  • The for loop runs from i=1 to i=10, incrementing i by 1 in each iteration.
  • If i is even, the continue statement skips the current iteration's remaining code.
  • If i is odd, it prints the value of i using printf.
  • The loop continues until i reaches 10.
  • The program returns 0, indicating successful execution.

Also Read: Keywords in C Language

Goto Statement in C

Goto Statement in C

A labeled statement within the same function can be controlled by the goto statement, which is a flexible control statement. It can be used to manage the flow inside loops even if it is not a statement that specifically controls loops. With goto, you can skip over certain sections of code or construct more intricate control structures by jumping to a labelled statement inside the loop. The use of goto is generally discouraged though, as it can make maintaining and reading code more difficult.

Syntax:

goto label;

Here, the label is the identifier followed by a colon (:) that marks the location in the code where the control will jump. The label must be declared before the goto statement in the same function or block.

Code:

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Explanation:

  • The code starts with #include <stdio.h>, which includes a library for basic input and output functions.
  • In the main function, an integer variable n is declared and initialized to 1.
  • There is a label called st: defined in the code.
  • The code prints the current value of n using printf and increments n by 1.
  • It checks if n is less than or equal to 5.
  • If the condition is true, it uses goto st; to jump back to the st label, creating a loop.
  • This process repeats until n is no longer less than or equal to 5.
  • The program then returns 0, indicating successful execution, and ends.

Which Loop to Select?

The C loop you choose will rely on the requirements of the particular issue you're seeking to solve. Here is a quick summary of the various C loops that are typically used:

  • For Loop: The 'for' loop is frequently used when you know the number of iterations ahead of time. It consists of an increment/decrement statement, an iteration condition, and an initialization expression. When you need to repeatedly iterate through a set of values, use a "for" loop.
  • While Loop: The 'while' loop is appropriate when you wish to repeat a block of code as long as a specific condition is true. Before beginning each iteration, the condition is examined; if it evaluates to true, the loop proceeds. When you don't know the precise number of iterations ahead of time and wish to repeat based on a condition, use a "while" loop.
  • The Do-While Loop: The 'do-while' loop is comparable to the 'while' loop, but with one important distinction: the condition is checked after each iteration. This ensures that even if the condition is initially false, the loop body will run at least once. When you need to run a piece of code at least once before repeating it based on a condition, use a "do-while" loop.

The exact criteria and features of the issue you are trying to solve will determine the loop you choose. Think about elements like the known number of repetitions, the requirement for initial setup, and the condition for repeating. You might also need to think about the code's effectiveness and readability.

Difference between Conditional and Looping Statement

Difference between Conditional and Looping Statement

Conditional statements and looping statements are two fundamental constructs in programming that serve different purposes.




Conditional Statements

Looping Statements

Purpose

Execute a block of code based on a condition

Repeatedly execute a block of code for a certain number of iterations

Syntax

if (condition) { statement(s); }

for (initialization; condition; increment/decrement) { statement(s); }

 

if (condition) { statement(s); } else { statement(s); }

while (condition) { statement(s); }

 

switch (expression) { case constant: statement(s); break; ... }

do { statement(s); } while (condition);

Execution

Executes the block of code if the condition evaluates to true

Repeatedly executes the block of code as long as the condition is true

Number of Executions

Executes the block of code once or at most twice

Executes the block of code multiple times

Termination Condition

Termination condition is optional and not required

Termination condition is required and determines the number of iterations

Examples

if (x > 0) { printf("Positive"); }

if (x < 0) { printf("Negative"); } else { printf("Zero"); }

switch (option) { case 1: printf("Option 1"); break; ... }

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

while (x > 0) { printf("%d ", x); x--; }

do { printf("Hello"); count++; } while (count < 5);

Advantages of Loops in C

  • Reusability of programming: Loops let you write a block of code once and run it numerous times. This encourages code reuse and lessens code duplication, making the program shorter and easier to maintain.
  • Efficiency: Automating repetitive operations using loops minimizes the need for manual repetition. As a result, less code needs to be created and run, which improves programming efficiency.
  • Control flow: is made simpler because of loops, which offer a structured approach to do it. You may simply regulate the flow of operations and repeatedly carry out a certain activity by specifying loop conditions and managing loop variables.
  • Data structure iteration: Loops are particularly helpful for iterating through strings, arrays, lists, and other types of data structures. They let you access and control every piece in a collection without the need for individual handling or manual indexing.
  • Flexibility: Loops are flexible in that they can be adjusted to accommodate varying data sizes or shifting demands. Change the loop's conditions, add control variables, or use break and continue statements to dynamically change the loop's behavior based on the circumstances at runtime.

Conclusion

In summary, C loops are control structures that enable the repeated execution of a block of code in response to certain circumstances. They are a crucial component of programming because they allow us to rapidly complete repetitive operations and minimize code redundancy. Loops are useful for handling complex patterns, iterating through data structures, and automating procedures.

C supports the For, While, and Do-While loop types. While the while loop is appropriate when the number of iterations is unknown but depends on a condition, and the do-while loop is used when you want to guarantee that the loop body executes at least once, the for loop is used when the number of iterations is known in advance.

Using loop control statements like break, continue, and goto, loops can be managed. These statements give us the ability to alter how a loop executes, allowing us to skip a few iterations, exit the loop early or go to a labelled statement.

Frequently Asked Questions

Q1.  How do I use a do-while loop in C?

In C programming, a do-while loop is used when you want to execute a block of code at least once and then continue executing it as long as a specific condition is true.  Here's how you can use a do-while loop in C:

  • Begin with the do keyword, followed by an opening curly brace {.
  • Write the code that you want to execute inside the loop.
  • After the code block, add a closing curly brace }.
  • Use the while keyword, followed by a condition within parentheses (). This condition determines whether the loop should continue executing or not.
  • End the line with a semicolon ;

The key difference between a do-while loop and other loop types, like for or while, is that the condition is checked at the end of each iteration. This ensures that the code block is executed at least once, even if the condition is initially false.

Q2.  What is a nested loop in C?

In C, a nested circle is a circle structure that's defined inside another circle. It involves placing one circle inside the body of another circle. This allows for the prosecution of the inner circle multiple times for each replication of the external circle. The main purpose of using nested circles is to perform repetitious tasks that bear multiple situations of replication or to reiterate over multi-dimensional data structures similar to arrays or matrices.

Q3. What are looping statements?

There are three main looping instructions in the C programming language that enable the repetition of a block of code depending on specific criteria. These statements that loop are

  • 'for' loop: The 'for' loop is a popular loop that enables you to repeatedly run a piece of code for a predetermined number of iterations. Initialization, a condition, and an increment or decrement make up this component. As long as the condition is true, the loop keeps running the code.
  • "while" loop: A block of code is repeatedly run in a "while" loop while the provided condition is still true. Since the condition is verified before each iteration, no startup or increment/decrement statements are needed.
  • The "do-while" loop ensures that the code block is run at least once before verifying the condition. It is comparable to the "while" loop. The code block is first run, and then the condition is verified. The loop keeps running if the condition is true.

These loop statements give you flexibility in how you can design various control flow patterns and repeat code based on particular circumstances. They are crucial programming constructs that enable the creation of loops and the effective execution of recurring tasks.

Q4. Can I use a loop inside a switch statement in C?

No, you cannot directly use a loop inside a switch statement in C. The switch statement in C is used for making decisions based on the value of a variable or an expression. It allows you to choose among multiple cases based on the value of a specific variable.

The syntax of a switch statement in C is as follows:

switch (expression) {
case constant1:
// Code block executed when expression equals constant1
break;
case constant2:
// Code block executed when expression equals constant2
break;
// Additional cases
default:
// Code block executed when expression doesn't match any case
}

Each case represents a specific value or constant that the expression can take, and the code block associated with the matching case is executed. The break statement is used to exit the switch statement after a case is executed.

If you need to repeat a sequence of statements multiple times, you would typically use a loop like for, while, or do-while outside the switch statement. The loop can control the repetition of the switch statement, allowing you to perform the desired operations iteratively.

Q5. What are the 3 elements of looping?

The three elements of looping in C are commonly associated with the `for` loop structure, but they can be applied to other types of loops as well. The three elements are:

  • Initialization: This element initializes the loop variable(s) and is executed only once at the beginning of the loop. It typically sets the initial value for the loop control variable.
  • Condition: The condition is a logical expression that is evaluated before each iteration of the loop. If the condition is true, the loop is executed. If the condition is false, the loop is terminated, and the program moves on to the next statement following the loop.
  • Increment/Decrement: This element specifies how the loop variable(s) should be modified after each iteration. It updates the loop control variable to progress towards the termination condition. It is executed at the end of each iteration, just before re-evaluating the loop condition.

These three elements work together to control the flow and repetition of the loop. The initialization sets up the loop, the condition determines whether to continue or terminate the loop, and the increment/decrement updates the loop control variable to eventually satisfy the termination condition.

We hope the above article was helpful. For more such topics, keep a tab on Unstop - your playground of opportunities! 

Suggested Reads:

Edited by
Shreeya Thakur
Sr. Associate Content Writer at Unstop

I am a biotechnologist-turned-content writer and try to add an element of science in my writings wherever possible. Apart from writing, I like to cook, read and travel.

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.