+ 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; }

25th Feb 2019, 10:40 AM
[No Name]
[No Name] - avatar
7 odpowiedzi
+ 9
It's the modulus operator and its gives remainder For example 5%2=1
25th Feb 2019, 3:05 PM
Rstar
Rstar - avatar
+ 8
But why do we need it to calculate the sum and the product
25th Feb 2019, 5:22 PM
[No Name]
[No Name] - avatar
+ 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:
25th Feb 2019, 7:51 PM
unChabon
unChabon - avatar
+ 4
I want to know what is the role of the % sign, and the division in the sum and product
25th Feb 2019, 2:13 PM
[No Name]
[No Name] - avatar
+ 3
b is never initialized. You're most likely operating with some garbage value.
25th Feb 2019, 10:50 AM
Anna
Anna - avatar
+ 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"
25th Feb 2019, 12:41 PM
unChabon
unChabon - avatar