In this project, I will show you how to print following pattern using for loops in C++ programming language.
Problem Statement: You have to print a pattern of numbers from 1 to n as shown below. Where n is an input. Each of the numbers is separated by a single space.
Input:
The input will contain a single integer n.
Constraints:
1<=n<=1000
Output:
Print the demanded pattern.
Input:
4
Output:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
Following is the source code in C++ programming language for above problem statement:
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
int t=2*n;
for(int i=1;i<=n;i++){
int k=n;
for(int j=1;j<=t-1;j++){
if(j<i){
cout<<k--<<" ";
}else if(j>=i && j<=t-i){
cout<<k<<" ";
}else{
cout<<++k<<" ";
}
}
cout<<"\n";
}
for(int i=n-1;i>=1;i--){
int k=n;
for(int j=1;j<=t-1;j++){
if(j<i){
cout<<k--<<" ";
}else if(j>=i && j<=t-i){
cout<<k<<" ";
}else{
cout<<++k<<" ";
}
}
cout<<"\n";
}
}
Submitted by Ebtesam Ahmad Karimi (ebtesam)
Download packets of source code on Coders Packet
Comments