Skip to main content

Featured

C Program to Solve Two Sum Using Brute Force (With Algorithm & Output)

 Introduction The Two Sum problem is a popular coding interview question where we must find two indices of an array whose values add up to a given target. This program demonstrates a simple brute-force solution in C using nested loops and dynamic memory allocation. Problem Statement Given an integer array and a target value, return the indices of the two numbers such that they add up to the target. Each input has exactly one solution, and the same element cannot be used twice. The result should return the indices, not the values. If no solution exists, return NULL.  Algorithm / Logic Explanation Start the program. Traverse the array using a loop from index 0 to numsSize - 1 . Inside this loop, use another loop starting from i + 1 to numsSize - 1 . For every pair (i, j) , check if nums[i] + nums[j] == target . If condition becomes true: Allocate memory for 2 integers using malloc() . Store indices i and j . Set returnSize = 2 . Return the result poi...

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

🌙