0
Why 'reminder'(rem) is declared globally here?
#include<iostream> using namespace std; int palindrome(int); int rem=0; int main() { int num,res; cout<<"Enter number:- "; cin>>num; res=palindrome(num); if(num==res) { cout<<"Entered number is palindrome"; } else { cout<<"Enter number is not palindrome"; } return 0; } int palindrome(int num) { int number; if(num!=0) { number=num%10; rem=rem*10+number; palindrome(num/10); } return rem; }
13 Answers
+ 2
Test 123 below code without global declaration:
#include<iostream>
using namespace std;
int palindrome(int,int&);
int main()
{
int rem = 0;
int num,res;
cout<<"Enter number:- ";
cin>>num;
res=palindrome(num,rem);
if(num==res)
{
cout<<"Entered number is palindrome";
}
else
{
cout<<"Enter number is not palindrome";
}
return 0;
}
int palindrome(int num,int &rem)
{
int number;
if(num!=0)
{
number=num%10;
rem=rem*10+number;
palindrome(num/10,rem);
}
return rem;
}
+ 2
Test 123 whatever I mentioned in my previous comment works as you don't need same rem variable outside..you are just returning value as function return..
also static mentioned ask compiler to retain value of same through out application...so, value is retained and initialisation to zero happens only once for first call
+ 1
Test 123 yup I missed that recursion call inside function...but it's good that you only answered your question of why it is declared globally...
+ 1
Oh yeah, i just answered it myself, thanks for ur time
+ 1
const value you can't change..use static as below :
static int rem = 0;
+ 1
ok thanks for explanation
+ 1
check once and you will get error
+ 1
Ketan Lalcheta thanks once again to clarify my doubt , now rem is read only variable we cannot change it value after intilization...
0
Test 123 it's not required to have something globally only.. you can pass function argument or return variable or use call by reference to access something within different code blocks..
in your case, without doing any changes, you can declare rem locally inside function...
0
if i declare it inside palindrome function it's value is changing after each call, this is changing the output
0
what if we declare it inside palindrome only and make it constant
example
const rem=0;
is this right?
0
it can be changed inside it's scope i think but we can't change it using a method so our value is preserved while recursive calling of function . correct me if i'm wrong
0
const will tell the compiler to initialise rem =0 once .