











MindTree Coding Pattern Questions – 3
Ques. Print the following Pattern and get the output to match test cases?
To print the pattern like
for n=3
the program should print
1 1 1 2
3 2 2 2
3 3 3 4
Program in C++
#include <iostream>
using namespace std;
int main()
{
int n=3,c=n-1;
for(int i=1;i<=n;i++)
{
if(i%2==0)
cout<<c++;
for(int j=1;j<=n;j++)
{
cout<<i;
}
if(i%2!=0)
cout<<c++;
cout<<“\n”;
}
return 0;
}
Program in C
#include
int main(void) {
int i,j,n=3,c=n-1;
for(i=1;i<=n;i++)
{
if(i%2==0)
printf(“%d”,c++);
for(j=1;j<=n;j++)
{
printf(“%d”,i);
}
if(i%2!=0)
printf(“%d”,c++);
printf(“\n”);
}
return 0;
}
Please do comment the code in other languages :).
For MindTree Programming – Coding Questions Visit our MindTree Previous Coding Dashboard
Program in JAVA:
import java.util.Scanner;
public class Prog61
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int count1=1;
int count2=n-1;
int a=0,b=n;
int flag=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n+1;j++)
{
if(flag==0)
{
if(j==n){
System.out.print(count2+" ");
flag=1;
break;
}
else{
System.out.print(count1+" ");
}
}
else
{
if(j==n)
{
System.out.print(count2+" ");
flag=0;
break;
}
else
{
System.out.print(count1+" ");
}
}
}
count1=count1+1;
count2=count2+1;
System.out.println();
}
}
}
Thanks for contributing the code Adit
public class mindtreePattern3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j,n=3,c = n-1;
for(i = 1 ;i <= n ; i++)
{
if(i % 2 == 0)
System.out.print(" "+c++);
for(j = 1; j <= n ; j++)
{
System.out.print(" "+i);
}if(i % 2 != 0) {
System.out.print(" "+c++);
}
System.out.println("");
}
}
}
# python-3
t=int(input())
val=1
for i in range(1,t+1):
if(i%2==0):
val+=1
print(val,end=’ ‘)
val-=1
for j in range(t):
print(val,end=” “)
print()
val+=1
else:
for j in range(t):
print(val,end=” “)
val+=1
print(val)
static void mindtreePattern3(int n)
{
int k=1;
for(int i=0;i<n;i++)
{
for(int j=0;j0)
System.out.print(k);
else
{
System.out.print(k+1);
}
}
}
System.out.println();
k++;
}
}
#include
int main()
{
int n,i,j;
scanf(“%d”,&n);
for(i=1;i=1;j–)
{
if(i%2==0)
{
if(j==n+1)
{
printf(“%d”,i+1);
}
else
{
printf(“%d”,i);
}
}
else
{
if(j==1)
{
printf(“%d”,i+1);
}
else
{
printf(“%d”,i);
}
}
}
printf(“\n”);
}
return 0;
}
comment