Program to print numbers columns wise

2

We have to print natural numbers columns wise with decreasing size, depending upon given number of lines as described in the examples below –

Examples :

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

Input : 3
Output :
1
2 4
3 5 6

Approach :

  1. We will take outer for loop, which is for how many lines we want to print.
  2. Since we want to print natural number column by column, for this we will take an inner for loop.
    In the above example the number of element is depending upon number for i, therefore we take a variable k which is equal to i

    Value of i    ||     Number of Element
        1         ||          1
        2         ||          2
        3         ||          3     so on
    
  3. Using the logic k = k + n – j, we will get natural numbers according to requirement.
// Java Program to natural numbers columns wise
import java.util.Scanner;
class Pattern 
{
    void display()
    {
        int n = 5;
        
        // Outer loop for how many lines we want to print
        for (int i = 1; i <= n; i++) 
        {
            int k = i;

            // Inner loop for printing natural number
            for (int j = 1; j <= i; j++) 
            {
                System.out.print(k);
                
                // Logic to print natural value column-wise
                k = k + n - j;
            }
            System.out.println();
        }
    }

    // Driver Code
    public static void main(String[] args)
    {
        Pattern p = new Pattern();
        p.display();
    }
}

Output :

1
2 6 
3 7 10
4 8 11 13
5 9 12 14 15

Hello everyone, I am a team player and most importantly an idea creator.when I do programming, I love to do the program in an another way not the typical way that everyone doing I.e. by the help of any trick or by any other concept and love to know new concepts everyday,every minute,every second.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 1 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.