recursion

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  bool f2(char * str)

{

if (!*str)

return true;


if (*str>'0'||*str<'9')

return false;

return f2(str+1);

}




how it cheks if the string is build only from digits???
Last edited on
OK i get it because its ||

like de morgane.
You have to make a and-connection.
If the string characters value is between 0 and 9 it is a digit.
if(*str >= '0' && *str <= '9')

In the standard c-library there is a function named isdigit(char);
http://www.cplusplus.com/reference/cctype/isdigit/

that's just a minor issue but when checking if the 0-termination is reached try to write *str == 0 because it's easier to understand at first sight :)
1
2
3
4
5
6
7
8
9
10
bool f2(char * str)
{
    if (*str == 0)
        return true;

    if (*str>='0' && *str<='9')
        return false;

    return f2(str+1);
}
yeh thanks man..but its a part from a test they wanted to make it complex..

look at my other topic about files
Last edited on
So is this problem of yours solved?

yeh thanks man..but its a part from a test they wanted to make it complex..

What does that have to do with your question?
Last edited on
if the 0-termination is reached try to write *str == 0 because it's easier to understand at first sight :)

becuase you wrote that ^
closed account (D80DSL3A)
The function doesn't work. Line 10 makes it return false for every non-empty string input.
if (*str>'0'||*str<'9')
Picture a number line. All values are either >0 or <9.

Fix by replacing with if (*str>'9'||*str<'0')// false if outside the range 0-9

Demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using std::cout;

// original (except for const qualifier)
bool f2(const char * str)
{
if (!*str) return true;
if (*str>'0'||*str<'9') return false;// wrong
return f2(str+1);
}

// corrected
bool f3(const char * str)
{
if (!*str) return true;
if (*str>'9'||*str<'0') return false;// right
return f3(str+1);
}

int main ()
{
    const char * a = "123";
    cout << "a " << ( f2(a) ? " is" : " is not" ) << " a number.\n";// it isn't
    cout << "a " << ( f3(a) ? " is" : " is not" ) << " a number.\n";// yes, it is

    const char * b = "1b3";
    cout << "b " << ( f3(b) ? " is" : " is not" ) << " a number.\n";// no, it isn't

    cout << '\n';
    return 0;
}
Last edited on
its not wrong it goes like de morgan rules!!!!!!!

(*str>'0'||*str<'9')

(*str>'0'&&*str<'9')

theres a diffrence...
closed account (D80DSL3A)
Test the function. It doesn't work.
It will return false for everything but an empty string = "".
Topic archived. No new replies allowed.