0

I've tried to refractor my very very easy programm (I'm beginner, sorry for stupidity). I wanted to put scanf() into first paragraph of loop initialization and I thought that everything would have been alright but it doesn't work as I had "predicted". The programm should get and intiger and then write following numbers till the last number would be 10 times bigger tahn the first one but instead of this it writes out numbers from 1 to the number 10 times bigger. I would be grateful for any tips and debugg. Have a nice day!

Code:

 #include <stdio.h>
int main()
{
  int x, i;

  printf("Please put intiger:\n");

  for(i = (scanf("%d", &x)); i < x + 10; i++)
    printf("%d\n", i);

  return 0;


}

Execution:

Please put intiger: 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Press any key to continue . . .

1 Answer 1

1

scanf returns the number of values it has successfully scanned, not the value of input you have given. But what you wanted is to to print 10 numbers starting x.

You'd need:

scanf("%d", &x);
for (i = x; i < x + 10; i++) 
    printf("%d\n", i);

Read the documentation of scanf for what it returns. Also remember scanf could fail too.

Sign up to request clarification or add additional context in comments.

3 Comments

Re "Also remember scanf could fail too": Which is why you always check the return value and balk if it is not what you expect.
Thank you very much, firstly i had done it like u have shown but i thought i can make it easier, now i will remember i cannot:(
By "easier" you mean, combine the input in the loop itself, you can do with comma operator: for (i = (scanf("%d", &x), x); i < x + 10; i++) But I wouldn't call this easier or recommend. This also doesn't allow error checking of scanf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.