Program to print numbers columns wise
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 :
- We will take the outer for loop, which is for how many lines we want to print.
- 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
- Using the logic k = k + n – j, we will get natural numbers according to requirement.
C++
#include <bits/stdc++.h>
using namespace std;
void pattern( int n)
{
for ( int i = 1; i <= n; i++) {
int k = i;
for ( int j = 1; j <= i; j++) {
cout << k << " " ;
k = k + n - j;
}
cout << " \n" ;
}
}
int main()
{
int n = 5;
pattern(n);
return 0;
}
|
Java
import java.util.Scanner;
class Pattern
{
void display()
{
int n = 5 ;
for ( int i = 1 ; i <= n; i++)
{
int k = i;
for ( int j = 1 ; j <= i; j++)
{
System.out.print(k);
k = k + n - j;
}
System.out.println();
}
}
public static void main(String[] args)
{
Pattern p = new Pattern();
p.display();
}
}
|
Python3
def display():
n = 5
i = 1
while (i< = n):
k = i
j = 1
while (j < = i):
print (k,end = " " )
k = k + n - j
j = j + 1
print ( "\r" )
i = i + 1
display()
|
C#
using System;
class Pattern
{
void display()
{
int n = 5;
for ( int i = 1; i <= n; i++)
{
int k = i;
for ( int j = 1; j <= i; j++)
{
Console.Write(k + " " );
k = k + n - j;
}
Console.WriteLine();
}
}
public static void Main()
{
Pattern p = new Pattern();
p.display();
}
}
|
PHP
<?php
function pattern( $n )
{
for ( $i = 1; $i <= $n ; $i ++)
{
$k = $i ;
for ( $j = 1; $j <= $i ; $j ++)
{
echo $k . " " ;
$k = $k + $n - $j ;
}
echo " \n" ;
}
}
$n = 5;
pattern( $n );
?>
|
Javascript
<script>
function pattern(n)
{
for (let i = 1; i <= n; i++) {
let k = i;
for (let j = 1; j <= i; j++) {
document.write(k+ " " );
k = k + n - j;
}
document.write( "<br>" );
}
}
let n = 5;
pattern(n);
</script>
|
Output
1
2 6
3 7 10
4 8 11 13
5 9 12 14 15
Time Complexity: O(n2)
Auxiliary Space: O(1)
Last Updated :
17 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...