Sum of factorial of positive and single digit numbers in an array
Write a java program to find the sum of factorial of the numbers in an array. Consider the number for finding the factorial only if it is positive and single digit. If not print "No positive and single digit numbers found in an array".
Example if the array is {2,-7,14,-24,41,5} the output should be 122
Answers
Answered by
1
Program in C++:
#include<iostream>
using namespace std;
int factorial(int n)
{
int f = 1;
for(int i = 1; i <= n; i++)
{
f = f * i;
}
return f;
}
int main()
{
int n;
cout<<"Enter number of elements in the array : ";
cin>>n;
int A[n];
cout<<"Enter elements in the array : "<<endl;
for(int i = 0; i < n; i++)
{
cin>>A[i];
}
int sum = 0;
for(int i = 0; i < n; i++)
{
if(A[i] >= 0 && A[i] <= 9)
{
sum = sum + factorial(A[i]);
}
}
cout<<"Sum = "<<sum;
return 0;
}
Output:
Enter number of elements in the array : 6
Enter elements in the array :
2
-7
14
-24
41
5
Sum = 122
Similar questions