Remove an element from a vector in C - 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'.

Related

Values are getting stored in different stack even though different variables are used in the code for each stack

I wanted to create 4 stacks, 1 for each subject. Then in each stack store number of days left for each assignment to be submitted. This is the code I have written. The code works with the exception of 1 flaw:
When values are stored in one stack they also show up in the other stacks with value 0 and same number of elements for example :
I store values 5,20,7 in the stack of ds exit that stack and go to the stack of dsgt and store 9,11 and then on printing the values in stack of dsgt the code prints out as " 0 0 0 9 11" here 0 0 0 are the 3 elements of the 1st stack. Now on exiting the stack of dsgt and going back to stack of ds and printing its value the output is "5 7 20 0 0 " , 0 0 here are the elements of the stack of dsgt which I dont want to print with ds and rest of the stacks.
#include <stdio.h>
#include <conio.h>
#define MAXSIZE 20
int st1[MAXSIZE];
int st2[MAXSIZE];
int st3[MAXSIZE];
int st4[MAXSIZE];
int top = -1;
void push(int st[], int item);
int pop(int st[]);
int peek(int st[]);
void display(int st[]);
void sort(int st[]);
int main() {
int subj;
printf("\nEnter the number associated with the Subject assignment that has to be tracked\n");
int choice = 0, item1;
do {
printf("\n 1. Data Structures");
printf("\n 2. DSGT ");
printf("\n 3. CG ");
printf("\n 4. Math");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
ds();
break;
case 2:
dsgt();
break;
case 3:
cg();
break;
case 4:
math();
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
return 0;
}
int dsgt() {
int choice, item2;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item2);
push(st2, item2);
sort(st2);
break;
case 2:
item2 = pop(st2);
printf("\n Removed Assignment is: \n %d", item2);
break;
case 3:
item2 = peek(st2);
printf("\n The Latest Assignment to be Submitted is:%d", item2);
break;
case 4:
display(st2);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
int ds() {
int choice, item1;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item1);
push(st1, item1);
sort(st1);
break;
case 2:
item1 = pop(st1);
printf("\n Removed Assignment is: \n %d", item1);
break;
case 3:
item1 = peek(st1);
printf("\n The Latest Assignment to be Submitted is:%d", item1);
break;
case 4:
display(st1);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
int cg() {
int choice, item3;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item3);
push(st3, item3);
sort(st3);
break;
case 2:
item3 = pop(st3);
printf("\n Removed Assignment is: \n %d", item3);
break;
case 3:
item3 = peek(st3);
printf("\n The Latest Assignment to be Submitted is:%d", item3);
break;
case 4:
display(st3);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
int math() {
int choice, item4;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item4);
push(st4, item4);
sort(st4);
break;
case 2:
item4 = pop(st4);
printf("\n Removed Assignment is: \n %d", item4);
break;
case 3:
item4 = peek(st4);
printf("\n The Latest Assignment to be Submitted is:%d", item4);
break;
case 4:
display(st4);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
void push(int st[], int item) {
if (top == MAXSIZE - 1) {
printf("\n You Have a lot of Assignments Due, GET WORKING!!!");
} else {
top = top + 1;
st[top] = item;
}
}
int pop(int st[]) {
int item;
if (top == -1) {
printf("Great Work No Assignment Are Pending");
return 0;
} else {
item = st[top];
top = top - 1;
}
return item;
}
int peek(int st[]) {
int item;
if (top == -1) {
printf("Great Work No Assignment Are Pending");
return 0;
} else {
item = st[top];
return item;
}
}
void display(int st[]) {
if (top == -1) {
printf("Great Work No Assignment Are Pending");
} else {
for (int i = top; i >= 0; i--) {
printf("\n%d\n", st[i]);
}
}
}
void sort(int st[]) {
int tmp, i, j;
for (int i = top; i >= 0; i--) {
for (j = i + 1; j <= top; j++) {
if (st[i] < st[j]) {
tmp = st[j];
st[j] = st[i];
st[i] = tmp;
}
}
}
}
I would recommend that you use a structure for your stacks that contains the array and the top value e.g.
typedef struct{
int stack[MAXSIZE];
int top;
}stack_t;
Then you can declare your stacks and initialize them:
stack_t st1 = {{0}, -1};
stack_t st2 = {{0}, -1};
stack_t st3 = {{0}, -1};
stack_t st4 = {{0}, -1};
or place them in an array
stack_t stacks[4]={
{{0}, -1},
{{0}, -1},
{{0}, -1},
{{0}, -1}, };
You need to declare your functions as follows and update their implementation accordingly:
void push(stack_t* st, int item);
int pop(stack_t* st);
int peek(stack_t st);
void display(stack_t st);
void sort(stack_t* st);
void dsgt(void);
void cg(void);
void math(void);
void ds(void);
The push, pop, sort functions then all use pointers to stack_t e.g.
int pop(stack_t* st) {
int item =0;
if (st->top == -1) {
printf("Great Work No Assignment Are Pending");
} else {
item = st->stack[st->top];
st->top = st->top - 1;
}
return item;
}
display and peek function are okay with stack_t parameter as they don't change it.
If you place all of your stack structures in an array, you then can use a global variable as an index into your stack_t array and reduce the duplication of your choice code.

Finding Items in Struct and edit them

i have a problem in my code (Case 2), I try to get the position of the item what I get from the scanf() but when I try to get the position it give me a complete random number like 537890.
I can't figure out why my code do that, because the max size of my struct ist 200.
I'm not sure if its because I tried to do &find==wh[a]->artikel
int main() {
struct managementtool {
char artikel[200];
int anzahl;
};
//wh = warehouse
struct managementtool **wh = malloc(200 * sizeof(struct managementtool *));
for (int i = 0; i < 200; i++) {
wh[i] = malloc(sizeof(struct managementtool));
}
printf("Welcome to Warehouse Management 97\n\n\nWhat do you want to do ?\n");
int x,v,f,i,exit,all,end,a,b;
char ques,find, nu1;
do {
i=0;
printf("\n(1)Add article\n(2)Edit article.\n(3)Search entry.\n(4)Show stock.\n(5)Exit\n");
scanf("%x",&x);
switch (x) {
case 1://add
do {
printf("\nEnter the product name: ");
scanf("%s", wh[f]->artikel);
printf("\nAmount of products: ");
scanf("%i", &wh[f]->anzahl);
printf("\n\nAdd another product ? (Y/N)");
// add a space before % to skip leading whitespace
scanf(" %c", &ques);
f++;
switch (ques) {
case 'Y':
v++;
break;
case 'N':
end = 1;
v = 0;
break;
default:
printf("Wrong entry\n");
break;
}
} while (end != 1);
if (v >= 2) {
printf("Product added successfully\n\n");
}else {
printf("Products have been successfully added\n\n");
}
break;
case 2://edit
printf("Which article do you want to edit?");
fflush(stdin);
scanf("%s", &find);
for (a=0;a<f;a++) {
if (&find==wh[a]->artikel) {
b=a;
}
}
if (b==0) {
printf("Article not found");
}
printf("f: %i, b:%i",f,b);
puts(wh[b]->artikel);
printf("Amount: %d\n", wh[b]->anzahl);
break;
case 3://search
break;
case 4://Spam-it
while (i<f) {
printf("\nProduct number %i\n", i+1);
printf("Name: ");
puts(wh[i]->artikel);
printf("Amount: %d\n", wh[i]->anzahl);
i++;
}
printf("\nTotal amount of Items: %i", all);
break;
case 5://go away
printf("Goodbye :)");
exit=1;
break;
default://well
printf("Wrong Input\n");
break;
}
all=0;
while (i<f) {
all += wh[i]->anzahl;
i++;
}
} while (exit==0);
}
In C you need to use strcmp instead of using == to compare strings. You should also use fgets instead of scanf it will make your life easier, you don't have to worry about trying to flush. Example : fgets( my_string_buffer, number_of_char_maximum_to_read , stdin ) . Example for strcmp : if(! strcmp( string1 , string2) , strcmp returns 0 if they are identical.

How to call functions in C

I'm working on my final project for my intro to programming class and the assignment is to create a code that will display a menu and will ask the user to enter a choice. After that it will display the total for the order and the name of the item the user chose.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#define TEQUENOS_PRICE 5.00
#define AREPA_PRICE 3.00
#define CACHAPA_PRICE 2.50
#define EMPANADA_PRICE 2.00
#define SODA_PRICE 0.80
#define QUESILLO_PRICE 1.70
#define DULCE_DE_LECHE_PRICE 1.20
int main()
{
int choice = 0, tequenos = 0, arepa = 0, cachapa = 0, empanada = 0;
int soda = 0, quesillo = 0, dulceDeLeche = 0;
double sum = 0.0, totalPrice;
printf("Welcome to Daniela's Venezuelan emporium.\n");
printf("\nMay I take your order please?\n");
do
{
printf("\n\tMenu");
printf("\n1. Tequenos (5 ct.)\t $%5.2lf", TEQUENOS_PRICE);
printf("\n2. Arepa\t\t $%5.2lf", AREPA_PRICE);
printf("\n3. Cachapa\t\t $%5.2lf", CACHAPA_PRICE);
printf("\n4. Empanada\t\t $%5.2lf", EMPANADA_PRICE);
printf("\n5. Soda \t\t $%5.2lf", SODA_PRICE);
printf("\n6. Quesillo\t\t $%5.2lf", QUESILLO_PRICE);
printf("\n7. Dulce de Leche\t $%5.2lf", DULCE_DE_LECHE_PRICE);
printf("\n8. Done with this order.\n");
printf("\nEnter Item: ");
scanf("%i", &choice);
switch (choice)
{
case 1:
sum += TEQUENOS_PRICE;
tequenos++;
break;
case 2:
sum += AREPA_PRICE;
arepa++;
break;
case 3:
sum += CACHAPA_PRICE;
cachapa++;
break;
case 4:
sum += EMPANADA_PRICE;
empanada++;
break;
case 5:
sum += SODA_PRICE;
soda++;
break;
case 6:
sum += QUESILLO_PRICE;
quesillo++;
break;
case 7:
sum += DULCE_DE_LECHE_PRICE;
dulceDeLeche++;
break;
case 8:
break;
default:
printf("\n\t***ERROR: This is not on the menu.\n");
}
printf("\nTotal so far: $%.2lf\n", sum);
} while (choice != 8);
printf("\nThat's: ");
if (choice = 1)
{
printf(" %i Tequenos\n", tequenos);
}
if (choice = 2)
{
printf("\t %i Arepa\n", arepa);
}
if (choice = 3)
{
printf("\t %i Cachapa\n", cachapa);
}
if (choice = 4)
{
printf("\t %i Empanada\n", empanada);
}
if (choice = 5)
{
printf("\t %i Soda\n", soda);
}
if (choice = 6)
{
printf("\t %i Quesillo\n", quesillo);
}
if (choice = 7)
{
printf("\t %i Dulce De Leche\n", dulceDeLeche);
}
totalPrice = sum;
printf("\nYour total is $%.2lf\n", totalPrice);
printf("\nThank you for coming to Daniela's Venezuelan Emporium.");
printf("\nCome back soon!\n");
system("pause");
return 0;
}
The code works fine but my professor told me that I needed to call functions throughout the entire code, and that main should only be calling other functions. I have been trying but is really confusing for me and I do not know how to do it. I would really appreciate it if you guys could help me.
Thanks!
Here's your code, refactored slightly to break the major parts of your program out into separate functions.
#include <stdio.h>
#include <stdlib.h>
#define TEQUENOS_PRICE 5.00
#define AREPA_PRICE 3.00
#define CACHAPA_PRICE 2.50
#define EMPANADA_PRICE 2.00
#define SODA_PRICE 0.80
#define QUESILLO_PRICE 1.70
#define DULCE_DE_LECHE_PRICE 1.20
int tequenos = 0,
arepa = 0,
cachapa = 0,
empanada = 0,
soda = 0,
quesillo = 0,
dulceDeLeche = 0;
double sum = 0.0;
void print_header()
{
printf("Welcome to Daniela's Venezuelan emporium.\n");
printf("\nMay I take your order please?\n");
}
int get_menu_choice()
{
int choice;
printf("\n\tMenu");
printf("\n1. Tequenos (5 ct.)\t $%5.2lf", TEQUENOS_PRICE);
printf("\n2. Arepa\t\t $%5.2lf", AREPA_PRICE);
printf("\n3. Cachapa\t\t $%5.2lf", CACHAPA_PRICE);
printf("\n4. Empanada\t\t $%5.2lf", EMPANADA_PRICE);
printf("\n5. Soda \t\t $%5.2lf", SODA_PRICE);
printf("\n6. Quesillo\t\t $%5.2lf", QUESILLO_PRICE);
printf("\n7. Dulce de Leche\t $%5.2lf", DULCE_DE_LECHE_PRICE);
printf("\n8. Done with this order.\n");
printf("\nEnter Item: ");
scanf("%i", &choice);
return choice;
}
void process_menu_choice(int choice)
{
switch (choice)
{
case 1:
sum += TEQUENOS_PRICE;
tequenos++;
break;
case 2:
sum += AREPA_PRICE;
arepa++;
break;
case 3:
sum += CACHAPA_PRICE;
cachapa++;
break;
case 4:
sum += EMPANADA_PRICE;
empanada++;
break;
case 5:
sum += SODA_PRICE;
soda++;
break;
case 6:
sum += QUESILLO_PRICE;
quesillo++;
break;
case 7:
sum += DULCE_DE_LECHE_PRICE;
dulceDeLeche++;
break;
case 8:
break;
default:
printf("\n\t***ERROR: This is not on the menu.\n");
}
printf("\nTotal so far: $%.2lf\n", sum);
}
void take_order()
{
do
{
choice = get_menu_choice();
process_menu_choice(choice);
} while (choice != 8);
}
void print_total_for(char *item_type, int item_count)
{
if(item_count > 0)
printf(" %i %s\n", item_count, item_type);
}
int print_total(double totalPrice)
(
printf("\nYour total is $%.2lf\n", totalPrice);
printf("\nThank you for coming to Daniela's Venezuelan Emporium.");
printf("\nCome back soon!\n");
}
void print_total_header()
{
printf("\nThat's: ");
}
int main()
{
int choice = 0;
print_header();
take_order();
print_total_header();
print_total_for("Tequenos", tequenos);
print_total_for("Arepa", arepa);
print_total_for("Cachapa", cachapa);
print_total_for("Empanada", empanada);
print_total_for("Soda", soda);
print_total_for("Quesillo", quesillo);
print_total_for("Dulce De Leche", dulceDeLeche);
print_total(sum);
system("pause");
return 0;
}
Note: not compiled or tested. And if you copy this code, hand it in as your own, and your instructor flunks you for doing so - that's on you.
Best of luck.

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);
}

Switch statement executes case 2 even after break

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 ");
// ...

Resources