Functions and Parameters | Sololearn: Learn to code for FREE!

+1

Functions and Parameters

In the following code I do not understand why we need to create a function to output a number. Is this better than just creating a variable named X and assigning a value? This code came from your tutorial "Function Parameters" Question 2/3. I got real lost in my C++ Programming book at this chapter. Came here for more learning and help as recommended by a friend. Here is the code: Function Parameters Once parameters have been defined, you can pass the corresponding arguments when the function is called. For example: #include <iostream> using namespace std; void printSomething(int x) { cout << x; } int main() { printSomething(42); } // Outputs 42 Try It Yourself The value 42 is passed to the function as an argument, and is assigned to the formal parameter of the function: x. Making changes to the parameter within the function does not alter the argument.

11/28/2017 6:18:27 AM

Lisa Kordich

2 Answers

New Answer

+3

You do not need to create a function to output the number, actually. It's just a simple example of a function. A function is basically a block of code that does something. For example: int factorial(int x): count = 1; for (int i = 0; i <= x; i++){ count *= i; } return count; } int main(){ for (int y = 0; y < 4; y++){ cout << factorial(y) } } //126 This code outputs the factorial of 1, 2, 3. Instead of having to manually hardcode how to calculate a factorial, you write a function to help you do that. Saves time. Hope this helped. 😉

+1

Yes it does. Thank you so much for your answer. :)