0
0
R Programmingprogramming~15 mins

Return values in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Return values
📖 Scenario: Imagine you are creating a simple calculator function in R that adds two numbers and returns the result. This is like using a vending machine: you put in money (input), press a button (function), and get a snack (output). Here, the snack is the sum of two numbers.
🎯 Goal: You will build a function called add_numbers that takes two numbers as input and returns their sum. Then, you will call this function and print the result.
📋 What You'll Learn
Create a function called add_numbers with two parameters: a and b
Inside the function, return the sum of a and b
Call the function with the numbers 5 and 7 and store the result in a variable called result
Print the value of result
💡 Why This Matters
🌍 Real World
Functions that return values are used everywhere in programming to perform calculations, process data, and give back results. For example, a shopping app might use functions to calculate total prices.
💼 Career
Understanding how to write functions that return values is a key skill for any programming job, enabling you to write reusable and organized code.
Progress0 / 4 steps
1
Create the function add_numbers
Write a function called add_numbers that takes two parameters named a and b. For now, leave the function body empty.
R Programming
Need a hint?

Use the syntax function(parameter1, parameter2) { } to create a function in R.

2
Add the return statement
Inside the add_numbers function, write a line that returns the sum of a and b using the return() function.
R Programming
Need a hint?

Use return(a + b) to send back the sum from the function.

3
Call the function and store the result
Call the function add_numbers with the numbers 5 and 7. Store the returned value in a variable called result.
R Programming
Need a hint?

Use result <- add_numbers(5, 7) to call the function and save the output.

4
Print the result
Write a line to print the value of the variable result.
R Programming
Need a hint?

Use print(result) to display the sum.