Every row prints 1 to n, giving a square of numbers. The logic is explained step by step, and the full program is given in C, C++, Java and Python.
This program is part of the Number Patterns collection.
Number Square output
Output (n = 5):
12345 12345 12345 12345 12345

How the number square works
Both loops run n times and the value is the column number j.
- Run the outer loop for
ifrom1ton, one row per pass. - Print
nnumbers (valuej). - Move to the next line.
Number Square in C
#include <stdio.h>
int main(void) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
printf("%d", j);
printf("\n");
}
return 0;
}Number Square in C++
#include <iostream>
using namespace std;
int main() {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cout << j;
cout << endl;
}
return 0;
}Number Square in Java
public class NumberSquare {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
System.out.print(j);
System.out.println();
}
}
}Number Square in Python
n = 5
for i in range(1, n + 1):
for j in range(1, n + 1):
print(j, end="")
print()Time and space complexity
The program prints one character for each position in the pattern, so for n rows it runs in O(n²) time. It only needs a few loop variables, so the extra memory is O(1).





