Skip to study material
← Question index

QUESTION 24 · Loops

Explain nested loops with a rectangular output example.

5 marks

Answer in brief

Nested loops repeat one loop inside another. They are useful for rows and columns, tables and repeated comparisons.

Working

  1. The outer loop selects a row.
  2. For that row, the inner loop processes every required column.
  3. After the inner loop ends, the outer loop moves to the next row.

Example trace

The outer loop runs for rows 1 and 2. For each row, the inner loop runs for columns 1, 2 and 3, printing a star each time. A newline is printed after the inner loop so that each outer iteration produces a separate row. Resetting the inner counter at the beginning of its for loop makes all three columns print on every row.

Common mistakes

Printing the newline inside the inner loop puts each star on a different line. Failing to reset an inner counter can cause later rows to print nothing. Use different counter names, such as row and col, so that updating one loop does not accidentally change the other.

Time complexity

For r outer iterations and c inner iterations each time, the body runs r × c times, giving O(rc) time. If both dimensions equal n, this becomes O(n²). Not every nested loop is quadratic: the limits and total number of executions determine the result. This fixed 2-by-3 sample has six star-print operations.

Space complexity

Only two counters are stored in this example. No array grows with the output size, so auxiliary space is O(1). Printed output itself is not counted as working memory.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    for (int row = 1; row <= 2; ++row) {
        for (int col = 1; col <= 3; ++col) {
            putchar('*');
        }
        putchar('\n');
    }
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

***
***

Related exam questions

Related questions in the loops category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q6(b) · 8 marks

    How is an entry-controlled loop different from an exit-controlled loop? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q2(b) · 5 marks

    Devise an algorithm for the sum of n numbers using while and for loops.

    Paper P02 · page 1

View this category in the exam question bank →