Data Structures Practical 18

Question 1
Implement a C program to print Fibonacci series using recursion
fibonacci.c
C
				#include <stdio.h>
#include <conio.h>

int fibonacci(int n);

void main() 
{
    int terms, i;
    clrscr();

    printf("Enter the number of terms for Fibonacci series: ");
    scanf("%d", &terms);

    if (terms <= 0) 
    {
        printf("\nPlease enter a positive integer greater than 0.\n");
    } 
    else 
    {
        printf("\nThe Fibonacci Series is:\n");
        for (i = 0; i < terms; i++) 
        {
            printf("%d\t", fibonacci(i));
        }
        printf("\n");
    }

    getch();
}

int fibonacci(int n) 
{
    if (n == 0) 
    {
        return 0;
    }
    else if (n == 1) 
    {
        return 1;
    }
    else 
    {
        return (fibonacci(n - 1) + fibonacci(n - 2));
    }
}

			
Output
Question 2
Write a program in C to calculate the sum of numbers from 1 to n using recursion.
sum.c
C
				#include <stdio.h>
#include <conio.h>

int calculateSum(int n);

void main() 
{
    int n, sum;
    clrscr();

    printf("Enter a positive integer (n): ");
    scanf("%d", &n);

    if (n < 1) 
    {
        printf("\nPlease enter a positive integer greater than or equal to 1.\n");
    } 
    else 
    {
        sum = calculateSum(n);
        printf("\nThe sum of numbers from 1 to %d is: %d\n", n, sum);
    }

    getch();
}

int calculateSum(int n) 
{
    if (n == 1) 
    {
        return 1;
    }
    else 
    {
        return (n + calculateSum(n - 1));
    }
}

			
Output

Leave a Comment

Your email address will not be published. Required fields are marked *