-
Yes/No in a loop
Here is part of my program that im having issues with. I know it still needs work and im not done, but on my loop, how can i get it to stop with a "n" or "N" selection? should i get rid of the for loop completely?
Code:
int k;
int choice;
char selection;
cout <<"You can make up to 8 single order selections"<<endl;
cout <<"Do you want to make a selection Y/y(Yes), N/n(No):";
cin >> selection;
if(selection == 'y'||selection == 'Y')
{
for(k=0;k<8;k++){
cout<<"Enter item number: ";
cin >> choice;
cout<<"Select another item Y/y(Yes), N/n(No): ";
cin >>selection;
switch(choice)
{
case 1: m.menuitem[k]="Plain Egg";
m.menuprice[k]=1.45;
break;
case 2: m.menuitem[k]="Bacon and Egg";
m.menuprice[k]=2.45;
break;
case 3: m.menuitem[k]="Muffin";
m.menuprice[k]=.99;
break;
case 4: m.menuitem[k]="French Toast";
m.menuprice[k]=1.99;
break;
case 5: m.menuitem[k]="Fruit Basket";
m.menuprice[k]=2.49;
break;
case 6: m.menuitem[k]="Cereal";
m.menuprice[k]=.69;
break;
case 7: m.menuitem[k]="Coffee";
m.menuprice[k]=.50;
break;
case 8: m.menuitem[k]="Tea";
m.menuprice[k]=.75;
break;
}
}}
else if (selection=='N'||selection=='n')
cout<<"OK. Good bye."<<endl;
else
cout<<"Invalid selection"<<endl;
-
im relatively new to programming ,but why not put an if statement within the loop?
-
Ideally you'd put the condition (choice is not y) as part of the loop body.
If you find that the check needs to happen in the middle of the loop, you can break when the condition is met. Alternatively you could set a flag, and skip the rest of the loop. Then ad the flag variable to the condition. There is no consensus on which of these methods is better, so use whatever seems more clear to you, or your instructor.
Also, indentation should follow curly brases. If you open a curtly brace, increase the indent. If you close one, decrease the it. It makes your code easier to read and saves you from errors.