Aryan Ragavan
Aryan Ragavan

Reputation: 117

Sum of n numbers

#include <stdio.h>

int main()
{   
    int m,i,sum,num;

    i=0;
    sum=0;
    scanf("%d ",&m);
    while(i<m){
        scanf("%d ",&num);

        sum=sum + num;

        i=i+1;
        printf("Value of sum= %d\n",sum);
        //continue;
    }
    printf("Sum= %d ",sum);
}

In the above code it should display the sum of n numbers. But in my code it is taking one extra value of m (m is number of values to take to compute the sum).

For example if I take m as 3 it takes 4 input and displays the sum of 3.

Upvotes: 1

Views: 385

Answers (4)

Enzo Ferber
Enzo Ferber

Reputation: 3094

As others(@BLUEPIXY and @BillDoomProg) have already pointed in the comments, your problem is the space in your scanf format string. Also check this answer.

Change both your scanf format string from:

scanf("%d ",&m);
...
scanf("%d ",&num);

To:

scanf("%d", &m);
...
scanf("%d", &num);

Just remove the space and it will work fine.

scanf()

From the manual

The format string consists of a sequence of directives(...)

A directive is one of the following:

A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.

Also note that stdin is buffered, so the results are a little different from what you would expect:

man stdin

Notes

The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline is printed. This can produce unexpected results, especially with debugging output. The buffering mode of the standard streams (or any other stream) can be changed using the setbuf(3) or setvbuf(3) call. Note that in case stdin is associated with a terminal, there may also be input buffering in the terminal driver, entirely unrelated to stdio buffering. (Indeed, normally terminal input is line buffered in the kernel.) This kernel input handling can be modified using calls like tcsetattr(3); see also stty(1), and termios(3).

So, lets examine your program step by step.

Your program starts running and you enter the number 2. This is what the input buffer looks like:

2\n

scanf("%d ", &m) assigns 2 to the m variable and starts trying to match a space. It gets a NL and EOL. Control is still with this scanf because it just matched a newline (considered a white-space) and is waiting to match more, but instead it got the End-Of-Line, so it is still waiting when you type:

1\n

Then reads stdin again and realizes that the next character in the input stream is not a space and returns (it's format string condition was done). At this point, you enter the loop and your next scanf("%d ",&num) is called and it wants to read an integer, which it does: it reads 1 and stores that in the num variable. Then again it starts matching white-spaces and gets the new-line and it repeats the above pattern. Then when you enter:

2\n

That second scanf gets a character different than a white-space and returns, so your loop scope keeps executing printing the current sum. The loop break condition is not met, so it starts again. It calls the scanf and it effectively reads an integer into the variable, then the pattern repeats itself...

3\n

It was waiting for a white-space but it got a character instead. So your scanf returns and now the loop break condition is met. This is where you exit your loop, prints the whole sum and get that weired felling that it "added" 3 numbers but the sum is adding only the first 2 (as you intended in the first place).

You can check that 3 hanging in stdin with a simple addition to your code:

#include <stdio.h> 

int main()
{

    int m, i, sum, num;
    char c;

    i = 0;
    sum = 0;
    scanf("%d ", &m);

    while (i < m) {
        scanf("%d ", &num);

        sum = sum + num;

        i = i + 1;
        printf("Value of sum= %d\n", sum);
    }

    while((c = getchar()) != '\n') 
        printf("Still in buffer: %c", c);

    return 0;
}

That will output (with the above input, of couse):

$ ./sum1
2
1
2
Value of sum= 1
3
Value of sum= 3
Still in buffer: 3

Upvotes: 2

Shreevardhan
Shreevardhan

Reputation: 12641

A refactored code will look like this

#include <stdio.h>

int main() {
    int m, num, sum = 0;
    scanf("%d", &m);    // Let scanf automatically skip whitespace
    while (m--) {
        scanf("%d", &num);
        sum += num;
    }
    printf("Sum= %d\n", sum);
    return 0;
}

Upvotes: 0

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

It's causes of extra space in scanf(). Change scanf("%d ",&num) to scanf("%d",&num)

From Scanf(), fscanf(), You can follow this.

The scanf() family of functions reads data from the console or from a FILE stream, parses it, and stores the results away in variables you provide in the argument list.

The format string is very similar to that in printf() in that you can tell it to read a "%d", for instance for an int. But it also has additional capabilities, most notably that it can eat up other characters in the input that you specify in the format string.

You should write:

int main()
{
    int m,i,sum,num;

    i=0;
    sum=0;
    scanf("%d",&m);
    while(i<m){
        scanf("%d",&num);

        sum=sum + num;

        i=i+1;
        printf("Value of sum= %d\n",sum);
        //continue;
    }
    printf("Sum= %d ",sum);
}

Upvotes: 0

Reece Kenney
Reece Kenney

Reputation: 2964

This is because you have a space after your %d in the scanf lines.

Change

scanf("%d ",&num);

To

scanf("%d",&num);   

Scanf usually ignores whitespaces, so you don't want spaces in your format strings.

Upvotes: 1

Related Questions