Write a C program to print odd number pattern using loop. How to print the given odd number pattern using for loop in C programming. Logic to print the given number pattern using loop in C program.
Required knowledge
Logic to print the given number pattern 1
If you look to the pattern you will find that the pattern only consists of odd numbers. There are N rows (where N is the total number of rows to be printed). As you can see that each row contains exactly N – i + 1 columns (where i is the current row number).
For printing the numbers we will be using an extra variable lets say k that will keep track of next odd number. For each row odd number starts with the expression i * 2 – 1.
Step-by-step descriptive logic:
- To iterate through rows, run an outer loop from 1 to N.
- Inside this outer loop, initialize variable k = i * 2 – 1 (where k is used to keep track of next odd number to be printed).
- To iterate though columns, run an inner loop from i to N (where i is the current row number).
Inside this loop print the value of k and increment it to k = k + 2.
And finally you are done, lets code it down.
Program to print the odd number pattern
/**
* C program to print number pattern
*/
#include <stdio.h>
int main()
{
int i, j, k, N;
printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
k = (i * 2) - 1;
// Logic to print numbers
for(j=i; j<=N; j++, k+=2)
{
printf("%d", k);
}
printf("\n");
}
return 0;
}
Output
Enter N: 5 13579 3579 579 79 9
Logic to print the odd number pattern with spaces
The above pattern is similar to the first pattern we just printed above except the trailing spaces printed before the numbers. The logic for printing numbers will be similar as first pattern we printed, we only need to add logic of printing spaces. As you can see that each row contains exactly i – 1 spaces (where i is the current row number). You can also hover on to the pattern to see or count total spaces per row.
Step-by-step descriptive logic to print spaces:
- To print spaces, run an inner loop from 1 to i – 1. Inside this loop print single blank space.
Program to print the odd number pattern with spaces
/**
* C program to print number pattern
*/
#include <stdio.h>
int main()
{
int i, j, k, N;
printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
k = (i * 2) - 1;
// Logic to print spaces
for(j=1; j<i; j++)
{
printf(" ");
}
// Logic to print numbers
for(j=i; j<=N; j++, k+=2)
{
printf("%d", k);
}
printf("\n");
}
return 0;
}
Happy coding 😉