// Lab 5 - loops.cpp Working with looping structures
// Trung Pham
#include <iostream>
usingnamespace std;
int main()
{
cout << "Trung Pham. \n";
cout << "\nActivity 1 \n==========\n";
// Change the following do-while loop to a while loop.
int inputNum;
while (inputNum != 0)
{
cout << "Enter a number (or 0 to quit): ";
cin >> inputNum;
}
cout << "\nActivity 2 \n==========\n";
// Change the following while loop to a do-while loop.
char doAgain = 'y';
do
{
cout << "Do you want to loop again? (y/n)";
cin >> doAgain;
} while (doAgain == 'Y' || doAgain == 'y');
cout << "\nActivity 3 \n==========\n";
// Change the following while loop to a for loop.
for (int count = 1; count <= 5; count++)
cout << "Count is " << count << endl;
cout << "\nActivity 4 \n==========\n";
// Change the following for loop to a while loop.
int x = 0;
while (x <= 5)
{
x > 0;
cout << x << " seconds to go. \n";
x++;
}
cout << "\nActivity 5 \n==========\n";
// Make the following changes to the code below that uses nested loops:
// 1. The code is supposed to print 3 lines with a $ and 5 stars on
// each line, but it contains a logic error. Find and fix the error.
// 2. Then revise the code to follow each $ with just 4 stars, like this:
// $****
// $****
// $****
// 3. Change the two loop control variable names to be more descriptive.
for (int i = 1; i <= 3; i++)
{
cout << '$';
for (int j = 1; j <= 5; j++)
cout << '*';
}
cout << endl;
return 0;
}
int main()
{
cout << "Trung Pham. \n";
cout << "\nActivity 1 \n==========\n";
// Change the following do-while loop to a while loop.
int inputNum;while (inputNum != 0)
{
cout << "Enter a number (or 0 to quit): ";
cin >> inputNum;
}
Right here, on line 11 of your source code is the problem. You declare the variable, but do not give it any initial value. When you compare it to "0" on the next like, there's no way of knowing what the value of "inputNum" is. It could very well actually have the value of zero.
Your compiler is letting you know that you could get some unexpected behavior.
Try initializing the variable to some value that you know won't cause an issue in your program.
Try this:
1 2 3 4 5 6 7 8 9 10 11
int main()
{
cout << "Trung Pham. \n";
cout << "\nActivity 1 \n==========\n";
// Change the following do-while loop to a while loop.
int inputNum = 0;
do
{
cout << "Enter a number (or 0 to quit): ";
cin >> inputNum;
} while(inputNum != 0);
You could also assign "inputNum" to some other value, like -1
1 2 3 4 5 6 7 8 9 10 11
int main()
{
cout << "Trung Pham. \n";
cout << "\nActivity 1 \n==========\n";
// Change the following do-while loop to a while loop.
int inputNum = -1;
while (inputNum != 0)
{
cout << "Enter a number (or 0 to quit): ";
cin >> inputNum;
}