here is the picture of result of this program/My question is about how to keep the running total in loop?
because in my program, the total debt would only based on the last input of the user before the loop gets terminated instead getting the total debt from all creditors
/This program is for calculating the total debt
#include <stdio.h>
#include <string.h>
int main()
{
float cb,ir,si,totaldebt; //local declaration
int time,i,sum=0;
char c[25];
printf("------------Welcome to Debt Management System-------------");
printf("\nNOTE:\nDear users,\n\tYou have to enter the creditor's name if you have a debt. But if you have nothing debt left, just enter none");
for (i=1;i>=1;i++)
{
printf("\n%d)Name of the creditor: ",i);
//the user inputs the name of the creditor
scanf("%s", c);
if (strcmp(c, "none") == 0) // condition wherein if the user inputs "none" in the name of the creditor, the loop will terminate
{
break;
}
printf("Enter your current balance: ");//the user inputs current balance from the said creditor
scanf("%f",&cb);
printf("Enter its interest rate: "); //the user inputs the interest rate of of the debt
scanf("%f",&ir);
printf("Enter time for the loan: ");//the user inputs month
scanf("%d",&time);
si=cb*ir*time/100;//simple interest
totaldebt=si+cb; //simple interest + current balance
sum+=totaldebt;
}
printf("The total balance you have for now is: %.2f\n",totaldebt); //
if (totaldebt<=5000)
{
printf("\nCongratulations!\n You only have %.2f debt left\n",totaldebt);
}
else
{
printf("\nWork harder because out of DEBT is out of DANGER\n");
}
return 0;
}
You're already keeping track of the running total in sum. You just need to use that:
float sum = 0;
...
printf("The total balance you have for now is: %.2f\n",sum ); //
if (sum <=5000)
{
printf("\nCongratulations!\n You only have %.2f debt left\n",sum );
}
else
{
printf("\nWork harder because out of DEBT is out of DANGER\n");
}
Related
I am new to C programming and cannot seem to get the calculations for the code below to come in outside of the one calculation when I input 1 for distance which then calculates to $1.80. I have an if else that should recognize that as not meeting the minimum and therefore calculate it as $5.00, but it just calculates $1.80. Can you please point me in the right direction as to what I am missing for the needed calculations?
#include <stdio.h>
#include <stdlib.h>
#define MINFARE '$5.00'
int main() {
//Declare all of the variables types and their data types and values as applicable.
float distance, totalFare;
int numberOfPassengers, airport;
//Prompt passenger to enter the total distance (measured to 1/10 of a mile) with a keyboard
printf("Please enter the total distance, ");
printf("enter it measured to 1/10 mile, e.g. 25.5: ");
scanf("%f", &distance);
//Prompt the user to enter the number of passengers
printf("\nPlease enter the number of passengers: ");
scanf("%d", &numberOfPassengers);
printf("\nAre you going or coming from the Airport? ");
printf("Enter (1) for <yes> and (2) for <no>: ");
scanf("%d", &airport);
if(airport == 1) {
totalFare = (1.80 * distance) + 2.00;
}
else {
totalFare = 1.80 * distance;
}
/*Calculate the fare amount with the number of passengers, such that, the initial rider is charge the fare only,
the first additional passenger charge is the fare plus $1.00 and additional passengers are charge an additional
$0.50 per passenger*/
if (numberOfPassengers <= 1) {
totalFare = 1.80 * distance;
}
else {
totalFare = (1.80 * distance) + 1.00 + (0.50 * (numberOfPassengers - 1));
}
printf("\nYou entered %g as the total miles, %d passengers, and %d for Airport cab ride.", distance, numberOfPassengers, airport);
if (totalFare>5.00) {
printf("\nThe total fare owed is:\t MINFARE.");
}
else {
//Print the statements below based on the user input and the calculations total Fare for cab ride
printf("\nThe total fare owed is:\t $%.2f",totalFare);
}
return 0;
}
I agree with #MikeCAT, but just want to clarify this part about symbolic constant (#define MINFARE '$5.00'). In C single quotes (' ') represents a single character, not a string (You are probably confusing it with some other languages like python that works diferently). As already pointed what you write is a multi-character character literal and not string what you actually wanted. If you want to define a string in C you must use double quotes (" ") (Because even a single character string actually have two characters, that one and '\0' which is an indicator that marks the end of a string).
You are limitting the maximum instead of minimum and goint to print a string "MINFARE" when the maximum is hit.
One fix is:
totalFare>5.00 should be totalFare<5.00 to have the value work as minimum, not maximum.
#define MINFARE '$5.00' should be #define MINFARE "$5.00".
printf("\nThe total fare owed is:\t MINFARE."); should be printf("\nThe total fare owed is:\t " MINFARE ".");
Better fix avoiding using magic number is:
#define MINFARE '$5.00' should be #define MINFARE 5.00
totalFare>5.00 should be totalFare<MINFARE
printf("\nThe total fare owed is:\t MINFARE."); should be printf("\nThe total fare owed is:\t $%.2f.", MINFARE);
I've been trying to figure this out the last few days, but no luck. The objective is to find the sum, average, minimum, and maximum grades and display them.
Here is my code, everything except minimum, maximum and grade input seem to work
// Includes printf and scanf functions
#include <stdio.h>
int main(void) {
unsigned int counter; // number of grade to be entered next
int grade; // grade value
int total; // sum of grades entered by user
float average; // average of grades
int maxi; // Max grade
int mini; // min grade
int i;
int max;
int min;
maxi = 1;
mini = 1;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
//scanf("%d%d", &min, &max);
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
//scanf("%d",&counter);
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
break;
}
else {
total = total + grade;
average = (float)total / counter; // NOTE: integer division, not decimal
}
}
max = (grade < maxi) ? maxi : grade;
min = (grade > mini) ? mini : grade;
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
Output:
Enter number of grades: 2
5
7
Enter grade 1: 4
Enter grade 2: 3
Class average is: 3.500
Your maximum grade is 3
Your minimum grade is 1
Sum: 7
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade" then from there it calculates everything. Also, it seems that the Maximum is always the last grade that I enter and shows 1 as the minimum when no where in the input is 1. I am supposed to use a conditional operator for the max/min, I tried looking it up and reading the book, but they just use letters like a,b,c, etc. Which just confused me so I'm not sure if I did it wrong.
Could that be what is messing everything up? If it isn't what am I doing wrong?
Another thing is I'm thinking I need a While loop if I want to make the counter have an input from 1-100, is that right?
Edit: just realized I had to remove the scanf for max and min. Taht's why I had to inptu 2 nubmers first
There are two major problems, as I see it
The variable total is not initialized, so the first occurrence of total = total + grade; would invoke undefined behaviour.
You have to initialize it explicitly to 0.
The same variable grade is used for holding the repeated input. After the loop, grade will only hold the last input value.
You need to either use an array for storing inputs and comparison, or, compare and update the min and max as you go, inside the loop.
For future references, please seperate your code in different functions or add comments, since analyzing an unfamiliar code always takes much time.
min: Your problem here lies, that you're initializing your min value with 1. That value is most of the time below your input grades. If you want to initialize it, you should use a high number.
For example:
#include <limits.h>
int min = INT_MAX;
max: Your "grade" will be always the last typed grade, which you scanned. That's not what you want. It would be good, to save all values, which you get as input in an array or a list.
Also your codesnippet at the end
max = (grade<maxi) ? maxi : grade;
min = (grade>mini) ? mini : grade;
will just compare one grade. You need to compare all values, which you entered.
You could just put them in the for-loop.
gradeinput: You need to temporarily save your inputs in a datastructure like an array/list to use them in your program.
int x[counter];
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i);
x[i]=scanf("%d", &grade);
}
.. have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
This happens because OP's stdout is buffered and not one character at a time.
To insure output is seen before the scanf(), use fflush().
See What are the rules of automatic flushing stdout buffer in C?
printf("Enter number of grades: ");
fflush(stdout); // add
scanf("%d", &counter);
Rather than set the min = 1, set to a great value
maxi = 1;
mini = 1;
maxi = 0;
mini = 100;
// or
maxi = INT_MIN;
mini = INT_MAX;
Move the test for min/max in the loop to test each value and fold maxi, max into the same variable.
if (max > grade) max = grade;
if (min < grade) min = grade;
The first total + grade is a problem as total is uninitialized.
// int total; // sum of grades entered by user
int total = 0; // sum of grades entered by user
Unnecessary to calculate average each time though the loop. Sufficient to do so afterward.
Style: After the break; the else is not needed.
Good that code tests user input range. Yet the i-- is incorrect. If code is to break, just break. If code it to try again, the i-- makes sense, but then code should continue.
The comment // NOTE: integer division, not decimal is incorrect as (float) total / counter is FP division.
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n");
i--;
continue;
}
total = total + grade;
} // end for
average = (float) total / counter;
In general, casting should be avoided.
Advanced issue: Consider the situation if later on code was improved to handle a wider range of integers and used higher precision FP math.
The 1st form causes total to become a float (this could lose precision) and perhaps use float to calculate the quotient, even if average was a double. Of course the (float) cast could be edited to (double) as part of the upgrade, but that is a common failure about updates. Types may be changed, but their affected object uses are not fully vetted.
The 2nd form below causes total to become the same type as average and use the matching math for the type. Reduced changed needed as the types change. This form is also easier to review as one does not need to go back and check the FP type of average to see if a cast to float, double or even long double was needed.
average = (float) total / counter;
// or
average = total;
average /= counter;
For some reason when I start the program, I have to enter a few numbers, in this case 5 & 7 before it prompts me to "Enter grade"
You have two scanf before "Enter grade"
scanf("%d", &counter);
scanf("%d%d", &min, &max);
#include <stdio.h>
int main(void) {
int counter; // number of grade to be entered next
int grade; // grade value
int total=0; // sum of grades entered by user
float average; // average of grades
int i;
int max;
int min;
printf("Enter number of grades: "); // User enters number of grades
scanf("%d", &counter); // Countss number of grades
for (i = 1; i <= counter; i++) {
printf("Enter grade %d: ", i); // User enters grade
scanf("%d", &grade); // Counts grades
if (grade < 0 || grade > 100) {
printf("Please enter a number between 0 and 100!\n"); // Lets user know if input is invalid
i--;
} else {
if(i==1){
max = grade;
min = grade;
}
else{
max = (grade < max) ? max : grade;
min = (grade > min) ? min : grade;
}
total = total + grade;
average = (float) total / counter; // NOTE: integer division, not decimal
}
}
printf("Class average is: %.3f\n", average); // Displays average
printf("Your maximum grade is %d\n", max); // Displays Max
printf("Your minimum grade is %d\n", min); // Displays minimum
printf("Sum: %d\n", total); // Displays total
}
I've edited your Code as there were some mistakes. First, you were not initialising the total, which may make it take some garbage value. The second one is no need of using break as you are reducing the value of i.The third one is that you are updating the min and max outside the for loop, where the value of grade will be the last entered grade. And maxi and mini are not at all needed. The code was running perfectly without waiting for dummy values. Cheers!
I am trying to create a C program which calculates the monthly payment and print a table of payment schedule for a fixed rate loan. My issue is that the loop only iterates once but I cannot figure out why. Here is how the output should looked like:
#include <stdio.h>
#include <math.h>
double calculatePayments(double loan, double rate, int payment);
int main(){
double loan,rate,monthly,principal,interest,balance;
int payment, counter;
counter = 0;
balance = 0.0;
printf("Enter amount of loan: ");
scanf("%lf", &loan);
printf("Enter interest rate per year:%% ");
scanf("%lf", &rate);
printf("Enter number of payments: ");
scanf("%d", &payment);
monthly = calculatePayments(loan, rate, payment);
printf("Monthly payment should be %.2f\n", monthly);
printf("—————AMORTIZATION SCHEDULE—————\n ");
printf("N\tPayment\tPrincipal\tInterest\tBalance\n ");
do{
rate = rate/12/100;
interest = loan * rate;
principal = monthly - interest;
balance = loan - principal;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance < 0);
return 0;
}
double calculatePayments(double loan, double rate, int payment) {
rate = rate/12/100;
double mul = pow(1+rate, payment);
return (loan * mul * rate) / (mul - 1);
}
Changing up the do ... while loop
// e.g. 7.5/12/100 = 0.00625
rate = rate/12/100;
do{
// e.g. 500*0.00625=3.125
interest = loan * rate;
// e.g. 101.88-3.125=98.76
principal = monthly - interest;
// e.g. 500-98.76=401.24
balance = loan - principal;
// update loan
loan = balance;
counter++;
printf("%d\t%.2f\t%.2f\t\t%.2f\t\t%.2f\n", counter, monthly, principal, interest, balance);
}while(balance > principal);
Balance would never be < 0. That is why you loop is only running once. If you had done a while loop instead of do while it wouldn't run at all.
Change balance < 0 to balance > 0
You are checking to loop only if balance is less than Zero.
but at the first iteration the value of balance would be 401$ (not < 0)
So breaking.
You should be checking for balance > 0 in while
I am trying to create a program that runs until and unless the total transaction limit is Rs. 1000. But it stops if you enter 600 or 500 + 300 (sequentially) and so on. How to fix it?
#include <stdio.h>
int main(void)
{
int limit=1000, trans=0, cash;
do
{
printf("Enter the amount of cash");
scanf("%d", &cash);
if(limit>=trans+cash)
{
printf("Transaction Successful of Rs. %d\n", cash);
trans=trans+cash;
}
else
{
printf("Transaction overlimit!\n");
}
}
while(limit>=trans+cash);
printf("Total Transaction: Rs. %d\n", trans);
}
By the time you reach this line
while(limit>=trans+cash);
you have already added cash to trans. So in your first example, both variables have the value of 600, and their sum 1200 exceeds 1000, getting you out of the loop.
The problem is your last test while(limit>=trans+cash) in the case of a successful transaction, trans has been modified so you test against old value of trans + twice value of cash.
I didn't understand when you would like to terminate, I understand that it is possible to continue while it is possible to give cash, but what do you want to do if the given cash (plus the current transaction amount) exceed 1000?
Anyway, something like this may helps you:
#include <stdio.h>
int main(void)
{
int limit=1000, trans=0, cash;
do
{
printf("Enter the amount of cash");
scanf("%d", &cash);
if(limit>=trans+cash)
{
printf("Transaction Successful of Rs. %d\n", cash);
trans=trans+cash;
}
else
{
printf("Transaction overlimit!\n");
break; // get out the loop if over limit.
}
}
while(limit>=trans); // continue if under limit
printf("Total Transaction: Rs. %d\n", trans);
}
Im trying to write this code for school, and im absoultly stuck on what im doing wrong, if anyone could just point me in the right direction, that would be helpful. Trying to learn as much as i can.
My program doesnt calculate out, how much is owed at the end of each month, after subtrackting the payment, and then adding the interest.
IT just displays the same value.
#include<stdio.h>
int main()
{
float loan;
float interest;
int n;
float outstanding;
float outstanding2;
float princeable;
float payment;
printf("\nEnter the amount of the loan: \n ");
scanf("%f" , &loan);
printf("\nEnter monthly interest percentage\n ");
scanf("%f" , &interest);
printf("\nEnter monthly payments: \n ");
scanf("%f" , &payment);
printf("\nEnter number of monthly Payments: \n ");
scanf("%i" , &n);
while (n >= 0) {
outstanding = (loan - payment);
outstanding = (outstanding * (1 + (interest/100)));
printf("\Outstanding Balance after %i =%.2f\n\n", n, outstanding);
n--;
}
return 0;
}
In each iteration, you should calculate outstanding based on its previous value, and not on the initial loan's value, because you also pay interest for interest.
outstanding = loan;
while (n > 0) {
outstanding = (outstanding - payment);
outstanding = (outstanding * (1 + (interest/100)));
printf("\Outstanding Balance after %i =%.2f\n\n", n, outstanding);
n--;
}
This line:
outstanding = (loan - payment);
within the loop is incorrect since it starts with the initial loan value each time. It should be:
outstanding = (outstanding - payment);
You'll also have to set outstanding to loan before entering the loop.
On top of that, you have one too many loop iterations, and an illegal escape sequence \O in your printf string.