-6

in my code according to for loop Condtion it is clear that it must iterate only 5 times from 0 to 4. But it is taking 6 input from the user. Why it is happening. Please clear my doubt.

  #include <stdio.h>
#include <conio.h>
void main() {
  int i, num;
  clrscr();
  printf("Enter 5 elements in the array\n");
  for (i = 0; i < 5; i++) {
    scanf("%d\n", &num);
  }
  getch();
}
Samual
  • 67
  • 9

3 Answers3

1

According to your code i think you are mixing up the inputs you request with the system pause created by the getch() function you call at the end. The getch() initiates a pause which you can easily mix up with your input prompts since during this pause, user input is possible though not considered. I propose you introduce an instruction in the loop which indicates the line or some information so you can make the distinction.

1

You have two problems regarding input.

The first is the getch call at the end of the program. But the other problem is the newline in the scanf format string

scanf("%d\n",&num);

When the scanf function sees a space in the format string (newline is considered a space in this context) then it will read and discard all spaces in the input. The problem with a trailing space in a format string is that to know when the spaces in the input ends, there must be some non space input as well.

So (almost) never have a trailing space (space, newline, carriage-return, tab) in a scanf format string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The reason this code wait 5 times user input is the getch() at the end. It waits for the input of one character and probably used to prevent the shell window from directly closing after the program finshed.

MofX
  • 1,569
  • 12
  • 22