0
#include<stdio.h>

int main()
{
  int i, j;
  for(scanf("%d ",&i); i<=10; i++)
    printf("%d ",i);
  return 0;
}

I am a beginner in the programming world so please help me understand why on compiling the above C code it asks inputs twice.Maybe there's some logic to loop here I might be missing. Please help me understand.Thanks in advance.:)

gsamaras
  • 71,951
  • 46
  • 188
  • 305
shuberman
  • 1,416
  • 6
  • 21
  • 38

3 Answers3

4

Change this:

scanf("%d ",&i);

to this:

scanf("%d",&i);

Read more in What does space in scanf mean?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 2
    Thanks ..This is a very common mistake ...Now I know what was happening ...Thank you very much sir ... :) – shuberman Sep 10 '17 at 15:58
  • @user7841468 Better: don't use scanf at all. Always get input a line at a time (posix `getline`, or implement it yourself as a loop around `fgets`), and *then* parse it (possibly using `sscanf`) – o11c Sep 10 '17 at 17:18
0

Currencly, you placed scanf() in a for loop, which it asks for input for a 10 times.This will not happen when you remove scanf() from for loop.

0

I was facing the same problem and the only change I did was to change "%d " to "%d". This solves the problem.