C using recursion to implement the first n elements and

Source: Internet
Author: User

Recursive functions, that is, constantly call their own functions, using recursion can be more convenient to solve some of the more difficult to use the loop to solve the problem. In this example, for the first n of an array a[] and, that is, for a[n-1]+a[n-2]+...+a[0], if a function sum is used to find the first n of the array and sum is defined as sum (int a[],int n), then recursion is used
A[n-1]+sum (a,n-1).

It might be better to use code to express it:

#include <stdio.h>intSumintTest[],intn);/** * @brief main uses recursion to find the first n elements of an array and the * hypothesis array is a[], then the first n elements of the and that is to ask for * a[n-1]+a[n-2]+...a[0] * @return */< /c3>intMainvoid){intN printf"Please input the number of a array:\n"); scanf"%d", &n); printf"Please enter the element of the array:\n");intTest[n];intI for(i =0; i < n;i++) scanf ("%d", &test[i]);intCount = SUM (test,n); printf"The sum of the array is:%d.\n", count);return 0;}/** * @brief sum implementation of the first n elements of the and * @param test requirements and array * @param n Required First n elements * @return 
       returns the first n elements of the and */intSumintTest[],intN) {if(N <=0)return 0;returntest[n-1]+sum (test,n-1);}

The following is the output of my program, this program is relatively simple.

C using recursion to implement the first n elements and

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.