I am new to programming. and I wanted to see how I could enhance the efficiency of this program, in terms of conciseness and security.
Also, how can I ensure that the user will not break the program by typing a character or a special symbol when I have asked for a number?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <math.h>
int main()
{
//Declaring Variables
float num1, num2;
int op;
char ans;
//Getting the user to choose an option
Again:
printf("\n\t\tMENU FOR OPERATIONS:\n ");
printf("\t\t____________________\n\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Modulus\n");
printf("6. Power Function\n\n");
printf("Enter the MENU option: ");
scanf("%d", &op);
while ( op != 1 && op != 2 && op != 3 && op != 4 && op != 5 && op != 6)
{
printf("\nYou entered an invalid MENU option!\n");
printf("Kindly try again.\n\n");
printf("Enter the MENU option: ");
scanf("%d", &op);
}
//Getting the numbers from user
printf("Enter the first number: ");
scanf("%f", &num1);
printf("Enter the second number: ");
scanf("%f", &num2);
//Implementing a switch statement for processing the input
switch(op)
{
//Case for Addition function
case 1:
printf("Result = %.1f\n", num1 + num2 );
break;
//Case for Subtraction function
case 2:
printf("Result = %.1f\n", num1 - num2);
break;
//Case for Multiplication function
case 3:
printf("Result = %.1f\n", num1 * num2);
break;
//Case for Division function
case 4:
printf("Result = %.1f\n", num1 / num2 );
break;
//Case for Modulus function
case 5:
printf("Result: %d\n",(int)num1 % (int)num2);
break;
//Case for Power Function
case 6:
printf("Result: %.1f\n", pow(num1, num2));
break;
default:
printf("You entered an invalid operator!\n\n");
break;
}
//Asking the user if he wants to run the program again
printf("\nDo you want to continue (Y/N)? ");
ans = getche();
ans = toupper(ans);
//Implementing a while loop to get the user to enter a valid character
while((ans != 'Y' ) && (ans != 'N'))
{
printf("\n\nYou must type a Y or an N!\n");
printf("Do you want to continue (Y/N)? ");
ans = getche();
ans = toupper(ans);
}
//Implementing an if statement to ascertain whether the user wants to continue or quit
if( ans == 'Y')
{
system("cls");
goto Again; //links the program to the start in case of a YES
}
else
{
exit(1); //Successfully exits the program in case of a NO
}
}