I am trying to create a Menu Driven program in C but I unable to get back to menu after completing one function. How do I program it so that the program ask the user to continue or not after each function and return to menu?
//program of menu driven program
#include <stdio.h>
#include <stdlib.h>
int main() {
int fac = 1, b, num, p, prime, click, out; //click for selecting the function and ext for goto
while (1) {
printf("Welcome to Varied Maths!");
printf("\nYou can perform the following things here");
printf("\n1.Factorial of a number\n2.Prime or not\n3.Odd or even\n4.Exit");
printf("\nEnter your choice:");
scanf("%d", &click);
switch (click) { //for seleting from menu
case 1: //for factorial
printf("Factorial Calculator\n");
printf("Enter the number:");
scanf("%d", &num);
for (p = 1; p <= num; p++) {
fac = fac * p; //fac=1 which gets multiplied with the num entered the number gets increment and so on
printf("Factorial of %d is %d", num, fac);
}
break;
case 2: //prime numbers using for loop
//int prime,b,ent
printf("Prime or not\n");
printf("Enter the number:");
scanf("%d", &prime);
//int prime,b;
if (num == 1) {
printf("1 is Neither composite nor prime");
}
if (num == 0) {
printf("Neithher compossite nor prime");
}
for (b = 2; b <= num - 1; b++)
if (num % b == 0) {
printf("%d Not A prime", num);
break;
}
if (b == num) {
printf("Prime Number");
}
break;
case 3:
int odd;
printf("\nOdd or Even determiner");
printf("\nEnter the number you want to know about:");
scanf("%d", &odd);
if (odd % 2 == 0) {
printf("The entered number %d is a even number",odd);
}
if ((odd % 2) != 0) {
printf("The entered number %d is a odd number",odd);
}
break;
case 4:
printf("\nThanks for Using Me.\nI would have been too happy if you checked out my functions ");
break;
}
return 0;
}
}
What should I do? Should I use continue statement or anything else. Please Send Help
If you want to exit the while(1)
loop from inside the switch
, the best is to use a loop control variable:
int end = 0;
while (!end) {
switch(...) {
case 4:
end = 1;
break;
}
}
Alternatively if you want to use a break
to exit the loop you can do something like that:
while (1) {
switch(...) {
...
}
if (click==4)
break; // that break will exit the active control block, here the current while
}