0

Sum=0, when to use? C programming

Hello everybody! I'm very new to C and I have some difficulties about when to declare sum=0 and when not to. i.e, I want to make a multiplication table, I got it to work one way, without using sum. But when I use sum my output is very wrong and by the looks of it, it has something to do with sum. //Code without sum #include <stdio.h> int main () { int i, n; printf("Input the number : "); scanf("%d", &n); for(i=1;i<=10;i++) { printf("%d X %d = %d\n", n, i, (i*n)); } } //Code with sum #include <stdio.h> int main () { int i, n, sum=0; printf("Input the number : "); scanf("%d", &n); for(i=1;i<=10;i++) { printf("%d X %d = %d\n", n, i, sum); sum = n * i; } } What did I do wrong in the last code? output: Input the number : 15 15 X 1 = 0 15 X 2 = 15 15 X 3 = 30 15 X 4 = 45 15 X 5 = 60 15 X 6 = 75 15 X 7 = 90 15 X 8 = 105 15 X 9 = 120 15 X 10 = 135 expected output: Input the number : 15 15 X 1 = 15 15 X 2 = 30 15 X 3 = 45 15 X 4 = 60 15 X 5 = 75 15 X 6 = 90 15 X 7 = 105 15 X 8 = 120 15 X 9 = 135 15 X 10 = 150 What should I look for in a given task to know wether or not to include sum in my program?

1st Nov 2022, 9:04 AM
Joakim Möll
Joakim Möll - avatar
2 odpowiedzi
0
Try to execute first sum = n* i and after the printf... Anyway, i dont see any addition in this code.. Effectivly its like the other code but using sum var like temporary variable for contain the multiplication 🤔
1st Nov 2022, 9:29 AM
KrOW
KrOW - avatar
0
#include <stdio.h> int main () { int i, n; printf("Input the number : "); scanf("%d", &n); for(i=1;i<=10;i++) { printf("%d X %d = %d\n", n, i, (n*i)); } } Maybe this code is helpful for you try this.
1st Nov 2022, 11:07 AM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar