# Construct a frequency array of digits of the values obtained from x^1, x^2, ....., x^n in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have two integers x and n. We have to find the array such that it contains the frequency of index numbers occurring in (x^1, x^2,… x^(n – 1), x^n). So if x = 15 and n = 3, then output will be [0, 1, 2, 2, 0, 3, 0, 1, 0, 0]. As we know that x^1 to x^n, the values are 15, 225 and 3375. So the frequency array is 0, 1, 2, 2, 0, 3, 0, 1, 0, 0

To solve this, we will follow these steps −

• Maintain the frequency count array to store the counts of digits 0 to 9.

• Traverse through each digit of x^1 to x^n. For each digit add 1 to corresponding index in frequency count array

• Display the array.

## Example

Live Demo

#include <iostream>
#include <cmath>
using namespace std;
void digitCount(double val, long arr[]) {
while ((long)val > 0) {
long digit = (long)val % 10;
arr[(int)digit]++;
val = (long)val / 10;
}
}
void generateFreqArray(int x, int n) {
long freq_count={0};
for (int i = 1; i <= n; i++){
double val = pow((double)x, (double)i);
digitCount(val, freq_count);
}
cout << "[";
for (int i = 0; i <= 9; i++){
cout << freq_count[i] << " ";
}
cout << "\b]";
}
int main() {
int x = 15, n = 3;
cout << "The frequency array is: ";
generateFreqArray(x, n);
}

## Output

The frequency array is: [0 1 2 2 0 3 0 1 0 0]