Skip to main content

Control Statements and Loops in C

C Programming: Mastering Control Statements and Loops

By default, a C program executes line by line, perfectly straight from top to bottom. However, real-world problems require flexibility. You need the ability to skip certain lines, repeat others, and make intelligent choices based on data.

We call the tools that handle this logic Control Statements. They act as the steering wheel of your program. In this guide, we break down Decision Making, Loops, and apply them to five classic computer science problems.

1. Decision Making: Forking the Path

Decision-making statements force the computer to evaluate a condition. Based on the result (True or False), the computer takes a specific path.

  • if Statement: You use this to execute a block of code only if a condition is true. Real-life example: You check the sky. If it is raining, you take an umbrella. If not, you do nothing and continue walking.
  • if-else Statement: You use this to provide a backup plan. If the condition is true, execute block A. Else, execute block B. Real-life example: You check your wallet. If you have money, you buy a coffee. Else, you drink tap water.
  • Nested if: You place an if statement inside another if statement. You use this when you need to pass multiple checkpoints. Real-life example: A security guard checks your age. If you are over 18, he then checks your ticket. If you have a VIP ticket, he lets you into the front row.
  • switch Statement: You use this when you have many specific, known options (like a menu). Instead of writing a dozen bulky if-else blocks, you "switch" the execution path based on a matching case. Real-life example: Calling an automated customer service line. "Press 1 for Sales, Press 2 for Support, Press 3 for Billing."

2. Loops: The Power of Iteration

Loops allow you to execute the exact same block of code multiple times without rewriting it. Programmers rely on three main types of loops.

  • for Loop: You use a for loop when you know exactly how many times the code needs to run before you start. Real-life example: A gym coach tells you to run exactly 5 laps. You start at 1, count each lap, and stop when you reach 5.
  • while Loop: You use a while loop when you do not know how many times the code will run. You evaluate the condition before executing the code. Real-life example: Eating dinner. While you are still hungry, you take another bite. You check your hunger before every single bite.
  • do-while Loop: This loop works exactly like a while loop, but it guarantees the code runs at least once because it checks the condition at the end. Real-life example: Jumping into a swimming pool. You jump in first, and then you decide if the water is too cold to stay in.

3. Problem Solving Focus: Classic C Algorithms

To master control statements, you must write code. Below are five foundational logic problems that test your ability to use loops and decision-making effectively.

Problem 1: Prime Number Checker

A prime number is a number greater than 1 that only divides evenly by 1 and itself (like 7 or 11). We use a for loop to try dividing the number by everything from 2 up to half of the number. If we find a clean division, it is not prime.

#include <stdio.h>

int main() {
    int num = 29, i, isPrime = 1;

    for(i = 2; i <= num / 2; i++) {
        if(num % i == 0) {
            isPrime = 0; // We found a divisor!
            break; // Exit the loop instantly
        }
    }

    if(isPrime && num > 1)
        printf("%d is a Prime Number.\n", num);
    else
        printf("%d is NOT a Prime Number.\n", num);
    return 0;
}

Problem 2: Armstrong Number Checker

An Armstrong number (for 3 digits) is a number where the sum of the cubes of its individual digits equals the number itself. For example, 153 is an Armstrong number because (1*1*1) + (5*5*5) + (3*3*3) = 153. We use a while loop to strip off the last digit one by one.

#include <stdio.h>

int main() {
    int num = 153, originalNum, remainder, result = 0;
    originalNum = num;

    while(originalNum != 0) {
        // Extract the last digit
        remainder = originalNum % 10;
        // Cube it and add to result
        result += (remainder * remainder * remainder);
        // Remove the last digit
        originalNum /= 10;
    }

    if(result == num)
        printf("%d is an Armstrong number.\n", num);
    else
        printf("%d is NOT an Armstrong number.\n", num);
    return 0;
}

Problem 3: Palindrome Checker

A palindrome reads the exact same forwards and backwards (like 121 or 1001). We use a while loop to systematically rebuild the number in reverse, then check if it matches the original using an if statement.

#include <stdio.h>

int main() {
    int n = 1221, reversed = 0, remainder, original;
    original = n;

    while(n != 0) {
        remainder = n % 10;
        reversed = reversed * 10 + remainder;
        n /= 10;
    }

    if(original == reversed)
        printf("%d is a Palindrome.\n", original);
    else
        printf("%d is NOT a Palindrome.\n", original);
    return 0;
}

Problem 4: Factorial Calculation

The factorial of a number (like 5!) means multiplying it by every number below it (5 * 4 * 3 * 2 * 1 = 120). We use a simple for loop to multiply a running total by every integer up to our target number.

#include <stdio.h>

int main() {
    int num = 5, i;
    long long fact = 1; // Using long long because factorials grow huge rapidly

    for(i = 1; i <= num; i++) {
        fact *= i; // Same as fact = fact * i
    }

    printf("Factorial of %d is %lld\n", num, fact);
    return 0;
}

Problem 5: Fibonacci Sequence

The Fibonacci sequence generates numbers by adding the two previous numbers together (0, 1, 1, 2, 3, 5, 8...). We use a for loop and three variables to shift values forward sequentially.

#include <stdio.h>

int main() {
    int terms = 8, i;
    int t1 = 0, t2 = 1, nextTerm;

    printf("Fibonacci Series: %d, %d, ", t1, t2);

    // Loop starts from 3 because we already printed the first two terms
    for(i = 3; i <= terms; i++) {
        nextTerm = t1 + t2;
        printf("%d, ", nextTerm);
        
        // Shift the values forward for the next iteration
        t1 = t2;
        t2 = nextTerm;
    }
    return 0;
}



Summary: Control Statements

  • You use Decision Making statements (if, if-else, switch) to force the program to choose a path based on current data.
  • You use a for loop when you know the exact number of iterations before execution begins.
  • You use a while loop when the loop relies on an unpredictable condition remaining true.
  • You use a do-while loop to guarantee your code block executes at least one time before evaluating any conditions.
  • Mastering core logic algorithms like factorials and palindromes is the key to building strong problem-solving skills in C.

C Programming Interview Questions (FAQs)

1. What is the difference between the 'break' and 'continue' statements?

Programmers use the break statement to instantly destroy a loop. The moment the computer reads break, it exits the loop entirely, regardless of the condition. Conversely, programmers use continue to skip the current iteration. The computer ignores the rest of the code inside the loop for that specific turn, but jumps right back to the top of the loop to run the next iteration.

2. When should I use a 'switch' statement instead of 'if-else'?

You should use a switch statement when you are comparing a single integer or character variable against many constant, specific values. A switch statement makes the code much cleaner and faster to read than writing a massive chain of else if checks. However, you cannot use a switch statement to evaluate complex logic or ranges (like checking if x > 10 && x < 20).

3. Why do we usually use the modulo operator (%) to solve digit-based problems?

The modulo operator dividing by 10 (num % 10) isolates the final digit of any integer. Once you process that digit, performing an integer division by 10 (num / 10) completely deletes that last digit. By pairing these two operators inside a while loop, programmers can systematically break down any number, digit by digit. We use this foundational technique in Palindrome, Armstrong, and Reverse Number logic.

➔ Read more about Data Types ➔ Read more about Fundamentals ➔ Read more about Variables and Storage Classes ➔ Read more about String ➔ Read more about Operators ➔ Read more about Functions ➔ Read more about Arrays ➔ Read more about Pointers ➔ Read more about Structures ➔ Read more about Enum ➔ Read more about Union

Comments

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Data Types in C

C Programming: Understanding Data Types Think of your kitchen. You store a large bag of flour in a big bin, a pinch of saffron in a tiny jar, and milk in a liquid measuring jug. You do not put liquids into paper bags, and you do not use a massive bucket for a single teaspoon of sugar. C programming works the exact same way. When you create a variable, you must tell the computer exactly what kind of "container" to build in its memory. We call these containers Data Types . They dictate what kind of data the container holds, how much space it takes up, and what operations you can perform on it. 1. Primitive Data Types C offers several built-in, "primitive" data types. Think of these as the fundamental storage containers. int (Integer): You use this to store whole numbers without decimals. Real-life example: Counting the number of people in a room or tracking a player's score in a video game. char (Character): You use this ...