sunfresh

Triangle

Jan 20th, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. Triangle
  2. We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows.
  3.  
  4. Input
  5. On the first line you will be given the number of rows.
  6.  
  7. Output
  8. On the only output line you should print the total number of blocks.
  9.  
  10. Sample tests
  11. Input
  12. 0
  13. Output
  14. 0
  15. Input
  16. 1
  17. Output
  18. 1
  19. Input
  20. 3
  21. Output
  22. 6
  23.  
  24. import java.util.Scanner;
  25.  
  26. public class Triangle {
  27. public static void main(String[] args) {
  28. Scanner scanner = new Scanner(System.in);
  29. int n = Integer.parseInt(scanner.nextLine());
  30. System.out.println(blocks(n));
  31.  
  32. }
  33. public static int blocks(int n){
  34. if(n<2){
  35. return n;
  36. }
  37. return n + blocks(n-1);
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment