C++: Using a for loop to print a countdown

  • Context: C/C++ 
  • Thread starter Thread starter needOfHelpCMath
  • Start date Start date
  • Tags Tags
    Loop
Click For Summary
SUMMARY

The discussion focuses on writing a C++ program that utilizes a for loop to print a countdown from a user-defined number to "Blastoff!". The original code incorrectly resets the value of userNum within the loop, leading to incorrect output. The corrected version initializes a separate variable, i, to iterate from userNum down to 1, ensuring the countdown functions as intended. The final output correctly displays the countdown followed by "Blastoff!".

PREREQUISITES
  • Understanding of C++ syntax and structure
  • Familiarity with for loop constructs in C++
  • Basic knowledge of input and output operations using iostream
  • Ability to troubleshoot and debug simple C++ programs
NEXT STEPS
  • Explore C++ variable scope and lifetime
  • Learn about different loop types in C++, including while and do-while loops
  • Investigate error handling and debugging techniques in C++
  • Practice writing functions in C++ to modularize code
USEFUL FOR

C++ beginners, educators teaching programming fundamentals, and developers looking to improve their understanding of control structures in C++.

needOfHelpCMath
Messages
70
Reaction score
0
Write code that prints: userNum ... 2 1 Blastoff! Your code should contain a for loop. Print a newline after each number and after Blastoff!. Ex: userNum = 3 outputs:
3
2
1
Blastoff!

Code:
#include <iostream>
using namespace std;
int main() {
   int userNum = 0;
   int i = 0;
   userNum = 3;
   i = 1;
   for (userNum = 3; 1 <= userNum; --userNum) {
   cout << userNum << endl;   
   
   }
 cout << "Blastoff!" << endl;
   return 0;
}

Run
Testing with userNum = 3.
Your output: 3
2
1
Blastoff!
✖ Testing with userNum = 1.
Expected output: 1
Blastoff!
Your output: 3
2
1
Blastoff!
 
Technology news on Phys.org
Re: So close what is wrong with my program

You are resetting the value of [m]userNum[/m] when you begin the for loop. This is how I would write the program:

Code:
#include <iostream>
using namespace std;
int main()
{
	int userNum = 3;
	int i;

	for (i = userNum; i > 0; i--)
	{
		cout << i << endl;   
	}

	cout << "Blastoff!" << endl;
	return 0;
}

Please note that I have edited your thread title to describe the nature of the question being asked, and enclosed your code in the [CODE][/CODE] tags so that whitespaces are preserved and the indentation will enhance readability. :)
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
13K
  • · Replies 2 ·
Replies
2
Views
8K
  • · Replies 4 ·
Replies
4
Views
11K
  • · Replies 28 ·
Replies
28
Views
30K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 3 ·
Replies
3
Views
10K
  • · Replies 2 ·
Replies
2
Views
12K
  • · Replies 15 ·
Replies
15
Views
4K
Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K