Why is the loop not stopping? - c

#include <stdio.h>
#include <stdlib.h>
#define NEWGEAR 15.0
#define USEDGEAR 5.0
int main() {
int type;
int num_items;
float total;
printf("Welcome to the market\n");
printf("What would you like to do\n");
printf("\t1-Buy New Gear\n");
printf("\t2-Buy used gear\n");
printf("\t3-Quit\n");
scanf("%d", &type);
while (type != 3) {
switch (type) {
case 1:
printf("How many new items would you like?\n");
scanf("%d", &num_items);
total = num_items * 15.0;
break;
This is where the code keeps on asking how many new items would you like?
case 2:
printf("How many old items would you like?\n");
scanf("%d", &num_items);
total = num_items * USEDGEAR;
break;
This is where the code keeps on asking how many old items would you like?
case 3:
break;
default:
printf("Not a valid option\n");
break;
}
}
printf("Your total cost is %f\n",total);
return 0;
}
Both my choices are looping

You never update the type variable to 3, so the while loop never terminates. Although you do have a break statement, it is affecting the switch and not the while loop that surrounds it.

I think this will handle what you want to achieve.
#include <stdio.h>
#include <stdlib.h>
#define NEWGEAR 15.0
#define USEDGEAR 5.0
int main() {
int type = 0;
int num_items;
float total;
printf("Welcome to the market\n");
printf("What would you like to do\n");
printf("\t1-Buy New Gear\n");
printf("\t2-Buy used gear\n");
printf("\t3-Quit\n");
while (type != 3) {
printf("Enter an option: ");
scanf("%d", &type);
if(type == 3)
break;
switch (type) {
case 1:
printf("How many new items would you like?\n");
scanf("%d", &num_items);
total = num_items * 15.0;
break;
case 2:
printf("How many old items would you like?\n");
scanf("%d", &num_items);
total = num_items * USEDGEAR;
break;
default:
printf("Not a valid option\n");
break;
}
}
printf("Your total cost is %f\n",total);
return 0;
}
Basically, after your user finished doing cases 1-2 or default, your program would prompt your user for an option again if he wants to quit or perform another case 1 or 2 operation.

Your loop logic is flawed:
you should move the prompt code inside the loop.
you should update total for each answer.
you should test if scanf() is successful at converting user input.
Here is a modified version:
#include <stdio.h>
#define NEWGEAR 15.0
#define USEDGEAR 5.0
int main() {
int type;
int num_items;
double total = 0;
printf("Welcome to the market\n");
for (;;) {
printf("What would you like to do\n");
printf("\t1-Buy New Gear\n");
printf("\t2-Buy used gear\n");
printf("\t3-Quit\n");
if (scanf("%d", &type) != 1 || type == 3)
break;
switch (type) {
case 1:
printf("How many new items would you like?\n");
if (scanf("%d", &num_items) == 1)
total += num_items * 15.0;
break;
case 2:
printf("How many old items would you like?\n");
if (scanf("%d", &num_items) == 1)
total += num_items * USEDGEAR;
break;
default:
printf("Not a valid option\n");
break;
}
}
printf("Your total cost is %f\n", total);
return 0;
}

Related

Problem: Scholarship Endowment Fund Part 2 (fund2.c)

Problem: Scholarship Endowment Fund Part 2 (fund2.c)
How do I return back to main menu and add a counter for the total number of donations and investment made, here's what i got?
Then, your program should allow the user the following options:
Make a donation
Make an investment
Print balance of fund
Quit
#include <stdio.h>
#include <stdlib.h>
//main functions
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!\n");
printf("What is the initial balance of the fund\n");
scanf("%d", &fund);
int ans;
printf("What would you like to do?\n");
printf("\t1- Make a Donation\n");
printf("\t2- Make an investment\n");
printf("\t3- Print balance of fund\n");
printf("\t4- Quit\n");
scanf("%d", &ans);
if (ans == 1) {
printf("How much would you like to donate?\n");
scanf("%d", &donation);
}
if (ans == 2) {
printf("How much would you like to invest?\n");
scanf("%d", &investment);
return main();
}
if (ans == 3) {
total = donation + fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amount\n");
return main();
}
else {
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
}
}
if (ans == 4) {
printf("Type 4 to quit\n");
}
else {
printf("Not a valid option.\n");
}
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?\n");
scanf("%d", &donation);
return main();
case 2:
printf("How much would you like to invest\n");
scanf("%d", &investment);
return main();
case 3:
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
return main();
case 4:
break;
}
return 0;
}
You should put in a loop the part that you want to be repeated, using a varaible to decide when to stop.
here is an example, also in the switch costruct you should usa a default option, maybe to warn the user that the option they inserted is not valid.
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!\n");
printf("What is the initial balance of the fund\n");
scanf("%d", &fund);
//loop until the user decide so
int exit = 0;
while(exit == 0){
int ans;
printf("What would you like to do?\n");
printf("\t1- Make a Donation\n");
printf("\t2- Make an investment\n");
printf("\t3- Print balance of fund\n");
printf("\t4- Quit\n");
scanf("%d", &ans);
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?\n");
scanf("%d", &donation);
break;
case 2:
printf("How much would you like to invest\n");
scanf("%d", &investment);
break;
case 3:
total = donation + fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amount\n");
}
else {
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
}
break;
case 4:
exit = 1;
break;
default:
printf("Incorrect option\n");
break;
}
}
return 0;
}

Trying to find duplicates in a Struct Array in C

I've attempted to find if the user has inputted a product id value that's a duplicate and if so, it just tells them that it's a duplicate value and then returns to the menu in my switch statement.
The actual result i get, is that after "productsfilled == 0", it won't utilise the For Loops to check for the duplicates and productsfilled will remain at 1. I've looked online and this way of finding duplicates tends to work and i have used it previously in my code, so I don't think that could be the issue.
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <conio.h>
int productsfilled;
struct ProductData{
int product_id;
char product_name[120];
int price;
};
int quiz_5(){
char ch;
int size, input = 0;
struct ProductData products[20];
while(1){
printf("\nWelcome To The Super Mall's Product List. Please Select An Option:\n1. Add Product\n2. Display Product\n3. Delete Product\n");
fflush(stdin);
switch(getchar()){
case '1':
printf("\nPlease Enter Product ID:");
scanf("%d",&products[productsfilled].product_id);
printf("\nPlease Enter Product Name:");
scanf("%s",&products[productsfilled].product_name);
printf("\nPlease Enter Product Price:");
scanf("%d",&products[productsfilled].price);
printf("Productsfilled: %d",productsfilled);
if(productsfilled == 0){
productsfilled = 1;
break;
}
for(int i = 0; i < productsfilled;i++){
for (int j = i + 1; j < productsfilled;j++){
if(products[i].product_id == products[j].product_id){
printf("\nPlease Use Different Product ID");
break;
}else{
printf("test");
productsfilled += 1;
break;
}
}
}
break;
case '2':
while(1){
for(int i = 0;i < productsfilled;i++){
printf("Product ID: %d Product Name: %s Product Price: %d\n",products[i].product_id,products[i].product_name,products[i].price);
}
printf("Please Press Enter To Continue");
fflush(stdin);
if(getchar() == '\n'){
break;
}
}
case '3':
break;
case '\n':
break;
default:
printf("Please Select An Option:\n1. Add Product\n2. Display Product\n3. Delete Product: ");
}
}
}
int main() {
int input = 1;
printf("Welcome to my assignment. Which quiz do you want to run (please input the number of the quiz e.g. for quiz 1, type 1): \n-Quiz 1\n-Quiz 2\n-Quiz 3\n-Quiz 4\n-Quiz 5\n-Quiz 6\n-Quiz 7\n");
while(input == 1){
fflush(stdin);
switch(getchar()){
case '5':
quiz_5();
break;
case '\n':
printf("Welcome to my assignment. Which quiz do you want to run (please input the number of the quiz e.g. for quiz 1, type 1): \n-Quiz 1\n-Quiz 2\n-Quiz 3\n-Quiz 4\n-Quiz 5\n-Quiz 6\n-Quiz 7\n");
getchar();
default:
printf("Invalid Input\n");
} }
return 0;
}
The problem is that you don't increment productsfilled before you enter the loop...therefore, productsfilled is always 1 less than the actual length of your array which means that you don't compare all elements in the array.
Try your program on 2 inputs, both with the same ID. You'll see that you don't compare anything.
You are wrong when using scanf for string input:
scanf("%s",&products[productsfilled].product_name);
You should not use &, you should use as below:
scanf("%119s",products[productsfilled].product_name);
OT, in main function:
switch(getchar()){
case '5':
...
Because getchar() will return int value, so if you want to access to quiz_5, you have to type 35 (ANSCI code) instead of type 5 when you run your program.
char a = '5';
similar to:
int a = 35;

Gradebook, array not saving

So I'm trying to make a grade book that does everything displayMenu() says. But i cant even get the student ID to save when i go to view the grades. Please Help.
Everything is initialized here
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define EXAMS 100
#define STUDENT 4
void displayArray(float grades[STUDENT][EXAMS]);
void newStudent(float grades[STUDENT][EXAMS]);
void displayStudentAverage(float grades[STUDENT][EXAMS]);
int main() {
float grades[STUDENT][EXAMS];
This is everything the program should do
displayMenu(grades, 0 );
} // end of main;
int displayMenu(float grades[STUDENT][EXAMS]) {
printf("\t \t MENU \t \t");
printf("Enter Corresponding Number\n");
printf("1.Enter New Student\n");
printf("2.Change Existing Grades\n");
printf("3.View All Grades\n");
printf("4.View Average Score Per Student\n");
printf("5.View Average Score Per Exam\n");
printf("6.View Average Score For The class\n");
printf("7.CLEAR GRADEBOOK\n");
printf("8. Save Gradebook\n");
printf("8.Exit\n");
int choice = 0;
scanf("%d", &choice);
switch (choice) {
case 1:
newStudent(grades, 0);
CLS;
displayMenu(grades,0);
break;
case 2:
break;
case 3: displayArray(grades, 0);
CLS;
displayMenu(grades,0);
break;
case 4:
displayStudentAverage(grades, 0);
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
exit(0);
break;
case 9:
exit(0);
break;
default: printf("You Have entered an incorrect number");
PAUSE;
}
}
This is what displays the grades
void displayArray(float grades[STUDENT][EXAMS]) {
printf("%.1f\t", grades[STUDENT][EXAMS]);
}
I'm trying to add the values to the array here
void newStudent(float grades[STUDENT][EXAMS]) {
float addgrade;
printf("Please Enter Student ID: ");
scanf("%f", &grades[STUDENT][EXAMS]);
printf("Enter four exam grades, use comma to split grades");
scanf("%f", addgrade);
grades[STUDENT][EXAMS] += addgrade;
PAUSE;
CLS;
}
void displayStudentAverage(float grades[STUDENT][EXAMS]) {
int sum, loop;
float avg;
sum = avg = 0;
for (loop = 0; loop < 10; loop++) {
sum = sum + grades[loop];
}
avg = (float)sum / loop;
printf("Average of array values is %.2f", avg);
}
First of all, it's always good check the compiler warnings to get some hints to possible bugs...
Here's a list of problems in the code:
no header files included
displayMenu prototype is missing
the grades array is used with inconsistent types (float/int)
with grades[STUDENT][EXAMS] the grades array is accessed out of bounds (for example if you define an array of size 5 you can only access position 0 to 4)
the return type of main needs to be int
the function newStudent has return type void but the code tries to return something with return &grades[STUDENT][EXAMS];
Apart from that, the code should work...

Calling a function in printf in C?

I am a beginner in C programming.
I was writing a simple program to calculate average.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int n, s = 0, num, i;
float avg;
printf("Enter value of total no\n");
scanf("%d", &n);
for (i=1; i<=n; i++)
{
void pri(int i){
switch(i){
case 1:
printf("st");
break;
case 2:
printf("nd");
break;
case 3:
printf("rd");
break;
default:
printf("th");
break;
}
}
printf("Enter %d pri(i) number\n", i);
scanf("%d", &num);
s += num;
}
avg = s / n;
printf("The average is %f",avg);
return 0;
}
But pri(i) is not working as I expected. But later I found another way to do this, so here is the second version of this code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int n, s = 0, num, i;
float avg;
printf("Enter value of total no\n");
scanf("%d",&n);
for (i=1; i<=n; i++)
{
void pri(int i){
switch(i){
case 1:
printf("enter 1st number\n");
break;
case 2:
printf("enter 2nd number\n");
break;
case 3:
printf("enter 3rd number\n");
break;
default:
printf("enter %dth number\n",i);
break;
}
}
pri(i);
scanf("%d", &num);
s += num;
}
avg = s / n;
printf("the average is %f",avg);
return 0;
}
I want to get the results of this second piece of code from the first version.
Can I call functions in printf which are defined somewhere in program?
You cannot tell printf() to call another function in the middle of its execution. printf() expects to receive a formatting string and arguments to replace parts of this string. What you're trying to do (embed a function call in the formatting string) is not possible for a number of reasons.
What you can do is return the string instead of printing it and use it as argument.
const char *pri(int i) {
switch(i) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
printf("enter %d%s number\n", i, pri(i));
C doesn't support nested functions (function defined inside another function). Your code works because your compiler adds support for such functions as an extension. In general, you should probably avoid nesting functions.

ATM Machine in C

I've been writing the code for an ATM inter face where i include a pin that must be imputed by the user to access the options. Once thats done, I get 5 options to choose from such as fast cash, withdraw, deposit and check balance. everything seems to be running good the only thing is that the account balance is not be updated to the correct amount when the user deposits, withdraws, or gets fast cash. Can someone help me fix this. I'll post my code down below
#include <stdio.h>
int fastCash(int amount);
int deposit(int deposit);
int withdraw(int balence);
void checkBalence(int balence);
int main()
{
int pin;
int pins = 9999;
int pinTries = 1;
int reciept;
int options;
int options2;
int balence = 300;
int fastCashChoice;
printf("Enter your pin:");// the pin is 9999
scanf("%d", &pin);
while (pinTries <= 3)
{
if (pin == pins)
{
printf("Would you like a reciept:");
//1 is equal to yes and 2 is equal to no
scanf("%d", &reciept);
printf("Choose from the following:\n");
printf("1. Fast cash\n2. Withdraw\n3. Deposit\n4. Check balence\n5. Get card back");
scanf("%d", &options);
while (options <= 5)
{
switch (options)
{
case 1:
fastCash(fastCashChoice);
balence = balence - fastCashChoice;
break;
case 2:
withdraw(balence);
break;
case 3:
deposit(balence);
break;
case 4:
checkBalence(balence);
break;
case 5:
options2 == 2;
break;
}
printf("Would you like anohter transaction: ");// 1 is equal to yes and 2 is equal to no
scanf("%d", &options2);
if (options2 == 1)
{
printf("1. Fast cash\n2. Withdraw\n3. Deposit\n4. Check balence\n5. Get card back");
scanf("%d", &options);
}
else
{
options = 5;
pinTries = 4;
printf("Thank you for useing this ATM, GoodBye\n");
}
}
}
else if (pin != pins)
{
printf("Invalid pin, try again:");
scanf("%d", &pin);
pinTries++;
}
if (pinTries == 3)
{
printf("Sorry, you cant continue, please contact your bank");
}
}
return 0;
}
int fastCash(int amount)
{
int choice;
printf("1. $20.00\n2. 40.00\n3. 80.00\n4. 100.00\n5. Exit");
scanf("%d", &choice);
switch (choice)
{
case 1:
amount = 20;
case 2:
amount = 40;
case 3:
amount = 80;
case 4:
amount = 100;
case 5:
break;
}
return amount;
}
int withdraw(int balence)
{
int withdrawAmount;
printf("Enter the amount you would like to withdraw: ");
scanf("%d", &withdrawAmount);
balence = -withdrawAmount;
return balence;
}
int deposit(int balence)
{
int depositAmount;
printf("Enter an amount you would like to deposit: ");
scanf("%d", &depositAmount);
balence += depositAmount;
return balence;
}
void checkBalence(int balence)
{
printf("Your current balence is: %d\n", balence);
return;
}
When you pass an int (or any other non-pointer variable, for that matter) to a function, you only pass a copy of it. If the function then changes it (as deposit, e.g., does), it will only change the passed copy, and won't affect the original variable. Instead, you need to pass a pointer to the original value. E.g.:
int deposit(int* balance)
{
int depositAmount;
printf("Enter an amount you would like to deposit: ");
scanf("%d", &depositAmount);
*balance += depositAmount;
}
And the calling function should pass the pointer to this variable instead of the variable itself:
case 3:
deposit(&balance);
/* Here-^ */
break;
In your code, you seem to just pass in the deposit to the function, but you don't reference it back to the original balence variable, so the balance stays at 300.
For example, in the function:
int deposit(int balence)
{
int depositAmount;
printf("Enter an amount you would like to deposit: ");
scanf("%d", &depositAmount);
balence += depositAmount;
return balence;
}
You just sent in your balence in, but like how Mureinik said, you just passed in the original value without changing its value (it only changed the balence inside of deposit().
Instead, you can pass it in by reference, or you can move balence to the top of the code as a global variable so that all the functions can see it:
//code here.....
void checkBalence();
int balence = 300;
//more code here...
Also make sure to remove the balence call in the deposit() function to avoid ambiguity between the local and global variables..
int deposit()
{
/*..original code here..*/
}
...and now, in the deposit() function, your balence variable now points to the global balence.
Here is the final, corrected code:
#include <stdio.h>
int fastCash(int amount);
int deposit();
int withdraw();
void checkBalence();
int balence = 300;
int main()
{
int pin;
int pins = 9999;
int pinTries = 1;
int reciept;
int options;
int options2;
int fastCashChoice;
printf("Enter your pin:");// the pin is 9999
scanf("%d", &pin);
while(pinTries <= 3)
{
if(pin == pins)
{
printf("Would you like a reciept:");
//1 is equal to yes and 2 is equal to no
scanf("%d", &reciept);
printf("Choose from the following:\n");
printf("1. Fast cash\n2. Withdraw\n3. Deposit\n4. Check balence\n5. Get card back");
scanf("%d", &options);
while(options <= 5)
{
switch(options)
{
case 1:
fastCash(fastCashChoice);
balence = balence - fastCashChoice;
break;
case 2:
withdraw(balence);
break;
case 3:
deposit(balence);
break;
case 4:
checkBalence(balence);
break;
case 5:
options2 = 2;
break;
}
printf("Would you like anohter transaction: ");// 1 is equal to yes and 2 is equal to no
scanf("%d", &options2);
if(options2 == 1)
{
printf("1. Fast cash\n2. Withdraw\n3. Deposit\n4. Check balence\n5. Get card back");
scanf("%d", &options);
}
else
{
options = 5;
pinTries = 4;
printf("Thank you for useing this ATM, GoodBye\n");
break;
}
}
}
else if(pin != pins)
{
printf("Invalid pin, try again:");
scanf("%d", &pin);
pinTries++;
}
if(pinTries == 3)
{
printf("Sorry, you cant continue, please contact your bank");
}
}
return 0;
}
int fastCash(int amount)
{
int choice;
printf("1. $20.00\n2. 40.00\n3. 80.00\n4. 100.00\n5. Exit");
scanf("%d", &choice);
switch(choice)
{
case 1:
amount = 20;
case 2:
amount = 40;
case 3:
amount = 80;
case 4:
amount = 100;
case 5:
break;
}
return amount;
}
int withdraw()
{
int withdrawAmount;
printf("Enter the amount you would like to withdraw: ");
scanf("%d", &withdrawAmount);
balence -= withdrawAmount;
return balence;
}
int deposit()
{
int depositAmount;
printf("Enter an amount you would like to deposit: ");
scanf("%d", &depositAmount);
balence += depositAmount;
return balence;
}
void checkBalence(int balence)
{
printf("Your current balence is: %d\n", balence);
return;
}
Now, it should run as expected, here producing a final balance of $176:
Enter your pin:9999
Would you like a reciept:1
Choose from the following:
1. Fast cash
2. Withdraw
3. Deposit
4. Check balence
5. Get card back2
Enter the amount you would like to withdraw: 124
Would you like anohter transaction: 1
1. Fast cash
2. Withdraw
3. Deposit
4. Check balence
5. Get card back4
Your current balence is: 176
Well, an easy solution to your problem is to declare your int balence as global. Instead of declaring it inside main() function, you can declare it above the main() function.
This will solve your current problem.
Both deposit and withdraw returns the updated balance but you don't use the return value. Try changing the calls to:
case 2:
balence = withdraw(balence);
break;
case 3:
balence = deposit(balence);
break;
fastCash returns the amount of cash to withdraw, so you need to update the balance in main:
case 1:
balence = balence - fastCash(fastCashChoice);
break;
This avoids both pointers (for which you would want additional error handling, i.e. check for NULL) and global variables (which makes your program more complex*).
There are also a few more problems in your code. The argument sent to fastCash isn't really used at all, since you return the amount to withdraw.
* Are global variables bad?

Resources