算法训练1:递归与循环

版权声明:本文为博主原创文章,未经博主允许不得转载。@ceezyyy11 https://blog.csdn.net/ceezyyy11/article/details/86749652

算法训练1:递归与循环

用递归实现输出0-10

#include<iostream>
using namespace std;

void myfunction(int n)//参数选择
{
	if (n > 0)//递归出口
		myfunction(n - 1);
	cout << n << endl;

}

int main()
{
	myfunction(10);
	return 0;
}

用递归实现求数组元素累加和

#include<iostream>
using namespace std;

int GetSum(int *a,int n)//参数选择
{
	if (n == 0)//递归出口
		return 0;
	return GetSum(a, n - 1) + a[n - 1];

}

int main()
{
	int a[] = { 1,2,3,4,5,6,7,8,9 };
	int len = sizeof(a) / sizeof(a[0]);//C++求数组长度
	cout << GetSum(a, len);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ceezyyy11/article/details/86749652
今日推荐