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++) { ...

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

๐ŸŒ™