-
Help with C, loops
Newbie here, this is only my third program. I have to write a program that calculates simple interest. Then loops and does it again unless you input "-1". Seems like I've got it 98% done, just one little thing I can't get to work right. The program should stop as soon as you input "-1", but it keeps asking the other three questions before it stops.
Code:
#include <stdio.h>
/* function main begins program execution */
int main( void )
{
float principal; /* define principal variable */
float itr; /* define interest variable */
int tm; /* define term in days variable */
float rtch; /* define interest charge variable */
while ( principal != -1 ){
/* input info */
printf( "Enter loan principal (-1 to end): " );
scanf_s( "%f", &principal );
printf( "Enter interest rate:" );
scanf_s( "%f", &itr );
printf( "Enter term of the loan in days: " );
scanf_s( "%d", &tm );
/* calculate */
rtch = (principal * itr * tm) /365;
printf( "The interest charge is $%.2f\n\n\n", rtch );}
return 0;
} /* end */
BANG HEAD ON DESK for about an hour now.
-
You aren't checking after each line of input. If you want to potentially break right after that line of input, then you need to check right when you make that line of input.
Code:
while condition
spit out some text
get a number
check that number, if condition break
spit out more text
get another number
check that number, if condition break
...and so on...
You are only checking at the top of the loop. If you want to check after each input, then you need to actually do that.
Quzah.
-
Test for -1 after user input instead of at the top of the loop. The code cycles back to the while only after stepping o'er all the statements that are after it.
-
Thanks guys. This is so logical, AFTERWARDS! Perfectly clear, once your done, you can look back and say "Oh sure that makes sense", but how do you think like that before you've spent a couple hours banging you head on the keyboard?
OH yea, just follow the logic! From now on I'll just start by banging my head on the keyboard, then write the program.