Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I made this function that returns the number of digits in an integer:
it works fine when I used ELSE to return the count
int getIndex(int number, int count) { // at first call count is 0
number /= 10;
if (number > 0){
getIndex(number,++count);
}
else{
return ++count;
}
}
but when I first tried to execute without ELSE statement I thought function will be called recursively till IF condition is not met and then only it will encounter the return statement
And function will exit there as integer is returned, but
actually
if the number contains more than one digit, doesn't matter how many time it increase with recursive call it outputs 2
Just curious where as to why I am getting my concept wrong
it works fine when I used ELSE
Actually, the behaviour of the shown program is undefined. If the if branch is entered, then no return statement will be reached, and the behaviour of the program will be undefined.
When you remove the else statement and instead return unconditionally, the behaviour is well defined: The function will always return count + 1 or count + 2 depending on the value of number (which isn't correct).
Consider this, where do you use the value of the recursive function call? Nowhere; you simply discard the value. Would it make sense to return that value to the caller? Yes, it would. If only you returned within the if branch, the behaviour would be correct.
return getIndex(number,++count);
Then it won't matter whether the recursion-terminating branch is within else or not, it will only be executed if the if branch is not executed:
You are missing a return before the recursive call.
By default, it returns 0 (for some compilers).
Edit:
But actually the code should have looked like this:
int getIndex(int number) {
if (number > 0) {
return getIndex(number/10) + 1;
} else {
return 0;
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Getting Douglas Adams vibes here...
I just started out with c++ and doing some code challenges right now.
The current challenge is to create a function that takes a number as its only argument and returns true if it's less than or equal to zero, otherwise return false.
However, when I run the program I get the number 42??
I actually don't need help for the challenge itself, I just wonder if someone could explain why I get this result :)
#include <iostream>
#include <string>
using namespace std;
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
}
int main()
{
cout << lessThanOrEqualToZero(5);
}
The function bool lessThanOrEqualToZero(int);, as defined, makes your program have undefined behavior since not all paths in the function leads to the function returning a bool that you declared that it should return. Specifically: If num > 0 is true the function doesn't return a value.
When a program has undefined behavior, you can't trust anything it does. Your program could therefore print just about anything or nothing, crash or do something completely wild.
In some compilator implementations, a value could be picked from the stack where it expects to find the promised bool and then print whatever that value was (42 in your case). The stack will then be corrupt. Other implementations may compile it into a program that does something completely different. You'll never know.
The solution is to make sure that all paths leads to a return:
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
return false;
}
This however better written as:
bool lessThanOrEqualToZero(int num)
{
return num <= 0;
}
otherwise return false
Well then you do need to return false otherwise.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am very new to C++. My objective is to write the following logic:
if a = yes then print "ok", else return 0
Here is my code so far:
int a;
cin>>a;
if (a = "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
First of all, what do you want your program to do?
You need to distinguish assignment and equal to operator.
Please note that you need to understand the basics before proceeding to perform conditional statements.
A reasonable program should go like this:
int a;
cin>>a;
if (a == 5) { // 5 is an integer
cout<< "You entered 5!" << endl; // no semicolon after "
}
return 0; // must be out of the else statement
= assigns things.
Use == to compare, however you are comparing an int with a string.
If you are not careful, you compare the address of a char * with a number when dealing with strings.
Use a std::string instead.
#include <string>
//.... some context I presume
std::string a;
cin >> a;
if (a == "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
There are multiple errors in this code.
You need to use the comparison operator in your condition. This is denoted by the double equal sign "==". Your code is using assignment "=" which tries to assign the value "Yes" to the variable a. This is a common error in C/C++ so you need to be careful whenever you compare things.
The other error is that you have declared the variable a to be an integer, so you will get a type mismatch error when you try to compile because "Yes" is a string.
Your code is incorrect in terms of data types. You have a variable 'a' of type int which you are comparing to string "yes". Try to see it from a logical point of view; you can compare:
2 numbers (for example, 2 is greater than 1)
2 strings (for example, "food" is not the same word as "cat")
Etc...
In your case, you are comparing a number inputted(let's assume 5) to a word "yes". When you try to input a letter for var a, you will get a compilation error. Therefore, simply change the following:
string a;
Another problem with your code is when the if-then loop checks the condition; a comparison operator is 2 equal signs next to each other instead of a single equal sign. A single equal sign assigns the item on the right to the item on the left. For example, in:
int num = 5;
The variable num is assigned 5. But you want to make a comparison, not assign the variable its own condition!
Your loop is always true because you set the variable to the condition it is supposed to meet. You also need to do the following:
if (a == "yes")
This compares the value stored in var a to the value on the right side of the == .
Just some advice, I would recommend you to get some good books on c++. Search them online. You can also take online programming courses on edx, course record, etc... . There are a lot of other free learning resources online too which you can make use of. You may also want to dive into a simpler programming language; I would recommend scratch. It gives you a very basic idea about programming and can be done in less than a week.
** Note that I feel this is the simplest way; however, you can also set type of a to a char, accept input and then convert it back to a string. Good luck!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've tried to understand this one, but no chance. How it works?
#include <stdio.h>
int tavuk(int i)
{
return (i%3 != 0 ? i + tavuk(--i) : i);
}
void main(void)
{
int *p, array_a[]={5,2,4,7,3};
p = array_a;
printf("%d", tavuk(array_a[*(++p)]));
}
You should attach a debugger to the program, place some breakpoints and step through it one line at a time, so you can watch the code do its magic. Maybe adding additional parenthesis and spaces around illegible expressions could help you as well.
I wrote a step by step explanation of what happens below (read it at your own risk):
p points to the first element in array_a[] after p = array_a;
then ++p is executed and p points to the second element in array_a (and its address is returned to the dereference operator *)
* returns the value (2) of the second field in the array (since ++p returned the address of array_a[1])
now array_a[2] is retrieved and its value (4) is passed into tavuk(...)
inside tavuk(...) (4%3 != 0) evaluates to true
--i is executed (now i = 3)
tavuk(...) is called with 3, inside it (3%3 != 0) evaluates to false and 3 is returned
the decremented i (3) is added to the return value of the second tavuk(...) call (also 3) and 6 is returned
6 is printed to stdout
Initially p points to the beginning of the array array_p.
The statement array_a[*(++p)] can be broken down as follows:
++p ==> increment point to next memory address, in this case address of array_p[1]
*(++p) ==> integer value at this address, in this case 2 or array_p[1]
Therefore, you pass integer value of 2 to the tavuk method.
Upon returning from the method, you would get a value of 5.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have an isPrime function that is always returning true, regardless of the inputted number. This is the same for a couple other bool functions in my program.
My simple isPrime function:
bool isPrime(mpz_class num)
{
bool prime = true;
for (int i=2; i<num; i++)
if (num % i == 0)
prime = false;
return prime ;
}
Calling it (I suspect this is where the problem is but I don't know what the problem is):
do
{
do
{
cout << "Enter Prime 1: ";
getline(cin, sa);
isNum(sa);
firstPrime = sa;
}
while(!isNum);
isPrime(firstPrime);
}
while(!isPrime);
The isNum function is also returning "true" every time.
Runtime error:
warning: the address of 'void isNum(std::string)' will always evaluate as 'true' [-Waddress]|
Does anyone see the problem?
You need to store the return value from the call to isNum() before you can check it in the while look. What you're doing now with
while(!isNum)
is that you're checking the address of the function and not it's return type. What you probably mean to do is something like this:
bool isPrimeRetVal;
do
{
bool isNumRetVal;
do
{
cout << "Enter Prime 1: ";
getline(cin, sa);
isNumRetVal = isNum(sa);
firstPrime = sa;
}
while(!isNumRetVal);
isPrimeRetVal = isPrime(firstPrime);
}
while(!isPrimeRetVal);
Note the same issue with while(!isPrime).
You ignore the return value of isPrime and instead check the value of isPrime (which doesn't change, it's always a valid function).
You are not calling the function by merely mentioning its name, e.g. with while (!isNum).
The function name in that context evaluates to a pointer to that function. Since all non-null pointers evaluate to boolean true and a pointer to any function cannot be equal to the null pointer, isNum always evaluates to true and !isNum is always false.
Instead of this:
do { ... isPrime(x); } while (!isPrime);
you need to write something more like this:
do { ... } while (!isPrime(x));
These two lines:
isPrime(firstPrime);
while(!isPrime);
combine to suggest you're not clear on how functions are called in C++. The first line calls the function and then throws the result away. The second line doesn't even call the function, it just looks at its address (which will never be zero).
You probably want:
while(!isPrime(firstPrime));
This passes firstPrime to the function, and then looks at the return value of the function.
You are not using return value of isPrime function. IsPrime is a function and you should store its value in some variable and use that variable in while loop.
The same goes with the isNum variable.
This question already has answers here:
Does C++ limit recursion depth?
(6 answers)
Closed 9 years ago.
#include<iostream>
using namespace std;
int f()
{
static int count=0;
count++;
if (count>=5000)
return count;
return f();
}
int main ()
{
cout<<f();
return 0;
}
this function overflows the stack after the value of count exceeds 4800 can anybody tell how to resolve this issue ?
Don't use recursion - use a regular loop. Every time you call your f() method, you will occupy few words on the stack, and you will overflow it at some point.
Usually, there's way to increase stack size (depending on your system and/or compiler), but I don't want to recommend that (especially because it will overflow again, just with the value of count bigger than 4800).
Or just int f(){ return 5000; } would do.
Assuming you want to run recursively, you could turn off debug mode, then you'll succeed (as Visual Studio adds extra stuff on the stack to detect if you "clobber" the stack [it's how it can say "The stack around variable x was overwritten" or whatever the exact message is].
However, relying on being able to do LARGE number of calls recursively is a bad plan in general - at some point or another, it will still fall over. Whether that is 5000, 50000 or 500000 is just a matter of "how much stack-space does this function take". I'd say anything that doesn't have a natural limit of around 100 levels of recursion is a case of "you are solving the problem the wrong way". If you do have such large recursion levels, it's better to use a software stack (e.g. std::stack in C++), and save the crrent state on that stack, and restore it, using the software inside the function.
Running out of stackspace is one of the worst possible runtime problems, because there is really nothing you can do - there may be things you can do to print an error message or some such, but there is really no way to "give the process some more stackspace and continue". When a process runs out of memory or something similar, you can say "Ok, I won't allocate that, and give the user an nice error message saying 'I can't do this', and the nicely save the current state and exit, for example."
[And yes, you can increase the stack-size of your application, but that really should only be done as a true last resort, and only when you fully understand WHY you need such large stack - it's very often something else you're doing wrong if you need a bigger stack].
I'm assuming this is for an academic exercise to learn about recursion. (If it is not, please don't use recursion for this!)
A better way to write your function:
#include <iostream>
int f(int i)
{
if (i >= 5000)
{
return i;
}
else
{
return f(i + 1);
}
}
int f_alt1()
{
return 5000;
}
int f_alt2()
{
int i = 0;
for (; i <= 5000; ++i);
return i;
}
int main()
{
std::cout << f(0) << std::endl;
return 0;
}
This will still eat up far more runtime resources than returning the constant or incrementing in a loop, and you will need to increase your stack size if you increase the desired constant to a significantly larger number.