Question:
need help with a swich case statement?
paulus
2009-11-03 19:20:43 UTC
hi

ive tried using different types of while statements to my swich case, but it seems that my "break" clause's are being overridden. if you have a good solution it would be really appreciated

here is a list of my program:


#include
#include
#include
#include
using namespace std;

int main ()
{
bool found=0;
int number=0;
int total=0;
char option=0;
const int arraySize = 10;
int frequency[ arraySize ] = { 0 };



srand(time(0)); // seed random-number generator

for ( int roll = 1; roll <= 100; roll++ )
++frequency[ rand() % 10 ];

while (( option = cin.get ( )) != EOF)
{
cout << "-----------------------------------------------------------------------\n";
cout << " The random generated array is: ";
for ( int face = 1; face < arraySize; face++ )
{
cout << frequency[face]<<" ";
}
cout << endl;


cout << endl;
cout << " \n [R]everse [A]dd [S]earch [E]xit "<< endl;
cout << " \n select an option: ";
cout << option << endl;



switch(option)
{
case 'R':
case 'r':
cout << " The reversed array is: ";
for(int face=10;face < 1;face--)
{
cout << frequency[face]<<" ";
}
cout << endl;
break;
case 'A':
case 'a':

for (int face=1;face< arraySize; face++)
{
total += frequency [face];
}
cout << " the sum of the array is: ";
cout << total << endl;
break;

case 'S':
case 's':

cout << "please insert a number:";
cin >> number;
cout << endl;
for(int face=0;face<=9;face++)
{
if(number==frequency [face])
{
cout<<" the number "<< number<<"has been found at position number "< found=1;
}
}
if(found==0)
cout << " the number "< break;
case 'E':
case 'e':
return 0;
break;
}
}
return 0;
}
Four answers:
2009-11-05 20:25:22 UTC
Hm....



















Multiple declaration: "face", remove int-define at next for()-sttmnt.

And unreach "break" at last switch-sttmnt.



Lets see the struct of switch-sttmnt under while-sstmn

while (::option::){ // u can break with CTRL + Z

switch(option){

case ::RSA::

+++ call the related function +++

break;

case 'E':

case 'e': return 0;

}

}
2009-11-04 03:35:28 UTC
YOu are looping the while straight through the switch.

Switches are stand-alone, which means they should not be looped. The switch variable, however, can be altered with the loop which ultimately changes the events.

So make sure that you close the while loop before stating the switch statements.

Where you think its "bypassing", break is also use to BREAK out of a loop, not just a switch, so be careful.

Good Luck!

If you need further assistance/advice, feel free to contact me.
2009-11-04 03:37:42 UTC
I think your problem is you need break; after each case not too sure im not much of a c++ person more action script but there similar
?
2009-11-04 03:36:43 UTC
can you paste a sample input and output for this code


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...