C language recursive exercises

Source: Internet
Author: User

1. Ball objects like shells can pile up into a pyramid with a shell at the top, which is located on a layer composed of four shells, the four shells are located on a layer consisting of nine shells, and so on. Write a recursive function CannonBall that uses the height of the pyramid as a parameter and returns the number of shells it contains. Functions must be implemented recursively, and iterative structures such as while or for cannot be used.

Int CannonBall (int h) {if (h = 1) return 1; else return CannonBall (h-1) + pow (h, 2);} int main (void) {printf ("% d \ n", CannonBall (4); return 0 ;}


2. Compile an exponential function using C to implement n ^ k

Int RaiseToPower (int n, int k) {if (k = 0) return 1; else return n * RaiseToPower (n, k-1);} int main () {printf ("% d \ n", RaiseToPower (3, 4); return 0 ;}


3. Use the Euclidean formula to write a recursive function gcdm, n), which is used to calculate the maximum Appointment Between m and n.

Int gcd (int m, int n) {if (m % n = 0) return n; else return gcd (n, m % n);} int main () {printf ("% d \ n", gcd (18, 4); return 0 ;}


Related Article

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.