Advertisement
BojidarDosev

Pascal Triangle

Jan 28th, 2025
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.  
  6.         Scanner scanner = new Scanner(System.in);
  7.         //input number of lines
  8.         int n = scanner.nextInt();
  9.         //save the number of lines temporary
  10.         int temp = n;
  11.         //create array that will be printed
  12.         int[] arr = new int[n];
  13.         //that array will save the main one
  14.         int[] arrTemp = new int[n];
  15.         n = 0;
  16.  
  17.         while(n<=temp){
  18.             //lets loop through the array
  19.             for(int i = 0; i <n; i++){
  20.                 //if the number is in first or last place it is 1
  21.                 if(i == 0 || i == n-1){
  22.                     arr[i] = 1;
  23.                     //arrTemp[i] = 1;
  24.                 }
  25.                 //otherwise, the number would be the sum of the number above it and the number ot its left
  26.                 else{
  27.                         arr[i] = arrTemp[i-1] + arrTemp[i];
  28.                 }
  29.                 // print the next line of numbers
  30.                 System.out.print(arr[i] + " ");
  31.             }
  32.             //now save the current line to the temp line, that would be useful when we want to
  33.             //sum the numbers in the next line
  34.             for(int i = 0; i <n; i++){
  35.                 arrTemp[i] = arr[i];
  36.             }
  37.             // count of numbers per line increases
  38.             n++;
  39.             //space the lines
  40.             System.out.println();
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement