implement while and for loops in functions to return the first integer



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 ?

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
#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;
}
There is a problem with function p(). If i is not 20, then the return value is not specified.

Also p() returns a type bool - it it has the value 1 (true) or 0 (false). But in the for loop L8 you are comparing i to be >= p(). As n is 7 in this case, this is always true. The body of the for loop is return i, so the return value is 7!

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
include <iostream>

bool p(int i) { return i == 20; }

int searchfor(int n) {
	int i = n;

	for (; !p(i); ++i);

	return i;
}

int searcwhile(int n) {
	int i = n;

	while (!p(i)) { ++i; searcwhile(i); };

	return i;
}

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

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



20
20
20

Topic archived. No new replies allowed.