how to turn if else statement to a switch statement [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i want to know how to turn this if else statement to a switch statement.this is a c++ program to out put the integers in the right order. i can't figure out a way.please help.thank you in advance.
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (x <= y && y <= z)
cout << x << " " << y << " " << z << endl;
else if (x <= z && z <= y)
cout << x << " " << z << " " << y << endl;
else if (y <= z && z <= x)
cout << y << " " << z << " " << x << endl;
else if (y <= x && x <= z)
cout << y << " " << x << " " << z << endl;
else if (z <= x && x <= y)
cout << z << " " << x << " " << y << endl;
else
cout << z << " " << y << " " << x << endl;
if (x <= y) {
if (z <= x) {
cout << z << " " << x << " " << y << endl;
} else {
if (z <= y) {
cout << x << " " << z << " " << y << endl;
} else {
cout << x << " " << y << " " << z << endl;
}
}
} else {
if (z >= x) {
cout << y << " " << x << " " << z << endl;
} else {
if (y >= z) {
cout << z << " " << y << " " << x << endl;
} else {
cout << y << " " << z << " " << x << endl;
}
}
}

That is not a good way to write a program. What if you need 4 integers?
One way to do it would be to use a list like std::vector and sort it.
vector<int> numbers;
int number = 0;
while (numbers.size() < 3 && cin >> number)
numbers.push_back(number);
sort(cbegin(numbers), cend(numbers)); // sorts ascending by default
for (auto number : numbers)
cout << number << " ";
cout << endl;
You can also use std::multiset which sorts its items automatically as they are inserted.

Instead of this approach, why don't you store the input in an array and try any of the sorting alogrithms to sort your input?

The answer in your particular case is you can't,
Your if statements have particular conditions, which,
wouldn't really work inside a switch.
An example of if/else if/else statements that can be
translated into a switch would be:
if(i == 1) {
// code here
} else if(i == 2) {
// code here
} else if(i == 3) {
// code here
} else {
// code here
}
which would translate to:
switch(i) {
case 1:
//code here
break;
case 2:
//code here
break;
case 3:
//code here
break;
default:
//code here
break;
}
Hope that helps a bit to understand a little more about switch statements.

If the challenge is that you can't sort the numbers, and the limit is 3 integers, then there are better ways to accomplish what you're doing.
#include <iostream>
using namespace std;
int main()
{
int combo[6][3] = {{0,1,2},{0,2,1},{1,0,2},{1,2,0},{2,0,1},{2,1,0}};
int values[3];
cin >> values[0] >> values[1] >> values[2];
for (int i = 0; i < 6; ++i )
{
if ( values[combo[i][0]] <= values[combo[i][1]] &&
values[combo[i][1]] <= values[combo[i][2]] )
{
cout << values[combo[i][0]] << " " << values[combo[i][1]] <<
" " << values[combo[i][2]];
break;
}
}
}
The combo array holds all of the combinations that can occur with 3 slots. Also note that the input is an array. Even if you didn't use the loop, the maximum if() statements you would need is 6.
However you should mention up front that this is a challenge, and what the restrictions are. Otherwise, please look at the other answers concerning storing and sorting these numbers.

You only need three conditional swaps to sort a list of three elements:
int x, y, z;
cout << "please enter three integers:";
cin >> x >> y >> z;
if (y < x) swap(y, x);
if (z < y) swap(z, y);
if (y < x) swap(y, x);
cout << x << " " << y << " " << z << endl;
Note that this approach doesn't scale. For 10 numbers, you would already need 45 conditional swaps.

Related

How to find out why my program keeps having an infinite loop?

I can't seem to find what's wrong with my code, I'm trying to end the loop once the answers is equals to 0 but it keeps going on an infinite loop.
#include <iostream>
int main() {
using namespace std;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do{
while ( x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
while (x % 2 == 0)
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
}
while (x >= 0);
}
There are, essentially, two problems in your code, both of which, in themselves, will make your loop run endlessly.
Starting from the outside and working inwards: The test at the end of your (outer) while loop will always be "true", as you have while (x >= 0); so, even when x gets to zero (as it will), the loop will keep running! (And, once x is zero it will remain zero!)
Second, the two 'inner' while loops shouldn't be loops at all! You want one or the other 'block' to run once only for each main loop - so use an if ... else structure.
The following is a corrected version of your code:
#include <iostream>
int main() {
// using namespace std; // Generally, not good practice (and frowned-upon here on SO)
using std::cin; using std::cout; using std::endl; // Use only those you want to!
using std::string;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;
do {
if (x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
else // if (x % 2 == 0) ... but we don't need to test this again.
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}
There are a few other things that could be changed to make the code more "efficient," but I'll let you peruse the MNC (Minimum Necessary Change) before we start editing towards a BPC (Best Possible Code)!
EDIT: OK, due to 'peer pressure' from comments 😊, I'll put in a suggested BPC now:
#include <iostream>
int main() {
using std::cin; using std::cout; using std::endl; // Use only those you want to!
int x;// , remainder; // "remainder" is never used, so we can discard it!
cout << "Please enter a positive integer number: " << endl;
cin >> x; // Not critical, but I like to put such a cin right after the prompting cout.
std::string tab{ "\t" }; // Let's initialise more directly!
do {
// As there is only one line (now) inside each if/else block, we can leave out the {} ...
if (x % 2 != 0)
cout << x << " is odd" << tab << "Subtract 1" << tab << "Half of " << x - 1 << " is " << x / 2;
else
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
// We can put the following two line outside the tests, as they will be the same in both cases:
x = x / 2; // When x is ODD, this will give the SAME answer as x = (x - 1)/2 (as you noticed in your first cout)
cout << endl;
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}

How to print the and update the scoreboard on the same line here?

#include <iostream>
#include <cstdlib>
#include <iomanip>
int Human_Roll() {
int num1;
srand(time(0));
num1 = (1 + rand() % 6);
return num1;
}
int Human_Roll_2() {
int num2;
num2 = (1 + rand() % 6);
return num2;
}
int Computer_Roll() {
int num3;
num3 = (1 + rand() % 6);
return num3;
}
int Coumputer_Roll_2() {
int num4;
num4 = (1 + rand() % 6);
return num4;
}
int main() {
int counter1 = 0, counter2 = 0;
char start;
for (int i = 1; i <= 150; i++) {
std::cin >> start;
int x1{ Human_Roll() };
int x2{ Human_Roll_2() };
int y1{ Computer_Roll() };
int y2{ Coumputer_Roll_2() };
int x;
int y;
x = x1 + x2;
y = y1 + y2;
std::cout << "\nYou: " << x1 << " + " << x2 << " = " << x << "\n\n";
std::cout << "Computer: " << y1 << " + " << y2 << " = " << y << "\n";
if (x > y) {
std::cout << "\nYou win." << "\n";
++counter1;
}
if (y > x) {
std::cout << "\nYou lose. " << "\n";
++counter2;
}
if (x == y) {
std::cout << "\nDraw. " << "\n";
counter1 += 0;
counter2 += 0;
}
std::cout << " Scoreboard: " << counter1 << " - " << counter2 << "\n";
if (counter1 == 7) {
std::cout << "\n\n Victory! " << "\n";
break;
}
if (counter2 == 7) {
std::cout << "\n\n Loss! " << "\n";
break;
}
}
This is a supposed to be a dice game that calculates the sum of two randomly generated sides of the 6 sided dices. It does it two times and compares the sums to pick the winner with the bigger sum, and it should print out the scoreline every time the the winner is declared. My question is, how can I make the scoreline be updated on the same line as the game continues and not print "scoreboard x - y " every time the round is finished?
Hi from what I' m understanding you want o clear the console like this std::cout << "\033[2J\033[1;1H"; so when you roll the dices again the code comes in the same place but before you do this you need to stop the console make it wait for input and say something like "Press enter to play again" then the console clears and the next game comes in the same place or you can use something like Sleep(milliseconds); before cleaning.
Hope this is what you looking for.
As #enhzflep said this will end up being more than complicated solution for the system dependent code.
However the easy and quick solution is for visually having the same line being updated is to create many empty lines for every for loop iteration.
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
As i said earlier this is the best c++ could do when there is no system information available. Using the standard commands.
updated for loop would look like
for (int i = 1; i <= 150; i++) {
int x1{ Human_Roll() };
int x2{ Human_Roll_2() };
int y1{ Computer_Roll() };
int y2{ Coumputer_Roll_2() };
int x;
int y;
x = x1 + x2;
y = y1 + y2;
std::cout << " ----- Game " << i << " -----";
std::cout << "\nYou: " << x1 << " + " << x2 << " = " << x << "\n";
std::cout << "Computer: " << y1 << " + " << y2 << " = " << y << "\n";
if (x > y) {
std::cout << "\nYou win." << "\n";
++counter1;
}
if (y > x) {
std::cout << "\nYou lose. " << "\n";
++counter2;
}
if (x == y) {
std::cout << "\nDraw. " << "\n";
counter1 += 0;
counter2 += 0;
}
std::cout << "---------------------------------------------"
std::cout << "Scoreboard: " << counter1 << " - " << counter2 << "\n";
if (counter1 == 7) {
std::cout << "\n\n Victory! " << "\n";
break;
}
if (counter2 == 7) {
std::cout << "\n\n Loss! " << "\n";
break;
}
for (int n = 0; n < 50; n++)
{
std::cout << "\n";
}
}
There are other ways to do it such as
Sysetm call to clear the terminal
but this method not safe why
The standard way to print end lines
Using the curser library #include <curses.h>
Advantage it is a cross-platform but can not be mixed with standard I/O

Calculation after the for loop is incorrect (C++)

The code I am currently working on is a random walker. The code represents a person taking a step in any random direction (up,down,left,right), then the new location is printed out respectively. In the beginning the user is prompted to enter any amount of steps or how many times the loop should be iterated. The goal of the code is to calculate the squared distance between (0,0)initial and (x,y)final. The distance should be equal to (xx)+(yy) because the initial position that would normally be subtracted is (0,0). The issue or semantic issue I am running into is with the distance calculation. The calculation is not always using the correct x or y value. For example if the final location was (0,-4), somehow x = -1, therefore the distance equals 17 instead of 16. This first example is in image 1. Image 2 is another run for the code. Any help or tips would be greatly appreciated, here is the code:
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
for(int i = 0; i <= N; i++) {
cout << "(" << x << ", " << y << ")" << endl;
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
}
int d = (x*x)+(y*y);
cout << "the distance equals: " << d << endl;
cout << endl;
cout << "x equals before: "<< x << endl;
x = (pow(x,2));
cout << "x equals after squaring: "<< x << endl;
cout << endl;
cout <<"y equals before: " << y << endl;
y = (pow(y,2));
int sum = x + y;
cout <<"y equals after squaring: " << y << endl;
cout << endl;
cout << "x+y after squaring equals: " << sum << endl;
}
for(int i = 0; i <= N; i++)
Since you are starting from 0, the condition should be i < N.
Next issue, is int d = (x*x)+(y*y); The distance formula is
So the initialization should be
int d = sqrt((x * x) + (y * y));
Also what is the point of squaring the x and y values at the end?
You are printing the position BEFORE it is changed based on the value of r. So the last value that's printed out is not the actual final value of x and y, but the one of one step earlier. That's why you're getting unexpected distance.
Sorry for the delayed response, I figured out what I had to do. The object of the assignment was to print out each location and find the squared distance at the end of the loop. Here was the solution for anyone interested.
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <cmath>
using namespace std;
int main(){
int N;
cout << "Please enter N amount of steps, and for NetBeans users press
'enter' twice." << endl;
cin >> N;
cout << "% RandomWalker " << N << endl;;
int r;
srand( time(0));
int x = 0;
int y = 0;
cout << "(" << x << ", " << y << ")" << endl;
for(int i = 1; i <= N; i++) {
r=rand()%4;
if (r == 0 )
x++;
else if (r == 1 )
x--;
else if (r == 2 )
y++;
else if (r == 3 )
y--;
cout << "(" << x << ", " << y << ")" << endl;
}
x = (pow(x,2));
y = (pow(y,2));
int squaredDistance = x + y;
cout << "The squared distance is " << squaredDistance << endl;
}

What would be an optimal way to rewrite this into something simple [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
User enters a number ex, 7. This then returns all the multiples of that number up till 1000. X is user input. I have if / else if for each number. Would there be a different way to do this?
void printSeries()
{
if (x == 0)
{
cout << "Closing program" << endl;
}
else if (x == 1)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 1 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 2)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 2 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 3)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 3 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 4)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 4 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 5)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 5 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 6)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 6 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 7)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 7 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 8)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 8 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 9)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 9 == 0)
{
cout << "["<< x << "] ";
break;
}
x++;
}
}
}
cin >> x;
int counter = 1;
while ((x>0) && (true))
{
int multiple = x* counter;
if (multiple > 1000) break;
cout << multiple;
counter++;
}
It's fairly straight-forward using a for loop, as this manages your 'counting' variable nicely:
#include <iostream>
using namespace std;
int main() {
unsigned int x = 0;
cout << "Please enter a number (greater than 0): ";
cin >> x;
for (unsigned int i = 0; x * i < 1000; ++i)
cout << '\n' << x * i;
}
Are you looking for something like this?
#include <iostream>
int main() {
int x = 0;
std::cout << "Please input number: ";
std::cin >> x;
for (int i = 0; x*i < 1000; i++) {
std::cout << "[" << x*i << "]" << std::endl;
}
return 0;
}

Trying to step out of this loop [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm sorry if the code looks sloppy. I've only learned some loops and if checks so far in the book. I would like to code to step out of the loop. I've tried using break and then I tried with this loop.
#include "std_lib_facilities.h"
using namespace std;
int main()
{
double smallest = 0;
double largest = 0;
double x = 0;
string measure = " ";
double sum = 0;
vector<double> meters;
bool leave = false;
if (!leave)
{
while(cin>>x>>measure)
{
if (x < largest)
smallest = x;
else
largest = x;
if ( x == 'x')
leave = true;
cout << "You typed " << x << " Smallest number so far: " << smallest << " Largest number so far: " << largest << endl;
if(measure == "in") //inches
{
cout << "You wanted inches? : " << x << " inches" << endl;
cout << "That also happens to be : " << x * 2.54 << " cm" << endl; // inches to cm
sum += x * 0.0254;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else if(measure == "cm") //centimeter
{
cout << "You wanted centimeters? : " << x << " centimeter" << endl;
cout << "That also happens to be : " << x / 100 << " m" << endl; // inches to cm
sum += x / 100;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else if(measure == "f") //feet
{
cout << "You wanted feet? : " << x << " feet" << endl;
cout << "That also happens to be : " << x * 12 << " inches" << endl; // inches to cm
sum += x * 0.3048;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else if(measure == "m") //meters
{
cout << "You wanted meters? : " << x << " meters" << endl;
cout << "That also happens to be : " << x * 100 << " cm" << endl; // inches to cm
sum += x;
meters.push_back(sum);
cout << "Meters so far : " << sum << endl;
}
else
{
cout << "error invalid measurement. " << endl;
keep_window_open();
}
}
}
for(int i = 0; i<meters.size(); ++i)
cout << meters[i];
keep_window_open();
}
You check the leave condition before the loop, which will of course not work very well. You should check it inside the loop.
It can simplest be put into the actual loop condition:
while(!leave && cin >> x >> measure) { ... }
It seems like you want the input to be either a number and a string, or just a character. That will not work as the variable x is a double and can't handle strings or characters being input. You should actually get a warning about using a double as a character (the x == 'x' comparison).
It might be better to do something like
std::string input;
while (std::getline(std::cin, input))
{
std::istringstream is(input);
// Try to get a number and a string
if (is >> x >> measure)
{
// Got it, do stuff here...
}
else
{
// Input was not a number and a string, try to get a character
char ch;
if (is >> ch && ch == 'x')
break; // Exit loop
else
{
std::cout << "Wrong input, have to be a number and a string, or 'x' to exit\n";
}
}
}
The problem you're having with the program exiting abruptly is most likely because of this. When the input statement std::cin >> x >> measure can't read the input as a number, it will leave the character in the input buffer, so keep_window_open (which I guess reads a string or a character) will get that 'x' and exit immediately.