Skip to main content

Featured

C Program to Check Prime Number Using Efficient Logic

  Introduction A prime number is a number that has exactly two distinct positive divisors: 1 and itself. In this program, we check whether a given number is prime or not using a simple and efficient logic. This type of program is commonly used in mathematics, competitive programming, and basic algorithm learning for beginners in C programming. Problem Statement The task is to write a C program that determines whether a given integer is a prime number or not. The program takes a single integer input from the user and analyzes its divisibility. If the number has no divisors other than 1 and itself, it should be identified as a prime number; otherwise, it is not prime. This problem is important in number theory and has practical relevance in areas such as cryptography, data validation, and algorithm design.  Algorithm / Logic Explanation To check whether a number is prime, we need to verify that it is not divisible by any number other than 1 and itself. The algorithm follows a si...

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

๐ŸŒ™