ch3-GoTo statement, switch with gotos

Chapter_3     Exercise_3-4 Recursion     Exercise_3-5







CONTENTS:     GoTo.cpp     Menu3g.cpp




GoTo.cpp     TCP1, p. 136         download


// The infamous goto from C is also supported in C++
#include <iostream>
using std::cout;
using std::endl;

int main()
{
int i, j;
long val = 0;

for(i = 1; i < 1000; i++)
{
for(j = 1; j < 100; j += 10)
{
val = i * j;
if(val > 47000)
{goto bottom;} // break would only go to the outer 'for'
} // end of inner for()
} // end of outer for()
bottom: // A label
cout << i << " * " << j << " = " << val << endl;

return 0;
}
/*
g++ GoTo.cpp -o GoTo
./GoTo
517 * 91 = 47047
*/












// A menu using switch statements and gotos
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main()
{
char c; // To hold the response (input from keyboard)

while(true)
{
cout << "MAIN MENU:" << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;

switch (c)
{
case 'q':
goto bottom; // break would exit (outer) switch(), goto exits while()

case 'l':
cout << "LEFT MENU:" << endl;
cout << "Select a or b: ";
cin >> c;

switch (c)
{
case 'a':
cout << "You chose 'a'" << endl;
break; // out of first inner switch()
case 'b':
cout << "You chose 'b'" << endl;
break; // out of first inner switch()
default:
cout << "You didn't choose a or b!" << endl;
break; // out of first inner switch()
} // end of first inner switch()

break; // from outer switch(), back to main menu

case 'r':
cout << "RIGHT MENU:" << endl;
cout << "Select c or d: ";
cin >> c;

switch (c)
{
case 'c':
cout << "You chose 'c'" << endl;
break; // out of second inner switch()
case 'd':
cout << "You chose 'd'" << endl;
break; // out of second inner switch()
default:
cout << "You didn't choose c or d!" << endl;
break; // out of second inner switch()
} // end of second inner switch()

break; // from outer switch(), back to main menu

default:
cout << "You must type l or r or q!" << endl;
break; // from outer switch(), back to main menu
} // end of outer switch()
} // end of while()
bottom: // A label
cout << "Quitting menu..." << endl;

return 0;
} // end of main()
/*
g++ Menu3g.cpp -o Menu3g
./Menu3g
MAIN MENU:
l: left, r: right, q: quit -> n
You must type l or r or q!
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: a
You chose 'a'
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: c
You didn't choose a or b!
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: d
You chose 'd'
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: q
You didn't choose c or d!
MAIN MENU:
l: left, r: right, q: quit -> q
Quitting menu...
*/









Chapter_3     Exercise_3-4 BACK_TO_TOP Recursion     Exercise_3-5



Comments

Popular posts from this blog

Contents