Amine Marzouki Amine Marzouki - 3 months ago 7
C Question

How can I restart the program in C?

Hi I'm new to C and I wrote a simple program. I want to restart the program if the user picked the wrong choice, here is the code:

#include <stdio.h>
#include <cs50.h>
int main(void){
char choices;
float math, pc, svt, eng, philo;
do {
do {
printf("Enter your math score: ");
math = GetFloat();
}
while( math>20 || math<0);
do {
printf("Enter your pc score: ");
pc = GetFloat();
}
while(pc>20 || pc<0);
do {
printf("Enter your svt score: ");
svt = GetFloat();
}
while(svt>20 || svt<0);
do {
printf("Enter your eng score: ");
eng = GetFloat();
}
while(eng>20 || eng<0);
do {
printf("Enter your philo score: ");
philo = GetFloat();
}
while(philo>20 || philo<0);
printf("Are you pc or sm?\n");
printf("Write 1 for pc. 2 for sm\n");
int choice = GetInt();
if(choice == 1){
float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
printf("Your score is %.2f\n", score);
}
else if(choice == 2){
float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
printf("Your score is %.2f\n", score);
}
else{
printf("You've picked the wrong choice \n");

}

printf("Do you want to try it again? (Y/N) ");
choices = getchar();
while (choices != '\n' && getchar() != '\n') {};
} while (choices == 'Y' || choices == 'y');


}


So what I mean here, I want to insert the code in the else block to restart the program and give the user another time. It would be very nice if I can just make him choose again between 1 or 2.

If you have any suggestions or improvement please don't hesitate to comment.
Thanks :)

Answer

What you need is do while loop surrounding choice code:

int choice;

do {
    choice = GetInt();
    if (choice == 1) {
         float score = (math*7 + pc*7 + svt*7 + eng*2 + philo*2)/25;
         printf("Your score is %.2f\n", score);
    }
    else if (choice == 2) {
        float score = (math*9 + pc*7 + svt*3+ eng*2 + philo*2)/23;
        printf("Your score is %.2f\n", score);
    }
    else {
        printf("You've picked the wrong choice, try again.\n");
    }
} while(choice < 1 || choice > 2)
Comments