0

C++ Recursion Help needed

Pastry chefs are competing to win the battle of the cakes. For each additional cake made, the number of eggs required increases by 1 (1 egg for the first cake, 2 eggs for the second, etc.). Take the number of cakes that must be baked as the input, calculate (recursively) how many eggs were used to bake them by the end of the battle and output the result. My attempt: #include <iostream> using namespace std; int recSum(int n) { //complete the function if(n == 1){ return 1; } else{ return n* recSum(n+1); } } int main() { //getting input int n; cin >> n; //call the recursive function and print returned value recSum(n); cout << n << endl; return 0; } It works under only 1/5 conditions.

29th Jun 2021, 12:47 AM
Nick Brown
Nick Brown - avatar
2 Respuestas
0
#include <iostream> using namespace std; int factorial(int n) { if (n==1) { return 1; }else if (n==0){ return 1; }else{ return n + factorial(n-1); } } int main() { int n; cin >> n; cout << factorial(n); cout << endl; return 0; }
29th Aug 2022, 7:00 AM
the Monu
the Monu - avatar