Home > OS >  C code for multiplication of even numbers returns 0
C code for multiplication of even numbers returns 0

Time:11-16

#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.

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • c
  • Related