C++ program to find the first digit in product of an array of numbers

C++Server Side ProgrammingProgramming

In this article, we will be discussing a program to find the first digit in the product of the elements of the given array.

For example, let us say we have been given an array.

arr = {12, 5, 16}

Then the product is of these elements would be 12*5*16 = 960. Therefore, the result i.e the first digit of the product in this case would be 9.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int calc_1digit(int arr[], int x) {
   long long int prod = 1;
   for(int i = 0;i < x; i++) {
      prod = prod*arr[i];
   }
   while (prod >= 10)
      prod = prod / 10;
   return prod;
}
int main() {
   int arr[]={12,43,32,54};
   cout <<"The first digit will be: " << calc_1digit(arr,4)<< endl;
}

Output

The first digit will be: 8
raja
Published on 03-Oct-2019 11:59:36
Advertisements