Computer Science, asked by arnavagrawal876, 3 months ago

java program to print 1+2+3+4+5+n​

Answers

Answered by Mister360
2

Explanation:

Using nested array:-

public class Pattern1 {

// Function to display the pattern

public static void main(String[] args) {

int i,j,k,n;

System.out.println("Enter the number of lines");

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try{

n = Integer.parseInt(br.readLine());

}catch (Exception e){

System.out.println("An error occurred");

return;

}

System.out.println("The triangular pattern is");

int space = n-2;

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

for(k=space;k>=0;k--){

System.out.print(" ");

}

space--;

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

System.out.print(j + " ");

}

System.out.println();

}

}

}

Explanation:-

  1. In function main(), firstly the number of lines n is entered.
  2. The outer loop for(i=1; i<=n; i++) is used to print n lines.
  3. The nested loop for(k=space;k>=0;k–), is used to print the required spaces.
  4. The nested loop for(j = 1; j<=i; j++), is used to print the values.

Similar questions