# Calculation within function not iterating correctly (R)

1 view

I am trying to write a function that calculates my salary increase every year if I assume the same percent increase each year.

I have tried some of the following code already, but it just outputs the first iteration of the calculation several times.

Here is my function:

salary_func=function(a,b){

for(i in 1:a){

c=b+(b*0.035)

print(c)

}

}

The first argument should be the number of years I'd like to "forecast" out and the second argument should be the starting salary. So, I'd like to see the output that reads:

 103500

 107122.5

and so on until the a-th argument.

 103500

 103500

What little piece am I missing?

by (25.3k points)

To get the desired output, you can use any one of the following:

Eliminate c and use only b as output.i.e.,

salary_func=function(a,b){

for(i in 1:a){

b=b+(b*0.035)

print(b)

}

}

OR

Initialize c, and update c relative to its previous value.i.e.,

salary_func=function(a,b){

c = b

for(i in 1:a){

c=c+(c*0.035)

print(c)

}

}

Output:

salary_func(5,100000)

 103500

 107122.5

 110871.8

 114752.3

 118768.6