c - adding same variables with different values in loop -
so, need ask user how many numbers wants add, , ask him input numbers, have no idea how add numbers without having them stored in same variable, or how add same variable different values, extremely easy in pascal, don't know how in c.
here code far...
int main(int argc, char *argv[]) { int i, n, age; printf("how many numbers want add?\n"); scanf("%d", &n); (i = 1; <= n; = i++) { printf("type in number:\n"); scanf("%d", &age); } return 0; }
to compute sum of numbers entered, can define variable sum , add each number entered.
note there undefined behavior in code: i = i++;
cannot have both side-effect , modify i
in same expression, unless there sequence point, unlikely find in beginner's code. i++
sufficient increment i
.
here how fix , complete code:
#include <stdio.h> int main(int argc, char *argv[]) { int i, n, age, total = 0; printf("how many numbers want add?\n"); if (scanf("%d", &n) == 1) { (i = 0; < n; i++) { printf("type in number:\n"); if (scanf("%d", &age) != 1) break; total = total + age; } printf("the sum %d\n", total); } return 0; }
Comments
Post a Comment