Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to print four powers of numbers 1 to 9 using nested for loop
In C programming, nested loops are powerful constructs where one loop is placed inside another loop. This technique is particularly useful for creating tables, matrices, and complex patterns. Here we'll use nested for loops to generate a table showing the first four powers of numbers 1 to 9.
Syntax
for (initialization; condition; increment) {
for (initialization; condition; increment) {
// Inner loop statements
}
// Outer loop statements
}
How Nested Loops Work
In nested loops, the inner loop completes all its iterations for each single iteration of the outer loop. This creates a multiplicative effect where if the outer loop runs m times and inner loop runs n times, the total iterations will be m × n.
Example: Powers Table Using Nested For Loop
The following program creates a table showing numbers 1 to 9 and their powers (I, I², I³, I?) using three nested for loops −
#include <stdio.h>
int main() {
int i, j, k, temp, I = 1;
printf("I\tI^2\tI^3\tI^4<br>");
printf("--------------------------------<br>");
for (i = 1; i < 10; i++) { /* Outer loop: numbers 1-9 */
for (j = 1; j < 5; j++) { /* Middle loop: power levels 1-4 */
temp = 1;
for (k = 0; k < j; k++) { /* Inner loop: calculate power */
temp = temp * I;
}
printf("%d\t", temp);
}
printf("<br>");
I++;
}
return 0;
}
Output
I I^2 I^3 I^4 -------------------------------- 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561
How It Works
- Outer loop (i): Controls which number (1-9) we're calculating powers for
- Middle loop (j): Determines the power level (1st, 2nd, 3rd, 4th power)
- Inner loop (k): Performs the actual multiplication to calculate each power
- Variable temp starts at 1 and gets multiplied by the current number j times
Key Points
- The program uses three levels of nesting to create the powers table
- Each power is calculated by repeated multiplication rather than using the
pow()function - The tab character (\t) creates neat column alignment in the output
Conclusion
Nested for loops provide an elegant solution for generating mathematical tables and patterns. This example demonstrates how three nested loops can work together to create a comprehensive powers table with clean formatting.
