Skip to content

Commit d2df03f

Browse files
authored
Added all indices of an element in array.
1 parent 791807e commit d2df03f

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Recursion/All_indices_of_element.cpp

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// CPP program to find all indices of a number
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
// A recursive function to find all indices of a number in array.
5+
6+
int allIndexes(int input[], int size,
7+
int x, int output[])
8+
{
9+
10+
// If size of array is 0 then return 0
11+
12+
if (size == 0) {
13+
return 0;
14+
}
15+
16+
// recursion
17+
18+
int smallAns = allIndexes(input + 1,size - 1, x, output);
19+
20+
21+
// If the element at first index is equal to x then add 1 to the array values and shift them right by 1 step
22+
23+
if (input[0] == x) {
24+
for (int i = smallAns - 1; i >= 0; i--) {
25+
output[i + 1] = output[i] + 1;
26+
}
27+
// Put the start index in front
28+
29+
// of the array
30+
31+
output[0] = 0;
32+
33+
smallAns++;
34+
35+
}
36+
37+
else {
38+
39+
// If the element at index 0 is not equal to x then add 1 to the array values and no need to shift array.
40+
for (int i = smallAns - 1; i >= 0; i--) {
41+
42+
output[i] = output[i] + 1;
43+
}
44+
}
45+
return smallAns;
46+
}
47+
48+
// Function to find all indices of a number
49+
50+
void AllIndexes(int input[], int n, int x)
51+
{
52+
53+
int output[n];
54+
55+
int size = allIndexes(input, n, x, output);
56+
57+
for (int i = 0; i < size; i++) {
58+
59+
cout << output[i] << " ";
60+
61+
}
62+
}
63+
64+
// Driver Code
65+
66+
int main()
67+
{
68+
int n,arr[1000],x;
69+
cin>>n;
70+
for(int i=0;i<n;i++){
71+
cin>>arr[i];
72+
}
73+
cin>>x;
74+
75+
76+
77+
// Function call
78+
79+
AllIndexes(arr, n, x);
80+
81+
82+
83+
return 0;
84+
}

0 commit comments

Comments
 (0)