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

Click For Summary
SUMMARY

The discussion focuses on creating a while loop in C++ that prints counting numbers from 1 to a specified positive integer, userNum. The initial code incorrectly decrements userNum instead of incrementing a separate variable, i. The correct implementation requires initializing i to 0 and using the condition i <= userNum, incrementing i with ++i within the loop to achieve the desired output format. The expected output for userNum = 4 is "1 2 3 4".

PREREQUISITES
  • Understanding of C++ syntax and structure
  • Familiarity with while loops in programming
  • Basic knowledge of variable initialization and incrementing
  • Experience with console output in C++ using cout
NEXT STEPS
  • Learn about C++ variable scope and lifetime
  • Explore different types of loops in C++, such as for and do-while loops
  • Study best practices for console output formatting in C++
  • Investigate error handling techniques in C++ for user input
USEFUL FOR

Beginner C++ programmers, educators teaching programming fundamentals, and anyone looking to understand loop constructs in C++.

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"
 

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
6K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K