LearnFrenzy
Sign in Take a free test
C

C Programming · Topic 16 of 23

C Loops Questions and Concepts

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

Coding Techniques

C Loops · Study material

Sentinel-controlled loops

When you do not know how many values will come, read until a special "sentinel" value (or until input fails). Testing the result of scanf() also stops cleanly on bad input or end of file.

#include <stdio.h>

int main(void) {
    int x, sum = 0, count = 0;
    while (scanf("%d", &x) == 1 && x != -1) {   /* stop at bad input or the sentinel -1 */
        sum += x;
        count++;
    }
    printf("%d numbers, sum %d\n", count, sum);
    return 0;
}

Input

12 7 30 -1 99

Output

3 numbers, sum 49

Leaving nested loops in one step

break only leaves the inner loop. A single forward goto to a label after the loops is the clearest way out – or move the search into a function and return.

#include <stdio.h>

int main(void) {
    int grid[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int target = 6, row = -1, col = -1;

    for (int r = 0; r < 3; r++)
        for (int c = 0; c < 3; c++)
            if (grid[r][c] == target) {
                row = r;
                col = c;
                goto found;                  /* leaves both loops at once */
            }
found:
    if (row >= 0)
        printf("found %d at row %d, column %d\n", target, row, col);
    else
        printf("%d not found\n", target);
    return 0;
}

Output

found 6 at row 1, column 2

Move invariant work out of the loop

Anything that gives the same result on every pass – strlen(s), a size, a square root – belongs before the loop. for (i = 0; i < strlen(s); i++) rescans the string on every pass and turns O(n) into O(n²).

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "loop invariant code motion";
    size_t n = strlen(s);                    /* computed once, not on every pass */
    int spaces = 0;
    for (size_t i = 0; i < n; i++)
        if (s[i] == ' ')
            spaces++;
    printf("%d spaces in %zu characters\n", spaces, n);
    return 0;
}

Output

3 spaces in 26 characters

The do { … } while (0) macro idiom

A multi-statement macro wrapped in do { … } while (0) behaves like one statement, so it works after an if without braces and requires a semicolon.

#define SWAP(a, b) do { int tmp_ = (a); (a) = (b); (b) = tmp_; } while (0)

if (x > y)
    SWAP(x, y);          /* expands safely, even with an else after it */
else
    puts("already in order");

Good loop habits

  • Declare the counter in the for header so it cannot leak.
  • Loop with i < n; use size_t for sizes and indexes from sizeof/strlen.
  • Count down with for (size_t i = n; i-- > 0; ).
  • Use an integer counter, never a float/double one.
  • Always use braces when the body is more than one line.
  • Make sure every while changes something its condition tests.

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