0

i started to learn c++ with only tutorial from the internet and i have this problem when starting to learn about the loops the question was : The function P is total, and as states , has a return value of the type bool, further is only assumed that there are arbitarily larg t , so that p (t) is equal to 1 ,i.e. true. otherwise the particular choice of p does not matter.

all three functions return the first integer t greater than or equal to n to which the property p applies for the argument n . first function use for loop 2nd use while loop the 3rd is SearchFunctional

the SearchWhile and SearchFunctional are returning the value of i=20 but SearchFor is returning i=7 not i=20. how can i make it to return the i=20 ?

this is the code:

#include <stdio.h>
#include <iostream>
bool p(int i){if (i==20) return 1;}


int searchfor (int n) {
    int i = 0;
    for (i=n; i>=p(i); i++)
    return i;
        
}
int searcwhile(int n){ 
    int i=n;
    while (!p(i)) {i=i+1; searcwhile(i);};
    return i;

}

int SearchFunctional  (int n){return(!p(n) ? SearchFunctional (n+1) : n);}

int main()
{
std::cout<<searchfor (7);
std::cout<<searcwhile(8);
std::cout<<SearchFunctional(9);


    return 0;
}
Evg
  • 25,259
  • 5
  • 41
  • 83
Nariman
  • 1
  • 1
  • What do you think `i>=p(i)` evaluates to as an int? How would counting down from 7 ever reach 20? – Retired Ninja Aug 11 '21 at 05:40
  • `int searcwhile(int n)` may return `20`, but it doesn't do what's asked in the question. You were not supposed to use any recursion with the while-loop. – Ext3h Aug 11 '21 at 05:44
  • `bool p(int i){if (i==20) return 1;}` should be `bool p(int i){return 20 == i;}`. In `searchfor`, the condition in your for loop should be `!p(i)` instead of `i>=p(i)`. In addition, what happens if the user call your functions with a negative `n`? – Kfir Ventura Aug 11 '21 at 05:58
  • 1
    https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. Pick a better tutorial from there. Point is, that there are several things you seem to have picked up that are obsolete or otherwise bad. – Ulrich Eckhardt Aug 11 '21 at 06:06
  • Get yourself a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). There are no known good (or even decent) online tutorials. – molbdnilo Aug 11 '21 at 07:47

0 Answers0