How can we solve the simple loop problem with recursion without loops!
Question: How can I use the if, while, for, do... while statement to output all natural numbers smaller than the known number n. (Including 0)
I did not think of this problem, but I saw it in a blog of a buddy. The buddy actually wrote a loop to solve this problem. I don't know how to say it. The following are my own searches on the Internet or my own thoughts. I have made a little effort to sort them out, mainly by using recursion. Considering that recursion will eventually involve judgment: without the use of if, the three-object operator is used.
(1)
#include<iostream>using namespace std;int x=15;int work(int n){cout<< n-1<<endl; return n-1>0 ? work(n-1):0;}int main(void){ return x>0 ? work(x) : 0;}
(2)To end recursion, it must involve judgment. The essence of judgment is true and false (I .e., 1 and 0). To judge the final N and 0
Void myprint (int n)/* output 0---n-1 */{int flag = 1; pirntf ("% d", -- N); flag = (n> 0 ); // This can also be written as flag = n-0; Switch (FLAG) {Case 1: myprint (n); break; Case 0: break ;}}
(3)If the number of Division partitions is 0, an exception occurs and the program is exited. (Not recommended)
#include <stdio.h>#define MAX 15int boom;void foo(int n) { boom = 1 / (MAX-n); printf("%d\n", n); foo(n+1);}int main(void) { foo(0); return 0;}
(4)Comment on the first floor downstairs
Wohaaitinciu
Method: (Thank you)
#include<iostream>using namespace std;int func(int n){n && func(n - 1);return printf("%d\n", n);}int main(){func(15);return 0;}