Write a program to find Factorial of a number

28 September 2022

Write a program to find Factorial of a number


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get a number from user for which you need to fin the factorial, then calculate the factorial and give it as the output.

Input

4

Output

24

C Program

#include <stdio.h>

int main ()

{

    int num;

    long fact = 1;

    printf("Enter a number: ");

    scanf("%d",&num);

    if(num < 0)

        printf("Invalid Input");

    else

    {

        for(int i = 1; i <= num; i++)

            fact = fact * i;

    }    

    printf("Factorial is: %ld",fact);

}

C++ Program

#include<iostream>

using namespace std;

int main ()

{

    int num;

    long fact = 1;

    cout<<"Enter a number: ";

    cin>>num;

    if(num < 0)

        cout<<"Invalid Input";

    else

    {

        for(int i = 1; i <= num; i++)

            fact = fact * i;

    }

    

    cout<<"Factorial is: "<<fact;

}

Java 

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter an Integer: ");

int num = sc.nextInt();

int fact = 1;

if(num < 0)

        System.out.println("Invalid Input");

    else

    {

        for(int i = 1; i <= num; i++)

            fact = fact * i;

System.out.print("Factorial is "+fact);

}

 

}

}

Python

num= int(input("Enter a number "))

fact=1 

if (num<0):

    print("Invalid input")

else:

    for i in range(1,num+1):

        fact=fact*i

    print("Factorial is ",fact)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !