0
#include<stdio.h>
void main(){
int i;
int mul = 1;
for(i = 50; i > 1; i--){
    if(i % 2 == 0){
        mul = mul * i;
    }
}
printf("\n Multiplication is %d",mul);
}

The answer comes zero. Tried it many times but always shows zero.

  • 2
    what number do you expect? does it fit into 32-bit signed integer? – qrdl Nov 16 '21 at 09:49
  • 2
    Try to put intermediate `printf()` inside the loop and the if-condition and analyze the results. It's always a good practice in order to create a sort of debug. – Filippo Nov 16 '21 at 09:50
  • 1
    `mul` is much bigger than int – Bernana Nov 16 '21 at 09:51
  • 1
    Using python to calculate, product from 2 to 50 is 520469842636666622693081088000000. And signed int overflow is undefined behaviour in C and C++. Can your please tell us what compiler you use? – rustyhu Nov 16 '21 at 10:00
  • Does this answer your question? [How do I detect unsigned integer multiply overflow?](https://stackoverflow.com/questions/199333/how-do-i-detect-unsigned-integer-multiply-overflow) – rustyhu Nov 16 '21 at 10:06

2 Answers2

2

What you should do to debug:

for(i = 50; i > 1; i--){

    printf("i: %d i%2: %d mul: %d\n", i, i%2, mul);

    if(i % 2 == 0){
        mul = mul * i;
    }

    printf("i: %d i%2: %d mul: %d\n", i, i%2, mul);
}

But as other have pointed out, the answer is too big to fit in int. And when you overflow an int the behavior is undefined, so it's not guaranteed that this code prints zero.

klutt
  • 30,332
  • 17
  • 55
  • 95
0

As I said before mul is much bigger than int and even long.

You should use some else struct, you can look at this question and learn how to implement. number that bigger than long.

Good luck

Bernana
  • 245
  • 1
  • 12