Hi I'm trying to make an interactive menu with switch statement in C.
Though I'm unsure of how to trigger a function that has certain arguments.
I'm a total beginner and I'm stumped how to do this.
The function in the switch statement needs the arguments though I would like the function to ask for the numbers. I'm doing this as an assignment and cannot provide the actual code so I made this mock up. Thank you for your help.
Here is an example of code I might use.
#include <stdio.h>
void printMenu()
{
int choice;
do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
function(); /* though this needs the arguments */
break;
}
} while (choice != 7);
int main(void)
{
printMenu();
return 0;
}
void function(int number1, float number2)
{
/*calculation*/
printf("enter your numbers");
/* Not sure how to read the numbers in here */
printf("%d + %d = %d", number1, number2, number1 + number2);
return;
}
If you want the switch to be as minimal as possible then just call another function which takes in input and then calls the function...
case 1:
read_input_and_function()
break;
...
void read_input_and_function(void)
{
printf("Enter your numbers: ");
/* scanf number1, number2 */
function(number1, number2);
}
The function in the switch statement needs the arguments though I
would like the function to ask for the numbers.
How about asking the arguments first , and then calling the function. This way the two arguments can be declared once and be used in other functions of the same switch , but be defined according to the chosen case.
void function1(int, float);
void printMenu()
{
int choice = 0 , num1 = 0;
float num2 = 0;
do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter number 1\n");
scanf("%d",&num1);
printf("\nEnter number 2\n");
scanf("%f",&num2);
function1(num1,num2);
break;
}
} while (choice != 7);
}
#include <stdio.h>
#include <stdlib.h>
#define Pi 3.14159216
/*
*small program of how to create a menu
*/
main ()
{
float degree,radians;
int input;
/*degrees to radians */
float degreesToRadians (float deg)
{
return ((Pi * deg) / 180.0);
}
/*radians to degrees*/
float radiansToDegrees (float rad)
{
return rad * (180 / Pi);
}
void menu ()
{
printf ("\n");
printf ("1. degrees\n");
printf ("2. radians\n");
printf ("3. quit\n");
do
switch (input) {
case 1:
printf ("\n");
printf ("\n");
printf (" Enter value of degrees: ");
scanf ("%f", °ree);
printf ("RADIANS = %f \n\n", degreesToRadians (degree));
menu ();
break;
case 2:
printf ("\n");
printf ("\n");
printf (" Enter value of radians: ");
scanf ("%f", &radians);
printf ("DEGREES = %f \n\n", radiansToDegrees (radians));
menu ();
break;
case 3:
printf (" quiting app \n");
exit (0);
break;
default:
printf ("wrong option\n");
break;
}
while (input != 3);
getchar ();
}
}
menu ();
}
Related
I have been trying to program a tool, where I take input from the user if its a circle or square or rectangle and accordingly it will take the measurement inputs and print out the area for the same. But its not working, please help me with what are the problems with my code and how can i get it to work?
#include<stdio.h>
#include<math.h>
float square(float side);
float circle(float rad);
float rect(float a,float b);
int main(){
char lol;
printf("press s for square\n c for circle\n r for rectagle\n");
scanf("%c ", &lol);
if(lol == 's')
{
int t;
printf("enter side measurement");
scanf("%d", &t);
printf("the area is %f", square(t));
}
if(lol == 'c');
{
int r;
printf("enter radius of circle");
scanf("%d", &r);
printf("the area is %f", circle(r));
}
if (lol == 'r')
{
int m,n;
printf("enter 2 sides ");
scanf("%d %d", &m,&n);
printf("the area is %f", rect(m,n));
}
return 0;
}
float square(float side){
return side*side;
}
float circle(float rad){
return 3.14* rad*rad;
}
float rect(float a,float b){
return a*b;
}
Screenshot of execution
You want to remove the trialing ' ' in the first scanf(), and remove the ; after the if statement.
If main() is last you often can get away with not specifying prototypes for small programs like this. Added error checking of scanf(). Prefer if-else-if when the conditions are mutually exclusive, or as here a switch statement so you don't need to repeat the lol == . Prettied up the prompts a bit (colons, newlines), and sorted both the menu and matching implementation. It makes it easier for end-users and easier to navigate for anyone working on the code. math.h defined the constant M_PI if __USE_XOPEN is set. It's better to use a constant than hard-coding the 3.14 value in circle().
#define __USE_XOPEN
#include <math.h>
#include <stdio.h>
float circle(float rad) {
return M_PI * rad * rad;
}
float rect(float a, float b) {
return a * b;
}
float square(float side) {
return side * side;
}
int main(void) {
printf("press:\n"
" c for circle\n"
" r for rectangle\n"
" s for square\n"
);
char lol;
if(scanf("%c", &lol) != 1) {
printf("scanf failed\n");
return 1;
}
switch(lol) {
case 'c': {
printf("enter radius of circle: ");
int r;
if(scanf("%d", &r) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", circle(r));
break;
}
case 'r': {
printf("enter 2 sides: ");
int m, n;
if(scanf("%d %d", &m,&n) != 2) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", rect(m,n));
break;
}
case 's': {
printf("enter side measurement: ");
int t;
if(scanf("%d", &t) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", square(t));
break;
}
default:
printf("invalid selection %c\n", lol);
}
}
Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}
I have a stack where I want to push distinct elements. I wrote the following code. But it always checks only first element. If I enter a duplicate value first value, it doesn't accept that, but if I enter a duplicate value of 2nd or 3rd value it accepts it.
For example if I enter 20 and again enter 20 it will not accept the second,
but if I enter 20, 22, 22 it accepts the duplicate. How can I prevent this?
#include <stdio.h>
#define MAXSIZE 5
struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
void push(void);
int pop(void);
void display(void);
void main ()
{
int choice;
int option = 1;
s.top = -1;
printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> Bus Status \n");
printf (" 2 --> Enter Bus \n");
printf (" 3 --> Exit Bus \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1:
display();
break;
case 2:
push();
break;
case 3:
pop();
break;
case 4:
return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
/* Function to add an element to the stack */
void push ()
{
int num,i,j,status=0;
if (s.top == (MAXSIZE - 1))
{
printf ("Terminal is Full\n");
return;
}
else
{
printf ("Enter the Bus Number\n");
scanf ("%d", &num);
if(num<1 || num>30) {
printf("This bus Does not Exist.\n");
}
for(i=0;i<5;i++){
if(s.stk[i]==num){
printf("Bus Already in the Terminal\n");
break;
}
else {
s.top = s.top + 1;
s.stk[s.top] = num;
status=1;
break;
}
}
if(status==1)
printf("Bus %d Successfully Entered\n", num);
}
return;
}
You're bus insert loop is looping through and adds a bus the first time it finds s.stk[i] != num. You need to check to see if the bus is in the station ie search the whole stack before inserting a new bus.
for(i=0;i<5;i++) {
if(s.stk[i]==num){
printf("Bus Already in the Terminal\n");
break;
}
else {
s.top = s.top + 1;
s.stk[s.top] = num;
status=1;
break;
}
}
I want to make switch case in the switch case and make back switch. if remember we can use if else to make switch case move to the first switch case. thk
this is my current code now thk
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main() {
int a,b;
system("cls");
printf("Cara Membuat daftar Pertanyaan!\n");
printf("1. Matematika\n");
printf("2. Bahasa indonesia\n");
printf("3. Bahasa Inggris\n");
printf("4. Kewarganegaraan\n");
printf("0. Exit \n");
printf("Masukan no dari 1-4 (0) : ");
scanf("%d", &a);
switch(a)
{
case 1 : system("cls");
printf("1. Perkalian\n");
printf("2. Pertambahan\n");
printf("3. Perkurangan\n");
printf("4. Pembagian\n");
printf("5. Kembali \n");
printf("Masukan no dari 1-5 : ");
scanf("%d",&b);
if( b == 5)
{
switch(a);
}
else {
break;
}
break;
default : printf("Error");
}
return 0;
}
Put everything in a while loop, and only allow the loop to run for the Kembali option. You could also implement this as a recursive function, but that can get complicated.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int
main (void)
{
int a;
int b;
int loop = 1;
while (loop) {
loop = 0;
system ("cls");
printf ("Cara Membuat daftar Pertanyaan!\n");
printf ("1. Matematika\n");
printf ("2. Bahasa indonesia\n");
printf ("3. Bahasa Inggris\n");
printf ("4. Kewarganegaraan\n");
printf ("0. Exit \n");
printf ("Masukan no dari 1-4 (0) : ");
scanf ("%d", &a);
switch (a) {
case 0: {
printf ("Exited\n");
break;
}
case 1: {
system ("cls");
printf ("1. Perkalian\n");
printf ("2. Pertambahan\n");
printf ("3. Perkurangan\n");
printf ("4. Pembagian\n");
printf ("5. Kembali \n");
printf ("Masukan no dari 1-5 : ");
scanf ("%d", &b);
if (b == 5) {
loop = 1;
}
break;
}
default: {
printf ("Error\n");
break;
}
}
}
return 0;
}
i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}