I don't understand recursive functions.
I wrote this code to help me but i don't understand why it works the way it does.
It prints backwards the steps from 0 to the number n/2 i input but don't know what makes it print every step it skipped from low to high because it went recursive. I am close but not yet there...
#include <iostream>
#include <conio.h>
using namespace std;
int recursiv(int );
int times;
int main(){
int x;
cout<<"Imput number\n";
cin>>x;
recursiv(x);
getch();
return 0;
}
int recursiv(int x){
times++;
if(x)
recursiv(x/2);
cout<<"We are now at "<<x/2<<endl;
if (!x)
cout<< "We reached "<<x<<" but it took "<<times-1<< " steps\n";
return 0;
}
When you are dealing with recursion you have to understand two main part of the function code: the one that is executed on the way forward, and the one that is executed on the way back:
void X() {
// way forward
X();
// way back
}
The way forward part is executed while calling the function over and over until the end of the recursion; the way back is executed while coming back from the last call to the first.
void print(int x) {
if (!x) return; // end of recursion
std::cout << x << " ";
print(x-1);
}
The above example contains std::cout << x on the way forward which means that the call print(5) will print: 5 4 3 2 1.
void print(int x) {
if (!x) return; // end of recursion
print(x-1);
std::cout << x << " ";
}
The above example moved the actual printing to the way back part of the function which means that the same call print(5) will print: 1 2 3 4 5.
Let's take your function (cleaned up a bit):
int recursiv(int x){
times++;
if(!x) return 0; // split
recursiv(x/2);
cout << "We are now at "<< x / 2 << endl;
return 0;
}
We can distinguish our two parts quite easily. The way forward is:
times++;
if(x) return;
In which we just increment our int parameter times (we just ignore the conditional for the end of recursion here).
The way back is:
cout<<"We are now at "<<x/2<<endl;
return 0;
Which will be executed from the last call to the first one (just like the second version of the example). Therefore taking from the lowest number (the one nearer to 0 because of the end recursion condition) which is the last called before the end of recursion to the first, just like our example.
If i understand your question correctly:
It should print from high to low, but it actually prints from low to high. why is that?
The line cout<<"We are now at "<<x/2<<endl; is after the call for recursion.
so the function calls itself with a smaller amount again and again until it hits the break criteria.
the the function with the smallest amount calls the std::cout, return the second smallest amount does the std::cout and so on until the last one does it.
If you want the result in the other order, move the mentioned line two lines higher, so each iteration echos before calling the child.
example:
int recursiv(int x, int times = 0) {
std::cout << "We are now at " << x/2 << std::endl;
if(x)
return recursiv(x/2, times + 1);
else
std::cout << "We reached " << x << " but it took " << times << " steps" << std::endl;
return 0;
}
Unrelated: Global variables are considered a bad practice. There are use cases for them, this is not one of them. I fixed that within the function.
Related
Made a while-loop and I'm not getting the result I think I should be getting.
I've done a little debugging and got nothing. Visual Studio 2019 is saying I'm good to go.
int main()
{
double num_enter;
vector<double> nums(0);
while (cin >> num_enter)
{
nums.push_back(num_enter);
sort(nums.begin(), nums.end());
if (num_enter < nums.front())
{
cout << num_enter << " is the smallest one yet.\n" << endl;
}
else if (num_enter > nums.back())
{
cout << num_enter << " is the biggest one yet.\n" << endl;
}
return 0;
}
I want a while(cin>>enter_num) loop to read num_enter and do a vector.push_back(num_enter) followed by the vector sort function and have it out put if the number has been "the smallest yet" or "the biggest yet" but its not working. could you point out what I'm doing wrong? I'm new be gental.
There is only one number in the vector. None of the conditions are met, if you enter one, one is not greater than one or less than one, hence it is not printing anything because you are not handling that case. Add an else block that prints if the numbers are equal then hopefully it will be clear to you why that is happening.
try this
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
double num_enter;
vector<double> nums(0);
while (cin >> num_enter) {
nums.push_back(num_enter);
//sort(nums.begin(), nums.end());
// Lets say you entered 1
// 1 < 1 -> false
if (num_enter < nums.front())
{
cout << num_enter << " is the smallest one yet.\n" << endl;
}
// 1 > 1 -> false
else if (num_enter > nums.back())
{
cout << num_enter << " is the biggest one yet.\n" << endl;
}
else // 1 == 1
{
cout << "Numbers are equal" << endl;
}
return 0;
}
}
Syntax of vector:
vector vectorName(size);
vector nums(0)
In your code nums is a vector of size zero.
Vector is a dynamic array.
Array of zero size is meaningless.
Check this link to see different ways of declaring vector.
suppose you code order should be changed, the if-elseif-else block should be put in front of the push_back and sort,
or if you really want to maintain the order, if-elseif-else should be corrected like if(num_enter == nums.front()) ... else if(num_enter == nums.back())... else,
only then you can know if your input number has been the biggest or smallest yet.
And initialize like vector<double>nums(0) is little weird, just using vector<double>nums is fine
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
I am making a program that the user inputs integers and outputs them in reverse. It is a recursive function. The Problem now is that it outputs an infinite of 0's. Please tell me where is the error in my code. and I need some pointers. Please help.
#include <iostream>
using namespace std;
void printreverse(int);
int main()
{
int x;
cout << "Enter numbers: ";
cin >> x;
printreverse(x);
return 0;
}
void printreverse(int x)
{
if(x<10)
cout << x;
else
cout << x%10;
printreverse(x/10);
}
You have wrong identing in printreverse. It should be like this:
void printreverse(int x)
{
if(x<10)
cout << x;
else
cout << x%10;
printreverse(x/10);
}
First it prints x or x%10, then it recurses regardless of what x is. If you wanted more than one statement done in a consequent or alternative you need to use a block. Blocks are denoted with {} in C-decendants. They are so usual that some people actually think conditionals and control flow syntax need to have them. Anyway if the identing was the intended behaviour you should write it like:
void printreverse(int x)
{
if(x<10) {
cout << x;
} else {
cout << x%10;
printreverse(x/10);
}
}
Whenever I use braces on one term in an if I add them for every one even when it's not really needed. Some coding standards, like PSR2, require blocks always to remove the chance of ever getting bugs like this.
C++ is not Python. You need to surround your else block by braces, like so
else
{ // need brace here
cout << x%10;
printreverse(x/10);
} // and here
otherwise only the first statement after the else is being executed (and the final printreverse(x/10) will always be executed, even for 0, so you end up overflowing the stack).
I recommend you to always put braces, even for a single statement in an if/else, precisely for reasons similar to the one you just bumped into.
Hello i am learning recursion and currently i have couple of trick problems to dissect - here is one of recursive functions
int rec(int niz[], int start, int end){
if (start == end)
{
return niz[start]; // vraca zadnji
}
int temp = rec(niz, start+1, end);
// control output
cout << "\n-----\n";
cout << "start " << start << endl;
cout << "niz[start] " << niz[start] << endl;
cout << "end " << end << endl;
cout << "temp " << temp << endl;
cout << "\n-----------------------------------------\n";
//contrl output end
return ((niz[start] < temp) ? niz[start] : temp);
}
i included a cout block to control what is gong on in calls. here is main part
int niz[] = {1,2,3,4,5,6,7};
cout << rec(niz, 0, 3);
and here is my output:
-----
start 2
niz[start] 3
end 3
temp 4
------------------
-----
start 1
niz[start] 2
end 3
temp 3
------------------
-----
start 0
niz[start] 1
end 3
temp 2
------------------
1
can anyone explain me how is temp value being calculated and returned and how i am getting 1 as the return of this function?
Thank You in advance!
Recursive function is the function that calls itself.
int temp = rec(niz, start+1, end);
Here you call the "rec" function inside the one, but with the changed parameter (start + 1). You call these function inside each other until the "start" equals "end" (then it returns)
if (start == end)
{
return niz[start]; // vraca zadnji
}
After the deepest one returns the second deepest one continues its flow, printing some information.
cout << "\n-----\n";
cout << "start " << start << endl;
cout << "niz[start] " << niz[start] << endl;
cout << "end " << end << endl;
cout << "temp " << temp << endl;
cout << "\n-----------------------------------------\n";
Then it it returns the lowest value between niz[start] and temp (local values).
return ((niz[start] < temp) ? niz[start] : temp);
Then the third deepest one continues its flow and so on. Until it gets to the first function.
In your main part you set the end to 3, so it performs the operation on the first 3 elements (it gets to the fourth element, but doesn't do anything beside returning its value). You get 1 by comparing the niz[0], that you passed as start, and temp that is returned by recursive function (which happens to be the same). It equals, so the return value is niz[0] that is 1;
When using recursive functions, you should have some kind of "exit point" that prevents the recursion to become infinite, i.e.
if (start == end)
{
return niz[start];
}
In general, recursive functions look like this:
f()
{
//return condition
//some work
f();
//some work
//return
}
And you can look at them as this
f()
{
//some code
f()
{
//some code
f()
{
//some code
f()
{
...
//eventually the return condition is met
}
//some code
//return
}
//some code
//return
}
//some code
//return
}
Keep in mint that unhandled recursion may lead to possible memory leaks, because each function call comes with additional data.
f()
{
f();
}
This will lead to stack overflow due to system data that has been created;
You may want to watch "Inception" to understand it better :)
rec(niz, 0, 3) (D)
|
---->rec(niz, 1, 3) (C)
|
----> rec(niz, 2, 3) (B)
|
----> rec(niz, 3, 3) (A)
You call (D) which calls (C) to calculate temp and so on up to (A). In (A) start==end and it returns niz[3]=4.
In (B):
temp = 4 (result of (A))
start = 2
As 4 is bigger than niz[start]=3 (B) returns 3
In (C):
temp = 3 (result of (B))
start = 1
As 3 is bigger than niz[start]=2 (B) returns 2
In (D):
temp = 2 (result of (C))
start = 0
As 2 is bigger than niz[start]=1 (B) returns 1
Your recursive line is before your print statement block. By nature of recursion, it makes the function call on that recursive line and stops the caller function's execution until the callee is done. Therefore you call for the next element to be processed before you print the current element.
In your example the following is happening:
Layer 1:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 2:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 3:
Is start equal to end? No.
What is the result of the next element? Don't know yet, recurse.
Layer 4:
Is start equal to end? Yes!
Return the current element, 4.
End layer 4.
Layer 3:
Now know next element, start printing for the 3rd element.
Return 3.
End layer 3.
Layer 2:
Now know the next element, start printing for the 2nd element.
Return 2.
End layer 2.
Layer 1:
Now know the next element, start printing for the 1st element.
Return 1.
End layer 1.
End program.
As you can see, the array elements are printed backwards because the print statements are after the recursive call. I'd you want them to be printed in order, print them before the recursive call, or create a buffer and append each print section to the front of the buffer.
Okay, im just about done with my exercise and stuck on how to get each dice to roll their own individual randomly generated number. The program does in fact roll random numbers, it's just every time you re-roll both dice always roll the same exact numbers. And this simple but yet head scratching problem occurred, for some reason i'm also having
cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
I was also told by a class mate that my faceValue was an illegal value and should be set to a legal value. I didn't quite get what he meant and I'm sure it'll knock off (not a lot) a few of my grade.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
class PairOfDice
{
private:
int diceOne;
int diceTwo;
int score;
int faceVaule;
public:
PairOfDice(){
srand(time(NULL));
roll();
}
void roll(){
diceOne = (rand() % 6) + 1;
diceTwo = (rand() % 6) + 1;
setdiceOne(diceOne);
setdiceTwo(diceTwo);
}
void setdiceOne(int value){
faceVaule = value;
}
int getdiceOne(){
return faceVaule;
}
void setdiceTwo(int value){
faceVaule = value;
}
int getdiceTwo(){
return faceVaule;
}
void totalScore(){
score = diceOne + diceTwo;
}
void display(){
cout << "The first Dice rolled a " << getdiceOne() << " ." << endl;
cout << "The second Dice rolled a " << getdiceTwo() << " ." << endl;
// adding both dices gives an: No operator " < < " matches these operands
cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
PairOfDice game;
game.roll();
game.display();
game.totalScore();
return 0;
}
First of all: you roll two dice, store the results in dice1 and dice2, but then you send those values to two functions that put the value into a variable called faceValue.
It is logical that getting the value back will return only the second dice value, because that's what you last entered in faceValue.
That is why the same values are shown for both dice.
Now for the error: your totalScore function returns a void while the << operator expects some kind of type.
The totalScore function adds the two dice (correct values by the way) and puts the result in score, but nowhere, the value in score is returned.
Your code is really messy. You shouldn't have one member variable (faceValue) holding a copy of two different values. You shouldn't have this member at all. Just use the diceOne and diceTwo values.
When the values are set ( = rand() % 6 + 1 ), they should not be set again by calling the set-function: Either create a correct set-function (because this one isn't correct) and put the random as a parameter in there, or set the member variable diceOne and diceTwo directly in the constructor as you already do. Don't do both.
When returning the sum of the two dice, why not just return this sum (hint: the function totalScore should return something of the int-type). Why are you putting the summed result into a member variable? There is no need for that.
I could post the corrected code here, but it seems that you really have to learn this yourself.
Edit: And by the way: as stated above, learn to use the debugger. You will soon discover that the things I am telling you are correct. You will notice that faceValue first gets the value of diceOne and then the value of diceTwo, never getting the diceOne value back.