Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# Do/While Loop (C++) Question

Posted on 2004-08-23
Medium Priority
708 Views
I'm having a hard time trying to get my program to repeat.  Here is the code for my program:

/The header file iostream is included in any program that uses the cout object.
#include <iostream>

//Header file required for the string class.
#include <iomanip>

//Header file needed for pow functions
#include <cmath>

#include <conio.h>

//The statement using namespace std; declares that the program will be accessing
//entities whose names are part of the namespace called std.
using namespace std;

//This marks the beginning of the function
int main()

//The bracket indicates the beginning of the function main.
{

//declare variables
float loan;
float rate;
float years;
float balance;
float term;
float payment;
char again;

cout << "\t\t***************************************\n";
cout << "\t\t**                Mortgage Calculator                         **\n";
cout << "\t\t***************************************\n";
cout << "\n";
cout << "\n";

//User inputs loan information
cout << "Loan amount: \$";
cin >> loan;
cout << "Annual Interest Rate(ex. 0.0575):";
cin >> rate;
cout << "Years of Loan: ";
cin >> years;

//Equation for monthly payment
term = pow((1+rate / 12.0), 12.0 * years);
payment = (loan * rate / 12.0 * term) / (term - 1.0);

//Display monthly payment
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint | ios::left);
cout <<"Monthly payment: \$" <<payment <<endl;

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"---------------------------------------\n";

//Produce a listing for each month
balance = loan;
for (int month=1; month< month + 1; month++)
{
float minterest, principal;

{
if (balance > 0)

{
//Calculate monthly interest
minterest = rate / 12 * balance;
principal = payment - minterest;
balance -= principal;
if (balance < 0)
balance = 0;

//Display payment amounts
cout << setw(10) << (month);
cout << setw(10) << minterest;
cout << setw(10) << principal;
cout << setw(10) << balance << endl;

// pause output every twelve lines, except for the final output
if (month % 12 == 0 && month % (int)term != 0)
{
system("pause");
}
}
}
}
}

I have tried to enter a loop to get the program to repeat after it has run through it's calculation.  But I have been unable to get the program to repeat.  What am I doing wrong?
0
Question by:cristina1
• 10
• 8

LVL 2

Expert Comment

ID: 11877840
You actually have defined an infinite loop.  Congratulations!  We have all done it before.

With your for loop defined as follows, you never break out of your loop.

for (int month=1; month < month + 1; month++)

I suspect you wanted something like

int totalMonths = years * 12;  // calc the total number of payments assuming 12 months per year
for (int month = 1; month < totalMonths; month++)

LGawlik
0

LVL 8

Expert Comment

ID: 11880008
to add to LGawlik and correct him a bit:

in the FOR loop, you are testing for
month < month +1.
However since the variable 'month' is an int, it is in the range
-2147483648 to +2147483648.
In the 'for' loop, month will increment from 1 onwards till 2147483648.
When you try to compare month with month + 1 when it has a value +2147483648, it will essentially compare +2147483648 with 0, and the for condition will terminate.

Further, in LGawlik's for loop the condition to check should be
month <= totalMonths

Please clarify whether you want the entire program to repeat or just the 'for' loop.
If you want the entire program to repeat, then make the existing program into a function called 'calcint' and call it from main like this:

int main()
{
char resp;

while(1)
{
cout << "Do you want to continue? (Y/N)? "
cin >> resp;
if toupper(resp) == 'Y'
{
calcint();
}
else
{
cout >> "OK! I am quitting";
break;
}
}
return 0;
}

0

Author Comment

ID: 11880455
Doraiswamy,

Thanks for the help!  I'm trying to have the entire program loop to allow a user to input a new set of mortgage numbers.  The problem I'm having is where in the code to input the loop.
0

LVL 2

Expert Comment

ID: 11881881
Ok, you're correct.  Not an infinite loop; just a very large loop!  ;)
I'd certainly hate to have a mortgage with 2^31 payments.

doraiswamy's suggested solution should give you the results you desire.
0

Author Comment

ID: 11882753
I put the suggested changes into the code.  I'm receiving several errors with this code.  Please be patient with me I'm new to C++.  My just happy I got the code to compile and produce something.  What I want it to do is ask for the users input, print the results a year at a time and then ask if the user wants to input another mortgage or quit.  I have everything except the loop back.  It seems easy but I'm missing something.  Here's the code:

//Code Begins//
#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>

using namespace std;

int main()
{

float loan;
float rate;
float years;
float balance;
float term;
float payment;
char again;

while(1)
{
cout << "Do you want to continue? (Y/N)? "
cin >> resp;
if toupper(resp) == 'Y'

{
calcint();
}
else
{
cout >> "OK! I am quitting";
break;
}
}

cout << "\t\t***************************************\n";
cout << "\t\t**                Mortgage Calculator                         **\n";
cout << "\t\t***************************************\n";
cout << "\n";
cout << "\n";

cout << "Loan amount: \$";
cin >> loan;
cout << "Annual Interest Rate(ex. 0.0575):";
cin >> rate;
cout << "Years of Loan: ";
cin >> years;

term = pow((1+rate / 12.0), 12.0 * years);
payment = (loan * rate / 12.0 * term) / (term - 1.0);

cout.precision(2);
cout.setf(ios::fixed | ios::showpoint | ios::left);
cout <<"Monthly payment: \$" <<payment <<endl;

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"---------------------------------------\n";

balance = loan;
int totalMonths = years * 12;  // calc the total number of payments assuming 12 months per year
for (int month = 1; month=<totalMonths; month++)
{
float minterest, principal;

{
if (balance > 0)

{
minterest = rate / 12 * balance;
principal = payment - minterest;
balance -= principal;
if (balance < 0)
balance = 0;

cout << setw(10) << (month);
cout << setw(10) << minterest;
cout << setw(10) << principal;
cout << setw(10) << balance << endl;

if (month % 12 == 0 && month % (int)term != 0)
{
system("pause");
}
}
}
}
}
0

LVL 2

Expert Comment

ID: 11883852
As mentioned before, break your code down.
Since this appears to be a type of homework assignment many of us have done, I won't give you a complete answer, but the following should give you a pretty good clue.

// they appear to have been incomplete
#include <iostream.h>
#include <iomanip.h>
#include <cmath.h>
#include <conio.h>

// define the mortCalc
// this function will prompt the user for input
// and provide the mortgage calculation details
void mortCalc() {
... // you add the details here
}

// definition of the main function
// process until the user decides to quit
void main() {
char resp;
// continue looping until the user quits
while(1) {
// show the calc screen and process data entered
mortCalc();
cout << "Do you want to continue? (Y/N)? ";
cin >> resp;
// determine if the loop should end
if toupper(resp) != 'Y' {
cout >> "OK! I am quitting";
//break out of the loop
break;
}
}
}

0

Author Comment

ID: 11884046
#include <string>
0

LVL 2

Expert Comment

ID: 11884097
To correct myself, the includes were correct
#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>
using namespace std;

I've also noted your for loop isn't properly defined

for (int month = 1; month=<totalMonths; month++) // this is syntactically incorrect

for (int month = 1; month<=totalMonths; month++) // this is correct

=< isn't an operator in C++
<= is an operator in C++
0

LVL 2

Expert Comment

ID: 11884137
Another code correction

cout >> "OK! I am quitting";  // this is incorrect

cout << "OK! I am quitting";  // this is correct

0

LVL 2

Expert Comment

ID: 11884315
Also note, when declaring your calculation variables it is a good idea to initialize them to 0.

float loan = 0;
float rate = 0;
float years = 0;
float balance = 0;
float term = 0;
float payment = 0;
int totalMonths = 0;

0

Author Comment

ID: 11884690
Thanks for the help.  I think I have a good version of the program.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>

using namespace std;

int main()
{

float loan = 0;
float rate = 0;
float years = 0;
float balance = 0;
float term = 0;
float payment = 0;
int totalMonths = 0;

cout << "\t\t***************************************\n";
cout << "\t\t**                Mortgage Calculator                         **\n";
cout << "\t\t***************************************\n";
cout << "\n";
cout << "\n";

cout << "Loan amount: \$";
cin >> loan;
cout << "Annual Interest Rate(ex. 0.0575):";
cin >> rate;
cout << "Years of Loan: ";
cin >> years;

term = pow((1+rate / 12.0), 12.0 * years);
payment = (loan * rate / 12.0 * term) / (term - 1.0);

cout.precision(2);
cout.setf(ios::fixed | ios::showpoint | ios::left);
cout <<"Monthly payment: \$" <<payment <<endl;

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"---------------------------------------\n";

balance = loan;
int totalMonths = years * 12;  // calc the total number of payments assuming 12 months per year
for (int month = 1; month<=totalMonths; month++)
{
float minterest, principal;

{
if (balance > 0)

{
minterest = rate / 12 * balance;
principal = payment - minterest;
balance -= principal;
if (balance < 0)
balance = 0;

cout << setw(10) << (month);
cout << setw(10) << minterest;
cout << setw(10) << principal;
cout << setw(10) << balance << endl;

if (month % 12 == 0 && month % (int)term != 0)
{
void main() {
Char again;
while(1)
{
mortCalc();
cout << "Do you want to continue? (Y/N)? "
cin >> again;
if toupper(again) == 'Y'

{
calcint();
}
else
{
cout << "OK! I am quitting";
break;
}
}

system("pause");
}
}
}
}
}
0

LVL 2

Expert Comment

ID: 11884829
I see a few problems here.

In the code you've provided, you haven't defined a mortCalc function.  Instead you have two main functions defined, one with return type void and one with return type int.

Your file should like similar to the code below.  The meat of your program (the user interface and calculations) should be in your mortCalc function.  The loop that asks the user to continue is defined in the main function.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>

using namespace std;

void mortCalc() {
float loan = 0;
float rate = 0;
// *****************
// all your other code here
// *****************
if (month % 12 == 0 && month % (int)term != 0) {
system("pause");
}
}
}
}  // end of the mortCalc function

// definition of the main function
// process until the user decides to quit
void main() {
char resp;
// continue looping until the user quits
while(1) {
// show the calc screen and process data entered
mortCalc();
cout << "Do you want to continue? (Y/N)? ";
cin >> resp;
// determine if the loop should end
if (toupper(resp) != 'Y') {
cout << "OK! I am quitting";
//break out of the loop
break;
}
}
}  // end of the main function

0

Author Comment

ID: 11897356
lgawlik,

Well the entire program works except for the loop.  The program currently is stuck within the first iteration of the program.  I have changed the loop to reflect the users ability to loop from the beginning of the program.  Here's what I have:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>

using namespace std;

int main()

{

//declare variables
float loan =0;
float rate =0;
float years =0;
float balance =0;
float term =0;
float payment =0;
char again;
do
{
cout << "\t\t***************************************\n";
cout << "\t\t**                    Mortgage Calculator                     **\n";
cout << "\t\t***************************************\n";
cout << "\n";
cout << "\n";

//User inputs loan information
cout << "Loan amount: \$";
cin >> loan;
cout << "Annual Interest Rate(input % in decimal format):";
cin >> rate;
cout << "Years of Loan: ";
cin >> years;

//Equation for monthly payment
term = pow((1+rate / 12.0), 12.0 * years);
payment = (loan * rate / 12.0 * term) / (term - 1.0);

//Display monthly payment
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint | ios::left);
cout <<"Monthly payment: \$" <<payment <<endl;

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"---------------------------------------\n";

//Produce a listing for each month
balance = loan;
for (int month=1; month<month + 1; month++)
{
float minterest, principal;

if (balance > 0)

{
//Calculate monthly interest
minterest = rate / 12 * balance;
principal = payment - minterest;
balance -= principal;
if (balance < 0)
balance = 0;

//Display payment amounts
cout << setw(10) << (month);
cout << setw(10) << minterest;
cout << setw(10) << principal;
cout << setw(10) << balance << endl;
}
// pause output every twelve lines, except for the final output
if (month % 12 == 0 && month % (int)term != 0)
{
cout << "\nPress any key to continue . . .\n";
//program flow stops here until a key is pressed on the keyboard
getch();

//Clear output screen
system("cls");

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"-------------------------------------\n";
}
}

do
{
cout << "Would you like to calculate another mortgage (Y/N):";
cin >> again;
cout << '\n';
}

while ((again != 'n') && (again != 'N') && (again != 'y') &&
(again != 'Y'));

}

while ((again != 'n') && (again != 'N'));
}
0

LVL 2

Expert Comment

ID: 11897762
Ok.  I understand you are learning C++, but the structure of your program is changing each time you post a response.

The problems you are experiencing this time are based on how you are structuring your loops and old code we've already discussed as being incorrect (ie. month < month + 1).

With the code you've provided this time you should structure your program like this;

int main
{
// declare variables here
// float loan; ...
do {  // outside loop to determine if user want to continue
// initialize variables here
// loan = 0; ...

// insert your mortgage calculator code here

do {  // inside loop to get user input about continuing
// insert your code to ask if the user wants to continue here
}  while ((toupper(again) != 'N') && (toupper(again) != 'Y')); // end inside loop

} while (toupper(again) != 'N');   // end outside loop
} // end main
0

Author Comment

ID: 11898169
Thanks,

I know it has changed a few times.  I have been trying to experiment with various loop structures.  The problem is the program listed above (all of them) will let me run the initial program but not break out of the loop.  I beleive I have all the required code, but it is not placed correctly.  When I move the inner loop to:

// pause output every twelve lines, except for the final output
if (month % 12 == 0 && month % (int)term != 0)
{
cout << "\nPress any key to continue . . .\n";
//program flow stops here until a key is pressed on the keyboard
getch();

//Clear output screen
system("cls");
do
{

The program runs and then continues to run the "Press any key to continue ".  So I tried to move the loop further up the code, then the code does not work.  I move the loop after the desired output:

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"-------------------------------------\n";
}
}

Same results as before.  I'm trying to learn what I'm doing wrong.  Believe me, it has been many long nights.  Thanks for your patience!
0

LVL 2

Accepted Solution

lgawlik earned 280 total points
ID: 11898374
OK.  You're almost there. I've taken your code verbatim and simply applied some proper indenting and styling.  Not a single line of code has changed logic wise.

To get your code to work properly you need modify your for loop so it isn't incorrection comparing (month < month + 1); as mentioned earlier in this thread, this is a VERY large loop.  You're looking to limit the loop to (12 * years) worth of months.  If you setup a totalMonths variable with a value of (12 * years) and then compare month <= totalMonths your code will start working.

There are other problems with the code that would need to be addressed if it were for the real world.  You'll come to learn what those gotchas are as you code more.  Some hints are, always initialize your variables, properly format your code for ease of reading, and check for potential divide by zero situations (look at line 73!!! hint, hint, hint)

Let me know if you need anything else.

#include <iostream>
#include <iomanip>
#include <cmath>
#include <conio.h>

using namespace std;

int main() {
//declare variables
float loan = 0;
float rate = 0;
float years = 0;
float balance = 0;
float term = 0;
float payment = 0;
char again;

do {
cout << "\t\t***************************************\n";
cout << "\t\t**                    Mortgage Calculator                     **\n";
cout << "\t\t***************************************\n";
cout << "\n";
cout << "\n";

//User inputs loan information
cout << "Loan amount: \$";
cin >> loan;
cout << "Annual Interest Rate(input % in decimal format):";
cin >> rate;
cout << "Years of Loan: ";
cin >> years;

//Equation for monthly payment
term = pow((1+rate / 12.0), 12.0 * years);
payment = (loan * rate / 12.0 * term) / (term - 1.0);

//Display monthly payment
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint | ios::left);
cout <<"Monthly payment: \$" <<payment <<endl;

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"---------------------------------------\n";

//Produce a listing for each month
balance = loan;
for (int month=1; month<month + 1; month++) {
float minterest, principal;

if (balance > 0) {
//Calculate monthly interest
minterest = rate / 12 * balance;
principal = payment - minterest;
balance -= principal;
if (balance < 0)
balance = 0;

//Display payment amounts
cout << setw(10) << (month);
cout << setw(10) << minterest;
cout << setw(10) << principal;
cout << setw(10) << balance << endl;
}

// pause output every twelve lines, except for the final output
if (month % 12 == 0 && month % (int)term != 0) {
cout << "\nPress any key to continue . . .\n";
//program flow stops here until a key is pressed on the keyboard
getch();

//Clear output screen
system("cls");

cout << endl;
cout << setw(10) <<"Month";
cout << setw(10) <<"Interest";
cout << setw(10) <<"Principal";
cout << setw(10) <<"Balance" << endl;
cout << setw(10) <<"-------------------------------------\n";
}
}

do {
cout << "Would you like to calculate another mortgage (Y/N):";
cin >> again;
cout << '\n';
} while ((again != 'n') && (again != 'N') && (again != 'y') &&
(again != 'Y'));

} while ((again != 'n') && (again != 'N'));
}
0

LVL 2

Expert Comment

ID: 11898402
My hint above about "divide by zero" also applies to "modulo by zero" as well!
If you copy and paste the code above, take a close look at line 72!  While you don't have a problem using realistic values, see what happens if you enter the following:

Loan amount: 30000
Interest: 12  (not .12)
Years of Loan: 30
0

Author Comment

ID: 11898477
lgawlik,

Ok, I think I almost have it!  I have added "int totalMonths = 12", and I changed the totalMonths portion of the if statement.  The program takes the users input and provides a 12 month break out of the mortgage, not the complete mortgage.  It then asks me the loop[ question (Do you want to do this again?).  I realize the "int totalMonth =12"  is the reason why it is only print 12 payments.  However, I'm trying to figure out how to change the variable so it prints out the entire mortgage.  I tried the following variable with no success:

int totalMonths = 12 * years

Thank you again for your patience.
0

Author Comment

ID: 11898618
I did it!!!!!   I finally figured out what I was doing wrong.

I had to declare the following variables:

int month = 12
int totalMonths = 0

and then...

totalMonths = years * month

It compiled and did everything it was suppose to do!!!!

Thank you for your time and patience.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We live in a world of interfaces like the one in the title picture. VBA also allows to use interfaces which offers a lot of possibilities. This article describes how to use interfaces in VBA and how to work around their bugs.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and â€¦
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to goâ€¦
###### Suggested Courses
Course of the Month11 days, 12 hours left to enroll