#include <iostream>
usingnamespace std;
int Loop ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
//cout << "value of a: " << a << endl;
return a;
a++;
}
}
int main()
{
int b;
b = Loop();
cout << "value of a is: "<< b << endl;
}
here in above code I want to return value of 'a' by calling function 'Loop'. Is there any way to do this??
for above code output should be:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
When a function returns, it is finished and moves to the next line after the call.
you would be better off putting the cout << "value of a is: "<< a << endl;
inside the loop and removing the return a; from inside as the loop will only run once as you are leaving the function as soon as the return statement is hit.
It really depends on what your overall goal of the program is. How you want to use a in the code. If your only goal is to print the value of a then the function you have is really not needed.
#include <iostream>
usingnamespace std;
int Loop(int &a)
{
// recursion loop execution
if( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
Loop(a);
} else
{
return a;
}
}
int main()
{
int a = 10;
int Final = Loop(a);
cout << "The function returned the value: " << Final << endl;
system("pause");
return 0;
}
Seems like a weird question, but is this what you're looking for?
That particular implementation results in undefined behavior. I'm not sure why you folks supplying recursive non-solutions are using a reference.
1 2 3 4 5 6 7 8 9
int Loop(int a)
{
std:: cout << "value of a: " << a << '\n' ;
if ( a == 20 )
return a ;
return Loop(a+1) ;
}
With the rather generic looking code and description the OP gave, it is difficult to figure out what he's after. Perhaps if he could describe what he's trying to accomplish instead of describing the solution he's trying to implement, we could be of more help.