0

Below is my program.

    #include<stdio.h>
int main(){
int i,n,m;
int sum=0;
scanf("%d",&n);
for(i=0;i<n;i++){
    printf("Enter the %d mark:\n",i+1);
    scanf("%d\n",&m); //here I used \n 
    sum=sum+m;
}
printf("%d\n",sum);
printf("%.2lf",(double)sum/n);
return 0;
}

The output I got is like

  3
 Enter the 1 mark:
 3
 4
 Enter the 2 mark:
 2
Enter the 3 mark:
5
9
3.00

what is the effect of \n in the scanf for this output?

sonicbuzz
  • 5
  • 2
  • Can't reproduce. Did you copypaste this output, or did you type it by hand? – HolyBlackCat May 29 '21 at 06:21
  • I just pasted the output. – sonicbuzz May 29 '21 at 06:23
  • Sorry, but I don't believe that you have those leading spaces in the output. – HolyBlackCat May 29 '21 at 06:24
  • that I just did for pasting in this site as a code block. – sonicbuzz May 29 '21 at 06:27
  • My doubt is when I put \n near the format specifier, the first time it goes to newline (first loop execution) but for the rest of the execution it didn't. why? – sonicbuzz May 29 '21 at 06:31
  • Have you read the links? Any whitespace in the format string is *significant*. – Weather Vane May 29 '21 at 06:33
  • When you call scanf for the first time, the input stream is empty. When you call it the second time, even though you entered 2 lines, the second number hasn't been processed yet and remains in the input stream, and scanf receives it first, then whatever you entered in the third line. Regarding the spaces: they confused me at first, I thought you were asking about them. You might wanna use a consistent amount of spaces to keep the text aligned. – HolyBlackCat May 29 '21 at 06:35
  • You can format text as code by "selecting" it and clicking the `{}` button. – Weather Vane May 29 '21 at 06:39
  • Thank u ! @HolyBlackCat Now I got it. Btw sorry for that alignment. – sonicbuzz May 29 '21 at 06:40
  • @WeatherVane yeah..will do it from next time :) – sonicbuzz May 29 '21 at 06:41

0 Answers0