Calculate factorial using cycles and Recursion respectively

Source: Internet
Author: User
// Factor. C -- uses loops and Recursion to calculate factorials # include <stdio. h> long fact (int n); long rfact (int n); int main (void) {int num; printf ("this program calculates factorials. \ n "); printf (" enter a value in the range 0-12 (Q to quit): \ n "); While (scanf (" % d ", & num) = 1) {If (Num <0) printf ("no negative numbers, please. \ n "); else if (Num> 12) printf (" Keep input under 13. \ n "); else {printf (" loop: % d factorial = % LD \ n ", num, fact (Num); printf (" recursion: % d factorial = % LD \ n ", num, rfact (Num);} printf (" enter a value in the range 0-12 (Q to quit ): \ n ");} printf (" Bye. \ n "); Return 0;} long fact (int n) // loop-based function {long ans; For (ANS = 1; n> 1; n --) ans * = N; return ans;} Long rfact (int n) // recursive version {long ans; If (n> 0) ans = N * rfact (n-1 ); else ans = 1; return ans ;}

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.