1

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);
}
1
  • 1
    Get rid of the extraneous input = syscall_read_int(); line. Commented Aug 28, 2012 at 22:34

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.