Recursion in the main function - c++

I tried recursion in the main function, but why 'i' variable is not getting updated, it only gets updated till i=1 and then remains constant.
Below is the code:-
int main(int i = 0)
{
std::cout << "i value" << i << std::endl;
if (i == 3)
return 0;
std::cout << "hello" << std::endl;
main(i++);
}

See for example cppreference/main_function:
The main function has several special properties:
It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
[...]
You cannot call main recursively. Also your signature is not correct. Correct signatures are:
int main () { body } (1)
int main (int argc, char *argv[]) { body } (2)
/* another implementation-defined form, with int as return type */ (3)
For (3) you need to check your implementation, I am not aware of one that allows int main(int) (though I didn't bother to check).
Last but not least, foo(i++); will increment i and then call foo with the original value of i. You probably want foo(++i); or rather foo(i + 1);.
TL;DR
int my_main(int i=0) {
// put code here
my_main(i + 1);
}
int main() {
my_main();
}

Related

recursive method for array element printing

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.

How to use values created inside a loop function?

I would like to know which one would be the best way of using values created inside a loop, outside of that loop. I have for example the function:
void Loop(int a)
{
// recursion loop execution
for ( int i = 0; i < 10; i++ )
{
int new_a = a + i;
}
}
I would like to use that "new_a" as it is being "looped" in another function which is plotting a graph and only needs the "yAxe" value. Like that:
int main ()
{
int a = 5;
plot (x,Loop(int a);
}
I know I could create an array with the values of the loop but I wouldn't like to store them and for big plottings would be too much memory.
Any local variable will be destroyed when the scope of them be finished. For example, in your code new_a will be destroyed when the for loop is finished, and the a is destroyed when the function be finished. I mean if you care about memory, don't be worry.
If I understand you correctly, you want to call Loop multiple times (like e.g. Loop(a)) and each call you should get the next "iteration" of the loop?
That would have been easy if C++ had continuations which it doesn't. Instead it can be emulated by using classes and objects and operator overloading.
For example:
class LoopClass
{
public:
LoopClass(int initial_value = 0)
: current_value{initial_value}
{
}
int operator()(int a)
{
return a + current_value++;
}
private:
int current_value;
};
It can be used as such:
LoopClass Loop; // The value initialized with zero
int a = 5;
std::cout << "First call : " << Loop(a) << '\n';
std::cout << "Second call: " << Loop(a) << '\n';
The above code, if put into a program, should print
First call : 5
Second call: 6

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.

Undefined behaviour or may be something with memset

I was trying to save the binary equivalent of a 32 bit number in an array A. For testing my showbits() function , I choosed 8,9 when I came across this thing:
I am facing an unreasonable thing in my code when I am placing memset in the function showbits(),I am geting absurd integers while I expect an output something as
00000000000000000000000000001000
that is the binary equivalent of 8 . While when I place memset in the main() method, it works properly and gives me the right output.Am I going out of bounds(I cannot see it !) .
My code :
SHOWBITS:
void showbits(int A[32],int num)
{
int k=0;
memset(A,0,sizeof(A));
while(num>0)
{
A[k] = num&1;
k++;
num>>=1;
}
return ;
}
Note: I have placed memset in showbits ,and I am getting incorrect answers!
MAIN:
int main()
{
int A[32],i;
showbits(A,8);
for(i=31;i>=0;i--)
printf("%d",A[i]);
return 0;
}
Whole program for testing:
#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
void showbits(int A[32],int num)
{
int k=0;
memset(A,0,sizeof(A));
while(num>0)
{
A[k] = num&1;
k++;
num>>=1;
}
return ;
}
int main()
{
int A[32],i;
showbits(A,8);
for(i=31;i>=0;i--)
printf("%d",A[i]);
return 0;
}
When I place that memset statement in Main method before showbits() , I am getting correct output!
EDIT
If someone is interested in what I am getting
398420075242008462686872420075219611920941961187434-2205336646196127610926869242
68672826866724200752000202903316219611874341961187478819611565142686716196182637
61961141748268665201000
The A[32] in the method is actually just a pointer to A. Therefore, sizeof is the size of *int. Take the following test code:
void szof(int A[32])
{
std::cout << "From method: " << sizeof(A) << "\n";
}
int main(int argc, char *argv[])
{
int B[32];
std::cout << "From main: " << sizeof(B) << "\n";
szof(B);
return 0;
}
which give the following output:
From main: 128
From method: 8
Thus, the memset sets fewer bits than you think.
You must pass A by reference
void showbits(int (&A)[32],int num)
See here for more details: C++ pass an array by reference
Avi explained the problem in your code already. Another possible solution is to use C++-style arrays, instead of C-style arrays and memset. Then there is no possibility of a memset length error. Also there is no loss of performance.
#include <array>
void showbits(std::array<int, 32> &A, int num)
{
A = {}; // set all entries to 0
// ...
}
int main()
{
std::array<int, 32> A;
// ...
}

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.