Recursive method problems in C + +

Source: Internet
Author: User

How to solve problems with recursion method

Problem:

  1. A recursive function is used to calculate the factorial of the n value of the user input and to output it.

Problems encountered

1, recursive understanding is not deep enough, first of all to think of what conditions to meet with recursion, under what conditions to meet the end of recursion and return a value.

2, the most important is the logic of recursion, such as the following code

Experiment Nine (1). CPP: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>using namespace std;int factorial (int n) {int f=1;if (n > 1) {f = factorial (n-1) *n;} Elsereturn F;} int main () {int n;cin >> n;cout << factorial (n); return 0;}

It seems that the value of F will be re-assigned to 1 at each recursive time, and then the result is not correct, but the logic is

When N=1 is not satisfied with the condition of recursion, the return value is 1 and the result is correct

When n=2 satisfies the condition but does not recursively run only once so that the return value is 2, the result is correct

When the n=3 is recursive, that is, F = factorial (2), and because factorial (2) =2 so the final result is 6 is correct, and so on, and so on is the right one after the other

This is the way to push backwards from behind.

Recursive method problems in C + +

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.