Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in R Programming by (5.3k points)

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:

[1] 103500

[1] 107122.5

and so on until the a-th argument.

But it just reads:

[1] 103500

[1] 103500

What little piece am I missing?

1 Answer

0 votes
by

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)

[1] 103500

[1] 107122.5

[1] 110871.8

[1] 114752.3

[1] 118768.6

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...