I know from my code it's a bit of a mess as I'm a beginner to programming. I just wanted to see if someone could just quickly help me out by letting me know how to get the users input stored into an array and do what my code already does. So, I want the user to input the amount of tickets and then that gets stored in an array then printed like my code already does. Just want to try and cut down my code as it is very messy and need to store it in an array I've been told but I'm stumped at the moment.
#include <stdio.h>
#include<conio.h>
#include<stdbool.h>
#define MAX 10
void showPrices();
void showRoutes();
void orderTickets();
void main()
{
int userChoice;
while(1)
{
// Looping the menu for the user
printf("\n\n**** MENU ****");
printf("\n*NOTE* MAX TICKETS PER CUSTOMER = 10");
printf("\n1. Show Prices\n2. Show Routes\n3. Order Tickets\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &userChoice);
//gets to chose between the different options
switch(userChoice)
{
case 1: showPrices();
break;
case 2: showRoutes();
break;
case 3: orderTickets();
break;
case 4: exit(0);
default: printf("\nInvalid, try again!!!");
}
}
}
void showPrices()
{
//for the switch statement, this is what I want to be displayed when they pick this option
printf("\n\n---- Prices - ALL DAY ----");
printf("\n1. Child = £3\n2. Teenager = £5\n3. Standard = £10\n4. Student = £7\n5. Senior = £6");
}
void showRoutes()
{
//for the switch statement, this is what I want to be displayed when they pick this option
printf("\n\n---- Routes - ALL DAY ----");
printf("\n---- Leaving from Nottingham Station ----");
printf("\nDestinations:\nDerby\nLeicester\nSheffield\nBirmingham");
}
void orderTickets()
{
int ticketArray[tickets];
int age;
int userInput = 0;
int tickets;
int ticketSum = 0;
int ticketNumber = 1;
int sum;
int userDesti;
//Main function where the user oders the tickets!
printf("\nWhere do you want to go?");
printf("\n1. Derby\n2. Leicester\n3. Sheffield\n4. Birmingham");
scanf("%d", &userDesti);
//asks the user how many tickets they want
printf ("\nHow many tickets do you need?: ");
scanf ("%d", &tickets);
//loop to keep asking the user to input the information they need to enter for each ticket until it reaches 0
while (tickets > 0)
{
/*only does this if they enter 10 or less and more than 0
if (tickets <= 10 && tickets > 0)
{
printf("\nHow old are you?: ");
scanf("%d", &age);
if(age < 10)
{
printf("\nChild Ticket = £3\n");
ticketSum = ticketSum + 3;
}
else if (age < 16)
{
printf ("\nTeenager Ticket = £5\n");
ticketSum = ticketSum + 5;
}
else if (age >= 16 && age < 60)
{
printf("\nStandard Ticket = £10\n");
ticketSum = ticketSum + 10;
}
else
{
printf("\nSenior Ticket = £6\n");
ticketSum = ticketSum + 6;
}
}
//if they enter an invalid number
else
{
printf("Error, invalid number of tickets!!\n");
break;
}*/
// this allows the student discount to be deducted from the final price
printf("\nAre you a student? Enter 1 for yes or 2 for no: ");
scanf("%i", &userInput);
if(userInput == 1)
{
printf ("\nYou are eligible for the student discount = £3 deducted\n");
//sum to deduct the discount
ticketSum = ticketSum - 3;
}
//if they aren't a student then they will get this message
else if (userInput == 2)
{
printf ("\nYou are not eligible for the student discount, sorry!\n");
}
// gives the user their number for that ticket
printf("\n------------------");
printf("\nTicket Number: %d ", ticketNumber);
printf("\n------------------\n");
ticketNumber++;
// lets the user know how much each ticket adds onto the previous
printf("\n-----------------------");
printf("\nThe summary so far: %d ", ticketSum);
printf("\n-----------------------\n");
// gets out of the main loop when the tickets are less than or equal to 0
if (tickets <= 0 )
{
break;
}
//takes away the value of tickets each time so if they want 2 tickets then it takes away 1 so then it equals 1 left umtil it reaches 0
tickets--;
}
//the receipt of all the tickets added together.
printf("\n-----------------------------------");
printf("\n-----------------------------------");
printf("\nThe receipt for your order: £%d", ticketSum);
printf("\n-----------------------------------");
printf("\n-----------------------------------");
}
Related
I'm new to C language and have been staring at my (probably abysmal) code for a while and can't figure out what's off about it.
Can anyone check my mistake :(
On compiler in said that error: ‘else’ without a previous ‘if’
else //[HIGHLIGHTED]
^~~~ , I have highlighted in comment [HIGHLIGHTED] the error lines to help you searching the line
#include <stdio.h>
#include <string.h>
void main()
{
int option;
option = 0;
while (option != 10)//For option purpose
{
char blood_type[5],next;// blood type purpose
char name[20];//name purpose
int count = 1;//turn on loop(True)
float discount, amountToBePaid, bill;
int amount;
int trial = 0, PIN, age;
float mass, generate;
printf("\n\n\t\t\t\tNational Blood Center x Tenaga Nasional Berhad Campaign");
printf("\n\n--------------------------------------------------------------------------------------------------------------------------");
printf("\n\t\t\t\tThank you for joining our campaign!");
printf("\n\t\t\t\tIf you donate :");
printf("\n\t\t\t\t ____________________________________ ");
printf("\n\t\t\t\t| Volume | Discount given |");
printf("\n\t\t\t\t ____________________________________");
printf("\n\t\t\t\t| 150 ml - 300 ml | 16 |");
printf("\n\t\t\t\t| 301 ml - 400 ml | 20 |");
printf("\n\t\t\t\t| 401 ml - higher | 25 |");
printf("\n\t\t\t\t ____________________________________");
printf("\n\n ! All contributor are advise to NOT donate your blood for over 470ml");
printf("\n\nDonator Condition:");
printf("\n1. Aged between 18 and 60 years old (for those less than 18, written consent from parents or legal guardian is required)");
printf("\n2. Body weight of at least 45 kg.");
printf("\n3. In good physical and mental health with no chronic medical illness.");
printf("\n4. Not on long term medications and has not been intoxicated by alcohol within 24 hours prior to donation.");
printf("\n\nDo you wish to continue?\n"); // this part ask user if they want to continue or not
printf("1.Yes\n");
printf("2.Cancel");
printf("\n\nEnter one of the above : "); //option, user are ask whether he/she wants to continue or not
scanf("%d", &option);
switch (option)// if the user wants to continue
{
case 1:
printf("Enter age:"); // security measurement, the user is ask to enter the his/her age/mass for confirmed that he/she fulfill all of the recuirment
scanf("%d", &age);
printf("Enter mass [in two decimal place]:");
scanf("%f", &mass);
if( age >=18 && age <=60)
if(mass > 60.00)
{
generate = age*mass; //a generated security code that derived from multiplication of age & mass (for increase the security measurement)
printf("Your code is %.2f", generate); //display generated code
}
else
{
printf("You may not fulfill all the conditions, try again later."); // if the user not fulfill all the conditions, the program will end
return ;
}
do
{
printf("\nInsert the generate code:");
scanf("%d", &PIN);
trial++;
}while (PIN != generate && trial != 3);
if (PIN == generate) //[HIGHLIGHTED]
printf("\nEnter your name: ");// next step to start the program
scanf("%s", name);
printf("\nPlease Enter Your Blood Type: ");
scanf("%s", blood_type);
printf("Please enter amount of your total blood donation (in ml) :");
scanf("%d", &amount);
printf("Enter your current electricity bill: Rm");
scanf("%f", &bill);
printf("\n");
printf("loading");//just a loading (no animation)
int value = 5;
while (value > 0)
{
printf(".");
value--;
}
while (count == 1 )
{
if ((strcmp(blood_type,"A")==0)||(strcmp(blood_type,"a")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else if((strcmp(blood_type,"B")==0)||(strcmp(blood_type,"b")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else if((strcmp(blood_type,"AB")==0)||(strcmp(blood_type,"ab")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else if((strcmp(blood_type,"o")==0)||(strcmp(blood_type,"O")==0))
{
printf("\nYour Blood Type is %s", blood_type);
count = 0 ; //turn off loop (False)
}
else
{
printf("\n-------------\n");
printf("Invalid input\n");
printf("-------------\n");
count = 0;//turn off loop (False)
main();
if(amount<150)
{
printf("\nYou have to paid: Rm%0.2f", bill);
printf("\nDonate for over 150 ml to enjoy a discount cut!");
}
else
{
if(amount>=150 && amount<=300)
{
discount = (bill*16)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
else if(amount>300 && amount<=400)
{
discount = (bill*20)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
else if(amount>400 && amount<600)
{
discount = (bill*25)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
printf("\nThank you %s for your contribution!", name);
break;
else //[HIGHLIGHTED]
printf("\nSorry, Maximum attempt has been exceded. Please refer officer on duty." );
case 2:
return ;
default:
printf("Invalid input\n");
}
}
}
}
}
}
In this code:
else if(amount>400 && amount<600)
{
discount = (bill*25)/100;
amountToBePaid = bill-discount;
printf("\nAfter applying the discount, you have to paid: Rm%0.2f", amountToBePaid);
}
printf("\nThank you %s for your contribution!", name);
break;
else //[HIGHLIGHTED]
you have three statements after the if. The first is the compound statement from { to }. The second is the printf call, and the third is break;. However, in an if-else statement, if (expression) statement else statement, there can be only one statement after the if (expression) and before the else. To have multiple statements between them, you must enclose them in { and }, making a single compound statement.
It looks like you want that printf and break after all of the cases handling amounts less than 600 and want the else to handle amounts over 600. You cannot do that with the current structure you have. Instead, use a structure like this:
if (amount < 600)
{
// Write all the under-600 cases here, using `if` and `else if`.
// Execute a printf after all code for the under-600 cases.
printf("\nThank you %s for your contribution!", name);
}
else
{
// Handle the 600-or-over case here.
}
break;
I believe you're simply missing { } after the if, and else statements you have marked with
//[HIGHLIGHTED].
I have run in to a bug in my code I cannot figure out. I am using an array and a switch statement together. a default is set for if user enters invalid selection, then the program loops back to ask for user input. Following the default selection the data entered by the user is not stored. This is only for the loop immediately after the default selection. Following is the main body of my code
//ask user to enter up to 20 numbers, find the average of the numbers and display average to user
main()
{
double number[SIZE] = { 0 };
int i;
int selection = 0, numCount = 0;
double total = 0, average = 0;
while(selection != 4){
for (i = 0; i <= SIZE; i++)
{
printf("\nPress 1 to enter a number, you may enter up to 20\nPress 2 to display your numbers\nPress 3 to see the average of your numbers\nPress 4 to quit\n");
scanf_s("%i", &selection);
switch (selection) {
case 1:
if (numCount < SIZE) {
//prompt user for input and store data
printf("Please enter your number\n");
scanf_s("%lf", &number[i]);
numCount++;
total += number[i];
}
else
printf("\nThe array is full, choose another selection\n");
break;
case 2:
if (numCount != 0)
{
//displays input back to user
for (i = 0; i < numCount; i++)
printf("%.2lf\t", number[i]);
}
else
printf("You must input at least one number first\n");
break;
case 3:
if (numCount != 0)
{
//calculates average of only numbers entered into the array by the user
average = total / numCount;
printf("The average of your numbers is %.2lf\n", average);
break;
}
else
printf("You must input at least one number first\n");
case 4:
{
printf("Thank you\n\n");
return;
}
default:
{
printf("This is not a valid selection, please try again\n\n");
break;
}
}
}
}
}
The instructions for the part of the project I am having trouble with are:
"Playing" the game:
A second function playing() will be used to play a single game of craps until the player either wins or loses a bet, based upon the rules given above. This function should be modify the current $ amount of the player's bank roll according to the game result, modify the array values of the player won or lost, and whether the player bet for or against him/herself. Within the function, the player is asked whether s/he would like to place a bet. If so, the player must choose whether to bet "for" or "against" him/herself (see game rules above). The player then "rolls the dice" (simulated by a call to the dice-rolling function rolling()). This should be done interactively (via a key press from the player), rather than simply having the program continuously roll the dice until the game is over. After each roll, this function should report the two random dice values and the sum of the two. If, after the first roll, the game is not over, the player should be asked whether s/he would like to double the amount of the bet. When a roll causes the end of a game, the player is notified whether s/he won or lost money in that game overall, and the amount won or lost. In all other cases, the player is notified that s/he needs to roll again.
I have to code in a craps game that asks user for a bet amount and then they play craps. They have an initial bank roll of $100. I have to scan a bet amount in using scanf but it keeps making my bet amount very large without any user input. Can someone please help me, I have this project due tonight.
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h>
//function prototype
int rolling(void);
int playing(int c_amt);//inital money $100, min bet of $5, no max except money you have
void beginning(void);
void ending(void);
int
main()
{
printf("\nWelcome to Craps! Get ready to play!");
int bank_amt = 100;
char y_n = 'n';
do
{
bank_amt = playing(bank_amt);
if(bank_amt == 0)
{
printf("\nYou bet and lost all your money! You can't play anymore. Goodbye!");
exit(0);
}
if(bank_amt != 0)
{
printf("\nYour current balance is %d %d", &bank_amt, bank_amt);
printf("\nDo you want to play again? (y/n): ");
scanf("\n%c", &y_n);
}
}
while(y_n != 'n' && y_n != 'N');
}
int
rolling(void)
{
int dice1, dice2;
char roll;
srand((int)(time(NULL))); // "Seed" random number gen. with system time
printf("\nPress enter to roll the dice!");
fflush(stdin);
scanf("%c",&roll);
dice1 = 1+rand()%6; // random num from 1-6
dice2 = 1+rand()%6; // random num from 1-6
return dice1+dice2;
}
int
playing(int c_amt)
{
char gametype, y_n = 'n';
int total, point, for_u, against_u, winlose, win = 0, lose = 0;
int moneychange, bet_amt, final_amt;
printf("\nPlease press 'f' if you are betting for yourself and 'a' if your are betting against yourself.\n");
scanf("\n%c", &gametype);
do
{
printf("\nYour current bank balance is %d.", c_amt);
printf("\nEnter the amount you want to bet: ");
scanf(" %d", &bet_amt);
printf("Bet amount: %d", bet_amt);
if(bet_amt > c_amt || bet_amt < 5)
{
printf("\nYou dont have that much money or you placed a bet less than the minimum. Please place a proper bet.");
}
}
while(bet_amt > c_amt);
if (gametype == 'f' || gametype == 'F')
{
for_u++;
printf("\nYou are betting for yourself!\nLets get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 7 || total == 11)
{
printf("\nGood job! You win :)");
winlose = 1;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("\nCraps, you lose.");
winlose = 0;
}
else
{
point = total;
printf("\nYour point is %d.", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == point)
{
printf("\nGood job! You win! :)");
winlose = 1;
break;
}
}
while(total != 7);
if(total == 7)
{
printf("You rolled a seven. You lose! :(");
winlose = 0;
}
}
}
else if (gametype == 'a' || gametype == 'A')
{
against_u++;
printf("You are betting against yourself!\nLet\'s get started!");
total = rolling();
printf("\nThe value rolled is %d.", total);
if (total == 2 || total == 3 || total == 12
{
printf("Good job! You win :)\n");
}
else if (total == 7 || total == 11)
{
printf("Craps, you lose.\n");
}
else
{
point = total;
printf("Your point is %d.\n", point);
if(bet_amt*2 <= c_amt)
{
printf("\nWould you like to double your bet? (y/n)");
scanf("\n%c", &y_n);
}
if(y_n == 'y' || y_n == 'Y')
{
bet_amt = bet_amt*2;
}
do
{
total = rolling();
if(total == 7)
{
printf("\nGood job! You win! :)");
winlose=1;
break;
}
}
while(total != point);
if(total == 7)
{
printf("You rolled a seven before making your point. You lose! :(");
winlose = 0;
}
}
}
if(winlose == 1)
{
final_amt = bet_amt + c_amt;
win++;
}
else
{
final_amt = c_amt - bet_amt;
lose++;
}
printf("Final amount is %d.", final_amt);
return final_amt;
}
Here is sample output:
Welcome to Craps! Get ready to play!
Please press 'f' if you are betting for yourself and 'a' if your are betting against yourself.
Your current bank balance is 100.
Enter the amount you want to bet: Bet amount: -1219958512
You dont have that much money or you placed a bet less than the minimum. Please place a proper bet.Final amount is 1219958612.
Your current balance is -1074871812 1219958612
Do you want to play again? (y/n):
Your formatting needs a lot of fixing to understand. However, the real issue is a buffer overflow, caused by not allocating enough memory to the char. Instead, I would suggest using simple int values like 0 and 1 to determine the player's choices.
I'm having a slight bit of trouble with saving data into arrays. Most of the code works as required, but what I'm having trouble doing is saving the data, such as deposits, withdrawals, transfers, into an array for them all to be printed out at the end. Two main problems are occurring.
1. Either nothing has been entered (which is completely acceptable) and then random digits are being output. 2. If something has been entered during a loop, such as a deposit, and then the user decides to enter another deposit before the loop is finished, the output will only be the last entry (whereas I want it to be two separate outputs). I can't seem to think of a way around these problems so any help is appreciated!
#include <stdio.h>
#include <stdlib.h>
//global variable for the overdraft
float OVERDRAFT = -1000;
//function to determine interest rate for users deposit
//return the interest rate to be used in the total() function
float interest(float money)
{
float int_rate;
if (money < 0 && money >= -100)
{
int_rate = 1.2f;
}
else if (money >= 0 && money < 100)
{
int_rate = 1.1f;
}
else if (money >= 100 && money < 200)
{
int_rate = 1.5f;
}
else if (money >= 200 && money < 500)
{
int_rate = 1.8f;
}
else if (money >= 500)
{
int_rate = 1.9f;
}
else if (money < -100 && money >= -500)
{
int_rate = 1.4f;
}
else if (money < -500 && money >= -1000)
{
int_rate = 1.8f;
}
return int_rate;
}
//function to calculate final amount with interest applied
//uses previous interest() function to calculate final amount by multiplying them together
//if the amount is less than -1000 (overdraft) then the OVERDRAFT value of -1000 is returned
//else, returns the normal amount
float total(float x)
{
float int_func;
int_func = interest(x);
float amount = x * int_func;
if (amount < OVERDRAFT)
{
return OVERDRAFT;
}
else
{
return amount;
}
}
//function that checks if user enters an amount greater than 0
//returns an integer dependent on this
//this is used in main function to determine if money can be added to the account (0 means yes, -1 means no)
float add_money(float *Account, float Amount)
{
if (Amount > 0)
{
return 0;
}
else
{
return -1;
}
}
float take_money(float *Account, float Amount)
{
if (Amount > 0)
{
return 0;
}
else
{
return -1;
}
}
//function to be used for the transfer section in the main function
//finds out if users input (multiplied by interest) is positive
//if it is, 0 is returned which can be used later
float transfer(float y)
{
float int_func;
int_func = interest(y);
float amount = y * int_func;
if (amount >= 0)
{
return 0;
}
else
{
return -1;
}
}
//creates a sentinel while loop so that user can exit it if they press 0, or reloops if they enter any other number
float main(void)
{
float sentinel = 1;
while (sentinel != 0)
{
//asks the user to enter amount they wish to deposit in both main and savings accounts
//asks the user how many months they want to simulate (3 months with a starting deposit of £50 will result in £55, £60.50, £66.55)
float deposit, add, take, savings, tran;
int count, amount, answer;
float x, dep[51], withd[51];
float m_to_s[51], s_to_m[51];
printf("Initial deposit for your main account:\n");
scanf_s("%f", &deposit);
while (deposit < OVERDRAFT)
{
//while loop to make sure user enters positive number for main account
printf("ERROR: You have an overdraft limit of \x9C%.0f.\nPlease enter a greater initial deposit:\n", (OVERDRAFT* -1));
scanf_s("%f", &deposit);
}
printf("Initial deposit for your savings account:\n");
scanf_s("%f", &savings);
while (savings < 0)
{
//while loop to make sure user enters positive number for savings account
printf("ERROR: Please enter a positive value:\n");
scanf_s("%f", &savings);
}
printf("Amount of months to simulate:\n");
scanf_s("%d", &amount);
while (amount <= 0)
{
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%d", &amount);
}
//for loop with a switch statement to allow user to choose option from main menu
//user can deposit money, withdraw money, transfer money, and move to the next month with interest applied from the menu
for (count = 1; count <= amount; count++)
{
printf("\nPlease choose one of the below options:\n");
printf("1: Deposit money (Main account only)\t");
printf("2: Withdraw money (Main account only)\n");
printf("3: Transfer money\t\t\t");
printf("4: Balance next month (with interest)\n");
scanf_s("%d", &answer);
while (answer <= 0 || answer >= 5)
{
//while loop to ensure user chooses one of the 4 options
printf("\nPlease choose one of the below options:\n");
printf("1: Deposit money (Main account only)\t");
printf("2: Withdraw money (Main account only)\n");
printf("3: Transfer money\t\t\t");
printf("4: Balance next month (with interest)\n");
scanf_s("%d", &answer);
}
//main menu
switch (answer)
{
//option 1 to deposit more money
//adds money to the account if 0 was returned in add_money() function
//errors given if -1 was returned in add_money() function
case 1: printf("\nYou chose to make a deposit\n");
printf("Amount to deposit:\n");
scanf_s("%f", &dep[count]);
add = add_money(&x, dep[count]);
while (dep[count] <= 0)
{
//while loop to ensure user enters a value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &dep[count]);
}
if (dep[count] > 0)
{
deposit = deposit + dep[count];
printf("Main account balance: \x9C%.2f.\n", deposit);
//reduces count by 1 so that it outputs correctly at end
count -= 1;
}
else
{
printf("ERROR: You entered an invalid amount.\n");
count -= 1;
}break;
//option 2 to withdraw money
//reduces count by 1 so that the program doesn't end sooner than the user wanted
case 2: printf("\nYou chose to make a withdrawal\n");
printf("Amount to withdraw:\n");
scanf_s("%f", &withd[count]);
take = take_money(&x, withd[count]);
while (withd[count] <= 0)
{
//while loop to ensure user enters value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &withd[count]);
}
if (withd[count] > 0)
{
//sets deposit variable to a new value according to the users input (may be reverted back in the if statement if it goes over overdraft)
deposit = deposit - withd[count];
if (deposit < OVERDRAFT)
{
//reverts the recentl deposit variable as it will not be possible as the user will go over the overdraft
printf("ERROR: You can't withdraw that much as you will go over your overdraft limit\n");
deposit = deposit + withd[count];
count -= 1;
break;
}
else if (deposit > OVERDRAFT)
{
printf("Main account balance: \x9C%.2f.\n", deposit);
count -= 1;
break;
}
}
else
{
printf("ERROR: You entered an invalid amount\n");
count -= 1;
}break;
//option 3 to transfer money from one account to another
case 3: printf("\nYou chose to transfer money\n");
printf("Please choose an option:\n");
printf("1: Transfer from Main account to Savings account\n");
printf("2: Transfer from Savings account to Main account\n");
int option;
scanf_s("%d", &option);
while (option < 1 || option > 2)
{
//while loop to ensure user chooses one of the two options
printf("Please choose an option:\n");
printf("1: Transfer from Main account to Savings account\n");
printf("2: Transfer from Savings account to Main account\n");
scanf_s("%d", &option);
}
//switch inside a switch
switch (option)
{
case 1: printf("\nYou chose to transfer money from your Main account to your Savings account\n");
printf("Please enter how much to transfer:\n");
scanf_s("%f", &m_to_s[count]);
tran = transfer(m_to_s[count]);
while (m_to_s[count] <= 0)
{
//while loop to ensure user enters a value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &m_to_s[count]);
}
//if statement that will be run if user enters value greater than 0
if (m_to_s[count] > 0)
{
savings = savings + m_to_s[count];
deposit = deposit - m_to_s[count];
if (deposit >= OVERDRAFT)
{
//prints out both balances of accounts after the transfer
printf("\nMain account balance %.2f\n", deposit);
printf("Savings account balance: %.2f\n", savings);
count -= 1;
}
else
{
printf("ERROR: You can't transfer that much as you don't have a large enough overdraft on your Main account\n\n");
//if user enters an incorrect amount (because overdraft is reached), variables are restored so that end output is correct
savings = savings - m_to_s[count];
deposit = deposit + m_to_s[count];
count -= 1;
}
}break;
//transfer money from savings to main
case 2: printf("\nYou chose to transfer money from your Savings Account to your Main account\n");
printf("Please enter how much to transfer:\n");
scanf_s("%f", &s_to_m[count]);
tran = transfer(s_to_m[count]);
while (s_to_m[count] <= 0)
{
//while loop so ensure user enters a value greater than 0
printf("ERROR: Please enter a value greater than zero:\n");
scanf_s("%f", &s_to_m[count]);
}
//if statement that will be run if user enters a value greater than 0
if (s_to_m[count] > 0)
{
//adjusts balances using users entered value (these variables may be reverted in the else statement if the savings go lower than 0 as there is no overdraft)
savings = savings - s_to_m[count];
deposit = deposit + s_to_m[count];
if (savings >= 0)
{
//prints out current balances
printf("\nMain account balance: %.2f\n", deposit);
printf("Savings account balance: %.2f\n", savings);
count -= 1;
}
else
{
//error if user tries to transfer too much money out of their savings account because there is no overdraft
printf("ERROR: You can't transfer that much as you don't have an overdraft on your Savings account\n\n");
savings = savings + s_to_m[count];
deposit = deposit - s_to_m[count];
count -= 1;
}break;
}
else
{
printf("ERROR\n\n");
count -= 1;
}break;
}break;
//option 4 to move onto the next month (with interest applied to both accounts)
case 4:
deposit = total(deposit);
savings = total(savings);
printf("\nYou chose to show account balances (with interest) for the next month\n");
printf("Month %d Main account balance: \x9C%.2f.\n", count, deposit);
printf("Month %d Savings account balance: \x9C%.2f\n", count, savings);
}
}
for (count = 1; count <= amount; count++)
{
//sting array
//prints out transactions
//NOT WORKING CORRECTLY
printf("\nDeposit %d: %.2f\n", count, dep[count]);
printf("Withdrawal %d: %.2f\n", count, withd[count]);
printf("Transfer Main to Savings %d: %.2f\n", count, m_to_s[count]);
printf("Transfer Savings to Main %d: %.2f\n", count, s_to_m[count]);
}
//if user enters 0, while loop is broken
//if user enter anything other than 0, loop reloops
printf("\nTo terminate program, enter '0'.\n");
printf("To run program again, enter any other number.\n");
scanf_s("%f", &sentinel);
}
return 0;
}
the code is long and really hard to go through but if I did understand it corectly you need to:
Initialize all the variables. Set them to zero or something accaptable for you.
you are using dep[count] but you always do count -= 1; after that. Try to look at that.
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]);
}