I have this function:
void m(int n)
{
if(n > 0)
m(--n);
cout << n << " "; //for n = 5 --> output is: 0 0 1 2 3 4
}
I have a problem with understanding how it works.
For example:
n(input) = 5
output: 0 0 1 2 3 4
My question is: Why does it show zero twice?
When I add brackets like this:
void m(int n)
{
if(n > 0)
{
m(--n);
cout << n << " "; // now, it shows 0 1 2 3 4 (n = 5)
}
}
So, what brackets cause in this code, that "0" exists only once?
And when I change pre-decrement (--n) to post-decrement (n--) it shows nothing. Why?
Could somebody help me to understand how it works?
First thing to note is : in C++ if you don't put brackets after an if statement, only the next line will be in the statement.
Example :
if(x > 0)
cout << 1;
cout << 2;
Here cout << 2 will always be executed no matter the value of x
The correct way of writing this is
if(x > 0)
{
cout << 1;
cout << 2;
}
Same thing goes for else statements
So this was for the brackets.
My wild guess for the post decrement is the following :
if you do m(n--), the value passed will be 5, the value of n will only change after the function call and go out of scope (so it won't matter). So what will happen is an infinite number of m(5) calls and that's why nothing is appearing. (I'm not sure about that part so please tell me if wrong) !
Hope it helped !
Looks like you confused with Python syntax, where scope of if is determined by indent. In C (and C++, C#, Java an many other languages) the scope is one statement (which ends with ;) unless you use curly brackets { and }. In the 1st variant of your code cout << n << ... will be always performed, regardless of value of n. In second variant it will be performed only if(n > 0)
Related
This question already has answers here:
C++ "return" without value [closed]
(7 answers)
Closed 6 months ago.
I couldnot find a logical reason as how this return statement is working. As much as i read,it should return undefined but the program takes it straight to the recursive call
function below
#include <iostream>
using namespace std;
// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
// Driver Program
int main()
{
int n = 16;
printPattern(n);
return 0;
}
the output of above code is
16 11 6 1 -4 1 6 11 16
Recursion isn't special. Here's your function again, but I hid the name so you can't see which function it is.
void XXXXXXXXXX(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
What does XXXXXXXXXX(-1) do? That's right: it prints -1
What does XXXXXXXXXX(16) do? That's right: it prints 16, then it prints the pattern for 11, then it prints 16 again.
Now can you see why XXXXXXXXXX(16) prints 16 at the start and the end?
return (irregardless if the function is recursive or not) will pass an optional value to caller, and execution will then continue in caller.
I am just learning recursion and I am confused about the output of this recursive function.
int Run(int x)
{
if (x > 0)
cout << Run(x - 1) << " ";
return x;
}
If I call this function with Run(5), I get the output: 0 1 2 3 4
I expected to get the output: 0 1 2 3 4 5.
I'm confused as to why 5 is not returned at the end of the output. It's the value I plugged in to the function, so after all the recursive calls are made, shouldn't the function be returning that same value I plugged in?
Run does return 5, but the recursive calls to Run never do, and only the return of the recursive calls are printed.
Think about it like this: you aren't printing every x given to Run; you're only printing the return of the recursive calls. Your first call to Run that makes the recursive calls returns the 5 that you're expecting to be printed.
Basically, the 0 index means that your function will be executed n times, where n = the argument integer plus 1. the thing is the cout << Run(x - 1) << " "; will be executed n-1 times. This is because the first function call, once it executed all the other recursive calls, will return its value of x. but since it is not returning it to a previous recursive call which would then cout that value, it is not being displayed.
try this cout << Run(int x) on your main function.
We can see that Run(n) is a function that prints the non-negative whole numbers less than n and returns n. This means that for Run(n) you will get an output of 0 1 2 ... n-1 if n is positive.
What you have here:
cout << Run(x - 1) << " ";
is the same as
int r = Run(x - 1);
cout << r << " ";
That is, Run(x-1) will print the numbers less than x-1 and return x-1. So if x == 5 that means Run(x-1) printed the numbers from 0 to x-2 and r was set to 4. Then the function will print r and return. If you're still confused, it's also exactly the same as doing:
Run(x - 1);
cout << x-1 << " ";
Since we know that Run(x-1) will always return x-1 we can skip storing it in a variable and print it directly. A trick when analysing recursive functions is just to assume that they work - assume that Run(x-1) successfully prints the numbers from 0 to x-2 - the only thing left to do then is to print x-1.
So as you can see, the variable x never gets printed, only the numbers less than it. The function returns 5 but it just never prints it.
If you want it to print the non-negative whole numbers less than or equal to x, make this modification:
int Run(int x) {
if (x >= 0) {
cout << Run(x-1)+1 << " ";
}
return x;
}
The if statement has been changed to include 0 being printed now. Run(x-1) prints the numbers from 0 to x-1 and returns x-1, so adding 1 to the result allows us to print x.
I'm a newbie here and I just started college. We are learning C++ and I find it a little bit difficult, because of the way the teachers explain.
Yesterday we did a task that says to create a program, which finds greatest common divisor of 2 numbers. So, the teacher started writing the code, but the explanation wasn't enough for me and I really need some help right now.
(I putted comments on the things I don't understand.)
Here is the code:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a, b;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "GCD (" << a << ", " << b << ") is ";
if (a != 0 && b != 0){
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
size_t max = abs(a) > abs(b) ? abs(a) : abs(b);
size_t diff = max - min; //What is that variable used for?
while (diff > 0)
{
min = diff < min ? diff : min;
max = diff > min ? diff : min;
diff = max - min;
}
cout << min << endl;
}
else{
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
else
cout << "not possible!!!\n";
}
system("pause");
return 0;
}
QUESTION: When should I put {} on if's, while's etc.?
This is the syntax for an if-statement
if ( condition ) statement-true else statement-false
statement-true is either one statement or a block of statements in {...}
So you can use if without {...} if there is only one line. But it is better to always use {...}.
It is necessary when you need more that one line/statement to be executed by the if/else/while. Valid examples:
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
if (a != 0 || b != 0) cout << (a>b ? a : b) << endl;
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
a++; }
If you did:
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
a++;
The the a++; would be executed regardless of the if condition.
Some programmers like to use {} even for single statements because they believe it leads to more usable and maintainable code. I do not belong to that group but I can see the arguments on either side.
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
C and C++ have a construct that is similar to an if-else statement. This line basically says that if abs(a) is smaller than abs(b), then min should take the value of abs(a); otherwise, it should take the value of abs(b).
size_t diff = max - min; //What is that variable used for?
It's not clear what you mean here. If you mean diff, the code essentially uses it in the subsequent while loop to perform division by repeated subtraction. This is a very strange thing to do, especially because it is so inefficient, and division would have been more compact and efficient in the loop. It's even stranger given that earlier the author uses ?: (which you asked about); that construction is used mainly because it's more compact and efficient than an if-else statement, but this is rather strange code, anyway.
When should I put {} on if's, while's etc.?
You should do it by default. You don't have to do it if only one statement is to be performed when the condition is true (resp. false) but people usually do as a matter of good style and to assist readability. For instance, this code
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
else
cout << "not possible!!!\n";
could just as easily be
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
} else {
cout << "not possible!!!\n";
}
...and a lot of instructors would actually require the latter from learners.
In addition to the other answers:
//What's that after (?)?
foo ? bar : qux;
Is the use of the ternary operator.
If foo is true the expression evaluates to bar else it evaluates to qux.
Just adding my two cents...
This
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
is equivalent to
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
}
The big difference comes when you realize that code is not something static that you write once and then never change again. Lets change the example a little bit (intentially weird intendation)
if ( x ) // (I)
y = a;
z = b;
is not the same as
if ( x ) { // (II)
y = a;
z = b;
}
Using brackets allows you to focus on only the part you care about. Consider that you later decide to swap the two lines, then
if ( x ) {
z = b;
y = a;
}
is still ok (its the same as (II), apart from swapping the two instructions), while
if ( x )
z = b;
y = a;
is doing something completely different as the version above (I). If you use the brackets you dont need to care whether those two lines are inside a if block. To decide if you can swap them you need to look at nothing more than those two lines. This is not the case if you do not use the brackets. This may seem like a minor thing, though I have seen countless bugs caused by not putting brackets where there could be some.
For 1 line of code following if, else, else if, while, etc
if (<some condition>)
//1 line of code`
and
if (<some condition>)
{
//1 line of code
}
...are equivalent and it is up to you (personal style,developer choice,readability etc.) to make that decision.
For > 1 line of code following if, else, else if, while, etc
{} is required if you want code completely scoped to the condition statement. It is up to you the developer to make sure to scope these lines of code (i.e. the compiler will not warn you about this.. it will not know if the intent was 1 line or multiple lines).
So an example
if(<some condition>)
{
//line of code 1
//line of code 2
}
the compiler will let you do this...
if(<some condition>)
// line of code 1
// line of code 2
but //line of code 2 has no relation to the if condition since it was not scoped with {} and will be executed regardless of the if statement condition.
So I've just started C++ programming, and am a little stuck on one particular program that was used to demonstrate how recursive functions work. I do know the premise of recursive functions, that being a function which calls itself until an exit condition has been met. I understood the concept using the program for factorials,
int factorial(int n)
{
if (n==1)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
the if statement being the exit condition in the above code.
However, the code that tripped me up was from this link:
http://www.cprogramming.com/tutorial/lesson16.html
specifically this code:
#include <iostream>
using namespace std;
void printnum ( int begin )
{
cout<< begin<<endl;
if ( begin < 9 ) // The base case is when begin is greater than 9
{ // for it will not recurse after the if-statement
printnum ( begin + 1 );
}
cout<< begin<<endl; // Outputs the second begin, after the program has
// gone through and output
}
int main()
{
printnum(1);
return 0;
}
OP:
1
2
3
4
5
6
7
8
9
9
8
7
6
5
4
3
2
1
In the immediately above code, I understand the output till the first 9. But after that, why does the cout statement following the if loop cause the begin variable to start counting backwards till it reaches the value it originally was when printvalue was first called? I suppose I don't really understand the exit condition here.
Not sure what I'm missing, and any help would be greatly appreciated.
Thanks.
Each begin is unique and belongs to the "current" active function – its value never changes.
Recursive functions work exactly like other functions; it doesn't matter to one what the parameter of another is named.
If you had these:
void f(int x);
void g(int x)
{
cout << x << endl;
f(x+1);
cout << x << endl;
}
you would be very surprised (I hope) if g printed two different numbers.
Your recursion works exactly like this (much smaller) example that uses unique functions instead of recursion with a parameter:
void printnum_3()
{
cout << 3 << endl;
cout << 3 << endl;
}
void printnum_2()
{
cout << 2 << endl;
printnum_3();
cout << 2 << endl;
}
void printnum_1()
{
cout << 1 << endl;
printnum_2();
cout << 1 << endl;
}
int main()
{
printnum_1();
}
So, lets see what happens when printnum(1) is called.
begin equals 1, it is printed with cout and then printnum(2) is called.
But what happens when the program leaves printnum(2) function? It continues to execute printnum(1) from the place, where printnum(2) was called. So, the next line to execute is cout << begin. begin still equals 1, because we are executing printnum(1) function. This is why 1 is printed once again at the end. The situation is totally the same with other function calls.
For example, when printnum(9) is called, it prints 9, then the if check fails (begin is not less, than 9) and then 9 is printed once again.
why does the cout statement following the if loop cause the begin variable to start counting backwards till it reaches the value it originally was when printvalue was first called?
To start with, there is no loop. There is call stack which you need to understand. Recursive call stops when (begin < 9) becomes false i.e. when begin = 9. You are seeing the call stack unwinding.
First cout in the function is printing sequence [1..9], and second cout is printing the decreasing sequence [9..1].
Your code execution is like this:
cout<< 1 <<endl; //enter1
cout<< 2 <<endl; //enter2
cout<< 3 <<endl; //enter3
...
cout<< 8 <<endl; //enter8
cout<< 9 <<endl; //enter9
cout<< 9 <<endl; //exit9
cout<< 8 <<endl; //exit8
...
cout<< 3 <<endl; //exit3
cout<< 2 <<endl; //exit2
cout<< 1 <<endl; //exit1
So in my class we are studying recursive functions. But I just do not understand how they work.
I'll use this code as an example.
// n is written to the screen vertically
// with each digit on a separate line.
void write_vertical(int n) {
if (n < 10)
{
cout << n << endl;
}
else // n is two or more digits long
{
write_vertical(n/10);
cout << (n % 10) << endl;
}
}
So if int n = 123; it will print each digit on its own line.How does this happen? how does this function work step by step?
Testing by random number (13)
Let's take 13 for an example. Well it's not less than 10, so it will execute the else block, and it will immediately execute the function itself with 13/10, which (as an integer) is 1. Now 1 is less than 10, so it will print 1 onto the screen with a new line because of endl. Now it will return back to the previous function call it had (before calling the function again with argument 1) and execute 13%10. 13 modulus 10 is 3, since its remainder becomes 3, with a new line (again because of endl). And voila, you printed the number in a vertical line!
For future
You should use a pencil and a paper, and debug it yourself manually just like we did above. OR even better use a debugger like GDB! This is an excellent quick startup on how to debug with GDB.
Recursion is simple. Assume you've already written your function; then use it.
Here it's the other way around - you are trying to figure out what the function does. Just the same, when you call it, it always does the same stuff.
So, in a general case of a number n > 10, what is n/10 (integer division)? It's that number without its last decimal digit.
What's n % 10? It's the number's last decimal digit.
So, your definition reads:
doing_something for a number `n` IS
doing_it for this number without its last decimal digit
(if there's something left, that is);
then printing its last decimal digit and a newline after it.
That's all.
1:
if(123 < 10) // fails
cout << 123; // skipped
else
{
recurse(123 / 10); // recurse(12) converted to int
cout << 123 % 10; // i'll be back here wait
}
2:
if(12 < 10) // fails
cout << 12; // skipped
else
{
recurse(12 / 10); // recurse(1)
cout << 12 % 10; // wiat I'll be back
}
3:
if(1 < 10) // succeeds! so now else executed
cout << 1; // printed
nothing is below until return of functions so we return
to 2:
cout << 12% 10; // (12 % 10 = 2) was wating it's its time
continue below: nothing below so return from function 2 to 1:
in 1:
cout << 123 % 10; // it was waiting so now it's its time
cout << 123 % 10; // 123 % 10 = 3
go below: nothing untile the end of function so retrun to main
where function was called first time (to the line after the call )
the result: 123