In the following code:
int sum(int a=40, int b=20)
{
int result;
result = a + b;
return (result);
}
int main ()
{
int a = 100;
int b = 200;
int result;
result = sum(a, b);
cout << "Total value is :" << result << endl;
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
This produces:
Total value is : 300
Total value is : 120
Why does the:
sum(a)
add the (int a) in the 2nd block to the (int b) in the 1st block?
Im confused why the (b) value in the 1st block is used in (sum(a)), but the (a) value in the 1st block is ignored.
int sum(int a=40, int b=20) {
...
}
declares the parameters a to be 40 and b to be to 20, if not specified. This is a compiler service, so sum(a) becomes sum(a, 20) (b not specified). Similar to this, sum() becomes sum(40, 20). a and b in your method sum are default parameters.
In function sum you are using default arguments. That's why when you call
result = sum(a); // where a = 100 and the second parameter is ommited
in the function sum, the first parameter is take the value of this caller's a (= 100), and as the second parameter is absent from the caller's end, the default b (= 20) will be used as b. Hence the result is
100 + 20
= 120
As David Rodríguez suggested in the first comment, use different variables name (say sum (int x, int y)) for no ambiguity and better understanding.
In order to make it shorter:
int sum(int a=40, int b=20)
{
return a + b;
}
int main ()
{
int a = 100;
int b = 200;
cout << "Total value is :" << sum(a, b) << endl;
cout << "Total value is :" << sum(a) << endl;
return 0;
}
In the sum(a,b) both of the parameters have values => it does a+b => 100 + 200 which is 300.
In the sum(a) the second parameter is not set, the function use the default value (ie: 20) => a + 20 => 100 + 20 which is 120
The a & b you define in your main are not the one of the sum function
Well, you should read a bit about default parameters in C++. Where you are on it, I recommend you to research a bit about overloading, since they are somewhat related.
On the first call you do to the sum() function, you provide both parameter to the call, so the variables a and b ,that you declared, are used, hence you get 100+200=300. On the second call tho, you only provide one parameter, so the second one uses the default parameter value, i.e. a=100, b gets the default value (20), so you get 100+20=120.
When you write a function like
returntype Function_name(data_type some_value), then this is called default parameters.
For eg: if you write a function like,
int calculate_area(int lenght=20, int width=25)
Then when you call this function from main, you can either pass values to length and width like this,
int main() {
int a=50;
int b=60;
calculate_area(a,b);
}
Or you can call it like this...
int main() {
calculate_area();
}
See the difference, we are not passing any parameter, still it is a valid call to the function, because in this case.... the default values mentioned by you for length and width will be considered, which in this case is 20 & 25.
And about variables 'a' & 'b' in your code, looks like you are getting confused between name of the variables. Main() and Sum() are two different functions.
'a' of sum has nothing to do with 'a' of main. You will understand this when you will read how the variables are stored in stack and all.
Related
I was wondering if someone could explain why the f2(a,a); is 13 13 and not 12 12?
Does this have something to do with the & sign, if so what does it mean?
Thanks in advance!
#include <iostream>
using namespace std;
void f1 (int a, int b){
a = 12; b = 13;
}
void f2 (int& a, int& b){
a = 12; b = 13;
}
int main()
{
int a = 10; int b = 11;
f1(a,b);
cout << a << ' ' << b << ' ';
f2(a,b);
cout << a << ' ' << b << ' ';
f2(a,a);
cout << a << ' ' << b;
}
In your call f2(a, a) both arguments refer to the same variable (a) (the ampersand means "reference") so that is all you are changing. The function first assign 12 to it, then you assign 13 to it - so that's the final value. The variable b in the main function is not changed by that function call and retains its value (13), so when you subsequently print a and b in main, you get 13 and 13.
This function
void f2 (int& a, int& b){
a = 12; b = 13;
}
accepts its arguments by reference. So calling it like
f2(a,a);
the both parameters are references to the same object a.
At first this object was assigned with the value 12
a = 12;
and then reassigned with the value 13
b = 13;
So the resulting value of the referenced object a is 13.
To make it more clear you can imagine the function call and its definition the following way (I will rename the parameters as a1 and b1 to avoid name collision)
f2(a,a);
// ...
void f2 ( /* int& a1, int& b1 */ ){
int &a1 = a;
a1 = 12;
int &b1 = a;
b1 = 13;
}
So the object a is being changed through the reference to it a1 and b1.
That is you may declare several references to the same object and use the references in any order to change the referenced object. The object will contain the last value assigned to it through one of the references.
Pay attention to that before this call
f2(a,a);
there was the following call
f2(a,b);
that set the value of the variable b to 13.
So this statement after the above two calls
cout << a << ' ' << b;
outputs
13 13
By assigning a to f2(a,a); as both parameters you are doing so as a reference parameter and your code is executed sequentially. So a is first given the value 12 (the value assigned to formal parameter a in the function) and then the same variable is given the value 13 (the value assigned to formal parameter b in the function). The variable b in the main part of your program was is 13 after the function call f2(a,b);.
I'm having a small issue in trying to figure out why a zero is printed out at the end of my while loop.
#include <iostream>
using namespace std;
int x;
int CountDown(int x);
int CountUp(int x);
int main()
{
int toCountUp = CountUp(x);
cout << x << endl;
}
int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
My best response would be that it is in the condition of the while loop. Or a return status from the function/main being fulfilled, but I don't have a return on there, and I know a function doesn't require a return statement but in this while loop I want there to be a integer returned, do I need to make the function void so there will be no return? But what about the parameter x that I need for the while loop?
code output:
0
1
2
3
4
5
6
7
8
9
10
0 < ---- this is the number I do not want.
Thinking about it, it has to be a value returned at the end of the function, any ideas?
This outputs the values 0 through 10:
int toCountUp = CountUp(x);
Then, this outputs 0:
cout << x << endl;
The method does not change the value that is passed to it, it uses its own local copy of that variable.
—It's mainly because you are printing cout << x << endl; twice. Once in the int CountUp(int x) function itself, but again in the main function.
—It could've printed any given value of x at this point, but since you're setting x=0 outside of the While{} loop in the int CountUp(int x) function, it's printing 0 at the end after the function call is executed.
*int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}*
—Is there a reason why you are setting x=0 within the function? since you're passing x as a parameter in the function call, and adding 1 to it in the While{} loop until it's x<= 10? Asking because you're not returning x back to the main() function.
—In case you wanted to use the end value of x to countdown using CountDown(x), you may like to reset x=0 in the main() function after calling the block—
*int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}*
At last 0 is printed in main() function because x is declared global.
If you want latest x after loop got over to be printed in main() then you should reference variable and don't declare it globally.
int CountUp(int &); /* function prototype*/
Since passed variable(actual argument) and reference variable having the same memory So modification will affects in calling function.
int CountUp(int &x) { /* catch with reference variable so that modification affects in calling function also */
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
First read Shadowing variables and What's the difference between passing by reference vs. passing by value?
The int x parameter of CountUp shadows the global variable int x so inside CountUp, the only x is the parameter.
int CountUp(int x)
int x defines x as passed by value, so it is a copy of the x used to call CountUp in main. This different x is counted up to 10 and then discarded.
the global int x has static storage duration and is default initialized to zero for you. Do not try this trick with a variable with Automatic duration because unless it has a constructor that does something useful, the contents are uninitialized and their value is undefined.
Sideshow issue:
A function that has a non-void return type MUST return a value on ALL paths. If it does not, you have Undefined Behaviour and the compiler can generate hopelessly invalid code that can get you even if the bad path is not taken. Don't smurf with Undefined Behaviour, as it might crash the program or do something hilariously wrong, but it might also look like it works until it suddenly doesn't at a really bad time.
Solutions:
void CountUp(int & x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
}
Passes x by reference allowing global x and the local x to be one and the same and returns nothing.
Usage would be
CountUp(x);
Not so useful in the asker's case because it doesn't leave a toCountUp.
int CountUp(int x)
{
x = 0;
while(x <= 10)
{
cout << x << endl;
x++;
}
return x;
}
Makes a copy if the provided x, operates on the copy, and then returns x. Usage would be
int toCountUp = CountUp(x);
And will set toCountUp to 10 higher than the global x.
I saw some codes on the web and trying to figure out how this works. I tried to leave comments on each lines but I cannot understand why y[0] changes to 5555. I'm guessing y[0] might change to numbers[0], but why?
x value is still 1. Well.. is this because y[0] = 1; has no int data type?
#include
using namespace std;
void m(int, int []);
/*this code explains a variable m that m consists of two parts, int and int array*/
int main()
{
int x = 1; /* x value is declared to 1*/
int y[10]; /*Array y[10] is declared but value is not given*/
y[0] = 1; /*Array y's first value is declared to 1 but data type is not given*/
m(x, y); /*This invokes m with x and y*/
cout << "x is " << x << endl;
cout << "y[0] is " << y[0] << endl;
return 0;
}
void m(int number, int numbers[]) /*variable names in m are given, number and numbers.*/
{
number = 1001; /*number has int 1001 value*/
numbers[0] = 5555; /*This overrides y to numbers[], so y[0] =1 changes to numbers[0] = 5555.*/
}
/*This program displays
* x is 1
* y[0] is 5005
* y[0] value has changed but x has not.
* */
I'm guessing y[0] might change to numbers[0], but why? x value is still 1.
Don't guess please. Your code works as commonly expected.
number = 1001; doesn't influence x in any way.
number is a local copy (as passed by value).
numbers decays to a pointer to the 1st element of the original array, thus it is changed outside the functions scope.
Well.. is this because y[0] = 1; has no int data type?
No, as explained above. y[0] actually is of type int.
int numbers[] is almost equivalent to int* numbers in this situation. You are not passing the vector as an immutable object but as a reference. So both numbers ( the local variable from the function ) and y ( the local variable from main ) will be pointing to the same memory address.
I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}
I am supposed to get the following code to display something along the lines of: "The sum of 1 to 10 is 55." (The larger number can be any number that was just the example I got.) I was given this code to use.
#include <iostream>
using namespace std;
// Compute the sum of all of the numbers from 1 to n where n
// is a natural number
// use the formula: n(n+1)/2
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
int main()
{
int sum = 0;
int maxNumber;
// get the maxNumber for the function call
cout << "Enter a whole number greater than 0" << endl;
cin >> maxNumber;
// call compute sum
compute_sum(maxNumber); // Call to compute_sum function
// display the sum calculated by the compute_sum function
cout << "The sum of 1 to " << maxNumber;
cout << " is " << sum << endl;
return 0;
}
I do not understand how funcctions work at all and do not have any idea how I would go about getting this to work. The only thing I know about this (and this is from the teacher) is that the change required is not major. "Note: If you are making major changes to the main and compute_sum funtions you are probably
doing way too much work." I have tried changing the function to an int function with a return but I could not get it to work properly (most likely due to not knowing how functions work). So can someone please help me?
The part you're missing is the return type of the function, and then to actually return that value from the function.
At the moment you have
void compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
}
A function prototype in C looks pretty much like this
<return type> <name> (<parameters>)
{
// your logic here
return <your_own_variable> // Note: You can omit this if the return type is void (it means the function doesn't return anything)
}
You want to modify your function so you are returning the integer value you're calculating inside of it
int compute_sum(int limit) // compute_sum function
{
int sum_to_limit;
sum_to_limit = limit * (limit + 1) / 2;
return sum_to_limit;
}
So what happens is after main runs, when the the point of execution hits
compute_sum(maxNumber);
The program flow jumps to that function and executes the code inside of it. When the function finishes, it returns the value back to where it was originally called from. So you also need to add this to store the value returned
int result = compute_sum(maxNumber);
and then make sure to output that value to the user.
You can also make the computer_sum function a little more terse my not storing a temporary variable, you can just do this
int compute_sum(int limit) // compute_sum function
{
return limit * (limit + 1) / 2;
}
I hope that helps. There's a lot more going on behind the scenes but that's the basic idea. Good luck! :)