Factorial_and_Fibonacci_Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Factorial and Fibonacci Programs in C

Factorial Program Using Recursion

#include <stdio.h>

// Function to calculate factorial using recursion

unsigned long long factorial(int n) {

if (n == 0 || n == 1)

return 1; // Base case: factorial of 0 or 1 is 1

else

return n * factorial(n - 1); // Recursive case

int main() {

int num;

unsigned long long result;

printf("Enter a number to calculate its factorial: ");

scanf("%d", &num);

if (num < 0) {

printf("Factorial is not defined for negative numbers.\n");

} else {

result = factorial(num);

printf("Factorial of %d is %llu\n", num, result);


}

return 0;

Fibonacci Series Program Using Recursion

#include <stdio.h>

// Function to calculate the nth Fibonacci number using recursion

int fibonacci(int n) {

if (n == 0)

return 0; // Base case: 0th Fibonacci number

else if (n == 1)

return 1; // Base case: 1st Fibonacci number

else

return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case

int main() {

int terms, i;

printf("Enter the number of terms in the Fibonacci series: ");

scanf("%d", &terms);

printf("Fibonacci series:\n");
for (i = 0; i < terms; i++) {

printf("%d ", fibonacci(i));

printf("\n");

return 0;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy