SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:1 | ISBN:9780132846813 | Edition: 5

Question

Write a recursive function definition for a function that has one parameter n of type int and that returns the n th Fibonacci number. The Fibonacci numbers are F0 is 1, F1 is 1, F2 is 2, F3 is 3, F4 is 5, and in general

Fi+2 = Fi + Fi+1 for i = 0, 1, 2, ...


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The following recursive function "FibNum" is used to accept an integer parameter and returns the nth Fibonacci number:

//Function definition of fibNum
//This function accepts an intger parameter n
int fibNum(int n)
{
    //Find the nth Fibonacci number
    //using recursive function
    if(n<=1)
        return n;
    else
        //recursive function
        return fibNum(n-1)+fibNum(n-2);
}

COMPLETE EXECUTABLE C++ CODE:

//Default header function
#include <iostream>
using namespace std;

//Function prototype
int fibNum(int n);

//Program starts with main method
int main()
{
    //Define an intger data type variable name, number
    int number;
    //Prompt statement for read an integer number
    cout<<"Enter an integer number:";
    //Read integer number from the student/user/programmer
    cin>>number;
    
    //Call the fibNum function and display result on screen
    cout<<"The Fibonacci number of F("<<number<<") is "<<fibNum(number);

    return 0;
}

//Metho definition of fibNum
//This function accepts one
//intger parameter n
int fibNum(int n)
{
    //Find the nth Fibonacci number
    //using recursive function
    if(n<=1)
        return n;
    else
        //recursive function
        return fibNum(n-1)+fibNum(n-2);
}

OUTPUT OF THE PROGRAM CODE:

0 0

Discussions

Post the discussion to improve the above solution.