Reputation: 65
I'm trying to make my program to start again from the beginning after user has selected an option from a menu.
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu What would you like to do?
and not to just restart just the if statement.
Should I add a for loop inside of the if statement to accomplish this? thanks for the help.
printf("What would you like to do?\n");
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if(menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
}
Upvotes: 0
Views: 1089
Reputation: 32586
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu
just do
for(;;) {
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if(menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
// NO BREAK
}
else {
.... management of other cases
break;
}
}
or if you prefer
do {
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if(menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
}
// ... management of other cases
} while (menu_option==1);
But are you sure you do not want to redo also in cases 2 and 3 ? In that case replace while (menu_option==1);
by while (menu_option != 4);
or in the first proposal do the break
only when menu_option
is 4
I also encourage you to check the return value of scanf("%d", &menu_option);
to be sure a valid integer was given in input and menu_option
was set
Upvotes: 1
Reputation: 7882
#include <stdio.h>
int main()
{
int menu_option;
double donation;
int donations_made = 0;
int current_Balance = 0;
int initial_Balance = 0;
for (;;)
{
printf("What would you like to do?\n");
printf(" 1 - Donate\n");
printf(" 2 - Invest\n");
printf(" 3 - Print balance\n");
printf(" 4 - Exit\n");
printf("\n");
//scans menu choice
scanf("%d", &menu_option);
if (menu_option==1)
{
printf("How much do you want to donate?\n");
scanf("%lf", &donation);
donations_made++;
current_Balance = initial_Balance + donation;
}
else if (menu_option == 4)
break;
}
}
Upvotes: 0