Answer in brief
Nested loops repeat one loop inside another. They are useful for rows and columns, tables and repeated comparisons.
Working
- The outer loop selects a row.
- For that row, the inner loop processes every required column.
- 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
***
***