V-Shaped Number Pattern in C

What You’ll Learn
How to print a V-shaped number pattern by placing numbers on two diagonals and printing spaces everywhere else.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1 1
2 2
3 3
4 4
5Complete C Program
We use two loops per row: one for the left diagonal (i == j) and one for the right diagonal (i == k).
#include <stdio.h>
int main() {
int i, j, k;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 5; j++) {
if (i == j)
printf("%d", j);
else
printf(" ");
}
for (k = 4; k >= 1; k--) {
if (i == k)
printf("%d", k);
else
printf(" ");
}
printf("\n");
}
return 0;
}🧠 How It Works
Loop through rows
The outer loop prints 5 lines.
Left diagonal (i == j)
We print the row number on the left diagonal by checking i == j.
Right diagonal (i == k)
We print the matching value on the right diagonal by checking i == k.
Avoid double-printing the bottom
The right-diagonal loop starts at 4 so the last row prints only one 5.
V shape
Spaces fill the rest of the grid so the diagonals stand out.
Variation — User Input Version
Read the number of rows using scanf().
#include <stdio.h>
int main() {
int i, j, k;
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= rows; j++) {
if (i == j)
printf("%d", j);
else
printf(" ");
}
for (k = rows - 1; k >= 1; k--) {
if (i == k)
printf("%d", k);
else
printf(" ");
}
printf("\n");
}
return 0;
}💡 Tips for Enhancement
Try These
- Print asterisks instead of numbers for a classic V pattern
- Use
printf("%d ", ...)to add spacing - Make a thicker V by printing around the diagonals too
Avoid
- Starting the right loop at
rows(duplicates the center) - Using
rows <= 0without input validation
Key Takeaways
Two diagonal conditions create the V shape.
Spaces are printed everywhere else to highlight the diagonals.
Start the right diagonal at rows-1 to avoid duplicating the last number.
Nested loops over a grid lead to O(n²) time.
❓ Frequently Asked Questions
n rows.Explore More C Number Patterns!
Try more diagonal and symmetry patterns to master loop logic.
This pattern is a simple example of drawing shapes by printing only when a coordinate matches a condition like i == j.
12 people found this page helpful
