Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

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

🌙