fakhri96
fakhri96

Reputation: 7

C programming: Trouble summing numbers entered by the user with for loop

So, I have to write a program to ask the user for an integer, and then that integer will determine how many more entries the user gets before adding all the numbers that were entered. So, if the first entered integer is "5", then the user can enter 5 more integers. Those 5 integers are then added together at the end and displayed. I have written a program with for loops, but for some reason, it is only adding first 4 integers and not the 5th one. Here is the code:

int main() { //declare main function

       int c=0,n,i; //declare integers
       int sum=0;

       printf("\nEnter an integer: "); //ask user for input and create a label
       scanf("%d",&n);


       if (n>=0) { //use if statement

           for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers

           {
               sum+=c;
               printf("Enter an integer: ");
               scanf("%d",&c);
           }

       }

       else {

           printf("Wrong number. You can only enter positive integers!");

       }


       printf("The sum of the %d numbers entered is: %d",i,sum);

       return 0;
}

Upvotes: 0

Views: 608

Answers (2)

0___________
0___________

Reputation: 68079

It is good to split the program. use functions. Not everything in the main function.

int getInteger(void)
{
    char str[100];
    int number;

    while(!fgets(str, 100, stdin) || sscanf(str, "%d", &number) != 1)
    {
        printf("Wrong input. Try again:")  ; 
    }
    return number;
}

int main()
{
    int nsamples;
    long long sum = 0;

    printf("Enter number of samples:");
    while((nsamples = getInteger()) <= 0)
    {
        printf("Try again, entered number must be >= 0\n");
    }

    printf("Enter numbers:\n");
    for(int i = 1; i <= nsamples; i++)
    {
        printf("Sample no %d:", i);
        sum += getInteger();
    }
    printf("The sim is: %lld\n", sum);
}

Upvotes: 0

heeat
heeat

Reputation: 158

Just change the position of

sum+=c; 

to after the scanf it should work.

Upvotes: 1

Related Questions