C program number pattern example for beginner

C program to print a number pattern :

In this C programming tutorial, we will learn how to print a pattern like below :

1 2 3
2 3 4
3 4 5
4 5 6
5 6 7

or 

1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10

or 

1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

etc.

Means,
1. it can have any number of rows and any number of columns.
2. The first row will start from 1, second row starts from 2 etc.

To solve this problem, we will use two for loops. Outer one will be used for each rows and the inner loop will be used for each columns. We will ask the user to enter both row and column size for this pattern. Let’s take a look at the program first :

C program to solve this program :

#include<stdio.h>

int main(){
	//1
	int i,j,height,width;

	//2
	printf("Enter the height : ");
	scanf("%d",&height);

	//3
	printf("Enter the width : ");
	scanf("%d",&width);

	//4
	for(i=1; i<=height ;i++){
		//5
		for(j=0; j < width ; j++){
			printf("%d ",(i+j));
		}
		//6
		printf("\n");
	}

}

Explanation :

The commented numbers in the above program denote the step number below :

1. Create integer variables to save the height and width of the pattern.
2. Ask the user to enter the height . Read and save it in height variable.
3. Similarly, ask the user to enter the width and save it in width variable.
4. Run one for loop to print all rows. This loop will run for height times.
5. Run one inner for loop to print all column values. This will run for column amount of times. The column value should be (i+j).
6. Print one new line after one row is inserted.

Sample Output :

Enter the height : 5
Enter the width : 3
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7

Enter the height : 6
Enter the width : 4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
6 7 8 9

Enter the height : 6
Enter the width : 6
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10
6 7 8 9 10 11

Leave a Reply