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;
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;
}``````

## Recommended Answers

``````// ...
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" << " ";``````

This fragment finds the last occurrence if …

## All 2 Replies

How about setting up a reverse loop starting at the end of the array and looking for the first instance that you come across? You could also add a check to report if that instance is the same as the the first instance of the int.

``````// ...
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" << " ";``````

This fragment finds the last occurrence if any.

To locate the first occurrence, you need to break out of the loop once k has been found.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.