0

"Write a for loop that prints the integers 1 through 40, separated by spaces or new lines. You may use only one variable, count which has already been declared as an integer."

So I use...

for(count = 1; count <= 40; count++)
{
    cout << " " << count;
}

but they are using stdio.h as the only header and cout is not recognized. It hints that the output format should be (" ",count), but I can't figure out what print function to use. stdio.h can use fprintf or fwrite, but I don't have enough parameters for either function. Any ideas?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Chris
  • 41
  • 2
  • 5
  • 3
    I suspect that's suppose to be for C, and you'd use `printf`. (Though you can use `` in C++ and `std::printf`.) In any case, you might want one of our [recommended C++ books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – GManNickG Dec 31 '10 at 06:39
  • 1
    I would say "separated" means that you shouldn't have a leading space. There's a question here on stackoverflow about the best way to do that. – Ben Jackson Dec 31 '10 at 06:44
  • 1
    Also, cout is a variable too, and the use of the variables other than "count" is prohibited by the exercise. I think that 'printf' is the option. – mbaitoff Dec 31 '10 at 06:45

3 Answers3

1

You can use printf():

int count;
for (count=1; count<=40; count++)
{
    printf("%d ", count);
}
more on that here: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Mark
  • 2,082
  • 3
  • 17
  • 30
  • yeaaa count was already declared but I was unaware of printf.... thought it was fprintf... but I now notice the printf function on the cplusplus.com reference page... was the %d whitespace? – Chris Dec 31 '10 at 07:01
  • fprintf will print the numbers to a file, and it also takes an extra argument. You can find that on cplusplus.com – Mark Dec 31 '10 at 07:04
  • The %d indicates to the function that you want an integer value, so for example printf("%d, %d", 5, 10); would produce the output "5, 10" – Mark Dec 31 '10 at 07:06
  • What would result in the whitespace it requires... as /n isnt accepted. – Chris Dec 31 '10 at 07:20
  • simply put a space right after %d. Anything you put there that isn't right after the % is written exactly as is. So the above code will generate the whitespace you need because there's a space right after the %d. – Mark Dec 31 '10 at 07:35
0

You can cheat on the last item so it doesn't have the trailing space/newline/comma etc...

int count;
for( count = 1; count <= 39; count++ )
{
    printf( "%d ", count );
}
printf( "%d\n", ++count );

If this is homework, ignore my answer and figure it out for yourself! :)

JimR
  • 15,513
  • 2
  • 20
  • 26
-1

You are thinking too much try this.

for (count = 1; count <= 40; count++)
{
    cout << count << endl;
}
Tiny
  • 27,221
  • 105
  • 339
  • 599
Carlos
  • 1