We have learned how to make a computer repeat an operation a lot of times until a certain condition is achieved, with the while loop. Now we are going to learn another way to make loops, the “for” loop, which is fact is even more widely used.
To do so, let’s make a little program about investiment.
We will tell the program how much are we investing each month, how much is the interest, and how many months we will wait the money to grow.
Do this:
/***************
GLOBAL VARIABLES
***************/
var monthlyInv = 0;
var monthlyPercInt = 0;
var totalMonths = 0;
The brackets and the asterisk are another way to turn text into comments, that is, make the computer pass through it without looking for code to execute. After you write “ /* ” then everything that follows is just texts for humans to read, until you close the comment with “ */ “. I made a lot of asterisks for aesthetic reasons.
Anyway, the computer is going to ask the user what he needs to know.
/*********
The Program
***********/
window.onload = function( ) {
askHowMuch();
askHowLong();
askInterest();
calculate(monthlyInv, totalMonths, monthlyPercInt);
}
You can see where this is going, right? So, let’s define the functions:
askHowMuch = function () {
monthlyInv = prompt("How much do you intend to invest each month?")
if (isNaN(monthlyInv) ) {
alert("Invalid entry");
askHowMuch( );
}
}
askHowLong = function () {
totalMonths = prompt("For how many months would you invest?")
if (isNaN(totalMonths) ) {
alert("Invalid entry");
askHowLong( );
}
}
askInterest = function () {
monthlyPercInt = prompt("How much percent is the monthly interest?")
if (isNaN(askInterest) ) {
alert("Invalid entry");
askInterest( );
}
}
We told the computer to display the texts (the questions) and to store the values the user types, in a variable.
The conditional “if” is to check if the person really wrote a number. isNan means “is not a number”. We have no use for Strings (text) in this particular program so, if it is not a number, the computer asks again.
Well, we got the numbers we need. Now the function that really makes it happen:
calculate = function( monthlyInv, totalMoths, monthlyPercInt ) {
var sum = 0;
//this is the money you have, it will increase
var increase = 1 + monthlyPercInt / 100
/*
For something to increase in 1 porcent, in fact you multiply it for 1.01.
2 percent, 1.02
And so on. It’s the number itself plus the percentage
*/
Now we are finnaly putting the “for” loop.
for (var i = 0; i < totalMonths; i++) {
sum += monthlyInv;
sum *= increase;
}
First, the for syntax:
As you see, you give 3 parameters to the for loop: you give it a variable “i”, you say that the loop will go on as long as the condition “ i < totalMonths” is true, and then you say that at each iteration, “i” will be increased in 1.
Iteration: a repetition of na operation, usually coming closer to the result you want.
+= means that the variable, after the instruction, will be itself plus the number you are giving after it.
Same, *= means it will be itself multiplied by the other number
If I had writen:
For ( x = 5; x < 10 ; 5+=2)
It would take “x” (or any other name you give it), increase it by 2 each round of the loop (iteration) and go until x is no longer smaller than 10.
alert (“At the end of “ + totalMonths + “ you will have “ + sum);
} // closing function calculator.
See? We changed the sum at each round based on the interest and in the end the program says the result.
Now we will “wrap” it into a simple html that does basically nothing. The “invest.html” file.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="investor.js"></script>
<title>Super investing Page</title>
<head>
<body>
<h1> Invest With Us </h1>
<p>
You will have super like advantages
</p>
<body>
</html>
Here your
Javascript file complete. Call it "investor.js".
/***************
GLOBAL VARIABLES
***************/
var monthlyInv = 0;
var monthlyPercInt = 0;
var totalMonths = 0;
/*********
The Program
***********/
window.onload = function( ) {
askHowMuch();
askHowLong();
askInterest();
calculate(monthlyInv, totalMonths, monthlyPercInt);
}
askHowMuch = function () {
monthlyInv = prompt("How much do you intend to invest each month?")
if (isNaN(monthlyInv) ) {
alert("Invalid entry");
askHowMuch( );
}
}
askHowLong = function () {
totalMonths = prompt("For how many months would you invest?")
if (isNaN(totalMonths) ) {
alert("Invalid entry");
askHowLong( );
}
}
askInterest = function () {
monthlyPercInt = prompt("How much percent is the monthly interest?")
if (isNaN(monthlyPercInt) ) {
alert("Invalid entry");
askInterest( );
}
}
calculate = function( monthlyInv, totalMonths, monthlyPercInt ) {
var sum = 0;
//this is the money you have, it will increase
var increase = 1 + monthlyPercInt / 100
/*
For something to increase in 1 porcent, in fact you multiply it for 1.01.
2 percent, 1.02
And so on. It’s the number itself plus the percentage
*/
for (var i = 0; i < totalMonths; i++) {
sum += monthlyInv;
sum *= increase;
}
alert ("At the end of " + totalMonths + " you will have " + sum);
} // closing function calculator.
That’s it, friends. We are going to get rich.
URGENT CORRECTION at 10 february 2024:
Oh schaitz, it seems I made a mistake, and the program was giving a much lower result than the actual outcome of the investment. After studies, I found that Javascript was treating some numbers as texts. I inserted the lines in black bellow, that make the answer given by the user equal to itself converted to integer.
The updated code:
/***************
GLOBAL VARIABLES
***************/
var monthlyInv = 0;
var monthlyPercInt = 0;
var totalMonths = 0;
/*********
The Program
***********/
window.onload = function( ) {
askHowMuch();
askHowLong();
askInterest();
calculate(monthlyInv, totalMonths, monthlyPercInt);
}
askHowMuch = function () {
monthlyInv = prompt("How much do you intend to invest each month?");
monthlyInv = parseInt(monthlyInv);
if (isNaN(monthlyInv) ) {
alert("Invalid entry");
askHowMuch( );
}
}
askHowLong = function () {
totalMonths = prompt("For how many months would you invest?");
totalMonths = parseInt(totalMonths);
if (isNaN(totalMonths) ) {
alert("Invalid entry");
askHowLong( );
}
}
askInterest = function () {
monthlyPercInt = prompt("How much percent is the monthly interest?");
montlhyPercInt = parseInt(monthlyPercInt);
if (isNaN(monthlyPercInt) ) {
alert("Invalid entry");
askInterest( );
}
}
calculate = function( monthlyInv, totalMonths, monthlyPercInt ) {
var sum = 0;
//this is the money you have, it will increase
var increase = 1 + monthlyPercInt / 100
/*
For something to increase in 1 porcent, in fact you multiply it for 1.01.
2 percent, 1.02
And so on. It’s the number itself plus the percentage
*/
for (var i = 0; i < totalMonths; i++) {
sum += monthlyInv;
sum *= increase;
}
alert ("At the end of " + totalMonths + " you will have " + sum);
} // closing function calculator.
That's it. At least, if you used my fantastic tool to invest, in the end you got more money than I promised, not less! ;-)