Computer Science, asked by sandrasony17, 1 year ago

Write a java program to get the following output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Answers

Answered by arujaiswal12gmailcom
2

perm_identity

Print the following pyramid pattern

Given a positive integer n. The problem is to print the pyramid pattern as described in the examples below.

Examples:

Input : n = 4 Output : 1 3*2 4*5*6 10*9*8*7 Input : n = 5 Output : 1 3*2 4*5*6 10*9*8*7 11*12*13*14*15


Approach: For odd number row, values are being displayed in increasing order and for even number row, values are being displayed in decreasing order. The only other trick is to how to iterate the loops.

Algorithm:

printPattern(int n) Declare j, k Initialize k = 0 for i = 1 to n if i%2 != 0 for j = k+1, j < k+i, j++ print j and "*" print j and new line k = ++j else k = k+i-1 for j = k, j > k-i+1, j-- print j and "*"; print j and new line

C++

// C++ implementation to print the following 

// pyramid pattern

#include <bits/stdc++.h>

using namespace std;

  

// function to print the following pyramid pattern

void printPattern(int n)

{

    int j, k = 0;

      

    // loop to decide the row number

    for (int i=1; i<=n; i++)

    {

        // if row number is odd

        if (i%2 != 0)

        {

            // print numbers with the '*' sign in 

            // increasing order

            for (j=k+1; j<k+i; j++)

                cout << j << "*";

            cout << j++ << endl;

              

            // update value of 'k'    

            k = j;    

        }

          

        // if row number is even

        else

        {

            // update value of 'k'

            k = k+i-1;

              

            // print numbers with the '*' in 

            // decreasing order

            for (j=k; j>k-i+1; j--)

                cout << j << "*";

            cout << j << endl;    

        }

    }

}

  

// Driver program to test above

int main()

{

    int n = 5;

    printPattern(n);

    return 0;



Run on IDE

Mark as brainlist answer please

arujaiswal12gmailcom: hi
arujaiswal12gmailcom: mark as brainlist answer please
sandrasony17: Hi
arujaiswal12gmailcom: mark as brainlist answer please
Answered by Anonymous
1

Answer:

Hey your required answer is given below .

Explanation:

import java.util.Scanner;

public class MainClass

{

public static void main(String[] args)  

{

 Scanner sc = new Scanner(System.in);

 

 //Taking rows value from the user

 

 System.out.println(&quot;How many rows you want in this pattern?&quot;);

 

 int rows = sc.nextInt();

 

 System.out.println(&quot;Here is your pattern....!!!&quot;);

 

 for (int i = 1; i &lt;= rows; i++)  

 {

  for (int j = 1; j &lt;= i; j++)

  {

   System.out.print(j+&quot; &quot;);

  }

   

  System.out.println();

 }

 

 //Close the resources

 

 sc.close();

}

}

Similar questions