LearnFrenzy
Sign in Take a free test

C Programming · Topic 16 of 23

C Loops

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

C Loops · Study material

Loops in C repeat a block of code: for when you know how many times, while while a condition holds, and do-while when the body must run at least once. Every C program that processes data – arrays, strings, files, input – is built on loops, and placement tests love them: tricky output questions, off-by-one errors, unsigned countdowns that never end, and pattern programs. This page covers all of that, then gives you 40 practice questions checked on a real compiler.

On this page

  • for, while and do-while – syntax and when to use each
  • Nested loops, break and continue
  • Counting down safely with unsigned types; two counters in one loop
  • The loop bugs interviewers ask about

The three loops

LoopSyntaxUse it when
forfor (init; condition; update) bodythe number of steps is known (arrays, counting)
whilewhile (condition) bodyyou repeat until something happens (input, digits)
do-whiledo body while (condition);the body must run at least once (menus, retries)
#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 5; i++)          /* known number of steps */
        sum += i;
    printf("for:      %d\n", sum);

    int n = 1234, digits = 0;
    while (n > 0) {                        /* repeat while a condition holds */
        n /= 10;
        digits++;
    }
    printf("while:    %d digits\n", digits);

    int tries = 0, value = 0;
    do {                                   /* the body runs at least once */
        value += 7;
        tries++;
    } while (value % 5 != 0);
    printf("do-while: %d after %d tries\n", value, tries);
    return 0;
}

Output

for:      15
while:    4 digits
do-while: 35 after 5 tries

In a for loop the order is: init once, then condition → body → update repeatedly. Since C99 a variable declared in the init (for (int i = 0; …)) exists only inside the loop.

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one, so the total work is the product of both counts – n × n for a square grid, which is why nested loops are O(n²).

#include <stdio.h>

int main(void) {
    for (int r = 1; r <= 4; r++) {         /* outer loop: one row per pass */
        for (int c = 1; c <= 4; c++)       /* inner loop: one column per pass */
            printf("%4d", r * c);
        printf("\n");
    }
    return 0;
}

Output

   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16

break and continue

break leaves the innermost loop (or switch) at once. continue skips the rest of the current pass: in a for loop it jumps to the update, in while/do-while to the condition.

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i % 3 == 0)
            continue;          /* skip the rest of this pass */
        if (i > 8)
            break;             /* leave the loop completely */
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output

1 2 4 5 7 8

Counting down with unsigned types

for (size_t i = n - 1; i >= 0; i--) never ends: an unsigned value is always ≥ 0, and after 0 it wraps to a huge number. Test-and-decrement in the condition instead.

#include <stdio.h>

int main(void) {
    int a[] = {10, 20, 30};
    size_t n = sizeof a / sizeof a[0];
    for (size_t i = n; i-- > 0; )          /* i is 2, 1, 0 – then the test fails */
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Output

30 20 10

Two counters in one loop

The comma operator lets the init and update parts handle several variables – handy for two-pointer algorithms.

#include <stdio.h>

int main(void) {
    for (int i = 0, j = 5; i < j; i++, j--)    /* two variables, moving towards each other */
        printf("(%d,%d) ", i, j);
    printf("\n");
    return 0;
}

Output

(0,5) (1,4) (2,3)

Common loop mistakes

  • A semicolon after the header – for (i = 0; i < n; i++); loops over an empty statement.
  • Off-by-one – i <= n instead of i < n touches one element too many.
  • Unsigned countdown to 0 – the condition i >= 0 is always true.
  • Floating-point counters – x += 0.1 never lands exactly on 1.0; count with an int.
  • Forgetting to update the variable a while loop tests – an infinite loop.
  • Expensive work in the condition – i < strlen(s) rescans the string on every pass.

Key points to remember

  • do-while runs its body at least once; for and while may run zero times.
  • for (;;) and while (1) are infinite loops – leave them with break or return.
  • break exits only the innermost loop; use a flag, a function return or goto to leave nested loops.
  • Inside a switch, break leaves the switch, but continue applies to the surrounding loop.
  • Count with integers, loop up to i < n, and compute loop limits once.

Frequently asked questions

What is the difference between while and do-while?

while tests first, so its body may never run. do-while tests after the body, so the body always runs at least once.

Which loop is fastest in C?

None – the compiler turns all three into the same jumps. Choose the one that states your intent most clearly.

How do I break out of two nested loops?

Put the loops in a function and return, set a flag that both conditions test, or use a single goto to a label after the loops.

Where can I learn loops step by step?

Read Loops in C: for, while and do-while and Pattern Programs in C, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links