MHB Using a while loop to print the counting numbers up to a set value

Click For Summary
The discussion focuses on correcting a while loop in C++ that is intended to print numbers from 1 to a given positive integer, userNum. The initial code incorrectly counts down from userNum instead of counting up. To fix this, the loop should use the variable i as an index, starting from 1 and incrementing until it exceeds userNum. The correct implementation involves initializing i to 1, using a while loop that checks if i is less than or equal to userNum, and printing i followed by a space. This adjustment ensures the output matches the expected format, displaying numbers in ascending order.
needOfHelpCMath
Messages
70
Reaction score
0
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

Code:
#include <iostream>
using namespace std;

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

   userNum = 4;    // Assume positive
   
   
while ( userNum > i) {
cout << userNum << " ";
userNum = userNum - 1;
}

   cout << endl;

   return 0;
}
Run
✖ Testing with userNum = 4
Expected output: 1 2 3 4
Your output: 4 3 2 1
 
Technology news on Phys.org
Re: What i am doing wrong?

You need to use [m]i[/m] to "index" your while loop, which should run as it is less than or equal to [m]userNum[/m]. Since [m]i[/m] is initialized to zero, you will want to increment it before the comparison, using [m]++i[/m], and then you will not need to increment it within the loop, you will only need to print its value along with the trailing space.
 
Re: What i am doing wrong?

MarkFL said:
You need to use [m]i[/m] to "index" your while loop, which should run as it is less than or equal to [m]userNum[/m]. Since [m]i[/m] is initialized to zero, you will want to increment it before the comparison, using [m]++i[/m], and then you will not need to increment it within the loop, you will only need to print its value along with the trailing space.

"Awesome To The Max"
 
Anthropic announced that an inflection point has been reached where the LLM tools are good enough to help or hinder cybersecurity folks. In the most recent case in September 2025, state hackers used Claude in Agentic mode to break into 30+ high-profile companies, of which 17 or so were actually breached before Anthropic shut it down. They mentioned that Clause hallucinated and told the hackers it was more successful than it was...

Similar threads

  • · Replies 1 ·
Replies
1
Views
6K
  • · Replies 2 ·
Replies
2
Views
13K
  • · Replies 4 ·
Replies
4
Views
11K
  • · Replies 28 ·
Replies
28
Views
30K
  • · Replies 4 ·
Replies
4
Views
5K
Replies
12
Views
3K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 66 ·
3
Replies
66
Views
5K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K