C program: Calculating Interest - c

Intent : This program asks a user for The amount that is currently in their bank account, the APR and the number of years. The output is the starting and ending of the amount that shows an accumulative interest of the years specified by the user.
Question: I'm trying to find a way to correctly add the interest, as of right now for a specified amount of years all i'm doing is multiplying the (current amount in bank account * interest rate * years) I know this is wrong and I think I need a loop for the accumulating interest rate from one year to the next and that's where I need help.Thanks and here is my current code below...
The Code
#include <stdio.h>
#include <stdlib.h>
float getPV()
{
float d;
float start;
printf("Start: ");
scanf("%f", &start);
d = start;
return d;
}
void getIR(float *a)
{
printf("Rate: ");
scanf("%f",a);
}
void getNP(int *years)
{
printf("NumPeriods: ");
scanf("%d", years);
}
float interest(float a,float b,float c)
{
float x;
x = a*b*c;
return x;
}
int main()
{
float pv,ir,fv,Total;
int np;
pv = getPV(); //Amount in account
getIR( &ir ); // APR
getNP( &np ); // Number of years
fv = interest(pv,ir,np);
Total=fv + pv;
printf("Starting: %.2f\n", pv);
printf(" Ending: %.2f\n", Total);
return 0;
}

Maybe something like this?
float interest(float a,float b,float c)
{
return a * pow(1.0f + b, c);
}
Assuming b is a number like 0.05 to mean 5% a year, and c is a number of years (which doesn't have to be an integer).

Related

Why is this code not producing an output?

Im writing a simple program to show the distance/time between two converging trains. I wanted to test the program and return output value through the function float converge, and then apply that to the main function, but it seems that the converge function does not work.
#include <stdio.h>
float converge(int x, int y, int z) {
return x / (y + z);
}
int main(void) {
int dist, speed1, speed2;
printf("Enter distance in miles");
scanf("%d\n", &dist);
printf("Enter train 1 speed and train 2 speed in mph");
scanf("%d%d\n", &speed1, &speed2);
converge(dist, speed1, speed2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
float converge (float x, float y, float z)
{
int time=x/(y+z);
return time;
}
int main ()
{
float dist, speed1, speed2;
printf("Enter distance in miles:\t");
scanf("%f", &dist);
printf("Enter speed of first train in mph:\t");
scanf("%f", &speed1);
printf("Enter speed of second train in mph:\t");
scanf("%f", &speed2);
printf("Time between this two trains is %f",converge(dist, speed1, speed2));
}
There are multiple problems in your code:
converge performs integer arithmetic and converts the result to float only for the return value. If you want to compute a fractional number, you should change it to: double converge(int x, int y, int z) { return (double)x / ((double)y + z); } or better use double for the input values and the argument types:
double converge(double x, double y, double z) { return x / (y + z); }
There are trailing newlines in the scanf() conversion formats: this will cause scanf() to consume any trailing white space typed after the numbers, including any number of newlines typed at the prompts. You will not get the second prompt as long as you enter empty lines. Remove these \n from the format strings.
The result of the computation is not printed.
Here is a modified version:
#include <stdio.h>
double converge(double x, double y, double z) {
return x / (y + z);
}
int main(void) {
double dist = 0, speed1 = 0, speed2 = 0;
printf("Enter distance in miles: ");
scanf("%lf", &dist);
printf("Enter train 1 speed and train 2 speeds in mph: ");
scanf("%lf%lf", &speed1, &speed2);
if (speed1 + speed2 <= 0)
printf("No collision\n");
else
printf("Time until collision: %f seconds\", 3600 * converge(dist, speed1, speed2));
return 0;
}
Why is this code not producing an output?
It produces no output for the expected output from the result of converge() because there is no statement in the provided code, which could cause this output.
You need for example one printf() statement after the call to converge() in order to print the result of converge():
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
float converge_result;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
converge_result = converge(dist, speed1, speed2);
printf("The time until the two trains encounter each other is:\n %f",converge_result);
return 0;
}
or alternatively:
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
printf("The time until the two trains encounter each other is: \n%f ",
converge(dist,speed1,speed2);
return 0;
}
By the way, the calculation of the distance in time seems incorrect or at least incomplete.

Infinite Recursion loop C

We have been learning about recursion vs iteration in C this week and we were required to make a program that recursively determines the value of the nth term of a geometric sequence defined by the terms a, ar, ar^2, ... ar^(n-q).
For the most part, I think I have it figured out, as it seems to display the correct values per run, but it doesn't manage to break the recursion when the tested value reaches zero. Also, if possible to get a better explanation of recursion, and some examples of when recursion would be preferred over iteration as I'm still struggling with the concept.
// 2/20/2018
//Lab 6 Solution for Page 369 PE 4 B
//including libraries to be used
#include <stdio.h>
#include <math.h>
int main() {
//Function prototype
double goAnswer(int *, double, double, double, double *, int);
//Declaring variables
int nValue = 0;
double ratio = 0;
double firstTerm = 0;
double answer = 0;
double addedAnswer = 0;
int count = 1;
//Setting up to ask for each value
printf("Please enter in the value of n: ");
scanf("%d", &nValue);
printf("Please enter in the ratio you'd like to use: ");
scanf("%lf", &ratio);
printf("Please enter in the first term to use: ");
scanf("%lf", &firstTerm);
addedAnswer = goAnswer(&nValue, ratio, firstTerm, answer, &addedAnswer,
count);
//Printing out the value of the first nth terms
printf("The value of all terms added together is: %lf\n", addedAnswer);
return 0;
}
//function header
double goAnswer(int *nValue, double ratio, double firstTerm, double answer,
double *addedAnswer, int count) {
if (nValue == 0){
return 0;
}
else{ //This part calculates the answer, prints the value to the screen,
adds the answer to a running sum, decreases the nValue by one and calls the
function again with the lower nValue
answer = firstTerm * pow(ratio, count);
printf("The value of term %d is: %lf\n", count, answer);
printf("This is the nValue: %d \n", *nValue);
*addedAnswer += answer;
nValue -= 1;
return (goAnswer(nValue, ratio, firstTerm, answer, addedAnswer,
(count + 1)));
}
}

Book error? Unnecessary semi-colon at function (Head First C example, Griffiths & Griffiths 2012)

It looks like this might be a typo in Head First C, 2012, Griffiths and Griffiths, published by O'Reilly. On p. 165, there's an exercise:
"There’s a new program helping the waiters bus tables at the Head First Diner. The code automatically totals a bill and adds sales tax to each item. See if you can figure out what needs to go in each of the blanks"
The error appears to be at line 7, float add_with_tax(float f);. The semicolon should not be here when defining a function. Am I correct on this?
#include <stdio.h>
float total = 0.0;
short count = 0;
short tax_percent = 6;
float add_with_tax(float f); // we're returning a small cash value, so it'll be a float
{
float tax_rate = 1 + tax_percent / 100.0;
total = total + (f * tax_rate);
count = count + 1;
return total;
}
int main(){
float val;
printf("Price of item: ");
while (scanf("%f", &val) == 1){
printf("Total so far: %.2f\n", add_with_tax(val));
printf("Price of item: ");
}
printf("\nFinal total: %.2f\n", total);
printf("Number of items: %hi\n", count);
return(0);
}
Yes, it's a syntax error. float add_with_tax(float f); is a valid prototype, so the actual error then is on the next line because you can't have a lone block { ... } at file scope.

How to return a value with void function without parameter in c

I'm new to C language and coding and I encountered a question asking me to change the function header of:
float RealRoot_1(float a, float b, float c);
float RealRoot_2(float a,float b,float c);
to become:
void RealRoot_1(void);
void RealRoot_2(void);
I was told that it has something to do with Global Variables but I still couldn't figure it out after trying quite some time. Can anyone please explain on how to do it? Thanks a lot.
The source file is as below:
#include<stdio.h>
#include<math.h>
int main()
{
float RealRoot_1(float a, float b, float c); // Prototype declaration
float RealRoot_2(float a, float b, float c);
// Defining Input Variables
float x, y, z;
// Defining Output Variables
float Root_1, Root_2;
printf("Please enter the factor of X^2: ");
scanf("%f",&x);
printf("Please enter the factor of X: ");
scanf("%f",&y);
printf("Please enter the free factor: ");
scanf("%f",&z);
Root_1 = RealRoot_1(x,y,z);
Root_2 = RealRoot_2(x,y,z);
printf("the First Root is: %f \n", Root_1);
printf("the Second Root is: %f \n", Root_2);
system("pause");
}
float RealRoot_1(float a, float b, float c)
{
float x;
x = (-1*b + sqrt(pow(b,2) - 4 * a * c)) / (2 * a);
return x;
}
float RealRoot_2(float a, float b, float c)
{
float x;
x = (-1*b - sqrt(pow(b,2) - 4 * a * c)) / (2 * a);
return x;
}
This can be done by using global variables. You need to ensure that the variable names used in the function are the same as the ones used in the main code.
#include<stdio.h>
#include<math.h>
void RealRoot_1(void); // Prototype declaration
void RealRoot_2(void);
float x, y, z;
float Root_1, Root_2;
int main()
{
// Defining Output Variables
printf("Please enter the factor of X^2: ");
scanf("%f",&x);
printf("Please enter the factor of X: ");
scanf("%f",&y);
printf("Please enter the free factor: ");
scanf("%f",&z);
RealRoot_1();
RealRoot_2();
printf("the First Root is: %f \n", Root_1);
printf("the Second Root is: %f \n", Root_2);
system("pause");
}
void RealRoot_1(void)
{
Root_1 = (-1*y + sqrt(pow(y,2) - 4 * x * z)) / (2 * x);
}
void RealRoot_2(void)
{
Root_2 = (-1*y - sqrt(pow(y,2) - 4 * x * z)) / (2 * x);
}
Please note that this is a worse way of doing things than was given in the initial problem. In the initial exercise. You are loosing modularity and using too many globals is in general a bad idea.
You can also see Are global variables bad?
This should be self explanatory:
float RR_a, RR_b, RR_c;
float RR_d; // store result here(like a return value)
void RealRoot_1(void); // prototypes
void RealRoot_2(void);
void main(void)
{
printf("Please enter the factor of X^2: ");
scanf("%f",&RR_a);
printf("Please enter the factor of X: ");
scanf("%f",&RR_b);
printf("Please enter the free factor: ");
scanf("%f",&RR_c);
RealRoot_1();
printf("the First Root is: %f \n", RR_d);
RealRoot_2();
printf("the Second Root is: %f \n", RR_d);
system("pause");
}
void RealRoot_1(void)
{
float x;
x = (-1*RR_b + sqrt(pow(RR_b,2) - 4 * RR_a * RR_c)) / (2 * RR_a);
RR_d = x;
}
void RealRoot_2(void)
{
float x;
x = (-1*RR_b - sqrt(pow(RR_b,2) - 4 * RR_a * RR_c)) / (2 * RR_a);
RR_d = x;
}
Notice that after calling RealRoot_1 we now print the result before calling RealRoot_2. That's because the result of RealRoot_1 which is stored in RR_d is overwritten by RealRoot_2, thus it is lost.
You can circumvent this by declaring a second return variable, RR_d_2 and storing the result of RealRoot_2 in it.
We do not need duplicates for RR_a, RR_b or RR_c because their values are not modified within the functions.
This way of writing functions has limitations, which will be obvious when faced with recursion or multi-threading.

C. Check input of a float for a certain number of decimal places

Good morning. The code I have written is made to calculate the amount of change given in a transaction, the change portion only, the paper change is ignored. I would like to do an error check to make sure that the user entered # does not exceed 2 decimal places. This is my code.
#include <stdio.h>
#include <stdlib.h>
void intro();
void instructions();
void getvalues(float *owe, float *paid);
float totalchange(float *owe, float *paid);
void quarters (float *change);
void dimes (float *change);
void nickels (float *change);
void pennies (float *change);
int main()
{
float owe = 0.0, paid = 0.0, change;
int a = 2;
intro();
instructions();
printf("Would you like to continue?\n1: Continue\n0: Exit\n");
scanf("%i", &a);
if (a== 0)
exit(0);
while (a == 1){
getvalues(&owe, &paid);
while (owe > paid)
getvalues(&owe, &paid);
change = totalchange(&owe, &paid);
quarters (&change);
dimes (&change);
nickels (&change);
pennies (&change);
printf("Would you like to make another calculation?\n1: Continue\n0: Exit\n");
scanf("%i", &a);
}
return 0;
}
void intro(){
printf("Program: Homework 1 Part 1 :: Change Calculator\nAuthor: Jason Golightly\nDate:5-13-15\nVersion 1.0\n\n");
}
void instructions(){
printf("This program is designed to calculate the coin\nportion of the change given after a purchase.\n");
printf("When prompted, please enter the purchase amount and the amount paid.\nThe amount paid must exceed the purchase amount.\n");
}
void getvalues(float *owe, float *paid){
printf("Please enter the amounts in a dollars.cents fashion\n\nPurchase amount?\n");
scanf("%f", owe);
printf("\nAmount paid?\n");
scanf("%f", paid);
printf("\n");
if (*owe > *paid)
printf("ERROR. Please enter valid amounts.\n");
if (*owe == *paid)
printf("You have given exact change.\n")
}
float totalchange(float *owe, float *paid){
int a;
a = (*paid - *owe)*100;
a = a % 100;
printf("total change = %i\n",a);
return a;
}
void quarters (float *change){
int q;
q = *change / 25;
printf("Quarters = %i\n", q);
*change = *change - 25*q;
}
void dimes (float *change){
int d;
d = *change / 10;
printf("Dimes = %i\n", d);
*change = *change - 10*d;
}
void nickels (float *change){
int n;
n = *change / 5;
printf("Nickels = %i\n", n);
*change = *change - 5*n;
}
void pennies (float *change){
int p;
p = *change / 1;
printf("Pennies = %i\n\n", p);
*change = *change - 1*p;
}
Also, in case you have not noticed, I am fairly new to programming. If you see anything else I could be doing better, please feel free to point it out.
Thanks, Jason
On simple approach to avoid the in-exact floating point calculation is to read the input as a string, parse it into a int, and display it as *.##
i.e.
char number[11];
scanf("%10s", number);
int actual_number = parse(number); // parse the string here.
This actual number is basically dollar*100 + cents - which is an int.
Now perform all the calculations and display like this:
float f = (float)actual_number/100.f ;
printf("%.2f", f);
In the parse routine, you only consider the first two digits after encountering a .
Here is an example of the parse routine in C.

Resources