write a program to print the following pattern of java
a
a a
a a a
a a a a
a a a a a
a a a a
a a a
a a
a
Answers
Pattern in Java, C++
Pattern Programs usually require some analysis. Here we see that we have 9 rows.
First 5 rows are increasing in length, next 4 are decreasing in length.
So we must run a loop 5 times, and then 4 times.
In each case, we must have an inner loop to print the elements.
For the increasing row length, we initialise a variable, say to 1 and run it in a for loop with end condition and increment of . In each iteration of this loop, we run an inner loop times each to print "a".
For the decreasing row length, we initialise this to 4 and run it with end condition and decrement of . Again, an inner loop must run times.
Here is a Java program which prints the pattern:
public class Pattern
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++) //Loop runs 5 times for 5 rows for increasing row length
{
for(int j=0;j<i;j++) //Inner Loop runs i times to print "a "
{
System.out.print("a ");
}
System.out.println(); //Entering a new line after each row
}
for(int i=4;i>0;i--) //Loop runs 4 times for decreasing row length
{
for(int j=0;j<i;j++) //Inner Loop runs i times to print "a "
{
System.out.print("a ");
}
System.out.println(); //Entering a new line after each row
}
}
}
__________________
Adding C++ Code on request:
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=5;i++)
{
for(int j=0;j<i;j++)
{
cout << "a ";
}
cout << endl;
}
for(int i=4;i>0;i--)
{
for(int j=0;j<i;j++)
{
cout << "a ";
}
cout << endl;
}
return 0;
}