I have this code which outputs: 10 5 16 8 4 2 11
However, I don't have any clue from where the 11 is coming from since when tracing i get the following:
H(10)
H(5)
1+H(16) //does this result in 17?
H(8)
H(4)
H(2)
H(1) -> returns 0
Moreover what happens to the (1) in 1+H(16) ?
Thus shouldnt my output of the n values be: 10 5 17 8 4 2 1
#include <iostream>
using namespace std;
int H ( int n ) {
cout << " " << n<<" ";
if ( n == 1 ) return 0;
if ( n%2 != 0 ) return 1 + H ( 3*n + 1 );
else return H ( n/2 );
}
int main() {
// for ( int i=0; ++i<=20; )
// cout << H(i) << endl;
cout << H(10) << endl;
}
At the end of the recursion, the function prints 1 then the stack pops everything out and the main prints the returned value 1 (0 is returned at the end of the recursion and only the call to H(5) adds one to the result), so 11 is printed.
Related
I tried searching the answer but was not able to get any convincing answer. Can someone please explain me how does this c++ code print 1 2 3 4 5?
I understood up until the point when n=1. when n=1, fun(n-1) = fun(1-1) = fun(0) is not executed as n>0 is not satisfied, hence now cout << n << endl will be executed and n is still equal to 1 but then after printing 1 it should stop ? How does it go to the previous calls? How does it print 2 3 4 5?
Also when cout << n << endl is above fun(n-1) it makes sense as it prints 5 4 3 2 1.
#include <iostream>
using namespace std;
void fun(int n)
{
if (n > 0) {
fun(n - 1);
cout << n << endl;
}
}
int main()
{
int x = 5;
fun(x);
}
The above code prints 1 2 3 4 5 while from my understanding it should only print 1.
At every call of function fun() make a note of value of variable n and you can trace the output easily. When the recursive call to fun() return, the statements after it will be executed (w.r.t. function fun() it is cout << n << endl; statement). It work like this:
fun(5) --> First call : n is 5
5>0 : true
| fun(5-1) --> Recursive call 1 : n is 4
| 4>0 : true
| | fun(4-1) --> Recursive call 2 : n is 3
| | 3>0 : true
| | | fun(3-1) --> Recursive call 3 : n is 2
| | | 2>0 : true
| | | | fun(2-1) --> Recursive call 4 : n is 1
| | | | 1>0 : true
| | | | | fun(1-1) --> Recursive call 5 : n is 0
| | | | | 0>0 : false --> Return from call 5
| | | | |
| | | | Print n (n is 1) and return from call 4
| | | Print n (n is 2) and return from call 3
| | Print n (n is 3) and return from call 2
| Print n (n is 4) and return from call 1
Print n (n is 5) and return from first call to main()
Hence, the output is 1 2 3 4 5.
The key thing to recognize here is that the fun() recursive function prints the value after making the recursive call. So this is what is actually happening:
call fun(5) from main()
call fun(4) from fun()
call fun(3) from fun()
call fun(2) from fun()
call fun(1) from fun()
return from fun(0)
print 1
print 2
print 3
print 4
print 5
That is, the print statements happen the recursive calls, beginning with the value at the bottom of the recursion, which is 1, then backing out to 5.
Well, the key here is that the function will continue execution after the recursive call, so:
fun(n - 1);
cout << n << endl;
will call fun(n-1) and still continue the execution of cout << n << endl; after fun(n-1) returns. It doesn't just go away. It only postpones the execution of writing to cout until after the recursive call returns.
It is unclear to me what you wish to accomplish with this recursive function, but if you want to only print 1, you will need to encapsulate it in an if statement:
if(n == 1) {
cout << n << endl;
}
Or do something else to that effect. If that's not what you want, you may need to rewrite your recursive function completely (if you're not sure how to, you may need to ask another question explaining your needs more explicitly).
Follow the execution:
int x = 5;
fun(5); // Since x = 5
if (5 > 0) // Since n = 5
fun(4); // Since n - 1 = 4
if (4 > 0) // Since n = 4
fun(3); // Since n - 1 = 3
if (3 > 0) // As before...
fun(2);
if (2 > 0)
fun(1);
if (1 > 0)
fun(0);
if (0 > 0) // If fails, so function exits
cout << 1 << endl; // Then returns
cout << 2 << endl; // Then returns
cout << 3 << endl; // ...
cout << 4 << endl;
cout << 5 << endl;
I always write down the execution in the above format when I'm trying to understand some complicated algorithm. The method works both for newbies and more experienced programmers.
First, you should change the condition of end to (n >1) and then, you can have the result [2 3 4 5]. see here.
#include <iostream>
using namespace std;
void fun(int n)
{
if (n > 1) {
fun(n - 1);
cout << n << endl;
}
}
int main()
{
int x = 5;
fun(x);
}
Second, you can have the revese result [5 4 3 2 1] if you change the line position. see here.
#include <iostream>
using namespace std;
void fun(int n)
{
if (n > 0) {
cout << n << endl;
fun(n - 1);
}
}
int main()
{
int x = 5;
fun(x);
}
I think, rather than asking about this exact function. Please learn how recursion works. There are plenty of resources out there. You can also follow: https://www.geeksforgeeks.org/recursion/
Here is the code:
#include <iostream>
using namespace std;
void countdown(int n);
int main(){
countdown(4); // call the recursive function
return 0;
}
void countdown(int n){
cout << n << endl;
if (n > 0){
countdown(n-1); // function calls itself
}
cout << n << endl; // intended part of code
}
Simple run :
4
3
2
1
0
0
1
2
3
4
Question: why does this recursive function counts back up from 0 to 4 and do not stop at 0?
Because recursion function call is stored in stack. So, when one function call returns, it is popped out of stack and then it executes the next line of the function call.
void countdown(int n){
cout << n << endl; // This line calls 4 3 2 1 0
if (n > 0){
countdown(n-1); // function calls itself
}
cout << n << endl;; //This line print 0 1 2 3 4
}
Suppose the numbers before the line of the code are the line numbers:
1 void countdown(int n){
2 cout << n << endl; // This line calls 4 3 2 1 0
3 if (n > 0){
4 countdown(n-1); // function calls itself
5 }
6 cout << n << endl;; //This line print 0 1 2 3 4
7 }
Suppose countdown is called with n = 2,
Then, Your stack will initially contain function call with n = 2.
Because of line 2, 2 gets printed.
Because of line 4, function with n = 1 gets called. So, now stack has 1|2
Now because of line 2 again, 1 gets printed.
Because of line 4, function with n = 0 gets called. So Now stack is 0|1|2
Line 2 prints 0.
Line 3 condition fails and so line 4 is not executed.
Line 6 prints 0.
Line 7 tells that function execution is over and hence it will pop out of stack. Now stack is 1|2.
Now, function with n = 1 resumes its operation from line 5.
So, line 6 makes it print 1.
line 7 tells that function execution is over and hence it will pop out of stack. Now stack is 2.
So, function with n =2 resumes its operation from line 5.
line 6 makes it print 2.
line 7 tells function execution is over and hence it will pop out of stack. And now it will return to main.
You print n twice - before calling the function recursively, and then again after it returns. If you only want to print the number counting down, just print it once:
void countdown(int n) {
cout << n << endl;
if (n > 0){
countdown(n-1);
}
// Another cout call was removed here...
}
To put it very simply, calling a function - even your own function - does not end execution of the current function. Consider the following:
void countdown() {
std::cout << countdown << "\n";
}
int main() {
countdown();
std::cout << "main\n";
}
you would not be surprised that this prints
countdown
main
Nor would you be surprised if you wrote:
int main() {
int i = 0;
if (i == 0)
countdown();
std::cout << "main\n";
}
We can also simply demonstrate that a recursive function backtracks through its call points like this:
#include <iostream>
void countdown(int n) {
std::cout << "countdown(" << n << ") entry\n";
if (n == 0)
countdown(n + 1);
std::cout << "countdown(" << n << ") exit\n";
}
int main() {
std::cout << "main entry\n";
countdown(0);
std::cout << "main exit\n";
}
live demo
outputs:
main entry
countdown(0) entry
countdown(1) entry
countdown(1) exit
countdown(0) exit
main exit
You have two output lines. Remove the last cout << n << endl. That last line is what is counting back up, after returning from the recursive call.
because of the second cout just before the end of the coutdown function
I have the following code that appends a part of a vector to another.
#include <algorithm> // std::copy
#include <iostream>
#include <vector>
#include <cmath>
#include <assert.h>
using namespace std;
void copyVec(const std::vector<double> in, std::vector<double> &out, int start, unsigned int length) {
assert(start>=0 && in.size()>=start+length);
out.reserve(length);
cout << in.at(9) << endl;
out.insert(out.end(), &in.at(start), &in.at(start+length));
}
int main(int argc, char ** argv) {
int start = 0;
int end = 9;
int window_size = 10;
// initialize
vector<double> vec1 = vector<double>(window_size);
for (unsigned int i=0;i<window_size;++i) vec1[i] = i;
vector<double> vec2 = vector<double>(window_size);
for (unsigned int i=0;i<window_size;++i) vec2[i] = i*10;
// print
cout << "vec1: ";
for (unsigned int i=0;i<vec1.size();++i) cout << vec1[i] << " "; cout << endl;
cout << "vec2: ";
for (unsigned int i=0;i<vec2.size();++i) cout << vec2[i] << " "; cout << endl;
copyVec(vec1,vec2,start,end);
// print
cout << "vec2: "; for (unsigned int i=0;i<vec2.size();++i) cout << vec2[i] << " "; cout << endl;
return 0;
}
I cannot seem to be able to access vec2's last element by reference.
The output for this example (int end = 9) is
size: 10 start: 0 end: 9
vec1: 0 1 2 3 4 5 6 7 8 9
vec2: 0 10 20 30 40 50 60 70 80 90
in[9]: 9 &in[9]: 0x186d118
vec2: 0 10 20 30 40 50 60 70 80 90 0 1 2 3 4 5 6 7 8
and, of course, for int end = 10 I get an out of range error:
size: 10 start: 0 end: 10
vec1: 0 1 2 3 4 5 6 7 8 9
vec2: 0 10 20 30 40 50 60 70 80 90
in[9]: 9 &in[9]: 0xae1118
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Aborted (core dumped)
So how should I (efficiently) append the last vector element?
Your insert should use iterator directly:
out.insert(out.end(), in.begin() + start, in.begin() + (start + length));
The correct function will look like
#include <iterator>
#include <vector>
//...
void copyVec( const std::vector<double> &in,
std::vector<double> &out,
std::vector<double>::size_type start,
std::vector<double>::size_type length )
{
assert( in.size() >= start + length );
out.reserve( out.size() + length );
out.insert( out.end(), std::next( in.begin(), start ),
std::next( in.begin(), start + length ) );
}
The first parameter is declared as constant reference. You should reserve memory for the destination vector taking into account its current size.
It is better to use own iterators of the vector instead of the raw pointers.
start and start + length specify a range like [start, start + length )
For example to copy the entire vector you can write
copyVec2b(vec1, vec2, 0, vec1.size() );
In general you may not write in the function like
cout << in.at( start + length ) << endl;
because index start + length is not included in the range of copied elements.
You may write
if ( length != 0 ) cout << in.at( start + length - 1 ) << endl;
I am learning C++ and right we are covering preprocessors but I am trying to solve a question from a quiz which I has confused me a bit or a lot.. I tried to worked out by my own before running the program.. and my output was..
System started...
Data at 2 is: 27 28 29 30
Data at 1 is: 23 24 25 26
The data is: 19
I checked the program in Xcode to see if my output is right but the right output is the next one:
System started...
Data at 1 is: 0 0 0 19
Data at 0 is: 7 0 0 0
The data is: 19 0 0 0
This is the code...
#include <iostream>
namespace test{
#define COMPILE_FAST
#define PRINT_SPLIT(v) std::cout << (int)*((char*)(v)) << ' ' << \
(int)*((char*)(v) + 1) << ' ' << (int)*((char*)(v) +2) << ' ' << \
(int)*((char*)(v) + 3) << std::endl
typedef unsigned long long uint;
namespace er{
typedef unsigned int uint;
}
void debug(void* data, int size = 0){
if(size==0){
std::cout << "The data is: ";
PRINT_SPLIT(data);
} else {
while(size--){
std::cout << "Data at " << size << " is: ";
char* a = (char*)data;
PRINT_SPLIT((a + (4+size)));
}
}
}
}// End of Test namespace...
int main(){
test::uint a = 19;
test::er::uint b[] = {256,7};
std::cout << "System started..." << std::endl;
test::debug(b,2);
test::debug(&a);
std::cout << "Test complete";
return 0;
}
My big doubt or what I actually don't understand is whats going on here in this preprocessor because clearly for what I did its totally wrong...
#define PRINT_SPLIT(v) std::cout << (int)*((char*)(v)) << ' ' << \
(int)*((char*)(v) + 1) << ' ' << (int)*((char*)(v) +2) << ' ' << \
(int)*((char*)(v) + 3) << std::endl
if someone can be so nice and give me a brief explanation I will extremely appreciate it.
The macro prints the values (as ints) of 4 consecutive bytes. It allows you to see how a 4 byte int is layed out in memory.
Memory contents, by byte, look like this (base10):
0x22abf0: 0 1 0 0 7 0 0 0
0x22abf8: 19 0 0 0 0 0 0 0
0 1 0 0 is 256, i.e. b[0]
7 0 0 0 is 7, i.e b[1]
19 0 0 0 0 0 0 0 is 19, i.e. a
The sizeof(a) is different than the sizeof(b[0]) because there are 2 different typedefs for uint. Namely, test:uint and test::er::uint.
The address of a is greater than the address of b[] even though b is declared after a because the stack is growing downwards in memory.
Finally, I would say the output represents a defective program because the output would more reasonably be:
System started...
Data at 1 is: 7 0 0 0
Data at 0 is: 0 1 0 0
The data is: 19 0 0 0
To get that output the program needs to be changed as follows:
while(size--){
std::cout << "Data at " << size << " is: ";
int* a = (int*)data;
PRINT_SPLIT((a + (size)));
I'm having trouble using recursion to add letters to a base 10 - base 12 conversion. How would I go about adding letters into my function? I was thinking about adding an if statement in, but i have no idea where and how to go about this. pointers are appreciated Thanks!
Given a count from 1 to 12:
Dec 1 2 3 4 5 6 7 8 9 10 11 12
Duo 1 2 3 4 5 6 7 8 9 X E 10
my function:
template<class myType>
myType convertDec(myType number){
if(number == 0)
return number;
//if statement somewhere in here? not sure considering i can't touch the return statement
return (number % 12) + 10*convertDec(number / 12);
}
example ideal output:
65280 = 31940 (works fine)
2147483626 = 4EE23088X (doesnt work!)
#include <iostream>
#include <string>
using namespace std;
string ConvertToDuodecimal(unsigned long long n)
{
if (n < 12)
return string() + "0123456789XE"[n];
return ConvertToDuodecimal(n / 12) + ConvertToDuodecimal(n % 12);
}
int main()
{
cout << ConvertToDuodecimal(0) << endl;
cout << ConvertToDuodecimal(1) << endl;
cout << ConvertToDuodecimal(10) << endl;
cout << ConvertToDuodecimal(11) << endl;
cout << ConvertToDuodecimal(12) << endl;
cout << ConvertToDuodecimal(13) << endl;
cout << ConvertToDuodecimal(65280) << endl;
cout << ConvertToDuodecimal(2147483626) << endl;
return 0;
}
Output (ideone):
0
1
X
E
10
11
31940
4EE23088X
The base is a property of the way a number is displayed and nothing to do with it's internal representation. You need to write a function that prints a normal int using base 12.
a = 12; // A = 12 (in base 10)
printf("%d",a); // Prints a in base 10 (still 12)
printf("%x",a); // Prints a in base 16 (now C)
You code is changing the actual value, which isn't the right thing to do.
(and yes, before the pedants strike, printf isn't good C++...)