0

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

Edited by Narue: added code tags

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by vijayan121
0

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.

0
// ...
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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.