recursive method for array element printing - c++

I am learning recursive calls implementation. i get stuck with return statements, i am trying to print an array elements by recursive call. though i print but it but i want to return it, can some body help
#include<iostream>
using namespace std;
int recursive_arr_traversal(int *arr, int length_of_array) {
if (length_of_array <= 0) {
return 0;
}
else {
return *arr; //this statement prints only one array element<endl
cout << *arr << endl;//this works fine
}
return recursive_arr_traversal(arr + 1, length_of_array - 1);
}
int main() {
int arr[10] = { 1,2,3,4,56,7,8,9,99,0 };
int length_of_array = 10;
//recursive_arr_traversal(arr,length_of_array);
cout << recursive_arr_traversal(arr, length_of_array);
return 0;
}

As Nathan stated, you do not need to return anything. Have a look at the following code which is your code only slightly modified, as I think you got the main idea of recursion:
#include<iostream>
using namespace std;
void recursive_arr_traversal(int *arr, int length_of_array) {
if (length_of_array <= 0) return;
cout << *arr << endl;//this works fine
recursive_arr_traversal(arr + 1, length_of_array - 1);
}
int main() {
int arr[10] = { 1,2,3,4,56,7,8,9,99,0 };
const int length_of_array = 10;
//recursive_arr_traversal(arr,length_of_array);
recursive_arr_traversal(arr, length_of_array);
return 0;
}
In each call one element is printed and it returns once you have traversed the array. Note that there is an implicit return at the end of recursive_arr_traversal.

A (basic) recursive function should have two parts--the base case, where all the work is already done or almost done and all we have to do is clean up and return, and the recursive case, where we need to do some small part of the work and then pass on the rest to the recusive function.
The base case here is pretty simple, and you already have it right. if(length <= 0), all we have left is an empty array, so we can just return and be done. There's no more work to do.
The recursive case is a little more difficult though and you almost have it!
Our recursive case in this problem should print the first element and then pass on an array that's one shorter and starts one element later. Also note that you never use the return value, and since this is a print function, it should probably be void. With those fixes the code could look like:
int arr_print(int *arr,int len){
//base case: if arr is empty, we're done
if(len <= 0) { return; }
//recursive case: print first element, then pass array along to print rest
cout << *arr << endl;
arr_print(arr + 1, len - 1);
}

If you are saying that you want to return all the values to function like main() so that you have permanent access to your array values, that is not possible just by returning in your recursive function. As said above by others, when you return a value, that value is returned to the function that called it (draw a callstack if you need).
If you just make a global variable to save which ever values you need, that could fix your needs.

Related

How do I return value to main function without directly calling the function

I have multiple functions in my program. Each function has some conditions. If conditions are met, then it passes on the value to another function which again checks the value with some conditions, modifies it.
The first function [named 'squarefree()'] is called from main [obviously] and it further goes on to call another function which in course calls another function untill the process stops at last function named 'end()'. Like this:
#include <iostream>
using namespace std;
int squarefree(int n);
int goodnumber(int sf);
int end(int gn);
int main() {
// your code goes here
int l,r;
cin>>l;
cin>>r;
for(int p=l;p<=r;p++)
{squarefree(p);}
/*int ret=end(int gn); PROBLEM LIES HERE
cout<<ret; */
return 0;
}
int squarefree(int n){
int i;
for(int i=2;i<n;i++)
{
if((n%(i*i))==0)
{
cout<<"number not square free"<<endl;
break;
}
else{
cout<<"number square free"<<endl;
goodnumber(n);
break;
}
}
return 0;
}
int goodnumber(int sf){
cout<<"Sf is:"<<sf<<endl;
int s=0,c=0,flag=0;
for(int j=1;j<=sf;j++)
{
if(sf%j==0)
{
s+=j;
for(int k=2;k<=j/2;++k)
{
if(j%k==0)
{
c++;
}
}
}
}
cout<<"s is:"<<s<<endl;
cout<<"no.of prime numbers dividin s are:"<<c<<endl;
for(int l=2;l<=c/2;++l)
{
if(c%l==0)
{
flag=1;
break;
}
}
if (flag==0)
{cout << "C is a prime number, so this is good number and needs to be passed to next function"<<endl;
end(s);
}
else
{cout << "C is not a prime number"<<endl;
}
return 0;
}
int end(int gn)
{
int sum=0;
sum+=gn;
cout<<"SUm of factors of the good number is:"<<sum<<endl;
return sum;
}
The 'end()' function returns a value sum. Now I want this value sum to be updated everytime the for loop in main() function runs. For example: Sum in first iterations is 5, sum is 2nd iteration is 10, so total sum gets 15 and so on.
If somehow, the value returned by end function can be fetched into main function, that would be great.
Look at all those int-returning functions that are always returning 0. You might be able to take advantage of that.
A trivial example:
#include <iostream>
int step3(int val)
{
return val * val;
}
int step2(int val)
{
return step3(val + 1);
}
int step1(int val)
{
return step2(val * 2);
}
int main()
{
std::cout << step1(1);
}
But take care. You might find a case where you don't get any valid results and need to inform the caller that no result was found.
In addition to the idea of having the functions return the result of the next stage in the pipeline, which is an excellent idea, you can pass the address of the variable in which to store the result (allowing you to return more than one result, or an error code), or store the result of each stage in a temporary variable and return that (allowing you to use a result in more than one computation). I would advise against using a global variable to bypass the stack; it’s considered poor practice.
Some Examples:
// Returning the result of the next stage in the pipeline:
int g(int);
int f(int x)
{
return g(x);
}
// Passing a variable by reference:
enum errcode { success, failure };
errcode sqr( int input, int& output )
{
output = input * input; // This modifies the second variable the caller gave.
return success;
}
// Storing in a temporary variable:
int stage2(int);
int stage1(int x)
{
const int y = stage2(x); // Store the result in a temporary.
const int z = sqr(y);
return z;
}
// Passing results through a global variable is a bad idea:
int necessary_evil = 0; // Declared in global scope; should at least be
// declared static if possible to make it visible only in this source file.
// Namespaces are a fancier way to do something similar.
void kludge(int x)
{
necessary_evil = x * x; // The caller will check the global.
return;
}
There are examples of all of these in the standard library: printf() is essentially a wrapper for vfprintf(), strtol() takes a parameter by reference that the function sets to a pointer to the remainder of the string, and errno is a global variable.

Run time error for dynamic memory allocation in C++

I am a newbie for OOP concepts and while trying to solve Project Euler Problem 7, to find 10001th prime number, I tried to do it using a class but encountered 2 major errors.
instantiating the class prime_n
initializing its argument
I have posted the code here for reference:
#include<iostream>
#include<cstdio>
using namespace std;
class prime_n
{
int j,k;
int n;
int *store;
public:
prime_n(int num)
{
n=num;
store[n];
}
static int isPrime(int j)
{
for(int i=2;i*i<=j;i++)
{
if(j%i==0) return 0;
}
return 1;
}
void find_n()
{
for(int i=0;i<n;i++)
{
store[i]=0;
}
store[0]=2;
j=3;
k=1;
while(store[n-1]==0)
{
if(isPrime(j)) store[k++]=j;
j+=2;
}
}
int get_num()
{
int value=store[n-1];
return value;
}
};
int main()
{
int num, req_num;
printf("Enter the position at which prime number is to be found ");
scanf("%d",&num);
printf("\nnumber = %d",num);
prime_n p = new prime_n(num);
req_num = p.get_num();
printf("The required prime number is %d\n",req_num);
return 0;
}
It would be a great help if someone could help me figure out where I am actually going wrong. Thanks a lot in advance!
Use
prime_n p(num);
or (not recommended in this particular case)
prime_n * p = new prime_n(num);
// some other code
req_num = p->get_num(); // note the -> operator replacing . in case of pointers
delete p;
The first case declares p on stack and it is automatically deallocated when the program leaves the scope (main function in this case)
The second one allocates space on heap and p is the pointer to it. You have to deallocate the memory manually.
As for your second question, the C++ way would be
#include <iostream>
...
int num;
std::cout << "Enter the position at which prime number is to be found "
std::cin >> num;
std::cout << std::endl << "Number = " << num << std::endl;
You provide a constructor:
prime_n(int num)
{
n=num;
store[n];
}
I think you are under the impression that store[n] creates an array with n elements, but that is not so; it attempts to access the (n+1)th element of an an array. Since store does not point anywhere (we are in the constructor, after all), the program crashes.
You probably want to write store = new int[num] instead.
And then I cannot see any call to find_n() originating from get_num() which is called in main(), so that your program would for now just return a random value.

Modifying a recursive string reverse function

I am doing some recursive exercises. The previous one was to make a reverse() function for a string which basically removes the first character and then combines the solution. I managed to do that, here is the source code (the entire source) The current task is to modify this function (the following exercise in the book) by adding a helper function which reverses a substring of the string. At this moment I am stuck at this. It is my understanding that you use helper functions when you need to pass additional arguments or something and this function takes none so I really have no idea how to approach this problem. Help appreciated.
#include <iostream>
#include <string>
using namespace std;
void reverse(string& text)
{
if (text.length() == 0)
{
return;
}
if (text.length() == 1)
{
return;
}
else
{
string firstLetter = text.substr(0,1);
text = text.substr(1, text.length()-1);
reverse(text);
text += firstLetter;
}
}
int main()
{
string a = "tyu";
reverse(a);
cout << a << endl;
return 0;
}
A guy suggested to use parameters, ect, this is my try with it:
#include <iostream>
#include <string>
using namespace std;
//is actually doing the hard work
void reverse1(string& input, int a, int b)
{
// base case
if( a >= b)
{
return;
}
//swap the characters
char tmp;
tmp = input[a];
input[a] = input[b];
input[b] = tmp;
//create the boundries for the new substring
a++;
b--;
//call the function again
reverse1(input, a, b);
}
// sets the parameters and calls the helper function
void strreverse(string& input)
{
reverse1(input, 0, input.length()-1);
}
int main()
{
cout << "Please enter the string which you want to be reversed:";
string a;
cin >> a;
strreverse(a);
cout << a << endl;
return 0;
}
The goal is probably to avoid creating all of the intermediate substrings. The helper function will take iterators, or a start and end index in addition to the string begin reversed.
Try to implement reversing so that there is only one instance of std::string (i.e. work with it as with an array). Then you will need a helper function with additional parameters (at least one parameter - which index to reverse now).
I would implement reverse here as series of exchanges: a[0] <-> a[n-1], a[1] <-> a[n-2] etc. where n is length of the string.
You can define a helper function that takes a start and an end index of the substring which it will reverse.
The function should exchange the element at the start index with that at the end index IFF the difference between the start and the end indices is 1. Otherwise, it places a recursive call to itself by decrementing the end index and incrementing the start index. You will need to keep check on the condition if the start and end index become same though.

Multiple return value method fails with goto statements

The following code:
#include <cstdlib>
#include <iostream>
using namespace std;
int function(void)
{
static int i,state=0;
switch(state)
{
case 0: goto labeL0;
case 1 :goto labeL1;
}
labeL0:
for (i = 0; i < 10; i++)
{
state=1;
return i;
labeL1:;
}
}
int main(int argc, char *argv[])
{
cout << function() << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
fails. I mean it returns only 0 instead of 0,1,2,...
I wanted just use label and goto statements to implement such functions. It is for practice (let's say homework), but I can't get it to work. Is this even possible?
How can I use goto and label statements so that this function prints 0 1 2... so on?
It's not clear to me exactly what you're trying to do. If your goal is
jsut to use goto, the simplest solution is to implement the algorithm
exactly as you'ld normally do, replacing looping constructs wit goto;
i.e. instead of:
for ( int i = 0; i < 10; ++ i ) {
std::cout << i << std::endl
}
you could write:
int i = 0;
goto label1:
label2:
std::cout << i << std::endl;
++ i;
label1:
if ( i < 10 ) goto label2;
Back in the old days, with Fortran IV, this is what we actually did.
There's absolutely no reason to do it today (except maybe obfuscation).
I wonder, however, given the static variables, if you're not trying to
implement some sort of co-routine; that each time you call the function,
you output one higher than the previous time. In this case, I'd
recommend maintaining the state in a class, rather than using static
variables. In addition the function will need some sort of return value
so that the caller will know when it's finished, and the caller will
have to loop. Something like the following should do the trick:
class CoRoutine
{
int i;
public:
CoRoutine() : i( 0 ) {}
bool function()
{
if ( i < 10 ) {
std::cout << i <<std::endl;
++ i;
}
return i < 10;
}
};
int
main()
{
CoRoutine c;
while ( c.function() ) {
}
return 0;
}
(There's still no need for goto, of course.)
This won't work since after the return statement, the compiler leaves the function ignoring all statements after it.
Also, using labels is ugly, horrible and unmaintainable. Why are you using them? Do you want the maintenance guy arriving at your house with a chain-saw?
After executing the return statement the execution returns from function().....
So initially when i=0, "return i" returns 0 and it is displayed on screen
You should use recursive call to function to get it executed and more over your use of GOTO is a typical example of why we should avoid using goto.
void function(void)
{
static int i=0;
for(;i<10;)
{
cout<<i;
i++;
function();
}
}
void main()
{
function();
}
but if you still want to use goto statements then use this
void function(void)
{
static int i =0;
lablelA:
cout<<i;
i++;
if(i == 10)
return;
goto lablelA;
}
Jumping to labeL1 is jumping in a loop with uninitialized variable i. How could this go right? This is only 1 of the reasons to avoid goto.
EDIT: actually, it should probably work as some sort of poor man's generator (because of the static local variables), but still the case of i >= 10 should be handled. Now it is returning nothing. So your main concern in the code is that you need a loop in main to call function maximum 10 times.
Still, this is not a construct I would want to see in real code.
The code reminds me of Coroutines in C.
To print 0, 1, etc you should call the function several times. That's the whole point.

maintaining a recursion count

I'm trying to count the number of calls within a recursive permutation function.
I've written a function that fills a queue with all the permutations but I can't seem to figure out how to maintain an accurate count.
Ultimately i'd like the function to return a subset of the permuatations specified by lbound and ubound arguments, and to do so I think i need someway to keep an internal count.
Using the size of the returned queue will not work since i'd like the function to be able to handle permutations too big to hold in memory.
For this code i'd like the count to be returned as 100.
#include <vector>
#include <iostream>;
using namespace std;
int& Permutations(vector<vector<int>> param, vector<vector<int>> &perm, int index=0)
{
static vector<int> iter;
static int count = 0;
if (index == param.size())
{
perm.push_back(iter); // add permutation to queue
count++;
return count;
}
for (int i=param[index][0]; i<=param[index][1]; i+=param[index][2])
{
if (iter.size() > index) iter[index] = i;
else iter.push_back(i);
Permutations(param, perm, index+1); // recursive function
}
}
void main()
{
vector<vector<int>> params; // vector of parameter vectors
vector<int> param1, param2;
int arr1[3] = {0,9,1}; // range for each parameter vector
int arr2[3] = {0,9,1}; // specified as lbound, ubound, step
param1.insert(param1.end(),arr1,arr1+3);
param2.insert(param2.end(),arr2,arr2+3);
params.push_back(param1);
params.push_back(param2);
vector<vector<int>> queue; // queue of generated permutations
int permcount = Permutations(params,queue);
cout << "the permutation count is " << permcount << endl;
cin.get();
}
Using a static count will not work, because it's not going to ever be reset (and will cause problems if you ever go multi-threaded).
Instead, how about this:
int Permutation(/* params */)
{
int count = 1; // Count ourself
for (whatever)
{
count += Permutation(whatever); // Count cumulative sum from recursion
}
return count;
}
Each call to Permutation() returns the total number of calls that were made below it in the call tree. As we unwind, all the counts from the sub-trees get summed together, to eventually produce the final return value.
int foo(int count,/*Other Params*/) {
/*Calucation*/
if (!terminatingCondition) {
foo(count++,/*Other Params*/);
}
logger.log("foo was called " + count + "times");
return /*calcualtion*/;
}
I'm just trying to answer the question by ignoring your actual algorithm purpose. The two statics should be moved to argument references, or you don't have a good way to reset their values.
void Permutations(vector<vector<int>> param, vector<vector<int>> &perm, vector<int> &iter, int &count, int index=0)
{
++count;
// ...
}