The exercise says:
Given a sorted array of elements and two elements a and b, with a<=b, print an array with all the elements between a and b.
Example:
INPUT
[1,3,6,8,70]
a=2
b=8
OUTPUT
[3,6]
I did the code but I think there's a problem with the element b:
#include <iostream>
usingnamespace std;
int main () {
//Initialization:
constint N = 5;
int vec1[N] = {1, 3, 6, 8, 70};
int a = 2, b = 8;
int vec2[N];
int pos1 = 0, pos2 = 0;
//Procedure:
for (int i = 0; i<N; i++) { //Finding position of a.
if(a < vec1[i]) {
pos1 = i;
break;
}
}
for (int i = 0; i<N; i++) { //Finding position of b.
if(b < vec1[i]) {
pos2 = i;
break;
}
}
int temp = pos1;
for (int i = 0; temp<=pos2; i++, temp++) {
vec2[i] = vec1[temp];
}
//Output:
//cout<<pos1<<"\n"<<pos2<<"\n";
cout<<"[";
for (int i = 0; i<pos2; i++) {
cout<<vec2[i]<<" ";
}
cout<<"]";
//Termination:
return 0;
}
It takes all the elements from a to the last one and I don't know why. The code seems okay to me. What did I do wrong?