We have triangles made of wooden 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 an arrangement of triangles with the given number of rows.
For example,
triangle(2) → 3
Note:
Refer to the problem requirements.
Function specification:
int triangle(int n)
Input and Output Format :
Input consists of a single integer corresponding to the number of triangles and the output consists of a single integer corresponding to the total number of blocks.Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and the rest corresponds to output.]
Sample Input and Output:
Enter the number of triangles
2
Total number of blocks : 3
Function Definitions:
| int triangles (int) |
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// sauravhathi
System.out.println("Enter the number of triangles");
int n = sc.nextInt();
// sauravhathi
System.out.println("Total number of blocks : " + triangle(n));
}
public static int triangle(int n) {
if (n == 0) {
return 0;
}
return n + triangle(n - 1);
}
}Happy Learning – If you require any further information, feel free to contact me.
![[Solved] Triangle with Java [Solved] Triangle with Java](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Triangle-with-Java.png)
![[Solved] Lewis is working on a game designing project called as Ball Blast Java, C++, Python, JavaScript](https://realcoder.techss24.com/wp-content/uploads/2022/10/Solved-Lewis-is-working-on-a-game-designing-project-called-as-Ball-Blast-Java-C-Python-JavaScript-300x201.png)
![[Solved] Lucky Pairs with Java, C++, Python](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-Lucky-Pairs-with-Java-C-Python-300x200.png)
![[Solved] To the Magic Show with Java, C++](https://realcoder.techss24.com/wp-content/uploads/2022/07/Solved-To-the-Magic-Show-with-Java-C-300x200.png)