+ 9
Can someone correct my code, because when i ran it, it doesn't give a correct output
#include <stdio.h> int main() { int sum=0, prod=1, a, b; printf("Enter a number: \n"); scanf("%d",&a); while (a!=0) sum = sum + a%10; a = a/10; while (b!=0) prod = prod + b%10; b = b/10; printf("Sum=%d\nProd=%d\n", sum, prod); return 0; }
7 Answers
+ 9
It's the modulus operator and its gives remainder
For example
5%2=1
+ 8
But why do we need it to calculate the sum and the product
+ 5
It's used to get the least significative digit from "a"
As an example:
a = 345; sum = 0
And
// added curly braces
while (a!=0){
sum = sum + a%10;
a = a/10;
}
345 != 0 => enter loop:
sum = sum + a % 10;
As 345 % 10 = 5 => sum = sum + 5 => sum = 5
Then a = a / 10
a = 345 / 10 => a = 34
Test loop condition:
34 != 0 => enter loop:
sum = sum + a % 10;
34 % 10 = 4 => sum = 5 + 4 => sum = 9
Then a = a / 10
a = 34 / 10 => a = 3
Test loop condition:
3 != 0 => enter loop:
sum = sum + a % 10;
3 % 10 = 3 => sum = 9 + 3 => sum = 12
Then a = a / 10
a = 3 / 10 => a = 0
Test loop condition:Test loop condition:
a == 0 => ends loop...
And sum = 3+4+5 = 12
3 != 0 => enter loop:
+ 4
I want to know what is the role of the % sign, and the division in the sum and product
+ 3
b is never initialized. You're most likely operating with some garbage value.
+ 3
https://code.sololearn.com/cMd42s5MeEXv/?ref=app
Remember to enclose loop body between { }
And assign the value of a to b (b = a;)
Also, you should change + by * in the expression used for "prod"