Learning Loops in C

Learning Loops in C

8 mins read72 Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 3, 2024 17:44 IST

Have you ever wondered how computer programs handle repetitive tasks so efficiently? The secret lies in loops, a fundamental concept in C programming. Loops allow a program to execute a block of code multiple times, making tasks like iterating through arrays, generating patterns, or performing calculations on a series of numbers both straightforward and efficient. Let's understand more!

Loops provide an efficient way to run the same code multiple times, thus reducing redundancy and making code more concise. C offers several loops, including the for, while, and do-while loops, each with unique use cases. Whether iterating through arrays, reading multiple data inputs, or simply wanting to repeat an action until a certain condition is met, loops in C offer the flexibility and control to achieve these tasks effectively.

Explore Online C Programming Courses

2023_08_Screenshot-2023-08-25-145520.jpg

Types of Loops in C:

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

Let’s understand each one of these in detail :

1. “for loop

The for loop in C provides a concise way to iterate over a block of code using an initializer, a condition, and an iterator. We commonly use it when the number of iterations is known beforehand.

It has three main parts:

  • Initialization: Executed once at the beginning of the loop. This step allows you to declare and initialize any loop control variables.
  • Condition: Evaluated before each iteration. The loop body is executed if the condition evaluates to true (non-zero). If it evaluates to false (zero), the loop is terminated.
  • Update: Executed after each iteration. It’s typically used to update loop control variables.

Syntax :

for (initialization; condition; update)
{
    // code to be executed in each iteration of the loop;
}

Flowchart :

2023_08_Screenshot-11-2.jpg

For example :

Let’s print a pattern using for loop


 
#include <stdio.h>
int main() {
int n = 10; // height
for (int i = 1; i < = n; i++) {
for (int j = 1; j < = i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Copy code

 

Output :

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 

This pattern starts with one star for the first row, and the number of stars increases by one for each subsequent row until the 10th row has 10 stars.

2. “while loop”

A while loop in C is a control flow structure that allows a piece of code to be executed repeatedly as long as a particular condition is true.

Here, the condition is evaluated before the execution of the loop’s body. If the condition is true, the code inside the loop will run. After the loop body has run, the condition is evaluated again, and if it’s still true, the body runs again. This process continues until the condition becomes false. If the condition starts off as false, the loop body will never execute.

Syntax :

while (condition)
{
    // code to be executed as long as condition is true;
}

Flowchart :

2023_08_Screenshot-13-2.jpg

Problem Statement :

Imagine you’re at a space centre, and there’s a rocket set to launch. Before the rocket launches, a countdown starts from a specific number and decrements until it reaches zero, signalling the rocket’s launch. The program below simulates this countdown, starting from 10 seconds and decrementing every second.

Code :


 
#include <stdio.h>
int main() {
int countdownSeconds = 10;
while (countdownSeconds > 0) {
printf("T-minus %d seconds...\n", countdownSeconds);
countdownSeconds--; // Decreasing the countdown by 1 second every iteration.
}
printf("Rocket has launched!\n");
return 0;
}
Copy code

Output :

T-minus 10 seconds...
T-minus 9 seconds...
T-minus 8 seconds...
T-minus 7 seconds...
T-minus 6 seconds...
T-minus 5 seconds...
T-minus 4 seconds...
T-minus 3 seconds...
T-minus 2 seconds...
T-minus 1 seconds...
Rocket has launched!

The program uses a loop to simulate the rocket’s countdown, decrementing the timer by one second in each iteration. The loop exits once the countdown reaches zero, and the rocket’s launch is signalled with the final message.

 

3. “do-while loop”

The do-while loop checks the condition after executing the loop body, which ensures that the loop body is executed at least once, even if the condition is initially false.

Syntax :

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

Flowchart :

2023_08_Screenshot-15-2.jpg

For example :

We have to calculate the factorial of a number N.

Code :


 
// C Program to calculate factorial using do-while loop
#include <stdio.h>
int main()
{
int N = 7, i = 1;
int factorial = 1;
do {
factorial *= i;
i++;
} while (i <= N);
printf("Factorial of %d is: %d\n", N, factorial);
return 0;
}
Copy code

Output :

Factorial of 7 is: 5040

In this program, we calculated the factorial of 7 using the do-while loop in C. The loop multiplies the current value of factorial with the iterator i until i exceeds the value of N

Control Statements in C | Meaning and Types
Control Statements in C | Meaning and Types
Control statements in C are used to determine the order in which the instructions within a program are executed. They are of three types: Selection, Iteration & Jump statements. Think...read more
Top 80+ C Programming Interview Questions and Answers
Top 80+ C Programming Interview Questions and Answers
Here’s a list of 80+ top frequently asked C programming interview questions and answers to help you crack your next interview. Preparing for a C programming interview? Here are the...read more
Addition of Two Numbers in C
Addition of Two Numbers in C
Delve into C programming with a foundational task: adding two numbers. This guide walks you through each step, from declaring variables to getting the output, making it a perfect starting...read more

Let’s take a scenario

Background:
When grocery shopping, having a list of items to purchase is common. Each item is added to the cart and marked off the list. The program should simulate this process, allowing users to input items they’ve added to their cart and check them off the list until it is complete.

Objective:
Write a C program to track the completion of items on a grocery shopping list using a do-while loop.

Constraints:

  • The program should use a do-while loop to take user input until the shopping list is complete.
  • totalItems is a positive integer.

Expected Outcome:

For each item added to the cart, print a message indicating the item has been added. Once all items are added, print a message indicating that the shopping is complete.

Code :


 
#include <stdio.h>
int main() {
int totalItems;
printf("Enter the total number of items on your shopping list: ");
scanf("%d", &totalItems);
int currentItem = 1;
char itemName[50];
printf("Start adding items to your cart:\n");
do {
printf("Item %d: ", currentItem);
scanf("%s", itemName);
printf("%s added to the cart!\n", itemName);
currentItem++;
} while (currentItem <= totalItems);
printf("Shopping complete! All items added to the cart.\n");
return 0;
}
Copy code

Output :

Enter the total number of items on your shopping list: 5
Start adding items to your cart:
Item 1: Apple
Apple added to the cart!
Item 2: Orange
Orange added to the cart!
Item 3: Banana
Banana added to the cart!
Item 4: Milk
Milk added to the cart!
Item 5: Soap
Soap added to the cart!
Shopping complete! All items added to the cart.

In this program, the user is prompted to input the total number of items on their shopping list. Then, the program uses a do-while loop to iteratively prompt the user for the name of each item they’ve added to the cart. After all items are added, a final message confirms the completion of the shopping.

Learn Data Types in C Programming With Examples
Learn Data Types in C Programming With Examples
Data types are the type of data stored in a C program. Data types are used while defining a variable or functions in C. It’s important for the compiler to...read more

C programming examples 
C programming examples 
If you want to learn C language by executing programming examples. Then this article offers you 17C programming examples with outputs, so that you can learn fast.

C programming Keywords: A list and Explanation of Usage
C programming Keywords: A list and Explanation of Usage
Keywords in C refer to a set of reserved words with predefined meanings that are used to write programs in the C programming language. These keywords cannot be used as...read more

Thus, loops in the C programming language are fundamental constructs that allow for the repetitive execution of a block of code. Every beginner must learn it thoroughly & then only go to the advanced level.

What’s Next?

Having understood basic operations, it’s time to build upon that foundation. Here’s a suggested roadmap:

  1. Data Types and Variables: Before diving into complex operations, it’s essential to understand the different types of data you can work with in C and how to store them.
  2. Basic Input/Output: Learn how to interact with users by taking input and displaying results. This will make your programs more interactive and user-friendly.
  3. Operators in C: Delve into arithmetic, relational, and logical operators. This will empower you to perform a variety of operations on your data.
  4. Control Structures: Once you’re comfortable with the basics, you can start exploring decision-making in programming, leading you to more dynamic code.

Boost Your Learning:

Consider enrolling in an online course if you’re serious about mastering C. Here are some top recommendations:

  1. Coursera’s “C for Everyone” Series: A comprehensive introduction to C, suitable for beginners and those looking to refresh their knowledge.
  2. Udemy’s “C Programming For Beginners”: This course takes a hands-on approach, ensuring you get practical experience as you learn.

By investing time in a structured course, you’ll gain a more profound understanding, benefit from expert insights, and have a clear path of progression.

So, gear up and dive deeper into the world of C programming. The journey you’ve embarked on is filled with challenges, but the rewards, in terms of knowledge and skills, are immeasurable. Happy coding!

FAQs

What Are Loops in C Programming?

Loops in C are control flow statements that repeat a block of code as long as a specified condition is true. They are essential for executing repetitive tasks efficiently, such as processing items in an array, generating patterns, or automating calculations.

What Types of Loops Are There in C?

C programming supports three main types of loops:

  • for loop: Executes a sequence of statements multiple times and simplifies the code that manages the loop variable.
  • while loop: Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
  • do-while loop: Like a while loop, but it tests the condition at the end of the loop body, ensuring that the loop is executed at least once.

How Do You Choose Which Loop to Use?

The choice depends on the specific needs of your program:

  • Use a for loop when the number of iterations is known before entering the loop.
  • Use a while loop when the number of iterations is not known and needs to be determined during execution.
  • Use a do-while loop when the loop body needs to be executed at least once, even if the condition is initially false.

Can Loops Be Nested Inside Other Loops?

Yes, loops can be nested within each other. This is particularly useful for dealing with multi-dimensional data structures like arrays or matrices, where an outer loop might iterate through rows and an inner loop through columns.

What Are Infinite Loops and How Are They Controlled?

An infinite loop runs without ever stopping, which can be intentional but is often a bug. They are controlled by ensuring that the loop condition is eventually made false. For intentional infinite loops, such as those used in event-driven programs, make sure there's a clear exit condition within the loop to break the execution when necessary.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio