My do while loop is not looping correctly - c

I might be giving more than enough but long story short I am working on an ATM machine program and I am trying to put the "switch" statement in the main function inside a loop so the user can get more transactions.
I am running into a problem where I would deposit 100 but then when I check the balance it is still at 0. I know everything else works fine but that loop is killing me, I would appreciate any help!
Don't mind all of the extra stuff it is just there to give an idea on what i am working on
int main ()
{
char option;
float balance ;
int count = 1;
option = displayMenu();
do
{
switch (option)
{
case 'D':
getDeposit(balance);
main();
count++;
break;
case 'W':
getWithdrawal(balance);
main();
count++;
break;
case 'B':
displayBalance(balance);
main();
count++;
break;
case 'Q':
printf("Thank you!");
break;
main();
}
} while ( count <= 5);
return 0;
}
char displayMenu()
{
char option;
printf("\n Welcome to HFC Federal Credit Union \n");
printf("\n Please select from the following menu: \n ");
printf("\n D: Make a deposit \n ");
printf("\n W: Make a withdrawal \n ");
printf("\n B: Check your account balance \n ");
printf("\n Q: To quit \n ");
scanf("\n%c" , &option);
return option;
}
float getDeposit(float balance)
{
float deposit;
printf("\n Please enter the amount you want to deposit! ");
scanf("%f" , &deposit);
balance += deposit;
return balance;
}
float getWithdrawal(float balance)
{
float withdrawal;
printf("\n Please enter the amount you want to withdraw! ");
scanf("%f" , &withdrawal);
balance -= withdrawal;
return balance;
}
void displayBalance(float balance)
{
printf("\n Your current balance is %f " , balance);
}

You're recursively calling main() on every iteration of the loop. Just remove this call, and you should be good to go.
You'll also need to assign the return values of your functions to balance, otherwise they won't be able to affect its value.

There are a number of issues with this code... Here are my main pointers (but not all of them, I'm just answering the question):
You're calling main over and over again, for simplicity, you could consider this as restarting the application every time (except for stack issues, that I'm ignoring and other nasty side effects).
You didn't initialize the balance (and friends) variables. They might contain "junk" data.
You're ignoring the return values from the functions you use. If you're not using pointer, you should use assignment.
Your menu printing function is out of the loop... I doubt if that's what you wanted.
Here's a quick dirty fix (untested):
int main() {
char option;
float balance = 0;
int count = 1;
do {
option = displayMenu(); // moved into the loop.
switch (option) {
case 'D':
balance = getDeposit(balance);
count++;
break;
case 'W':
balance = getWithdrawal(balance);
count++;
break;
case 'B':
balance = displayBalance(balance);
count++;
break;
case 'Q':
printf("Thank you!");
break;
}
} while (count <= 5);
return 0;
}
char displayMenu(void) {
char option;
printf("\n Welcome to HFC Federal Credit Union \n");
printf("\n Please select from the following menu: \n ");
printf("\n D: Make a deposit \n ");
printf("\n W: Make a withdrawal \n ");
printf("\n B: Check your account balance \n ");
printf("\n Q: To quit \n ");
scanf("\n%c", &option);
return option;
}
float getDeposit(float balance) {
float deposit;
printf("\n Please enter the amount you want to deposit! ");
scanf("%f", &deposit);
balance += deposit;
return balance;
}
float getWithdrawal(float balance) {
float withdrawal;
printf("\n Please enter the amount you want to withdraw! ");
scanf("%f", &withdrawal);
balance -= withdrawal;
return balance;
}
void displayBalance(float balance) {
printf("\n Your current balance is %f ", balance);
}
Good Luck!

I think the main problem is the update of the switch control variable outside the loop.
Reacting to "Q" with ending is somewhat necessary... then only allowing 5 becomes unneeded.
I fixed several other things, too; and provided comments on them.
And I improved testability a little (5->6). I kept the counting, just extended to 6, in order to allow a complete test "D 100 , B, W 50, B ,Q".
Nice design by the way, to return the balance from the functions, instead of using pointers or global variable. But you need to use the return value instead of ignoring it.
/* include necessary headers, do not skip this when making your MCVE */
#include <stdio.h>
/* prototypes of your functions,
necessary to avoid the "immplicitly declared" warnigns
when compiling "gcc -Wall -Wextra"; which you should
*/
char displayMenu(void);
float getDeposit(float balance);
float getWithdrawal(float balance);
void displayBalance(float balance);
/* slightly better header of main, with "void" */
int main (void)
{
char option;
float balance=0.0; /* initialise your main variable */
int count = 1;
/* your very important update of the switch control variable has been moved ... */
do
{
option = displayMenu(); /* ...here */
/* If you do not update your switch variable inside the loop,
then it will forever think about the very first command,
this explains most of your problem.
*/
switch (option)
{
case 'D':
balance=getDeposit(balance); /* update balance */
/* removed the recursive call to main(),
it is not needed as a solution to the problem that the program
always uses the first command (when updating inside the loop)
and otherwise just makes everything much more complicated and
risky.
*/
count++;
break;
case 'W':
balance=getWithdrawal(balance); /* update balance */
count++;
break;
case 'B':
displayBalance(balance);
count++;
break;
case 'Q':
printf("Thank you!");
/* adding a way to get out of the loop,
using a magic value for the count,
this is a mehtod frowned upon by most,
but it minimises the changes needed to your
own coding attempt.
*/
count=0;
break;
}
} while ( (count <= 6)&&(count>0) ); /* additionally check for the magic "Q" value
check against count<=6, to allow testing D,B,W,B,Q */
return 0;
}
/* use explicitly empty parameter list for functions */
char displayMenu(void)
{
char option;
printf("\n Welcome to HFC Federal Credit Union \n");
printf("\n Please select from the following menu: \n ");
printf("\n D: Make a deposit \n ");
printf("\n W: Make a withdrawal \n ");
printf("\n B: Check your account balance \n ");
printf("\n Q: To quit \n ");
scanf("\n%c" , &option);
return option;
}
float getDeposit(float balance)
{
float deposit;
printf("\n Please enter the amount you want to deposit! ");
scanf("%f" , &deposit);
balance += deposit;
return balance;
}
float getWithdrawal(float balance)
{
float withdrawal;
printf("\n Please enter the amount you want to withdraw! ");
scanf("%f" , &withdrawal);
balance -= withdrawal;
return balance;
}
void displayBalance(float balance)
{
printf("\n Your current balance is %f " , balance);
}

you haven't changed the variable in main().
you can change the loop to this:
do
{
switch (option)
{
case 'D':
balance = getDeposit(balance);
count++;
break;
case 'W':
balance = getWithdrawal(balance);
count++;
break;
case 'B':
displayBalance(balance);
count++;
break;
case 'Q':
printf("Thank you!");
break;
}
} while (count <= 5);

Related

Passing the value from this function

#define _CRT_SECURE_NO_WARNINGS
/*
Purpose: This program allows the user to bet on horses
in a race to earn money on said wagers. I'm trying to run the configureBalance function and then add money to the balance. I'm getting an exception read access violation
*/
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("pause")
#define CLS system("cls")
#define FLUSH myFlush()
//Prototyping
void getChoice(char *userChoice); // main menu choice
void displayMenu(); // visual menu
void myFlush(); // flush
void configureBalance(int *balance, int *wallet, int *withdraw, int *deposit); // this function is for editing account credentials
void currentBalance(int *balance); // displays the account balance
void coolRaceVisual(); // cool looking visual
//Structs
main() {
int balance = 0, wallet = 0, withdraw = 0, deposit = 0;
char choice = ' ';
do {
getChoice(&choice);
switch (choice) {
case 'A':
configureBalance(balance, wallet, withdraw, deposit);
PAUSE;
break;
case 'B':
coolRaceVisual();
PAUSE;
break;
case 'Q':
CLS;
printf("[][][][][][][][][][][]\n");
printf("[] Goodbye ! []\n");
printf("[][][][][][][][][][][]\n");
break;
default:
printf("[][][][][][][][][][][][][][][][][][][][][][][]\n");//
printf("[] Invalid Selection! Please try again []\n");// This
prompt shows up when the user
printf("[][][][][][][][][][][][][][][][][][][][][][][]\n");//
inputs something incorrectly
PAUSE;
CLS;
break;
return;
}
} while (choice != 'Q');
PAUSE;
}//end main
void getChoice(char *userChoice) {
displayMenu();
scanf("%c", userChoice); FLUSH;
*userChoice = toupper(*userChoice);
}//end getChoice
void displayMenu() {
CLS;
printf(" Horse Derby Ticket Office \n");
printf(" \n");
printf(" A) Configure Balances. \n");
printf(" \n");
printf(" B) Watch the Race. \n");
printf(" \n");
printf(" C) View Race Records. \n");
printf(" \n");
printf(" D) Save and Quit. \n");
printf(" \n");
printf(" Q) Quit. \n");
printf(" \n");
}// end displayMenu
void myFlush() {
while (getchar() != '\n');
}//end myFlush
void configureBalance(int *balance, int *wallet, int *withdraw, int *deposit) {
CLS;
char configureMenuChoice = ' ';
printf("What service would you like? (Not FDIC Insured)\n\n");
printf("A) Add funds to your account balance.\n");
printf("B) Withdraw funds to your wallet.\n");
printf("C) Check Account Balance.\n");
printf("\n\n");
scanf("%c", &configureMenuChoice);
configureMenuChoice = toupper(configureMenuChoice);
Uppercases the choice configuring balances
if (configureMenuChoice == 'A') {
CLS;
printf("How much would you like to add to your account balance? \n");
This adds directly to the balance
scanf("%i", &deposit);
*balance = *balance + *deposit;
}
if (configureMenuChoice == 'C') {
CLS;
currentBalance(*balance); // displays current balance, made a functino so it can be used at will
}
}//end conFigureBalance
void currentBalance(int *balance) {
printf("Your current balance is: %i\n", &balance);
}//end checkBalance
Change this:
scanf("%i", &deposit);
to this:
scanf("%i", deposit);
since deposit is of type int* in that context (the body of the function configureBalance).
It's the same logic as followed here: scanf("%c", userChoice);, so I wonder how you missed it.

Setting A Balance For My C ATM

Hey guys I am constructing an ATM Program, and I have everything ok
I have the menu it pulls up you can select an option and it runs the function HOWEVER, I cannot for the life of me
set a balance and
get it to stay until its changed
and I need it to save once it has changed in one of the two options (deposit, withdrawl) since this is a post test loop it will keep going until exit is selected and every time I need this to update the balance.
Here is my C Code for it, if anyone could help that would be amazing.
#include <stdio.h>
#include <stdlib.h>
// Function Declarations
int getChoice ();
double withdraw (int Choice, int Balance);
double deposit (int Choice, int Balance);
int VBalance (int Choice, int Balance);
double process (int Choice, int Balance);
int main (void)
{
// Local Declarations
int Choice;
int Balance;
// Statements
do
{
Balance = 2500.00;
Choice = getChoice ();
process (Choice, Balance);
}
while (Choice != 0);
return 0;
} // Main
/*============================process=*/
double process (int Choice, int Balance)
{
// Declarations
// Statements
switch(Choice)
{
case 1: withdraw (Choice, Balance);
break;
case 2: deposit (Choice, Balance);
break;
case 3: VBalance (Choice, Balance);
break;
case 0: exit;
break;
deafult: printf("Sorry Option Not Offered");
} // switch
return 0;
}
/*============================getChoice=*/
int getChoice (void)
{
// Local Declarations
char Choice;
// Statements
printf("\n\n**********************************");
printf("\n MENU ");
printf("\n\t1.Withdrawl Money ");
printf("\n\t2.Deposit Money ");
printf("\n\t3.View Balance ");
printf("\n\t0.Exit ");
printf("\n**********************************");
printf("\nPlease Type Your Choice Using 0-3");
printf("\nThen Hit Enter: ");
scanf("%d", &Choice);
return Choice;
} //getchoice
/*============================withdraw=*/
double withdraw (int Choice, int Balance)
{
// Local Declarations
double amount;
// Statements
printf("Funds:%d", &Balance);
printf("\nPlease Enter How Much You Would Like To Withdraw: ");
scanf("%f", &amount);
Balance = Balance - amount;
return Balance;
} //withdraw
/*============================Deposit=*/
double deposit (int Choice, int Balance)
{
// Local Declarations
double amount;
// Statements
printf("Funds:%d", &Balance);
printf("\nPlease Enter How Much You Would Like To Deposit: ");
scanf("%f", &amount);
Balance = Balance + amount;
return Balance;
} //Deposit
/*============================VBalance=*/
int VBalance (int Choice, int Balance)
{
// Statements
printf("\nYour Current Funds:%d", &Balance);
printf("\nThank Your For Viewing");
return 0;
}
First: Enable compiler warnings. If you use gcc, add -Wall to the command line. If you use an IDE the option to turn on warnings should be in the compiler settings.
When you compile with warnings you will find that you have some problems with your use of printf and scanf. Fix those!
Next you have the problem with Balance in main not getting updated. C uses call by value which means that the changes you make to a function argument are not visible in the calling function. To work around that you could declare the balance parameters as pointers and pass the address of Balance. Or you could return the new Balance, just like you do in your code. The only thing you forgot is to store the new value to Balance in main.
Changed line in main:
Balance = process(Choice, Balance);
Changed process:
double process(int Choice, int Balance)
{
// Declarations
// Statements
switch (Choice)
{
case 1: Balance = withdraw(Choice, Balance); // Changed line
break;
case 2: Balance = deposit(Choice, Balance); // Changed line
break;
case 3: Balance = VBalance(Choice, Balance); // Changed line
break;
case 0: exit;
break;
deafult: printf("Sorry Option Not Offered");
} // switch
return Balance; // Changed line
}
Third: Balance is declared an int, but you sometimes use double. You should choose one type and stick to it. Due to the nature of floating point numbers it is actually recommended that an integral type is used for money.

How to make getchar() read a negative number?

I am writing a program that can calculate the areas of a square, cube, and circle. The program needs to present an error message and allow the user to enter a new choice if they enter something not included in the menu. My problem is that if they type anything includes my menu options then the program still executes. (i.e. -1, 23, 344) I was wondering how to get it to ignore anything after the first character or to read the whole string. Or if there is something better than getchar(). I'm open to any solutions! Thank you!
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int choice;
int lengthsq;
int areasq;
int lengthcube;
int areacube;
int radius;
double circlearea;
printf("Area Calculation\n");
printf("(1) Square\n");
printf("(2) Cube\n");
printf("(3) Circle\n");
fputs("Please make a selction: ", stdout);
while((choice = getchar()) != '\n')
switch (choice) {
case '1':
printf("\nPlease enter the length: ");
scanf("%d", &lengthsq);
while(lengthsq <= 0){
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthsq);
}
areasq = lengthsq * lengthsq;
printf("The area of the square is %d.", areasq);
return 0;
case '2':
printf("\nPlease enter the length: ");
scanf("%d", &lengthcube);
while (lengthcube <= 0) {
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthcube);
}
areacube = 6 * lengthcube * lengthcube;
printf("The surface area of the cube is %d.\n", areacube);
return 0;
case '3':
printf("\nPlease enter the radius: ");
scanf("%d", &radius);
while(radius <= 0){
printf("Error! Pleae enter a postive number: ");
scanf("%d", &radius);
}
circlearea = 3.14159 * radius * radius;
printf("The area of the circle is %.2f.\n", circlearea);
return 0;
case '\n':
case '\t':
case ' ':
break;
default:
printf("\nInvalid choice entered.\n");
fputs("Enter a new choice: ", stdout);
break;
}
}
You could add another switch case for the dash, which would toggle some kind of negative flag and then read a number as you're already doing. If you do not like introducing such a flag, then the best option would be using fgets, which returns the entire input line. But that has the downside that you need to parse the input. I.e. do some string manipulation, which may be slightly more complex than a simple flag parameter.
On the other hand, from the code you attached, I deduct that the only valid input consists of mere numbers (integers). You could just read an integer then with scanf.

Receiving Run-Time Check Failure #2

I would like to ask why am i getting Run-time Check Failure #2 When i am doing my program?
I'm very new to C programming.
I'm trying to make a Console application that have some option after they key in Y/N,
But whenever i reach the end of all the option i get that error.
Could anyone tell me how i could solve it & what is the proper way of doing this kind of programming?
#define _CRT_SECURE_NO_WARNINGS // To allow Visual studio to use "scanf" function
#include <stdio.h> // Standard Input output . header
#include <Windows.h>
void codername() {
printf("Coder: Rong Yuan\n");
}
void projectname() {
printf("Project name: NPoly Learning\n");
}
void loadcurrentdate() {
SYSTEMTIME str_t;
GetSystemTime(&str_t);
printf("Date: %d . %d . %d \n"
, str_t.wDay, str_t.wMonth, str_t.wYear);
}
int main() {
char option;
int input;
int mincome, fmember, total;
printf("Do you like to see our option? Y/N \n");
scanf("%s", &option);
if (option == 'y' || option == 'Y') {
printf("1. Display Coder Detail\n");
printf("2. Display Project Name\n");
printf("3. Load Current Date\n");
printf("4. Calculator PCI\n");
printf("5. Exit\n");
scanf("%d", &input);
}
else
exit(1);
switch (input) {
case 1:
codername();
printf("Do you like to return to main?");
break;
case 2:
projectname();
break;
case 3:
loadcurrentdate();
break;
case 4:
printf("Enter your house monthly income: ");
scanf("%d", &mincome);
printf("Enter total family member: (INCLUDING YOURSELF) ");
scanf("%d", &fmember);
total = mincome / fmember;
printf("Total PCI: %d / %d = %d \n", mincome, fmember, total);
system("pause");
break;
case 5:
exit(0);
}
}
scanf("%s", &option);
is wrong as option is a char . So replace %s with %c there.%s should be used for strings (array of characters) and %c is the format specifier used for a character.

undeclared identifier in C

I am trying to compile a small bank program in C in visual studio 2012 express. It shows me this error "undeclared identifier" for almost all variables and this one too "syntax error: missing ';' before 'type'".Please tell me the correct syntax.Thank you.
#include<stdio.h>
#include<conio.h>
int main()
{
printf("Welcome to skybank\n");
int deposit,withdraw,kbalance;
char option;
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf_s("%c",option);
int decash,wicash;
switch(option)
{
int balance;
printf("Enter your current Balance\n");
scanf_s("%d",&balance);
case 1:
printf("Enter the amount you want to deposit\n");
scanf_s("%d",&decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n",decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf_s("%d",&wicash);
int wibal;
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n",wicash);
printf("Your balance is %d\n",wibal);
break;
case 3:
printf("Your balance is Rs.%d\n",balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
The Microsoft C compiler only supports a 25 year old version of the language. And one of the limitations is that all variables must be declared before any other statements. So move all your variable declarations to the top of the function.
The next error I can see is the use of scanf_s with the %c format string. You must pass a pointer to the variable, and pass the number of characters to read.
scanf_s("%c", &option, 1);
And likewise you need to pass an address for the read of balance.
You also need to change the switch statement so that it just contains cases. Move the bare instructions outside.
Your reading of option won't work. Because when you check for 1 you are checking for the character with ASCII code 1. Change option to be an int and read using %d.
Perhaps you are looking for something like this:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int deposit,withdraw,kbalance;
int option;
int decash,wicash;
int balance;
int wibal;
printf("Welcome to skybank\n");
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf_s("%d", &option);
printf("Enter your current Balance\n");
scanf_s("%d", &balance);
switch(option)
{
case 1:
printf("Enter the amount you want to deposit\n");
scanf_s("%d", &decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n", decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf_s("%d", &wicash);
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n", wicash);
printf("Your balance is %d\n", wibal);
break;
case 3:
printf("Your balance is Rs.%d\n", balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
Regarding the unidentified variables, try putting all declarations of variables at the top of the main block, something like:
int main()
{
int deposit, withdraw, kbalance, decash, wicash, wibal;
char option;
printf("Welcome to skybank\n");
Older variants of C frown upon mixing variable declarations with code. To my knowledge the C standard of Microsoft's C implementation is pre-C99 so perhaps this could be the issue.
A few other issues that you should look into:
scanf_s("%c",option); - option should be &option as you are taking a pointer to that variable.
Also here: case 1:
You want '1' (as in case '1') instead of plain 1 as it is a char, not an int you want.
Same for the other case checks.
With regards to the scanf_s problems, try compiling with warnings, it should have been pointed out by the compiler.
Finally, you might want to rid your code of the variables you're not using such as kbalance, withdraw and deposit.
do at the beginning of the block in the declaration of the variable for visual c.
E.g.
int main()
{
int deposit,withdraw,kbalance;
char option;
int decash,wicash
int balance;
int wibal;
...
try this code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("Welcome to skybank\n");
int deposit,withdraw,kbalance;
char option;
printf("Press 1 to deposit cash\n");
printf("Press 2 to Withdraw Cash\n");
printf("Press 3 to Know Your Balance\n");
scanf("%c",&option);
int decash,wicash;
switch(option)
{
int balance;
printf("Enter your current Balance\n");
scanf("%d",&balance);
case 1:
printf("Enter the amount you want to deposit\n");
scanf("%d",&decash);
printf("Thank You\n");
printf("%d have been deposited in your account\n",decash);
break;
case 2:
printf("Enter the amount you want to withdraw\n");
scanf("%d",&wicash);
int wibal;
wibal=balance-wicash;
printf("Thank You\n");
printf("%d have been withdrawed from your account\n",wicash);
printf("Your balance is %d\n",wibal);
break;
case 3:
printf("Your balance is Rs.%d\n",balance);
break;
default:
printf("Invalid Input\n");
break;
}
getchar();
}
Move this:
int balance;
printf("Enter your current Balance\n");
scanf_s("%d",&balance);
Before the switch statement.

Resources