C pointer giving random value - c

I am teaching myself C for fun. I looked online for some practice programs, and found one where you take two input's: One with the amount of an imaginary product, and second the amount of money the imaginary customers gives you. Then you return the number of dollars bills, and change you would give to the customer.
This is the complete code which I wrote to solve this problem:
#include <stdio.h>
#include <stdlib.h>
float getDif(float c, float m)
{
// First find the difference between
// c & m (m - c = d)
float dif = m - c;
// Return the difference
return dif;
}
void getChange(float dif, int* cash, float* change)
{
// If difference is less than 0 we have a problem
// because the customer gave us less money than
// the cost of the product
if(dif < 0)
{
fprintf(stderr, "The customer has not given enough money!...\n");
exit(EXIT_FAILURE);
}
// Cash is seen as the difference without any
// decimals. So if the difference is $13.45
// the cash would be 13 since cash is, in my
// mind paper money
*cash = (int) dif;
// Change is seen as the difference - cash
// if the difference is $13.45 the change
// would be .45
*change = dif - *cash;
}
void getCash(int cash, int* oneHundred, int* fifty, int* twenty, int* ten,
int* five, int* one)
{
if(cash == 0)
{
printf("Wow close to exact change! - No need for cash...\n");
// End the function there is no need to continue
return;
}
// Since cash is > 0 we need to determine the bills to return
// to the user
if(cash >= 100)
{
while(cash >= 100)
{
cash = cash - 100;
(void) ++*oneHundred;
}
}
if(cash >= 50)
{
while(cash >= 50)
{
cash = cash - 50;
(void) ++*fifty;
}
}
if(cash >= 20)
{
while(cash >= 20)
{
cash = cash - 20;
(void) ++*twenty;
}
}
if(cash >= 10)
{
while(cash >= 10)
{
cash = cash - 10;
(void) ++*ten;
}
}
if(cash >= 5)
{
while(cash >= 5)
{
cash = cash - 5;
(void) ++*five;
}
}
if(cash >= 1)
{
while(cash >= 1)
{
cash = cash - 1;
(void) ++*one;
}
}
printf("After all loops cash = %d\n", cash);
}
void getCoins(float change, int* quarter, int* dime, int* nickel, int* penny)
{
// To find the correct change we need to turn the
// current format of variable change (0.57) into
// a easier to work with 57.
int tenChange = change * 100;
if(tenChange >= 25)
{
while(tenChange >= 25)
{
tenChange = tenChange - 25;
(void) ++*quarter;
}
}
if(tenChange >= 10)
{
while(tenChange >= 10)
{
tenChange = tenChange - 10;
(void) ++*dime;
}
}
if(tenChange >= 5)
{
while(tenChange >= 5)
{
tenChange = tenChange - 5;
(void) ++*nickel;
}
}
if(tenChange >= 1)
{
while(tenChange >= 1)
{
tenChange = tenChange - 1;
(void) ++*penny;
}
}
printf("After all loops change = %d\n", tenChange);
}
int main(void)
{
// Create variables for the various things we create
float c, m, dif, change;
int cash, oneHundred, fifty, twenty, ten, five, one, quarter, dime, nickel,
penny;
printf("Enter the exact amount of the items (18.37): ");
// Obtain the cost
scanf("%f", &c);
printf("Enter the amount of money given by the customer: ");
// Obtain the money from customer
scanf("%f", &m);
// Obtain the difference of the cost
// And the money given by calling the
// getDif() function
dif = getDif(c,m);
// Send the difference to the getChange()
// function, as well as the pointers
// cash & change which will be used in the
// function and returned back here
getChange(dif, &cash, &change);
// First send the cash variable to the getCash
// function along with pointers for each bill
// The function will calculate the number of bills
// to give to the customer and return each
getCash(cash, &oneHundred, &fifty, &twenty, &ten, &five, &one);
// Print the number of bills to give to the customer
printf("Give the customer %d Hundred doller bill(s)!\n", oneHundred);
printf("Give the customer %d Fifty doller bill(s)!\n", fifty);
printf("Give the customer %d Twenty doller bill(s)!\n", twenty);
printf("Give the customer %d Ten doller bill(s)!\n", ten);
printf("Give the customer %d Five doller bill(s)!\n", five);
printf("Give the customer %d One doller bill(s)!\n", one);
// Second send the change variable to the getCoins
// function along with pointers for each type of
// coin. The function will calculate the number of
// coins to give to the customer and return each
getCoins(change, &quarter, &dime, &nickel, &penny);
// Print the number of coins to give to the customer
printf("Give the customer %d Quarter(s)\n", quarter);
printf("Give the customer %d Dime(s)\n", dime);
printf("Give the customer %d Nickel(s)\n", nickel);
printf("Give the customer %d Penny(s)\n", penny);
printf("%d\n", cash);
printf("%.2f\n", change);
printf("$%.2f\n", dif);
return 0;
}
It is working ok, until I print out the number of Nickels, and Pennies to the customer. Instead of giving me a number which would make sense it is giving me a random string of numbers.
For example this is the output for these inputs:
Enter the exact amount of the items (18.37): 123.32
Enter the amount of money given by the customer: 124.00
Wow close to exact change! - No need for cash...
Give the customer 0 Hundred doller bill(s)!
...
Give the customer 0 One doller bill(s)!
After all loops change = 0
Give the customer 2 Quarter(s)
Give the customer 1 Dime(s)
Give the customer 32768 Nickel(s)
Give the customer 1596836443 Penny(s)
0
0.68
$0.68
Now if the program was working correctly, it should say:
2 Quarter(s)
1 Dime(s)
1 Nickel(s)
3 Penny(s)
But I'm getting those random(?) values. Could this be a problem with me not clearing my pointers? I have never worked with a language that uses them, and I have not learned enough to use them properly.
I tried to set all the cash variables (for example oneHundred) to NULL, but it gives me this compiler error:
change.c:204:14: warning: incompatible pointer to integer conversion assigning
to 'int' from 'void *' [-Wint-conversion]
oneHundred = NULL;
^ ~~~~
Any help would be amazing! I am just beginning to learn this language, and I hope this question will give me some insight on how to write better C in the future! Thank you!!

You don't need to set them to NULL be cause they are not pointers, initialized them to 0 like this
cash = oneHundred = fifty = twenty = ten = five = one = quarter = dime = nickel = penny = 0;
NULL is used to initialized pointers to a special value, so you can test against it to check if the pointer is pointing somewhere or if it doesn't.

Related

write a program that will accept an integer value in the range of 5-95 and as a multiple of 5

Im a complete newbie in programming.
I've been instructed to write the program above in the title.
I'm here seeking help from everyone to help me understand and code better.
Can anyone tell me what is wrong with my code? i cant get it to exit the loop
more detailed information on the program:
You are asked to write a simple C program that will accept an integer value in the range
of 5-95 and as a multiple of 5 representing the number of cents to give to a customer in
their change. The program should calculate how many coins of each denomination and
display this to the user. Valid coin values are 50, 20, 10 and 5. Your solution (program
and algorithm) should be modular in nature.
/*This program acts as a coin changer that helps to provide
change user their changes in the highest amount.
*/
#include <stdio.h>
// Delcaration of functions
int coins(int fifty, int twenty, int ten, int five);
int main()
{
// Declare and initialize working storage
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int user_input = 0;
int counter = 3;
int coins(int fifty, int twenty, int ten, int five);
// Prompt user for input, prints, and loops for 3 attempts
while (counter > 0)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter the amount you wish to change: \n\n");
scanf("%d", &user_input);
if ((user_input < 5) || (user_input > 95))
{
printf("\nInvalid input\n");
printf("\nNumber of attemps: %d\n\n\n\n", counter);
}
counter--;
}
printf("\nYou have exceeded the number of attempts\n");
// Compute number of coins to be given
fifty = user_input / 50;
twenty = user_input / 20;
ten = user_input / 10;
five = user_input / 5;
if (fifty >= 1)
{
printf("\nNumber of fifty cent coins are: %d\n", fifty);
}
else if (twenty >= 1)
{
printf("\nNumber of twenty cent coins are: %d\n", twenty);
}
else if (ten >= 1)
{
printf("\number of ten cent coins are: %d\n", ten);
}
else if (five >= 1)
{
printf("\nNumber of five cent coins are: %d\n", five);
}
return 0;
}
Here is a program that does what you ask. This program could still be improved vastly.
#include <stdio.h>
// Delcaration of functions
int coinReturn(int coinSize, int value)
{
int tmp = 0;
while(value >= coinSize)
{
value-=coinSize;
tmp++;
}
printf("Number of %i cent coins are: %d\n", coinSize,tmp);
return value;
}
int main()
{
// Declare and initialize working storage
int user_input = 0;
int remainingValue;
// Prompt user for input, prints, and loops for 3 attempts
while (1)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter a multiple of 5\n");
printf("\nPlease enter the amount you wish to change: \n");
scanf("%d", &user_input);
if ( (user_input < 5 || user_input > 95) || (user_input % 5 != 0))
{
printf("\nInvalid input!\n");
}
else
{
break;
}
}
//Calculate and Print Output
remainingValue = coinReturn(50,user_input);
remainingValue = coinReturn(20,remainingValue);
remainingValue = coinReturn(10,remainingValue);
remainingValue = coinReturn(5,remainingValue);
return 0;
}
I would focus on a couple things if I were you and make sure I learned the concept. These are:
- Break Statements
- Function Declarations and function Definitions
- Modulo
- Flowcharting
This problem can be slightly tricky and flowcharting it when you start is your best bet.

C: Unable to use modulus operators to break down change into denominations, storing into an array and print the output to the user

I'm attempting to write a program in which:
The user inputs the cost of an item
The user inputs the amount they paid for the item
The program determines if the user is owed any change
The program calculates the amount of change owed
The program uses the modulus operator to break the amount of change down into coin denominations
The program stores the change and coin denominations into an array This is the first bit at which I'm getting stuck
The program displays the amount of change in coin denominations to the user
The purpose is to use an array to hold the values of the coins, so I "can write a general purpose change calculator that can be used for any coinage by changing the contents of the array".
Here is my code:
void vendingMachine()
{
// Declarations
#define ARRAY_LENGTH 6
int itemCost;
int amountEntered;
int fifty, twenty, ten, five, two, one;
int remainder;
// User input
printf("Please enter the cost of the item in pence: ");
scanf_s("%d", &itemCost);
while (itemCost <= 0 || itemCost > 99)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 99p: ");
scanf_s("%d", &itemCost);
}
printf("Please enter the amount entered into the machine in pence: ");
scanf_s("%d", &amountEntered);
while (amountEntered <= 0 || amountEntered > 100)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 100p: ");
scanf_s("%d", &amountEntered);
}
while (amountEntered < itemCost)
{
printf("You've entered an invalid amount. Please enter an amount equal to or higher than the cost of the item: ");
scanf_s("%d", &amountEntered);
}
// Program to determine if the customer is owed any change and, if so, how much is owed
if (amountEntered == itemCost)
{
printf("No change is owed to the customer");
}
else if (amountEntered > itemCost)
{
int change = amountEntered - itemCost;
printf("The amount of change owed to the customer is: %d pence, broken down as follows: \n", change);
fifty = change / 50;
remainder = change % 50;
twenty = remainder / 20;
remainder = remainder % 20;
ten = remainder / 10;
remainder = remainder % 10;
five = remainder / 5;
remainder = remainder % 5;
two = remainder / 2;
remainder = remainder % 2;
one = remainder;
// Program to store the change in an array
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
printf("The number of %d coins is: %d\n", //I don't know what to do here);
}
}
}
Store the type of coins in an array as well, e.g.
const int coins[ARRAY_LENGTH] = { 50, 20, 10, 5, 2, 1 };
Then you can easily refer to them in your loop:
printf("The number of %d coins is: %d\n", coins[i], count[i]);
This also allows you to perform your modulo calculations in a loop.
I am not sure what you are trying to achieve here:
The following piece of (your) code sets the values of count from index 0 to index 5, starting from fifty to one..
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
Then here, you are overwriting those with 0 in the for loop.
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
So above loop is not required, or at least must not be placed after you have assigned values of fifty, twenty, ten, five, two and one to count array indices.
I guess you are trying to print them? You don't have to use a loop here:
// Doing it the newbie-way:
printf("The number of coins of 50 are: %d\n", count[0]);
printf("The number of coins of 20 are: %d\n", count[1]);
printf("The number of coins of 10 are: %d\n", count[2]);
printf("The number of coins of 5 are: %d\n", count[3]);
printf("The number of coins of 2 are: %d\n", count[4]);
printf("The number of coins of 1 are: %d\n", count[5]);

making greedy algorithm work for every input

I wrote a code for greedy algorithm of cs50. It works for inputs between 0 and 1. How can I make it work to inputs like 4.2 , 6.5 , 8 etc?. I have listed my code below. What should I modify in the program?
#include<stdio.h>
#include<cs50.h>
#include<math.h>
int main()
{
int count , change;
float cents;
printf("Enter the change amount : ");
cents = GetFloat();
cents = cents * 100;
change = round(cents);
count = 0;
while(cents < 0 )
{
printf("Enter a positive number : ");
cents = GetFloat();
}
while (change >= 25)
{
change = change - 25;
count++;
}
while (change < 25 & change >= 10)
{
change = change - 10;
count++;
}
while (change < 10 & change >= 5)
{
change = change - 5;
count++;
}
while (change < 5 & change >= 1)
{
change = change - 1;
count++;
}
printf("Total number of coins used : " );
printf (" %d " , count );
printf("\n");
}
I believe that your problem is that you are using bitwise logical operators. You should use && in your comparisons to compare the values of two expressions. There are other little issues: The loop that guarantees positive input should multiply cents by 100 and round(), before assigning this new value to change. But you don't actually need both change and cents. And you don't need as many comparisons as you have written, and without the extra comparisons, you don't need the logical operators that were causing you trouble in the first place!
Edit
I noticed that a number like 4.20 was being rounded first, then multiplied by 100! Of course this is wrong, giving the same results for 4.20, 4.75, and 4. I changed the code below accordingly, but your original code was doing this part correctly (except in the input validation loop, as mentioned earlier). Now the program correctly handle such inputs.
Here is a cleaned-up version (I don't have the cs50.h library, so there are some small differences):
#include <stdio.h>
#include <math.h>
int main(void)
{
int count;
float cents;
printf("Enter the change amount: ");
scanf("%f", &cents);
cents = (float)round(cents * 100);
count = 0;
while (cents < 0) {
printf("Enter a positive number: ");
cents = (float)round(cents * 100);
}
while (cents >= 25) {
cents -= 25;
count++;
}
while (cents >= 10) {
cents -= 10;
count++;
}
while (cents >= 5) {
cents -= 5;
count++;
}
while (cents >= 1) {
cents -= 1;
count++;
}
printf("Total number of coins used: %d\n", count);
return 0;
}

Trying to write a code for a bill changer/coin vending kiosk

I'm trying to write a code for a bill changer where the amount of money inserted are converted back into coins for the user. The problem is I keep having decimals in my amount of 50c like 222.222 when i input 111.111. My 20c and 10c is unused.. Please help
#include <stdio.h>
int main()
{
double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0;
double amount;
do
{
printf("Please enter an amount(dollars):");
scanf("%lf", &amount);
amount=amount*100;
if(amount<0){
printf("Invalid Input\n");
printf("Re-enter your amount:");
scanf("%lf", &amount);
}
if(amount>=50){
remainder=amount/50;
sum50c=remainder;
}else
if(remainder!=0){
remainder2=remainder/20;
sum20c=remainder2;
}else
if(remainder2!=0){
remainder3=remainder3/10;
sum10c=remainder3;
}
if(sum50c>200||sum20c>200||sum10c>200){
end++;
}else{
end=0;
}
}
while(end<=0);
printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c);
}
There are basically two errors in your code:
Don't operate on floating-point numbers here. The number of coins will be a discrete number, which should be represented as int or maybe even unsigned int. The amount itself may be read in as floating-point number for simplicity, but it should also be converted to the number of cents as integerin order to avoid rounding errors.
You have to find combinations of coins: 30c is 1%times;20c + 1×10c. That means that you can't use else if chains, which will only consider one type of coin. Treat all types of coin, highes denomination first, and then reduce the amount still to handle. Note that with 10c as smallest coin, you might not be able to give full change for all amounts.
Here's you example without the outer loop and without the strange end business:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int num50c = 0,
num20c = 0,
num10c = 0;
int amount; // amount in cents
double iamount; // input amount in dollars
printf("Please enter an amount: ");
scanf("%lf", &iamount);
amount = iamount * 100 + 0.5;
if (amount < 0) {
printf("Invalid Input\n");
exit(1);
}
num50c = amount / 50;
amount %= 50;
num20c = amount / 20;
amount %= 20;
num10c = amount / 10;
amount %= 10;
printf("%d x 50c = %d\n", num50c, num50c * 50);
printf("%d x 20c = %d\n", num20c, num20c * 20);
printf("%d x 10c = %d\n", num10c, num10c * 10);
printf("Remainder: %dc\n", amount);
return 0;
}
To force amount to have integer values you should round the value after your division:
if(amount>=50)
{
remainder=round(amount/50);
sum50c=remainder;
}

Result of previous line (C programming)

I'm taking a C programming class and I'm doing practice questions in the book. One of the questions is:
Write a program that asks the user to enter a U.S. dollar amount and then shows how to pay that amount using the smallest number of $20, $10, $5, %1 bills:
The sample is as follows:something right away that I may have overlooked when trying my code.
Enter a dollar amount: 93 (user inputted)
$20 bills: 4
$10 bills: 1
$5 bills: 0
$1 bills: 3
What I have so far is:
#include <stdio.h>
int main (void)
{
int cash;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
printf("$20 bills = %d\n", cash / 20);
printf("$10 bills = %d\n", cash / 10);
printf("$5 bills = %d\n", cash / 5);
printf("$1 bills = %d\n", cash / 1);
return 0;
}
The problem is, the book suggests dividing the input number (93) by 20, and since I'm using int instead of float, that leaves 4 instead of 4.65. Then it suggests subtracting the result of that times 20, from 93, leaving 13, and repeating that for each one. So it would be:
93/20=4
13/10=1
3/1=3
How can I get the printf("$10 bills = %d\n", cash / 10); line to recognize the value left by the previous line, printf("$20 bills = %d\n", cash / 20);? I had originally tried to put most of it on the 20 bill line, like cash / 20 * 20, but it just displayed 80 on that line instead of the next line.
I think you are mistaken a bit here. As you said, values are not left by the previous printf. You need to update the value of the variable cash. Here is what could help:
#include <stdio.h>
int main (void)
{
int cash;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
printf("$20 bills = %d\n", cash / 20);
cash = cash % 20;
printf("$10 bills = %d\n", cash / 10);
cash = cash % 10;
printf("$5 bills = %d\n", cash / 5);
cash = cash % 5;
printf("$1 bills = %d\n", cash);
return 0;
}
The modulo (%) operator gives you back the remainder after performing the division. Hence:
93 % 20 = 13
13 % 10 = 3
and so on.
cash is a variable meaning that it can vary in value. In other words, you can change the value of cash.
The % operator returns the remainder from a division. So if you do cash = 93 % 20; then cash should contain 13.
Remember that you can also set cash in relation to itself. So cash = cash % 20; would set cash to the value of the remainder of cash / 20.
Also, for the record,
you may want to put the bill values in a table
and iterate on this to avoid copy-pasted code:
int main()
{
int billval[] = { 20, 10, 5, 1, 0 };
int cash, i;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
for(i = 0; billval[i]; i++) {
printf("$%d bills = %d\n", billval[i], cash / billval[i]);
cash = cash % billval[i];
}
return 0;
}
Here, the billval table is zero-terminated so we know when to stop
iterating<
You may have to use the modulo operator (%) which returns the remainder of the division of two numbers (for example, 93 % 20 equals 13).
For example :
int cash = 93;
int twenty, ten, five, one;
twenty = cash / 20;
cash = cash % 20;
ten = cash / 10;
cash = cash % 10;
/* etc. */
int main(){
int cash, bills_20, bills_10, bills_5, bills_1;
printf("Enter dollars amount: ");
scanf("%d",&cash);
bills_20=cash/20;
printf("$ 20 bills: %d\n",bills_20);
bills_10=(cash-bills_20*20)/10;
printf("$ 10 bills: %d\n",bills_10);
bills_5=(cash-bills_20*20-bills_10*10)/5;
printf("$ 5 bills: %d\n",bills_5);
bills_1=(cash-bills_20*20-bills_10*10-bills_5*5);
printf("$ 1 bills: %d\n",bills_1);
return 0;}
Thanks for all the help. Delroth & Imagist (well FooBar too, I dont know how I missed his comment while I was testing the theory since its exactly what I did) reminded me by simply adding another value for cash after each line would produce the result I was looking for.
#include <stdio.h>
int main (void)
{
int cash;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
printf("$20 bills = %d\n", cash / 20);
cash = cash % 20;
printf("$10 bills = %d\n", cash / 10);
cash = cash % 10;
printf("$5 bills = %d\n", cash / 5);
cash = cash % 5;
printf("$1 bills = %d\n", cash / 1);
cash = cash % 1;
return 0;
}
thats using the modulo % which hasnt been covered in the book yet, I'm going to try it again the way Pax suggested. Thanks again for the help
I would put another integer at the top to represent the number of bills for the current denomination:
int billCount;
then replace each section (except the $1 section) with:
billCount = cash / 20; // billCount <- 93/20 = 4.
printf("$20 bills = %d\n", billCount);
cash -= (billCount * 20); // cash <- cash - (4*20) = 13.
You can do it with modulo operators with less lines of code but the above code is what the suggestion from the book is pointing you toward.
Try to work it out using just the information above, if possible (it'll make you a better programmer). If you still can't do it, here's my full solution.
#include <stdio.h>
int main (void) {
int cash, count;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
count = cash / 20;
printf("$20 bills = %d\n", count);
cash -= (count * 20);
count = cash / 10;
printf("$10 bills = %d\n", count);
cash -= (count * 10);
count = cash / 5;
printf(" $5 bills = %d\n", count);
cash -= (count * 5);
printf(" $1 bills = %d\n", cash);
return 0;
}

Resources