In this tutorial, we are going to write a program that finds the k-th odd number from the given array.
Let's see the steps to solve the problem.
- Initialise the array and k.
- Iterate over the array.
- If the current element is odd, then decrement the value of k.
- If k is 0, then return the current element.
- Return -1.
Example
Let's see the code.
#include <bits/stdc++.h>
using namespace std;
int findKthOddNumber(int arr[], int n, int k) {
for (int i = 0; i <= n; i++) {
if (arr[i] % 2 == 1) {
k--;
}
if (k == 0) {
return arr[i];
}
}
return -1;
}
int main() {
int arr[] = { 4, 5, 22, 1, 55 }, k = 3;
cout << findKthOddNumber(arr, 5, k) << endl;
return 0;
}Output
If you run the above code, then you will get the following result.
55
Conclusion
If you have any queries in the tutorial, mention them in the comment section.