ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Fibonacci series in C, Java & C#

Updated on March 28, 2018
Source

What is Fibonacci?

Fibonacci (also known as Leonardo of Pisa, Leonardo Pisano, Leonardo Bonacci, and Leonardo Fibonacci) is 13th century Italian mathematician. He is known to our world because of number sequence which he used in his book and fibonacci series was one of them. You can know more about Fibonacci on Wikipedia.

What is Fibonacci Numbers?

In math world, Fibonacci series is the number sequence in which each number is the sum of the two previous numbers. The sequence begins with 0 and 1. The next number would be sum of 0 & 1. This process will continue till nth number.

Source

From above table you can see that value in the 2nd location is the sum of previous two values (i.e. values present in location 0 and 1). Similarly value of 6th location is sum of value of 4th and 5th. This is how Fibonacci numbers can be generated. I hope logic for the Fibonacci number is clear and we can move to example for better understandings. Below example will give you Fibonacci number of the given index or location, you can refer above image for the same.

Function or method for Fibonacci number series:

int GenerateFibbonacciSeries(int index)
{
    int lastNo = 0, currentNo = 1, temp = 0, i;

    if (index == 0 || index == 1)
        return index;  

    for (i = 0; i < index - 1; i++)
    {
        temp = lastNo;
        lastNo = currentNo;
        currentNo = temp + currentNo;
    }
    return currentNo;
}

Find nth fibonacci number

For your convenience I have created one function/method to generate Fibonacci number series. You can call this function/method and pass position or index of Fibonacci number you want to get.

Let’s delve into above method/function. If you pass 0 or 1 as index to above method/function then it will return the same value. If you pass greater than 2 then it will execute the for loop block to calculate the fibonacci number of that place. Inside for loop, we are calculating sum of last two numbers and swapping that value. But for me interesting point is loop condition, it’s “i < index -1”. So if you pass 4 as index (i.e. 0 to 4, 5 times loop) it will loop for 3 times, why?

Iteration 1: 0+1; = 1
Iteration 2: 1+1; = 2
Iteration 3: 1+2; = 3		//we got our desired value.

Because we are dealing with 2 values of fibonacci series number in one iteration of for loop like I showed you in above block. So we have to loop only “i <= index – 2” or “i < index – 1”.

Nth Fibonacci numbers in C

#include "stdio.h"
#include "conio.h"

int GenerateFibbonacciSeries(int index);

int main() {
	int index = 0;
	clrscr();
	printf("Enter any location to get fiboncci no. : ");
	scanf("%d", &index);

	printf("\n\nFibonacci number is : ");
	printf("%d", GenerateFibbonacciSeries(index));
	getch();
	return 0;
}

int GenerateFibbonacciSeries(int index) {

	int lastNo = 0, currentNo = 1, temp = 0;
	int i = 0;

	//If index is 0 or 1 then return same value.
	if (index == 0 || index == 1)
		return index;


	for (i = 0; i < index - 1; i++) {
		temp = lastNo;
		lastNo = currentNo;
		currentNo = temp + currentNo;
	}
	return currentNo;
}

Note: I think you can easily modify this code for C++. If you find any difficulty then please let me know, I will provide C++ code.

Nth Fibonacci numbers in C#

using System;

namespace BasicPrograms
{
    class Fibbonacci
    {
        static void Main(string[] args)
        {
            int index = 0;
            Console.Write("Enter any location to get fibonacci no. : ");
            index = Convert.ToInt32(Console.ReadLine());
            Console.Write("Fibonacci number is : ");
            Console.Write("{0}.", GenerateFibbonacciSeries(index));
            Console.ReadLine();
        }

        private static int GenerateFibbonacciSeries(int index)
        {
            int lastNo = 0, currentNo = 1, temp = 0, i;

            //If index is 0 or 1 then return same value. 
            if (index == 0 || index == 1)
                return index;

            for (i = 0; i < index - 1; i++)
            {
                temp = lastNo;
                lastNo = currentNo;
                currentNo = temp + currentNo;
            }
            return currentNo;
        }
    }
}

Nth Fibonacci numbers in Java

package basic;

import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {
		int index = 0;
		System.out.print("Enter any location to get fibonacci no. : ");
		Scanner input = new Scanner(System.in);
		index = Integer.parseInt(input.next());
		System.out.println(String.format(
				"%d location Fibonacci number is : %d", index,
				GenerateFibbonacciSeries(index)));
	}

	private static int GenerateFibbonacciSeries(int index) {
		int lastNo = 0, currentNo = 1, temp = 0, i;

		// If index is 0 or 1 then return same value.
		if (index == 0 || index == 1)
			return index;

		for (i = 0; i < index - 1; i++) {
			temp = lastNo;
			lastNo = currentNo;
			currentNo = temp + currentNo;
		}
		return currentNo;
	}
}

First N Fibonacci numbers

Let’s have one more example where we will generate first n Fibonacci numbers. For example, first 10 or 5 fibonacci numbers. For this purpose we will reuse the above GenerateFibbonacciSeries method or function in our program. IF you compare this program with first one then you will find only one difference in this program. In “Main()” method we have one for loop which loops depending on value entered by user. In loop body we are passing value of i to GenerateFibbonacciSeries method or function and showing the value returned by method or function. Logically it will pass values from 0 to index and will show the output.

Fibonacci series in C

#include "stdio.h"
#include "conio.h"

int GenerateFibbonacciSeries(int index);
int main() {
	int index = 0, i;
	clrscr();
	printf("How many fibonacci numbers? : ");
	scanf("%d", &index);
	printf("\n\nFibonacci number are : ");

	for (i = 0; i < index; i++) {
		printf("%d, ", GenerateFibbonacciSeries(i));
	}
	getch();
	return 0;
}
int GenerateFibbonacciSeries(int index) {
	int lastNo = 0, currentNo = 1, temp = 0, i;

	//If index is 0 or 1 then return same value.
	if (index == 0 || index == 1)
		return index;

	for (i = 0; i < index - 1; i++) {
		temp = lastNo;
		lastNo = currentNo;
		currentNo = temp + currentNo;
	}
	return currentNo;
}

Fibonacci series in C#

using System;

namespace BasicPrograms
{
    class FibbonacciN
    {
        static void Main(string[] args)
        {
            int index = 0;
            Console.Write("How many fibonacci numbers? : ");
            index = Convert.ToInt32(Console.ReadLine());
            Console.Write("Fibonacci numbers are : ");
            for (int i = 0; i < index; i++)
            {
                Console.Write("{0}, ", GenerateFibbonacciSeries(i));
            }

            Console.ReadLine(); // holds output sceen till you hit Return/Enter key.
        }

        private static int GenerateFibbonacciSeries(int index)
        {
            int lastNo = 0, currentNo = 1, temp = 0, i;

            //If index is 0 or 1 then return same value. 
            if (index == 0 || index == 1)
                return index;

            for (i = 0; i < index - 1; i++)
            {
                temp = lastNo;
                lastNo = currentNo;
                currentNo = temp + currentNo;
            }
            return currentNo;
        }
    }
}

Fibonacci series in Java

package basic;

import java.util.Scanner;

public class FibonacciN {
	public static void main(String[] args) {
		int index = 0, i;
		System.out.print("How many fibonacci numbers? : ");
		Scanner input = new Scanner(System.in);
		index = Integer.parseInt(input.next());

		System.out.println("Fibonacci numbers are : ");
		for (i = 0; i < index; i++) {
			System.out
					.print(String.format("%d, ", GenerateFibbonacciSeries(i)));
		}
	}

	private static int GenerateFibbonacciSeries(int index) {
		int lastNo = 0, currentNo = 1, temp = 0, i;
		
		// If index is 0 or 1 then return same value.
		if (index == 0 || index == 1)
			return index;

		for (i = 0; i < index - 1; i++) {
			temp = lastNo;
			lastNo = currentNo;
			currentNo = temp + currentNo;
		}
		return currentNo;
	}
}

Fibonacci series using recursion

In this section we will generate Fibonacci number using recursion; if you are new to recursion then you can learn more about it here. To incorporate recursion logic we need to modify GenerateFibbonacciSeries method or function. But don’t worry it’s going to be very minor changes.

Recursive Fibonacci in C

#include "stdio.h"
#include "conio.h"

int GenerateFibbonacciSeries(int index);
int main() {
	int index = 0;
	clrscr();
	printf("Enter any location to get fiboncci no. : ");
	scanf("%d", &index);
	printf("\n\nFibonacci numbers at given position is : %d.", 
			GenerateFibbonacciSeries(index));
	getch();
	return 0;
}
int GenerateFibbonacciSeries(int index) {
	if (index == 0 || index == 1)
	                return index;

	return GenerateFibbonacciSeries(index - 1) + GenerateFibbonacciSeries(
			index - 2);
}

Recursive Fibonacci in C#

using System;

namespace BasicPrograms
{
    class RecursiveFibbonacci
    {
        static void Main(string[] args)
        {
            int count = 0;
            Console.Write("Enter any location to get fibonacci no. : ");
            count = Convert.ToInt32(Console.ReadLine());
            Console.Write("Fibonacci numbers at given position is : {0}.",GenerateFibbonacciSeries(count));
            Console.ReadLine();
        }

        private static int GenerateFibbonacciSeries(int index)
        {
            if (index == 0 || index == 1)
                return index;

            return GenerateFibbonacciSeries(index - 1) + GenerateFibbonacciSeries(index - 2);
        }
    }
}

Recursive Fibonacci in Java

package basic;

import java.util.Scanner;

public class RecursiveFibonacci {

	public static void main(String[] args) {
		int count = 0;
		System.out.print("Enter any location to get fiboncci no. : ");
		Scanner input = new Scanner(System.in);
		count = Integer.parseInt(input.next());

		System.out.print(String.format(
				"Fibonacci numbers at given position is : %d.",
				GenerateFibbonacciSeries(count)));
	}

	private static int GenerateFibbonacciSeries(int index) {
		// If index is 0 or 1 then return same value.
		if (index == 0 || index == 1)
			return index;

		return GenerateFibbonacciSeries(index - 1)
				+ GenerateFibbonacciSeries(index - 2);
	}
}

You can modify above code to generate Fibonacci number up to N numbers using recursion. I hope this tutorial helped to learn the concept of Fibonacci number series. Thank you, keep visiting.

Fibonacci number logic

Did this tutorial help you understand Fibonacci number concept?

See results

© 2012 RAJKISHOR SAHU

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)