C++ Converting a while loop to a do-while loop - c++

I see a ton a questions for converting for loops to while and do while loops, but I cant seem to find anything on converting while loops to do while loops in C++. It still needs to maintain the same function as the original code as well.
Here is the original code:
int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
while (number != 0)
{
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
}
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
By moving it around, I was able to end up here, but I keep ending up with errors. When I run the program, it prompts me to enter a while number, like expected. If I enter a valid number, it loops and asks me the same question. Then when I enter 0, it kicks out as usual, but it displays that the product is 0 no matter the numbers entered before.
Here is my attempt at adjusting it into a do while loop:
int main()
{
int number, product = 1, count = 0;
do
{
cout << "Enter a whole number to be included in the product" << endl << "or enter 0 to end the input: ";
cin >> number;
product = product * number;
count++;
}
while (number != 0);
{
if (count > 0)
cout << endl << "The product is " << product << "." << endl;
}
}

In the do .. while loop when you insert 0, first you multiply product by 0, than it exists. Therefore the product is always 0.
Move the product before:
int count = -1, number = 1, product = 1;
do
{
count++;
product = product * number; // you can use product *= number;
cout << "Enter a whole number to be included in the product" << endl << "or enter 0 to end the input: ";
cin >> number;
}
while (number != 0);
if (count > 0)
cout << endl << "The product is " << product << "." << endl;
Note: my code does not use additional if and still preserve the same functionality.

test number!=0 before assigning product = product*nuumber
otherwise, when user enters 0, you multiply by 0 and exit the loop

The problem is that in the do-while version, when the user inputs 0 this line:
product = product * number;
is executed, whereas in the while version not.
Because of this the product will always be 0.
If the number is 0 just don't multiply product.

Your problem was the number input on exit is 0, which makes your whole product equal to 0. Try this logic:
#include <iostream>
int main() {
int number = 0, product = 1, count = 0;
do {
std::cout << "Enter a whole number to be included in the product" << std::endl << "or enter 0 to end the input: ";
std::cin >> number;
if (number > 0) {
product = product * number;
count++;
}
} while (number != 0);
{
if (count > 0)
std::cout << std::endl << "The product is " << product << "." << std::endl;
}
}

If you just want to solve the problem that you are getting a 0 as your answer, then the problem is due to the following lines
cin >> number;
product = product * number;
you take the number which is 0 and multiply it with the product and obviously the result will be 0.
you can fix it by putting a break statement.
cin >> number;
if(number == 0)
break;
product = product * number;
However, in general I am not sure what you are achieving by trying to solve this problem i.e. converting a while to a do-while.

int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number; // you enter a non-0 number here
while (number != 0) // you now loop until you hit 0 ...
{
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number; // you overwrite the non-0 number you had previously input
}
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
Without knowing the full context of your program, I'm guessing here, but you can probably rewrite it as:
int number = 0, product = 1, count = 0;
do
{
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
if (number != 0)
{
count++;
product *= number;
}
} while (number != 0); // exit the loop when you have a non-zero entry
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
Or ...
int number = 0, product = 1;
do
{
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
if (number != 0)
{
product *= number;
}
} while (number != 0); // exit the loop when you have a non-zero entry
cout << endl << "The product is " << product << "." << endl;
You can avoid the 2nd condition since you are excluding 0 from potential inputs, and simply always output a product.

You are increasing count regardless of the input you get. First check if the input was zero (your abort input).
Change
count++
to
if (number)
count++;

Related

simple while loop calculator

Hello im stuck at SUBTRACTION AND DIVITION AND I CANT FIGURE OUT WHAT CODE to use because when I try to subtract 10 i inputed it then it will loop since the while condition is not meet which it needs to be negative to terminate the loop and i inputed 2 for the second number then loop again then i putted -number which lead to terminate loop and subtract all the number but the result is -12 its always wrong in every number cant figure out why Please help
Also with divition, only my addition is working havent started the divition cuz i cant figure out how
#include <iostream>
using namespace std;
int amt2, total;
double subNumbers();
double amt=1;
double number=0;
int main() {
int chc=0;
int amt = 0;
int amt2 = 1;
cout << "Welcome again User!\n";
cout << "______________________________________________________________\n" << endl;
cout << "Mathematical Operations(Improved):\n\n";
cout << "\t[1]-Addition" << endl;
cout << "\t[2]-Subtraction" << endl;
cout << "\t[3]-Multiplication" << endl;
cout << "\t[4]-Division\n" << endl;
cout << "______________________________________________________________\n" << endl;
cout << "Type the number corresponding to your chosen operation: ";
cin >> chc;
```
switch (chc) {
case 1:
```
system ("cls");
cout << "\n\n\tOperation chosen: Addition";
cout << "\n______________________________________________________________" << endl;
cout << "\n\nInput positive numbers to use the operation and input a negative number to end the operation.\n\n";
cout << "Enter your number: ";`
cin >> number;
while (number >= 0) {
// add all positive numbers
amt += number;
// take input again if the number is positive
cout << "Enter another number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum of all the numbers is: " << amt << endl;
break;
```
case 2:
system ("cls");
cout << "\n\n\tOperation chosen: Subtraction";
cout << "\n______________________________________________________________" << endl;
cout << "\n\nInput positive numbers to use the operation and input a negative number to end the operation.\n\n";
do{
cout << "Enter your number: ";
cin >> number;
amt=number-number ;
}while (number >= 0);// subtract all positive numbers
// display the difference
cout << "\nThe difference of all the numbers is: "<<amt;
return 0;
}}
```
enter code here
You are subtracting number from number:
amt = number - number; // Which is always 0
So that's why amt == 0 always.
So just change your loop to this:
while (true) {
cout << "Enter your number: ";
cin >> number;
if (number < 0) break;
if (amt == 0) amt = number;
else if (number >= 0) amt -= number;
}
What this does is that if amt == 0, then set amt to number. I have done this because as the default value of amt is 0 (due to int amt = 0;), when amt == 0, then we can assume that the user has entered the first number, and thus we can set amt to number. And then we can use -= operator, which basically means:
amt = amt - number;
But before all this, using if (number < 0) break; we can check if the user has entered a negative number, and if the user has entered a negative number, then the break keyword will break out of the while loop.

Trying to end for loop

I am trying to create a loop that allows the user to enter as many elements to the array as they would like then sum up those elements. I need the loop to terminate when the user enters a negative number. How would I go about terminating this?
double sum = 0;
double group[] = { 0 };
for (int i = 0; i >= 0; i++) {
cout << "Please enter employee salary. Enter negative number to end." << endl;
cout << "Employee " << i + 1 << ": $";
cin >> group[i];
if (i < 0) {
break;
}
sum += group[i];
}
cout << "The total salary ouput for Ernest Inc is: $" << fixed << showpoint << setprecision(2) << sum << endl;
I need the loop to terminate when the user enters a negative number.
For that a while loop would be better than for. You should also use vector which allows arbitrary number of items.
Something like this:
vector<double> group;
double salary;
while (true)
{
cout << "Please enter employee salary. Enter negative number to end." << endl;
cout << "Employee " << i + 1 << ": $";
cin >> salary;
if (salary<0)
{
break;
}
group.push_back(salary);
sum += salary;
}

How do I validate user input with c++?

Hey so this is really getting on my nerves.
I'm trying to validate user input within a loop.
I need the user input to be between 0 and 60. I can validate it no problem but what I want it to do is re-ask the previous question if the input is incorrect, you know? like repeat the loop if that makes sense
int main()
{
//Constants
const int MAXROUNDS = 4;
const int NUMARCHERS = 3;
//Variables
int archerNum;
int roundNum;
double score;
double total;
//Start of outer loop, this loop displays each Archer
for (archerNum = 1; archerNum <= NUMARCHERS; archerNum++)
{
total = 0; //This clears the total for the archer
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
cin >> score;
if (score < 0 | score > 60)
{
cout << "ERROR! Number must be between 0 and 60!";
}
}
total = score + score + score + score; //This calculates the total score for the tournament
cout << "\nThe total score for archer " << archerNum << " is: "
<< total << "\n\n";
}
return 0;
}
This is my code ^
Now I have tried so many things. I've looked through my textbook and I've googled everything but I cant seem to find the answer.
I've tried putting the error message in a do-while loop
i've used if-else statements
i've used while loops
I think I've literally used every different type of loop there is and I still cant seem to figure it out and I'm becoming very frustrated.
Thanks in advance
Here is a simple version of just the number input and error message:
//#include "pch.h" if using Visual Studio 2017
#include <iostream>
using namespace std;
int main(){
cout << "Please enter a number between 0 and 60." << endl;
int input;
cin >> input;
while(input < 0 || input > 60 || cin.fail()){ //Using cin.fail() here in case the user enters a letter or word
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cerr << "Number must be between 0 and 60. Please try again." << endl;
cin >> input;
}
return 0;
}`
Alternatively, you could use a goto statement though, as I am sure many others on this site will tell you, that is not recommended as it leads to the infamous 'spaghetti code'.
Simply add roundNum -= 1; inside the validation If statement. It will make the counter decreased by 1, and re-ask the previous question
//Start of second loop, this loop displays each round
for (roundNum = 1; roundNum <= MAXROUNDS; roundNum++)
{
std::cout << "Enter Round " << roundNum << " score for Archer "
<< archerNum << ": ";
std::cin >> score;
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!"<<endl;
roundNum -= 1; //or roundNum--
}
}
Try:
bool inputError;
do {
inputError = false;
std::out << "Enter Round "
<< roundNum
<< " score for Archer "
<< archerNum << ": ";
if (std::cin >> score) {
if (score < 0 || score > 60)
{
std::cout << "ERROR! Number must be between 0 and 60!";
inputError = true;
}
}
else {
std::cout << "ERROR! Your input must be a number";
inputError = true;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
} while(inputError == true);

How do you make a counter to count the number of even and odd numbers entered by user?

I have this code so far that is supposed to keep asking the user for a number until they type 0. Then the program will tell the user how many odds and evens they typed. I cannot get the latter function to work correctly. Any tips? I am a beginner, so please no advanced ways to solve this :D
#include <iostream>
using namespace std;
int main ()
{
int n;
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
return 0;
}
A couple things:
Code indentation (or lack thereof) makes this really hard to read. Indentation is not only cosmetic, but can help in understanding code.
You are setting the counter variables to zero each time the loop runs. Declare them outside of the loop so they retain their values.
The else clause of the if statement has erroneous syntax. Use a simple else instead, as there are only two cases for the parity of n.
When the user types 0 to exit the loop, it too is counted as an even integer. Add a condition in the if statement to account for this.
Applying these changes yields this code:
int n;
int myCounter1 = 0, myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do {
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0 && n != 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
} while (n!=0);
cout << "You entered " << myCounter1 << " even numbers, and " << myCounter2 << "odd numbers " << endl;
This
else n == 0
{
myCounter2++;
}
should be
else
{
myCounter2++;
}
Honestly, I don't even know why it didn't grab your attention, since it can't compile.
Also, you shouldn't set the counters to zero in the loop. So
int myCounter1, myCounter2;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
myCounter1 = 0;
myCounter2 = 0;
should be
int myCounter1=0, myCounter2=0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
And, finally, since you probably shouldn't count the 0 as one of the integers entered...
cout << "You entered " << myCounter1-1 << " even numbers, and " << myCounter2 << " odd numbers " << endl;
You have 2 bugs and 1 syntax error.
line:else n == 0 should be simply else
The 2 bugs are related to your counters:
1) You have to exclude the 0 input from the counters.
2) Every time you are reading a number your are setting them (the counters) to zero, which means that you will always ending with zero and one.
Here it is for anyone interested:
include
using namespace std;
int main ()
{
int n;
int myCounter1 = 0;
int myCounter2 = 0;
cout << "Odds and Evens\n\n" << endl;
do
{
cout << "Please enter an integer: ";
cin >> n;
if (n%2 == 0)
{
myCounter1++;
}
else
{
myCounter2++;
}
}
while (n!=0);
cout << "You entered " << myCounter2 << " odd numbers, and " << myCounter1-1 << " even numbers " << endl;
return 0;
}

for loop C++ Don't stop for Cin

shipname[0] = "Aircraft";
shipname[1] = "Battleship";
shipname[2] = "Destoryer";
shipname[3] = "Submarine";
shipname[4] = "Patrol Boat";
cout << "Do you wish to place your own ships. Y/N ";
cin >> Isplaceship;
if ((Isplaceship = "Y") | (Isplaceship = "y"))
{
for (int i = 0; i < 5; i++){
cout << "Please Enter a location for your " << shipname[i] << endl;
cout << "type row. col & direction(0 horizontal, 1 vertical) split by spaces: ";
cin >> x >> y >> dir;
cout << "your input is " << x << " " << y << " " << dir;
}
cout << endl;
}
else if ((Isplaceship = "N") | (Isplaceship = "n"))
{
};
}
So I want to make a battleship game, but in this stage i want the user input their input according the the ship, but it never stop and just display all the result in the shipname. I never can enter any input.
I did some coding myself:
int i = 0;
for (int i = 0; i <= 5; ++i)
{
cout << "input a number:" << endl;
cin >> i;
cout << "The number you input is:" << i << endl;
}
And the result is:
input a number:
1
The number you input is:1
input a number:
2
The number you input is:2
input a number:
3
The number you input is:3
input a number:
4
The number you input is:4
input a number:
5
The number you input is:5
I am not so sure why you would get that result, but I think you can compare my code to yours or do some other similar coding, which may help you figure out some details that you miss.
Change this: if ((Isplaceship = "Y") | (Isplaceship = "y")) to this: if ((Isplaceship == "Y") | (Isplaceship == "y")).