Computer Science, asked by jainakash1350, 1 year ago

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


Anonymous: i also want to know
jainakash1350: what
Anonymous: if u get answer tel me
Anonymous: its solution

Answers

Answered by QGP
17

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 i to 1 and run it in a for loop with end condition i\leqslant 5 and increment of i++. In each iteration of this loop, we run an inner loop i times each to print "a".


For the decreasing row length, we initialise this i to 4 and run it with end condition i > 0 and decrement of i--. Again, an inner loop must run i 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;

}

Attachments:

Anonymous: can u plzz tell me its coding for C++
QGP: Code added in answer
Anonymous: thanksss
QGP: You are welcome :)
Similar questions