+ 1

Utilizing a function with a passing value

Hi, I am a student and new to proramming. I just learn function last week and yesterday i got an assignment from my teacher that i can't solve. Here are the tasks: 1. Make a program using "nested if" with the following scenario: A shop give a discount to costumer that buy 3 items with condition, at least 2 items exceed $15 each. 2. Using the scenario above, make a "loop" which numbers of "loop" are inputed by user or as long as the user need to use the "loop". 3. Using scenario that mentioned in question number 1, make a program with "Discount" function with a "passing value". i can solve number 1 and 2 but i stuck at number 3. as what i understand with function with passing value is you change the value of variable by a process inside another function [[is it right?]]. but i don't seem to understand how to use that in question number 3. thanks beforehand for helping.

21st Dec 2016, 5:57 AM
Cheka Dragwar
Cheka Dragwar - avatar
2 Antworten
+ 6
The question itself on wording "passing value" is unorthodox. Since the question mentioned nothing about return type, I believe I have a good gist of what it wants, that is, passing *by* value. From what I have read, there are two ways to pass a variable into a function from main. - Passing by value - Passing by reference --- Passing by value means that we pass a copy of the variable into the function. E.g. void somefunc(int x); When we call the function and pass a variable into the function, e.g. somefunc(somevar); The value of somevar is passed, but not somevar itself. --- Passing by reference means that we pass the variable (or rather the address of it) directly into the function, e.g. void somefunc(int& x); When we call the function and pass a variable, somefunc(somevar); somevar is passed into the function. Any changes done to somevar will reflect in main(). As a conclusion, - passing by value passes a copy of the variable into the function. Any changes done to the variable will not reflect in main(). For example, we pass somevar into the function by value and do somevar = 7. The variable somevar will still retain its original value in main() instead of taking 7. - passing by reference passes the address of the variable into the function. Any changes done to the variable will be reflected in main(). For example, we pass somevar into the function via reference and do somevar = 7. In main(), somevar will be assigned the value 7.
21st Dec 2016, 7:04 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
@Hatsy Rei thank you i think i get it now!
21st Dec 2016, 7:56 AM
Cheka Dragwar
Cheka Dragwar - avatar