cloopsfor-loop

C FOR Condition


I need to create a simple program which asks for 10 numbers from user and then shows the sum of those numbers or, if the user gives 0 as input, stops and immediately displays the sum of those numbers, and I need to create it only by using a "for" condition. Here is the code:

#include <stdio.h>
int main(){
int num = 0;
for(num = 0; num < 10; num++){
    printf("Input a number: \n");
    scanf("%d", &num);
    if(num == 0){
        printf("Sum: %d\n", num);
    }
}
printf("Sum: %d\n", num);
getchar();
getchar();
}

It stops only when the number is greater than "10".Whats wrong?


Solution

  • I think you want to do this kind of work with your code.

    #include <stdio.h>
    int main(){
    int num = 0;
    int sum=0;
    for(num = 0; num < 10; num++){
       int i;
       printf("Input a number: \n");
       scanf("%d", &i);
       sum = sum+i;
       if(i == 0){
          printf("Sum: %d\n", sum);
          getchar();
          return 0;
       }
    }
    printf("Sum: %d\n", sum);
    getchar();
    return 0;
    }