CFORBEGINNERS.COM


C++ Loops

Loops are an essential tool in programming they allow the same code to be run as many times as you like. If you have never used loops before then it is hard to imagine why running the same code over and over again would be useful but the more and more you use the clearer it will become. First let us look at a program that prints out a few numbers.

#include <iostream>

using namespace std;

int main()
{
	cout<<"1"<<endl;
	cout<<"2"<<endl;
	cout<<"3"<<endl;
	cout<<"4"<<endl;
	cout<<"5"<<endl;
	cout<<"6"<<endl;
	cout<<"7"<<endl;
	cout<<"8"<<endl;
	cout<<"9"<<endl;
	cout<<"10"<<endl;

return 0;
}

As you can probably see coding something like this could get very tedious but fortunately there is a solution. Using a loop we are able to reduce this same program to just a few lines of code. Here is what is called a for loop which is the most common loop. Here is the syntax for a for loop.

for (intialization; condition; increment/decrement)

Here is the same program that prints out a few numbers only this time a for loop will be used.

#include <ostream>

using namespace std;

int main()
{

int x;

     for (x=0; x<=10; x++)
	{
		cout<<x;  //code that will execute inside the loop
	}

return 0;
}

This program will run exactly the same as the program before only this one is much more efficient. Here is how it works, the heart of this program is the for loop, start with the keyword for with a set of parenthesis. Inside the parenthesis are three thing; the intialization, the condtion and the incrementing/decrementing. In this loop the intialization is x=0 notice how I declared x as an integer in the beginning of the program but actually assigned it a value in the for loop. The condition is how long the loop will run for in this case as long as x is less than or equal to 10. Last is the incrementing, x++ means that 1 will be added to the current value of x after each execution of the loop. So x begins at 0 which is less than 10 so it's given the green light to continue; x is then printed out which right now is 0 finally x is added by 1. X is now 1 which again passes the condition of being less than or equal to 10; x is then printed out which is right now 1 and finally x is added 1 to it's current value. X is now 2....catching on yet? Once x is 11 it no longer passes the condition so the loop breaks and the program continues with the rest of the program. Also remember to put the semicolon after the intialization and the condition as this is absolutely required. Last notice the two curly brackets the first signifies the beginning of the loop and the last curly bracket ends the loops. A for loop is the most common loop used but there are two others that serve their purposes. The next loop is called a while loop. A while loop gives you more versatility in some situations but for the sake of understanding lets start with something simple. Here is the syntax for a while loop.

while (condition)
{ //Beginning of loop

	statements
} //End of loop

Here is the same program written with a while loop instead of a for loop keep your eye on the differences.

//Full Working Program

#include <iostream>

using namespace std;

int main()
{

int x=0;
	

	while (x<=10)
	{
		cout<<x<<endl;
		x++;
	}

return 0;
}

First notice how x had to be intialized before the loop even started, this is because a while loop only is concerned about the condition and the incrementing. If the incrementing wasn't there then the loop would keep going forever until the end of time or your computer dies; this is what's called an infinite loop. Also notice that the incrementing came after the cout statement. In this order x is printed out then incremented but if it was vice versus x would be incremented before it was even printed to the screen. This while loop can actually be put into just one line here is how.

while (x<=10)
{
	cout<<x++<<endl;
}

This will not effect the program because x will still be printed out before it is incremented this is because the "++" is after the x. If the "++" came before the x like this "++x" then the incrementation would happen before x is printed out. Try it for yourself and see the difference. The last loop is called a do while loop. The do while loop is somewhat similar to the while loop but does have some differences. Unlike the while loop which checks the condition before it even executes the do while will always execute atleast once, this is because the condition is at the end of the loop so naturally it won't check the condition until it executes the first time. Here is the program.

//Full Working Program

#include <iostream>

using namespace std;

int main()
{
int x=0;

	do
	 {
	
	    cout<<x<<endl;
		x++;
	
	}while(x<=10);//notice the semicolon

return 0;
}

As you can see the condition is the very last thing that is coded therefore it will be the last thing checked this is how the do while loop gets away with executing atleast once. So now that we have these new tools we are able to something a little more interesting. Here is a program that first calculates how much a car payment would be when given the loan amount (principal), interest rate, and duration. Here is the program!

//Full Working Program

#include <iostream>
#include <stdlib.h> //this is required to use system pause
#include <math.h>  //this is required in order to perform more advanced math
using namespace std;

int main()
{

    double i,l,r,m,p,cnt=1,tot_interest=0;
	
    cout<<"Enter the principal"<<endl;
    cin>>p; //takes in the amount of the loan

    cout<<"Enter the interest rate"<<endl;
    cin>>r; //takes in the interest rate

    cout<<"Enter the length of the loan in months"<<endl;
    cin>>m; //takes in the duration of the loan in months

    r=r/100; //converts the rate into decimal form
    l=(p*(r/12.0))/(1-(pow((1+r/12.0),-m))); //equation to calculate an amount of a loan
	
    cout << "Your car payment will be "<<l<<" dollars"<<endl;

    system("pause"); //this will pause the program allowing the user to be able to see the car payment amount

    while(cnt<=m) //the loop will continue as long as cnt is less than or equal to the loan duration
    {
        i=30.4167*(p*(r/365)); //this will calculate the interest paid in a given month
        tot_interest=tot_interest+i; //total interest equals what it was plus that interest for the month
        cout<<"Interest charged in month "<<cnt<<":  "<<i<<endl;
cout<<""<<endl; cnt++; //cnt is incremented by one each time the loop runs p=p-(l-i); //the principal equals what is was minus the loan after the loan is substracted from the interest cout<<"Remaining balance: "<<p<<endl; cout<<""<<endl; } cout<<"Total interest paid "<<tot_interest<<" dollars"<<endl; system("pause"); return 0; }

Once the program calculates the car payment amount it jumps into a while loop, What is nice about this program is that every month it will give you a break down on how much interest was paid in that month and the new principal amount. After every loop the interest is added into a variable called tot_interest so that the user will know exactly how much they would have paid in interest throughout the loan. The loop first allows flexibility with the condition (cnt<=m). This allows the user to input any amount of months for a loan if there was no condition then the program would not be flexible and only would be able to have a fixed loan duration. What if one user had a loan duration of 60 months but another 48? The program would not be ideal. If a user inputs 60 for the months then the loop will execute 60 calculations in nearly an instance pretty convenient I'd say!