1
#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.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Aryan Ragavan
  • 117
  • 1
  • 6

4 Answers4

2

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
Community
  • 1
  • 1
Enzo Ferber
  • 3,029
  • 1
  • 14
  • 24
  • Your answer was very useful . I wanna ask you about deep learning when it comes to C. I have just started learning C and i wanna get into the mood of deep learning.How should i do it? I m taking the help of video tutorials. – Aryan Ragavan Sep 04 '15 at 13:31
  • Learning each and everything from the scratch. Trying to know everything that is to be known about C. – Aryan Ragavan Sep 04 '15 at 13:40
  • @AryanRagavan Read the [K&R Book](http://tiny.cc/5ruv2x) then jump to [this site](http://www.cs.cf.ac.uk/Dave/C/). The thing with C is that it's a fairly **simple** language and shouldn't take you long to get how it works. But C was designed to build operating systems: that means you should understand how **computers work** in order to use it's full power. A good starting point on that is the excellent book (**WARNING PDF**) [Programming from the Ground Up](http://download-mirror.savannah.gnu.org/releases/pgubook/ProgrammingGroundUp-1-0-booksize.pdf), which will also teach you some Assembly. – Enzo Ferber Sep 04 '15 at 13:56
  • @AryanRagavan As for video tutorials, I can't help you. I never watched any introductory C video lectures, so I can't point good one. On some good stuff though, [Rusty Russel](https://en.wikipedia.org/wiki/Rusty_Russell) has some pretty nice videos on [YouTube](https://www.youtube.com/results?search_query=rusty+russell). – Enzo Ferber Sep 04 '15 at 14:01
1

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.

Reece Kenney
  • 2,734
  • 3
  • 24
  • 57
0

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);
}
Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
0

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;
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50