128k views
5 votes
Write codes to calculate: p = 3 * 6 * 9 * 12 * ... * 21, can you use if-else instead of step = 3 to do this?

User Celin
by
8.0k points

1 Answer

3 votes

Final answer:

Yes, you can use if-else statements to calculate the product of a series. Here's an example code that initializes the product variable and iterates over the range with a variable step value.

Step-by-step explanation:

Yes, you can use if-else statements to calculate the product of a series like p = 3 * 6 * 9 * 12 * ... * 21. However, instead of using a constant step value of 3, you can use a loop with a variable step value that increments by 3 in each iteration.

Here's an example code that calculates the product using an if-else statement:

int p = 1;
for (int i = 3; i <= 21; i += 3) {
if (i % 9 == 0) {
p *= i;
}
}

This code initializes the product variable p to 1 and iterates over the range from 3 to 21 with a step of 3. The if statement checks if the current number i is divisible by 9 (to skip 15 and 18), and if so, multiplies it with the product p. At the end of the loop, the variable p will contain the calculated product.

User Sarah A
by
8.0k points

No related questions found