Loop and Recursion-if, while, for, and do-while statements are not used to output all natural numbers smaller than the known number n.

Source: Internet
Author: User

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.