Want t find all indices of a number using C++ programming language. Use following program to read the data from a properties file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <bits/stdc++.h> using namespace std; int AllIndexesRecursive(int input[], int size, int x, int output[]) { // If an empty array comes // to the function, then // return zero if (size == 0) { return 0; } // Getting the recursive answer int smallAns = AllIndexesRecursive(input + 1, size - 1, x, output); // If the element at index 0 is equal // to x then add 1 to the array values // and shift them right by 1 step if (input[0] == x) { for (int i = smallAns - 1; i >= 0; i--) { output[i + 1] = output[i] + 1; } // Put the start index in front // of the array output[0] = 0; smallAns++; } else { // If the element at index 0 is not equal // to x then add 1 to the array values for (int i = smallAns - 1; i >= 0; i--) { output[i] = output[i] + 1; } } return smallAns; } // Function to find all indices of a number void AllIndexes(int input[], int n, int x) { int output[n]; int size = AllIndexesRecursive(input, n, x, output); for (int i = 0; i < size; i++) { cout << output[i] << " "; } } // Driver Code int main() { int arr[] = { 1, 2, 3, 2, 2, 5 }, x = 2; int n = sizeof(arr) / sizeof(arr[0]); // Function call AllIndexes(arr, n, x); return 0; } |
Program Output
1 | 1 3 4 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.