help changing a simple statement

Sep 24, 2020 at 4:55am
can someone help me to rewrite this code so that break; is no longer needed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  // This program raises the user's number to the powers of 0 through 10
#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
    int value;

        if (choice == 'Q' || choice == 'q')
            break;
    }
    return 0;
}
Last edited on Sep 24, 2020 at 5:26am
Sep 24, 2020 at 5:32am
Here you go:
 
int main(){}
Sep 24, 2020 at 7:15am
Break out of what: There is no loop or case??

choice isn't even defined!
Sep 24, 2020 at 9:28am
Hello Leonardo797,

Properly indented this is what your program looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This program raises the user's number to the powers of 0 through 10
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int value;

    if (choice == 'Q' || choice == 'q')
        break;
}
return 0;
}

First you will notice that lines 14 and 15 are outside the main block. This code is never reached and the compiler should produce an error telling you this.

The "break" is used to exit a loop, (for, do/while or while), early. The break is also used to exit a switch.

You can use an if statement to trigger a break, but it still needs something to break out of.

Here is an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
//#include <cmath>

int main()
{
    char choice{}
    int value{};

    for (int i = 0; i < 10; i++)
    {
        // Other code here.

        std::cout << "\n Do another (y / n): ";
        std::cin >> choice;

        if (choice == 'N' || choice == 'n')
            break;  // <--- Leaves the for loop.
    }

    return 0;  // <--- Not required, but makes a good break point.
}


I am guessing that there is more to "main" than you have shown. As is what you have posted make so sense.

helios's example would do the same as what you have.

Andy
Topic archived. No new replies allowed.