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.