Printing dollar amounts using separate arrays for dollars and cents - c

I am trying to take user input, store it in an array for the number, and then take the dollars and cents portion of the numbers, store those in separate arrays, and then print the formatted number.
This is my code:
#include <stdio.h>
int main()
{
int i;
float amounts[5];
printf("Enter numbers as dollar amounts: \n");
for(i=0; i<5; i++) {
printf("Value %d: ", i+1);
scanf("%f", &amounts[i]);
}
long dollars[5];
long cents[5];
for (i=0; i<5; i++) {
dollars[i]=(int)amounts[i];
cents[i]=(amounts[i]-dollars[i]);
cents[i]*=100;
}
for (i=0; i<5; i++) {
printf("\n$%ld.", dollars[i]);
printf("%ld", cents[i]);
}
return 0;
}
I am somewhat unsure as to how I could take the cents and store them in an array as a long type. When executing the program, I get the correct dollars but the cents portion always comes out as 0. Any suggestions?
Edit:
So I attempted to solve some of the issues by doing this:
#include <stdio.h>
int main()
{
int i, j;
float amounts[5];
printf("Enter numbers as dollar amounts: \n");
for(i=0; i<5; i++) {
printf("Value %d: ", i+1);
scanf("%f", &amounts[i]);
}
long dollars[5];
long cents[5];
double decimal[5];
for (i=0; i<5; i++) {
dollars[i]=trunc(amounts[i]);
}
for (i=0; i<5; i++) {
printf("\n$%ld.", dollars[i]);
decimal[i]=100*(amounts[i]-dollars[i]);
cents[i]=(int)decimal[i];
if(cents[i]<10)
printf("0%ld", cents[i]);
else
printf("%ld", cents[i]);
}
return 0;
}
However, now I'm getting everything that is less than 10 for cents[i] to output 1 less than what it should be. So 3.06 prints as $3.05. The same for 3.12 for some reason.
Also, to some of the critique about what variable types I'm using, this is for an assignment and it dictates what types are to be used.
4 Write a program that will read five values from the keyboard (use a loop) and store them in an array of type float with the name amounts. Create two arrays of five elements of type long with the names dollars and cents. Store the whole number part of each value in the amounts array in the corresponding element of dollars and the fractional part of the amount as a two-digit integer in cents (e.g., 2.75 in amounts[1] would result in 2 being stored in dollars[1] and 75 being stored in cents[1]). Output the values from the two arrays of type long as monetary amounts (e.g., $2.75)

You're losing the fractional part here:
cents[i]=(amounts[i]-dollars[i]);
cents[i]*=100;
The difference between the two is less than 1, so assigning that value to an int results in it getting truncated to 0.
You need to multiply the difference before assigning to avoid truncation:
cents[i]=100*(amounts[i]-dollars[i]);

for (i=0; i<5; i++) {
dollars[i]=(int)amounts[i];
cents[i]=(amounts[i]-dollars[i]);
cents[i]*=100;
}
instead use:
for (i=0; i<5; i++) {
dollars[i]=(int)amounts[i];
double decimal = 100*(amounts[i]-dollars[i]);
cents[i]= (int)decimal;
}

OP's approach has problems
printf("\n$%ld.", dollars[i]);
printf("%ld", cents[i]);
Negative numbers amount[i] == -1.23 come out like "$-1.-23"
Values like amount[i] == 9.998 print as "$9.99" and likely should be "$10.00"
Missing leading zeros amount[i] == 1.03 print as "$1.3" #Jonathan Leffler
dollars[i]=(int)amounts[i] fails when amounts[i] is outside int range.
A key issue for OP
// problem
dollars[i]=(int)amounts[i];
cents[i]=(amounts[i]-dollars[i]); // cents[i] is an integer, cannot hold a fraction
cents[i]*=100;
// Alternative
// round
amount[i] = round(amount[i] * 100)/100.0;
// take apart;
float ipart;
cents[i] = (int) roundf(modff(amounts[i], &ipart)*100.0f);
dollars[i] = (int) ipart;
If code is to use FP for money recommend:
Use double.
Round to the nearest monetary unit after any calculation that is not exact. In OP's case this is 1/100.
amount[i] = round(amount[i] * 100)/100.0;
Use a unified print
printf("\n$%0.2f", amount[i]);

#include <stdio.h>
#include <math.h>
int main()
{
int i, j;
float amounts[5];
printf("Enter numbers as dollar amounts: \n");
for(i=0; i<5; i++) {
printf("Value %d: ", i+1);
scanf("%f", &amounts[i]);
}
long dollars[5];
long cents[5];
float ipart;
for (i=0; i<5; i++) {
cents[i] = (int) roundf(modff(amounts[i], &ipart)*100.0f);
dollars[i] = (int) ipart;
if(cents[i]==100){
dollars[i]++;
cents[i]=0;
}
}
for (i=0; i<5; i++) {
printf("\n$%ld.", dollars[i]);
if(cents[i]<10)
printf("0%ld", cents[i]);
else
printf("%ld", cents[i]);
}
return 0;
}

Related

what does the variabel in printf do

Why didn't this code work after adding "res=pow(arr[i],x)"
I want it to print like this
"printf("%d * %d = %d \n",i+1,x,pow(arr[i],x));"
The code doesn't work untill i print like this
"printf("%d * %d = %d \n",i+1,x,res)));"
#include<stdio.h>
#include<math.h>
int main()
{
int arr[5];
for(int i=0 ; i<5 ; i++){
printf("enter the numbers %d\n",i+1);
scanf("%d",&arr[i]);
}
int x;
printf("what is power would you like...\n");
scanf(" %d",&x);
printf("The power of the array elements is...\n");
for(int i=0 ; i<5 ; i++){
printf("%d * %d = %d \n",i+1,x,pow(arr[i],x));
}
return 0; // 1*2=1*1 , 3*2=3*3
}
pow returns a double. You need %lf format for the third argument or you'll get undefined behaviour trying to format a floating point value with an integer %d format (most compilers issue a warning about this BTW).
quickfix
printf("%d * %d = %lf \n",i+1,x,pow(arr[i],x));
Assigning the result to an integer workarounds the issue. That's why it works then (but sometimes it leads to rounding errors so beware!)
You may have a look at integer power algorithms instead. pow is more suited for floating point operations.

Why is one for-loop working as wished but the other not iterating?

Here two somehow similar problems (1.-Sum of uneven numbers until n; 2.-Sum of the series 1/n) to be solved using for-loops.
I chose the shown strategy and while for the 1st problem my loop works as expected, for the 2nd it does not iterate.
I can't see the difference to understand what is wrong in the last case.
----1----- :
int main()
{
// Example: Input=5, Output=1+3+5=9
int i, lastNum ,sumUneven;
printf("Until what n should the uneven numbers be added: ");
scanf("%d", &lastNum);
sumUneven=0;
for (i=1; 2*i-1<=lastNum; i++) {
sumUneven=sumUneven + (2*i-1);
}
printf("Sum of uneven numbers until %d: %d", lastNum, sumUneven);
}
----2------------:
int main()
{
//My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
int i, n, sum;
printf("Until what n should this series be calculated: ");
scanf("%d", &n);
sum=0;
for (i=1; i<=n; i++) {
sum = sum + 1/i;
}
printf("Sum of the series until 1/%d: %d", n, sum);
}
The expression 1/i performs integer division (truncating any fractional part) since both operands have type int. So if i is greater than 1 the division will result in 0. The variable sum is also of type int so it can't hold fractional numbers.
Perform the division as 1.0/i, which is floating point division since one argument has type double, and change the type of sum to double. Also use %f to print sum.
int main()
{
//My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
int i, n;
double sum;
printf("Until what n should this series be calculated: ");
scanf("%d", &n);
sum=0;
for (i=1; i<=n; i++)
{
sum = sum + 1.0/i;
}
printf("Sum of the series until 1/%d: %f", n, sum);
}
you're using an int to keep track of floats which will not work.
1/n will be a float a simple fix would be
int main()
{
//My goal: Input=n; Output= 1+ 1/2 + 1/3....+1/n.
int i, n;
float sum;
printf("Until what n should this series be calculated: ");
scanf("%d", &n);
sum=0;
for (i=1; i<=n; i++) {
sum = sum + 1/i;
}
printf("Sum of the series until 1/%d: %f", n, sum);
}
you could also use the double declaration
hope this was helpful

A basic error using loops and functions in C

For some reason my code will consistently print out zeros.
I was supposed to make a code in which I enter three numbers,
The first number
The ratio
The amount of numbers to be displayed
The code should display those numbers.
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void forloop(int firstNum,int ratio,int repeats);
int main(void)
{
int firstNum = 0;
int ratio = 0;
int repeats = 0;
printf("First number of the series: ");
scanf("%d", &firstNum);
printf("the ratio of the series: ");
scanf("%d", &ratio);
printf("the amount of numbers to display is ");
scanf("%d", &repeats);
forloop(firstNum,ratio,repeats);
}
void forloop(int firstNum,int ratio,int repeats)
{
int i = 0;
for (i=1; i!=repeats+1;i++)
{
printf("%d ", firstNum*(pow( ratio, i)));
}
}
This should fix the issue with printing zeros:
void forloop(int firstNum,int ratio,int repeats)
{
int i = 0;
for (i=1; i!=repeats+1;i++)
{
printf("%.0f ", firstNum*(pow((double)ratio,(double)i)));
}
}
As mentioned by #JonathanLeffler in the comments, you have a bug. The line
printf("%d ", firstNum*(pow( ratio, i)));
is wrong because pow returns a double but in the printf specifications %d expects an integer.
So, you can either change the specifier in your printf to a floating point one, i.e., %f, %g, %e, %F, %G, %E et cetera or cast pow's output to int by doing (int)pow(ratio, i).
In the first case, as #JadMrad said, if you are printing a double and you don't want to have decimal numbers, you can specify the number of digits at the right of the decimal point using "%.Nf" instead of "%f" where N is the number of decimal points that you want.
Nevertheless, in your case it seems to me that you are expecting always integer numbers. Then,
printf("%d ", firstNum*((int)pow( ratio, i)));
sounds like a better solution to me.

Average of Even Numbers and Product of all Odd Numbers

#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.

C - how to display the numbers in an array that are lower than the average value of the numbers in the array

#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
system("pause");
}
The code runs fine and gives the correct average of the integers entered but the values that are less than the average comes out as -858993460
You are trying to print out ray[i], but i is currently 20which is outside the index of your array. Did you mean to copy your for loop around that if statement?
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
average=(sum/20);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
}
printf("Average = %.2f", average);
system("pause");
}
This gives the "the following integers are below the average" part after each value that is lower than the then average, but I need it to show the values which are below the average together at the end.
The out-of-index issue
As the others have already pointed, your index is out of bounds.
That happens because you've iterated for (i=0; i < 20; i++), which means once you left the for statement you were at i == 20. Your array was allocated with 20 positions, so you can access it from index 0 to 19. The awkward value you get is given because you are accessing "trash", or in other words, invalid positions with unpredictable (or almost) values.
The algorithm issue
Ok, once you got that index thing right, you still need an algorithm that displays the numbers that are lower than the average. You can't just copy your if statement into the loop because you only know the true average value once you've iterated through all of the values (which you are doing just fine).
So what you want is another loop that iterates throughout the array and that if statement inside of it (well, there are other ways to do it without running all of the values again, like sorting the array)
So, this is the algorithm I'll propose you
#include <stdio.h>
#include <stdlib.h>
#define array_size 20
void main()
{
int i;
int ray[array_size];
int sum=0;
float average;
for (i=0; i<array_size; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum += ray[i];
}
average=(sum/(float)array_size);
printf("Average = %.2f\n", average);
printf("The following values are less than the average: ");
for (i = 0; i < array_size; i++)
{
if (ray[i] < average)
{
printf("%d ", ray[i]);
}
}
system("pause");
}
This Part in Your Code:
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
//Now i = 20,that is why it left loop
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average) //You are saying if ray[20]<average
{
printf("The following values are less than the average: %d", ray[i]);
}
Now ray[20] is outside the scope because there are 20 elements and array index starts from 0 and goes on to 19, so ray[20] is out of bound access.
I highly recommend you to see this question for better understaning How dangerous is it to access an array out of bounds?.
Secondly You want to print all ray[i] where ray[i] < average so you should run a loop like
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i])
}
}
All That makes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i]);
}
}
system("pause");
}

Resources