russjohnson09
russjohnson09

Reputation: 271

C adding input with while loop

This is my first time programming in c. I have this code that is supposed to take whatever numbers the user types in until the enter a 0. Then it should add them all up. For example if they type in 1, then 2, then 3, and finally 0, it should print out 6. But for some reason it does not add the last value. In the case I mentioned it would print 3 instead of 6.

#include <stdlib.h>
#include <stdio.h>

static char syscall_buf[256];
#define syscall_read_int()          atoi(fgets(syscall_buf,256,stdin))

main()
{
    int input;
    input = syscall_read_int();

    int result = 0;
    input = syscall_read_int();
    while (input != 0){
        result = result + input;
        input = syscall_read_int();
    }
    printf("%i\n", result);
}

Upvotes: 1

Views: 3046

Answers (3)

Federico
Federico

Reputation: 3892

You have an extra syscall_read_int() at line 10. Anyway I suggest you to use a do-while loop because you need to read at least one integer. The following code with do-while loop works: 1 + 2 + 3 + 0 = 6

#include <stdlib.h>
#include <stdio.h>

static char syscall_buf[256];
#define syscall_read_int()          atoi(fgets(syscall_buf,256,stdin))

main()
{
    int input;
    int result = 0;

    do {
        input = syscall_read_int();
        result = result + input;
    } while(input != 0);

    printf("%i\n", result);
}

Upvotes: 1

teppic
teppic

Reputation: 8195

As your program is written it would be missing the first value you enter (which it's doing nothing with) rather than the last, so if you input 1, 2, 3 it'd return 5, not 3. Are you running a version with an extra syscall_read_int() at the end of the code?

Upvotes: 0

Cacho Santa
Cacho Santa

Reputation: 6914

You have an extra call of this function: syscall_read_int(). Try to debug and see what is happening.

You were overwriting the value of the variable int input; consequently, you were not adding the first value to the variable int result in the particular case you mentioned:

Insert 1, then 2, then 3 and finally 0. The first value - 1 -, was not being added so the program prints 5 (2 + 3) instead of 6 (1 + 2 + 3).

That is the problem, try this:

#include <stdlib.h>
#include <stdio.h>

static char syscall_buf[256];
#define syscall_read_int()          atoi(fgets(syscall_buf,256,stdin))

main()
{
    int input;
    //input = syscall_read_int(); //you need to comment this line
    int result = 0;
    input = syscall_read_int();
    while (input != 0){
        result = result + input;
        input = syscall_read_int();
    }
    printf("%i\n", result);
}

Hope it helps!

Upvotes: 1

Related Questions