java program to print 1+2+3+4+5+n
Answers
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:-
- In function main(), firstly the number of lines n is entered.
- The outer loop for(i=1; i<=n; i++) is used to print n lines.
- The nested loop for(k=space;k>=0;k–), is used to print the required spaces.
- The nested loop for(j = 1; j<=i; j++), is used to print the values.