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...

Factorial Calculation Using Recursion in C

Factorial Using Recursion in C

Factorial Calculation Using Recursion in C

This C program calculates the factorial of a given positive integer using a recursive function. The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n.

✅ C Program Code:


#include <stdio.h>

int fact(int n)
{       
    if (n == 0 || n == 1)
    {
        return 1;
    }
    else
    {
        return n * fact(n - 1);
    }
}

int main()
{
    int num;
    printf("Enter the number that you want to find factorial:\n");
    scanf("%d", &num);
    if (num < 0)
    {
        printf("Factorial number contain only positive:\n");
    }
    else
    {
        printf("Factorial of a given number %d is %d\n", num, fact(num));
    }
}
  
  
  

๐Ÿ“Œ How It Works:

  • fact(): This is the recursive function that calculates factorial. It returns 1 if n is 0 or 1 (base case). Otherwise, it multiplies n by the factorial of n-1.
  • main(): Takes user input for the number and checks if it is negative. If negative, it prints an error message. Otherwise, it calls fact() to calculate factorial and prints the result.

๐Ÿ’ป Sample Output:

enter the number that you want to find factorial:
5
Factorial of a given number 5 is 120

๐Ÿ” Keywords:

factorial in C, recursive factorial program, factorial using recursion, C programming recursion example, factorial function in C, beginner C programs, recursion in C, factorial calculation

Comments

Popular Posts

๐ŸŒ™