-1

Below is the prompt that I have:

Write a while loop that prints 1 to userNum, using the variable i. Follow each number (even the last one) by a space. Assume userNum is positive.

Ex: userNum = 4 prints: 1 2 3 4

I've tried a few things and below is the code that I have so far:

#include <iostream>
using namespace std;

int main() {
int userNum = 0;
int i = 0;

userNum = 4;    // Assume positive

cout<<("userNum = %d\n",userNum);
while(i != userNum) {
i++;
cout<<("%d",i);
}
cout << endl;

return 0;
}

The output is close to whats needed but its not correct and I cant seem to figure out what I did wrong.

the output is 41234

Could someone please guide me in the right direction as to what I did incorrectly?

freeWind
  • 148
  • 9
  • 1
    `cout` is not `printf`, so those format strings like `cout<<("%d",i);` aren't doing what you apparently think they will. Try `cout << i;` instead. – Jerry Coffin Mar 05 '16 at 01:21
  • 1
    @JerryCoffin: Well, they're doing what the OP wants to do, even if it's not at all how they actually work. Yay for the comma separated expressions evaluating to the final expression inside the parens? :-) – ShadowRanger Mar 05 '16 at 01:25
  • You are getting first 4 because of cout<<("userNum = %d\n",userNum); and to add spaces between 1..4 use cout<<("%d ",i); – Admir Sabanovic Mar 05 '16 at 01:32
  • @ShadowRanger: Yeah, I realize that this one is (though the `("userNum = %d\n",userNum)` almost certainly isn't), but it's all just a bit too strange and messy to let it stay. – Jerry Coffin Mar 05 '16 at 01:32

2 Answers2

1

The basic mechanism for this is something like this:

#include <iostream>

int main() {
    int i = 0;
    int userNum = 0;

    userNum = 4;
    while(i < userNum) {
        ++i;
        std::cout<<i<<" ";
    }
}

Output:

1 2 3 4

You could initialize userNum to be from cin if you'd like, naturally.

058 094 041
  • 495
  • 3
  • 6
1

The problem is because of this line: cout<<("userNum = %d\n",userNum).

cout does not support a formatting like that. And this resulted in a weird behaviour: it skipped the userNum = part and just printed userNum as int value, which is the first number 4 in your output.

Try to consider the following code instead:

#include <iostream>
using namespace std;

int main() {
    int userNum = 0;
    int i = 0;

    userNum = 4;    // Assume positive

    cout << "userNum = " << userNum << endl;
    while (i != userNum) {
        i++;
        cout << i;
    }
    cout << endl;

    return 0;
}

The output will be

userNum = 4 1234

as you would've expected. There are many other good sources on how to use string formatting out there. I'll give some links here but it should be easy for you to search them as well.

Link 1 - cplusplus.com - basic input/output

Link 2 - SOF

I hope it helped.

Community
  • 1
  • 1
Matt
  • 1,424
  • 1
  • 13
  • 17