Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

Fibonacci Series Using Recursion in C

Fibonacci Series Using Recursion in C

Fibonacci Series Using Recursion in C

This C program prints the Fibonacci series using recursion. The Fibonacci series is a sequence where each number is the sum of the two preceding ones. It starts from 0 and 1.

✅ C Program Code:


#include <stdio.h>

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

int main()
{
    int num;
    printf("Enter the number of terms you want to print:\n");
    scanf("%d", &num);

    if(num < 0)
    {
        printf("Fibonacci series is not defined for negative numbers.\n");
        return 1; 
    }

    printf("Fibonacci series up to %d terms:\n", num);
    for(int i = 0; i < num; i++)
    {
        printf("%d ", fib(i));
    }
    printf("\n");
    return 0;
}
  

📌 How It Works:

  • fib(): Recursively returns the nth Fibonacci number.
  • Input Check: Prevents calculation for negative numbers.
  • Loop: Calls fib() from 0 to n-1 and prints the result.

💻 Sample Output:

Enter the number of terms you want to print:
6
Fibonacci series up to 6 terms:
0 1 1 2 3 5

🔍Keywords:

fibonacci series recursion in C, recursive fibonacci code, print fibonacci numbers in C, C programs for beginners, DSA recursion logic, fib function explanation

Comments

Popular Posts

🌙