I have written this code to perform multiple mathematical operation, with main menu to select the operation, and repeat it until you want and revert back to main menu. I have looped it using switch case and go-to. I want to replace the go-to, and want suggestions regarding how can I make it function in same way without using go-to. Thank you.
//I want the program of be infinite until you want to exit.Thus I used goto to continuously loop it back to either main menu or the mathematical operation you are in.
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int a,b,i,num,n;
char rep;
void main (void)
{
//main menu-(main:-for goto function)
main:
{
printf("\nMAIN MENU\n\n1. Factorial\n2. Sum\n3. Odd/Even\n4. Prime Number\n5. Multiplication\n6. Exit\n");
scanf("%d", &n);
}
switch (n)
{
case 1:
{
fact:
{
printf("Number- ");
scanf("%d", &num);
a=1;
for(i=1;i<=num;i++)
{
a=a*i;
continue;
}
printf("\nFactorial of %d= %d\n\n", num, a);
//This is how I loop it back to main menu or for repeating the mathematical operation using combination of conditional operators and goto.
printf("Repeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto fact;}):({goto main;});
}
}
case 2:
{
sum:
{
a=0;
printf("Value of repetitions- ");
scanf("%d", &num);
printf("Enter Digits to sum:\n");
for(i=1;i<=num;i++)
{
scanf("%d", &b);
printf("+ ");
a=a+b;
continue;
}
printf("\nThe Sum of Digits= %d\n\n", a);
printf("Repeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto sum;}):({goto main;});
}
}
case 3:
{
oe:
{
printf("Enter a Number- ");
scanf("%d", &a);
(a%2==0)?(printf("\n%d is an Even Number\n",a)):(printf("\n%d is an Odd number\n", a));
printf("\nRepeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto oe;}):({goto main;});
}
}
case 4:
{
prime:
{
printf("\nEnter a Number- ");
scanf("%d",&num);
if(num==2)
printf("\n\n%d is a Prime Number\n\n", num);
for(i=2;i<=num-1;i++)
{
(num%i==0)?({printf("\n\n%d is Not a Prime Number.\n\n", num);break;}):({printf("\n\n%d is a Prime Number\n\n", num);break;});
}
printf("\nRepeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto prime;}):({goto main;});
}
}
case 5:
{
mul:
{
a=1;
printf("Value of repetitions- ");
scanf("%d", &num);
printf("Enter Digits to multiply:\n");
for(i=1;i<=num;i++)
{
scanf("%d", &b);
printf("* ");
a=a*b;
continue;
}
printf("\nThe Multiplication of Digits= %d\n\n", a);
printf("Repeat? y/n- ");
fflush(stdin);
scanf("%c", &rep);
(rep=='y')?({goto mul;}):({goto main;});
}
}
//Case 6 is only for aesthetic reasons.
case 6:
printf("\n\nPress Enter\n\n");
}
}
Considering the fact that you do not want to change your program in any way other than the goto function, you can put your entire code under a do while loop, a while loop or a for loop like this:
do {
....
} while(rep != 'y')