Hi i need help, what i am trying to do is that the program should search & print the first occurrence of that integer in the array and last occurrence of that integer in the array. If that integer does not exist in the array at all, then the program should print - using a random number to define the similar number. so far i am able to get the first occurrence but if there is two similar number, the second occurrence will be detected first.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
//guarantees a new random each time:
srand(time(0));
//declare the array:
int nums[10];
int i;
int j;
int temp = 0 , pos = 0;
//loop to assign the values to the array
for( i = 0; i < 10; i++)
nums[i] = rand()%25+1;
for (j =0; j < 10; j++)
cout << nums [j] << " " ;
endl(cout);
// random a number
int k;
for (k=0; k < 10; k ++)
k = rand ()%25+1;
cout << k <<" ";
endl(cout);
for (i=0; i<10; i++)
{
if (nums[i]== k)
{
temp=1;
pos=i;
}
}
if (temp==1)
cout << "first occurrence : " << pos << " ";
else
cout << "first occurrence : " << "-1" << " ";
endl(cout);
return 0;
}