Showing posts with label Fibonacci. Show all posts
Showing posts with label Fibonacci. Show all posts

C Program To Returns the nth element of the Fibonacci sequence.

How to write a C Program To Returns the nth element of the Fibonacci sequence in C Programming Language ?


Solution For C Program :

/*C Program To Returns the nth element of the Fibonacci sequence.*/

#include <stdio.h>

/**
 * Returns the nth element of the Fibonacci sequence.
 */
int fibRecursive(unsigned int n)
{
// There is no 0th element of the Fibonacci sequence.
if (n == 0) return -1;

// Base case: 1st or 2nd elements.
if (n == 1 || n == 2) return 1;

// Otherwise, return the sum of the (n-1)th and (n-2)th elements.
return fibRecursive(n - 1) + fibRecursive(n - 2);
}

int main()
{
printf("The fibonacci sequence is:\n");
for (unsigned int n = 1; n < 20; ++n) {
printf("%d\n", fibRecursive(n));
}
printf("...\n");
return 0;
}

C Program To Generating Fibonacci Series Using Recursion

How to write a C Program To Generating Fibonacci Series Using Recursion in C Programming Language ?

Solution For C Program :

/*C Program To Generating Fibonocci Series Using Recursion.*/

#include<stdio.h>
void main()
{
int a, b, j;
int fib(int);
printf("\nEnter N'th Number : "); scanf("%d", &a);
printf("\nPrinting Values of the Fibonacci Series :\n");
for(j = 0; j < a - 1; j++)
{
b = fib(j);
printf("%d,", b);
}
}
int fib(int n)
{
int x, y;
if(n == 0 || n == 1) return (1);
else
{
x = fib(n - 1);
y = fib(n - 2); return(x + y);
}
}

You may also learn these C Program/Code :

C Program To Swap Two Numbers Without Using Third Variable

C -Programm Fibonacci Folge Rekursiv

Wie man ein C -Programm Fibonacci Folge Rekursiv in der Programmiersprache C geschrieben?


Das C-Programm Sie die Fibonacci- Reihe rekursive Zahl bis n-te Nummer finden

Solution:

  1. int fib(int n) {
  2.     int i = 0; //Zählvariable
  3.     int a = 0; //Fibonacci Zahl an (i)-ter Stelle
  4.     int b = 1; //Fibonacci Zahl an (i+1)-ter Stelle
  5.     while (i<n) {
  6.         i++;
  7.         a = a^b; b = a^b; a = a^b;
  8.         b = a+b;
  9.     };
  10.     return a;
  11. }
  12.  
  13. int fib_rec(int n) {
  14.     if (== 0) return 0;
  15.     if (== 1) return 1;
  16.     return fib_rec(n-1)+fib_rec(n-2);
  17. }
  18.  
  19. int main(void) {
  20.     int n = 0; //Zielstelle
  21.     printf("\nGib ein n ein: ");
  22.     scanf("\n%i",&n);
  23.     printf("Die Fibonacci Zahl an n-ter Stelle ist %i \n", fib(n));
  24.     return 0;
  25. }

C -Programm Fibonacci-Folge

Wie man ein C -Programm Fibonacci-Folge in der Programmiersprache C geschrieben?


Das C -Programm finden Sie die Fibonacci-Zahl bis n-te Nummer