Switch statement executes case 2 even after break - c

When case 1, the program executes the code intended but then when it asks you if you want to calculate volume again if you pick yes it just executes case 2. I'm not sure what's wrong. How can I get it to only execute case 1 unless the you pick 2 in the menu?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float menu1, opt1, opt2, opt3, opt4, t;
int td;
printf("Enter: ");
scanf("%d",&td);
switch(td) {
case 1:
printf("Enter a, b, c, and h of the triangular prism in meters\n\n");
printf("a ");
scanf("%f", &opt1);
printf("b ");
scanf("%f", &opt2);
printf("c ");
scanf("%f", &opt3);
printf("h ");
scanf("%f", &opt4);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
case 2:
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
scanf("%f", &opt1);
printf("h ");
scanf("%f", &opt2);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
}
}

Your break statements [for case 1:] are only inside if blocks. If neither if is true, you get the fall through.
Here is your original:
case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
// BUG: there should be a break here
case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...
Here is the fixed code:
case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
break; // FIX: this is your _missing_ break statement
case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...

Related

How to stop a while loop in C

In this code, the computer asks the user what he wants to purchase between 1-7 options. And if the user presses the wrong option up to 3 times -> computer will print this message: "Do you want to leave or make a purchase? Press y(for leave) or n(for stay)". I know another way how to do this, but how can I stop the while loop and print a message?
!!!This is incorrect code(has mistakes), used for example!!!
#include <stdio.h>
int DisplayMenu();
double OrderPrice(int itemNumber);
int main
{
char process = 'y';
int mainOption;
while (process == 'y' || process == 'Y')
{
optionMain = DisplayMenu();
printf("\nYour choice was %d", optionMain);
};
return 0;
}
int DisplayMenu()
{
int option, optionCount;
printf("1 - ..., 2 - ..., 3 - ..., 4 - ..., 5 - ..., 6 - ..., 7 - ...");
scanf("%d", &option);
while (option > 7 || option < 1) {
printf("Make your chose between 1-7:");
scanf(" %d", &option);
optionCount++;
if (optionCount == 2) {
printf("Do you want to leave or make a purchase? Press y(for leave) or n(for stay)");
}
};
return option;
return 0;
}
double OrderPrice(int itemNumber)
{
double price;
switch (itemNumber) {
case 1 :
printf("\nSelection 1.");
price = 1.1;
break;
case 2 :
printf("\nSelection 2.");
price = 2.2;
break;
case 3 :
printf("\nSelection 3.");
price = 3.3;
break;
case 4 :
printf("\nSelection 4.");
price = 4.4;
break;
case 5 :
printf("\nSelection 5.");
price = 5.5;
break;
case 6 :
printf("\nSelection 6");
price = 6.6;
break;
case 7 :
printf("\nSelection 7.");
price = 7.7;
break;
// default:
// printf("Incorrect selection");
// price = 0.00;
}
return price;
}
was solved by #tadman: You need to get input at that point, test it, and if it's a stop request, break
optionCount++;
if (optionCount == 2) {
break;
}

C program to make a calculator that can perform simple arithmetic and toggle between int and double variables

I am a bit new to c programming. For my project I have been tasked with developing a simple calculator that asks the user to input an option then that option declares what operation is to be performed (i.e. if the user enters 1, this corresponds to selecting the addition option which then allows the user to add two numbers they choose. I have the majority of the code worked out, but the catch is that I need the calculator to toggle between int and double variables. When the user enters 5, the calculator should now work with integers then if the user hits 5 again, the calculator switches back to doubles and vice versa so long as you want to switch back and forth. The calculator automatically works with doubles. So, more specifically, if I wanted to use integer variables, I would enter 5, then lets say I wanted to switch back to doubles, I should enter five and receive the message "Calculator now works with doubles." So here is my code thus far:
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
int main()
{
int integermode, doublemode, m, a, b, sum2, difference2, product2,
quotient2;
double i, j, sum1, difference1, product1, quotient1;
printf("This program implements a calculator.");
while(m !=6) {
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%d", &m);
if(m > 6) {
printf("Invalid option.\n");
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%d", &m);
}
switch (m) {
case 1:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The sum is: %d\n", a+b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The sum is: %.15lf\n", i+j);
}
break;
case 2:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The difference is: %d\n", a-b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The difference is: %.15lf\n", i-j);
}
break;
case 3:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The product is: %d\n", a*b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The product is: %.15lf\n", i*j);
}
break;
case 4:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
if (b != 0) printf("The quotient is: %d\n", a/b);
if (b == 0) printf("Cannot divide by zero!\n");
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
if(j != 0) printf("The quotient is: %.15lf\n", i/j);
if(j == 0) printf("Cannot divide by zero!\n");
break;
}
case 5:
if (m = 5) {
integermode = true;
printf("Calculator now works with integers.\n");
}
if (m != 5) integermode = false;
}
}
return 0;
}
General improvements
First off, you should notice your main function is massive for what it needs to accomplish, and takes a ton of indent levels (when properly indented). That is mostly because you've got a ton of duplicated functionality. You could easily extract the code that asks for the input numbers into a function and reuse it, changing only the operation performed in each case. Or probably even better, you could ask for the input numbers as a part of the main while loop, and then perform a different operation with them depending on the operation mode you're in.
You're not using <math.h>, so you can leave it out.
Another thing I've noticed is you don't initialize the m variable before using it in the while loop. That could potentially cause a lot of problems, so you should initialize it to some value that isn't a valid mode, like for example 0 or -1.
You're also using two consecutive if statements when if/else could be used.
if (integermode == true) {
.....
}
if (integermode == false) {
.....
}
is the same as
if (integermode == true) {
.....
} else {
.....
}
but harder to read and less efficient, as you're doing two comparisons instead of one.
Implementation of double/integer modes
About the functionality you want to implement, you could very well define an enumeration with the possible modes:
typedef enum _datamode {
INTEGER_MODE,
DOUBLE_MODE
} data_mode;
and then have a variable holding the current mode:
data_mode datamode = INTEGER_MODE /* Initializing this to the default mode */
then use integers or doubles during the calculation and output depending on the current value of the variable. Of course, this could be done in a shorter way with an integer instead of an enum and a typedef, but I find this to be a more verbose way.
For the inputs and the result, you could use the union C type, which reserves memory for the biggest type you specify inside it and lets you store any of them in it. For example:
union io {
int i;
double d;
} a, b, result;
declares three variables that have the io union as type. That way, you can use them as integers or doubles as you like (as long as you don't mix types up and, for example, store an integer and read it as a double)
Full working implementation
The following would be my implementation of the program you have to do. It could be accomplished in a much shorter way (take into account the switches dealing with enums take a fair bit of the total space) but I think this is way more elegant and verbose.
I've respected your print statements and the flow of your application, even though I think they could be better (maybe this is something your assignment imposes on you?)
Please take this as an opportunity to learn and don't just copy-paste the code.
#include <stdio.h>
#include <stdlib.h>
typedef enum _datamode {
INTEGER_MODE,
DOUBLE_MODE
} data_mode;
typedef enum _operationmode {
ADDITION,
SUBSTRACTION,
MULTIPLICATION,
DIVISION,
TOGGLE,
EXIT
} operation_mode;
operation_mode ask_mode () {
int input = -1;
while (1) {
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%i", &input);
if (input < 1 || input > 6) {
printf("Invalid option.\n");
} else {
switch (input) {
case 1:
return ADDITION;
case 2:
return SUBSTRACTION;
case 3:
return MULTIPLICATION;
case 4:
return DIVISION;
case 5:
return TOGGLE;
case 6:
return EXIT;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
}
}
}
union _io {
int i;
double d;
};
void get_inputs_integer (int *a, int *b) {
printf("Enter first term: ");
scanf("%i", a);
printf("Enter second term: ");
scanf("%i", b);
}
void get_inputs_double (double *a, double *b) {
printf("Enter first term: ");
scanf("%lf", a);
printf("Enter second term: ");
scanf("%lf", b);
}
int main (int argc, char **argv) {
union _io operand1, operand2, result;
operation_mode o_mode;
data_mode d_mode = INTEGER_MODE;
printf("This program implements a calculator.");
do {
o_mode = ask_mode();
if (o_mode == TOGGLE) {
if (d_mode == INTEGER_MODE) {
d_mode = DOUBLE_MODE;
printf("Calculator now on double mode\n");
} else {
d_mode = INTEGER_MODE;
printf("Calculator now on integer mode\n");
}
} else if (o_mode != EXIT) {
if (d_mode == INTEGER_MODE) {
get_inputs_integer(&operand1.i, &operand2.i);
switch (o_mode) {
case ADDITION:
result.i = operand1.i + operand2.i;
break;
case SUBSTRACTION:
result.i = operand1.i - operand2.i;
break;
case MULTIPLICATION:
result.i = operand1.i * operand2.i;
break;
case DIVISION:
result.i = operand1.i / operand2.i;
break;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
printf("The result is %i\n", result.i);
} else {
get_inputs_double(&operand1.d, &operand2.d);
switch (o_mode) {
case ADDITION:
result.d = operand1.d + operand2.d;
break;
case SUBSTRACTION:
result.d = operand1.d - operand2.d;
break;
case MULTIPLICATION:
result.d = operand1.d * operand2.d;
break;
case DIVISION:
result.d = operand1.d / operand2.d;
break;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
printf("The result is %lf\n", result.d);
}
}
} while (o_mode != EXIT);
}

Program that displays each digit on an integer in english doesn't work with an integer beginning with "0"

I have an assignment were I have to write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. I'm not able to use arrays or recursion, we're just starting with programming.
For example:
"123" returns "one two three"
My program is working well (for the most part), but the problem is that when you enter something like "0123" in the terminal the program returns "eight three"... WTH??
This is my code:
// Program that takes an integer and displays each digit in English
#include <stdio.h>
int main (void)
{
int num, digit;
int reversed = 0, backupZero = 0;
printf("Please enter an integer:\n");
scanf("%i", &num);
if (num == 0) // In case the input is just "0"
{
printf("zero");
}
while (num > 0) // Loop to reverse the integer
{
digit = num % 10;
reversed = (reversed * 10) + digit;
if ((reversed == 0) && (digit == 0)) // If the integer finishes in zero
{
++backupZero; // Use this to add extra zeroes later
}
num /= 10;
}
while (reversed > 0)
{
digit = reversed % 10;
reversed /= 10;
switch (digit)
{
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
default:
printf("zero ");
break;
}
}
for (int counter = 0; counter < backupZero; ++counter) // Prints the extra zeroes at the end
{
printf("zero ");
--backupZero;
}
printf("\n");
return 0;
}
Probably is something on the mathematics, I admit I'm not good at it.
When you read in the number with
scanf("%i", &num);
You are letting scanf infer the base of the number. Numbers starting with 0 followed by other digits are interpreted as octal. So 0123 is not the same as 123. It is in fact, 83.
0100 = 64
020 = 16
03 = 3
---------
0123 = 83
To read the number as base 10, use
scanf("%d", &num);
If you want to handle numbers that start with '0', then I suggest that you read the user input as a string (array of characters) rather than as an integer.
In addition to that, instead of "doing a switch" on each character, you can use a simple array in order to map the correct word to each digit.
Here is one way for implementing it:
#include <stdio.h>
#define MAX_INPUT_LEN 100
const char* digits[] = {"zero","one","two" ,"three","four",
"five","six","seven","eight","nine"};
int main()
{
int i;
char format[10];
char str[MAX_INPUT_LEN+1];
sprintf(format,"%c%us",'%',MAX_INPUT_LEN); // now format = "%100s"
scanf(format,str); // will write into str at most 100 characters
for (i=0; str[i]!=0; i++)
{
if ('0' <= str[i] && str[i] <= '9')
printf("%s ",digits[str[i]-'0']);
else
printf("invalid character ");
}
return 0;
}
Oh, wow. It took me 3 or 4 hours to write following code. I'm into c only first week, so please be considerate.
Update: added working minus + some comments.
#include <stdio.h>
#include <math.h>
int main(void)
{
int num, count, user, out;
count = 0;
printf("Type in any int: ");
scanf("%d", &num);
// adding minus to the beginning if int is negative
if (num < 0)
{
num = -num;
printf("minus ");
}
user = num;
// creating a power to the future number
while (num != 0)
{
num = num / 10;
count++;
}
int i2;
i2 = count;
// main calculations: dividing by (10 to the power of counter) and subtracting from the initial number
for (int i = 0; i < i2; i++)
{
out = user / pow(10, count - 1);
user = user - out * pow(10, count - 1);
count--;
switch (out)
{
case 1:
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
case 0:
printf("zero ");
break;
default:
break;
}
}
printf("\n");
return 0;
}
There are some mistakes:
if ((reversed == 0) && (digit == 0)) (incorrect)
if ((reversed == 0) || (digit == 0)) (correct)
And in the last loop you should remove
--backupZero;
And code will read numbers better

How do I use a for loop to retrieve from the user the indicated number of items indicated?

int a = 1;
printf("Enter the number of items from 1 and 10: \n");
while (a <= 10)
{
scanf("%d", &a);
if (a >= 1 && a <= 10)
{
printf("Thank You!\n");
break;
}
else
{
printf("Wrong input! Try Again.\n");
continue;
}
}
To be more detailed about what I'm asking lets say that the user enters 3 (for 3 items) how would I use the for loop to retrieve that information so I can further finish the code.
You should keep in mind following points:
Get the no.of choice before starting loop
Check the condition in loop with no. of choices.
Only one loop is enough for your task.
I think you need this:
int a = 1;
bool bFlag = true;
int price[10];
printf("Enter the number of items from 1 and 10: \n");
while(bFlag){
scanf("%d", &a);
if (a >= 1 && a <= 10)
{
printf("Thank You!\n");
break;
}
else
{
printf("Wrong input! Try Again.\n");
continue;
}
}
for (int i = 0; i< a; i++)
{
printf("Enter price for item %d = ", i);
scanf("%d",&price[i]);
}

Remove an element from a vector in C

How can I remove an element from a vector in C without changing my print_vector function?
1) Here's the code that I made for removing an element on a position given from the keybord:
void remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if(nr>a)
{
printf("The remove is impossible!\n");
}
else
{
for(c=nr;c<=a;c++)
{
chelt[c]=chelt[c+1];
}
}
}
2)This is the print function
void print_costs(int a)
{
int i;
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nCost %d\n\n",i);
printf("Day: %s\n", chelt[i].day);
printf("Sum: %d\n", chelt[i].sum);
printf("Type: %s\n", chelt[i].type);
}
}
}
3) Here's the add_new_cost() function
int add_new_cost()
{
int a,i;
printf("Nr of costs = ");
scanf("%d", &a);
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nType the attributes for cost %d",i);
printf("\nDay = ");
scanf("%s",chelt[i].day);
printf("Sum = ");
scanf("%d", &chelt[i].sum);
printf("Type = ");
scanf("%s",chelt[i].type);
}
}
return a;
}
4) This is the main function
int main()
{
setbuf(stdout,NULL);
int b,choice;
do
{
printf("\nMenu\n\n");
printf("1 - Add a cost\n");
printf("2 - Print a cost\n");
printf("3 - Update a cost\n");
printf("4 - Delete a cost\n");
printf("5 - Exit\n\n");
printf("Command = ");
scanf("%d",&choice);
switch (choice)
{
case 1: b=add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: remove_a_cost(b);
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}
} while (choice != 0);
return 0;
}
Example:
If I have 4 elements on the vector:
1)Type the attributes for cost
Day = luni
Sum = 2
Type = dsasa
Type the attributes for cost 2
Day = marti
Sum = 23
Type = adsds
Type the attributes for cost 3
Day = miercuri
Sum = 23
Type = asd
Type the attributes for cost 4
Day = joi
Sum = 232
Type = asdas
and I try to delete, let's say the 3rd element, this is what I receive when I print:
Cost 1
Day: luni
Sum: 20
Type: maradf
Cost 2
Day: marti
Sum: 23
Type: afas
Cost 3
Day: joi
Sum: 45
Type: sdfadsf
Cost 4
Day:
Sum: 0
Type:
The element(COST 4) appears when it should've been deleted. Is there a solution for deleting the element WITHOUT changing the print function?
After updating of question, everything is clear, do these modifications:
int remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if (nr > a)
{
printf("The remove is impossible!\n");
}
else
{
for (c = nr; c <= a; c++)
{
chelt[c] = chelt[c + 1];
}
a--; // decrease a
}
return a; // return new size
}
And
switch (choice)
{
case 1: b = add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: b = remove_a_cost(b); // <- store returned value in b
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}
Your code is a bit messy. You should try to give meaningful names to your variables.
But, for what I understand, the print_costs function receives the value of the last 'cost' that it should print.
Perhaps you're passing it the wrong value after you remove a 'cost'.

Resources