Implement a function in C++ to compute factorial of a integer number

All QuestionsCategory: Cpp LanguageImplement a function in C++ to compute factorial of a integer number
Anonymous asked 3 years ago

# Implement a function in C++ to compute factorial of a integer number.
* The function should return -1 for negative numbers.
* Factorial of a number if a positive number.
* Do not add any additional prints in the code

# Sample input:
4
1
2
-1
0

# Explaination:
    * First line is the number of inputs.
    * Next lines are the integers to which the factorial needs to be found
   
# Sample output:
1
2
-1
1

# Explaination:
    * Factorial of 1 is 1
    * Factorial of 2 is 4
    * Factorial of -1 is -1
    * Factorial of 0 is 1

1 Answers
Anonymous answered 3 years ago

Here is the code:
 

#include<iostream>
using namespace std;

int main(){
    int n,i;
    cin>>n;
    int arr[n];
    for(i=0;i<n;i++){
        cin>>arr[i];
    }
    for(i=0;i<n;i++){
        if(arr[i]<0){
            arr[i]=-1;
        }
        else if (arr[i]==0)
        {
            arr[i]=1;
        }
        else
        {
            int f=1,j;
            for(j=1;j<=arr[i];j++){
                f*=j;
            }
            arr[i]=f;
        }
    }
    for(i=0;i<n;i++){
        cout<<arr[i]<<endl;
    }
    return 0;
}