Array exercise

closed account (LE8Cko23)
.
Last edited on
But is not finished? I ran it and i thing that is okay, can you be more explicit than the problem with the code?

I did this, but the code have a problem, i already not know what is the error...

I will post the code if it's serves for something:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;

int main(){

int list1[10], list2[10], number, i;

cout << "Array #1 - Array #2" << endl;

srand(time(0));

for (i=0; i<10; i++){
list1[i] = 5 + rand()% 20;
list2[i] = 5 + rand()% 20;
cout << setw(8) << list1[i] << setw(10) << list2[i] << endl;
}

cout << "Enter a number: ";
cin >> number;

if(number == list1[i] || number == list2[i]){
if(number == list1[i] && number != list2[i]){
for(i = 0; i < 10; i++){
cout << "The " << number << " number was found in array 1" << endl;
cout << "Location of " << number << " in array 1 is: "<< i << endl;
}
}
else{
for(i = 0; i < 10; i++){
cout << "The " << number << " number was found in array 2" << endl;
cout << "Location of " << number << " in array 2 is: "<< i << endl;
}
}
}
else{
if(number == list1[i] && number == list2[i]){
for(i = 0; i < 10; i++){
cout << "The " << number << " number was found in both arrays" << endl;
cout << "Location of " << number << " in array 1 is: " << i << endl;
cout << "Location of " << number << " in array 2 is: " << i << endl;
}
}
else if(number != list1[i] && number != list2[i]){
cout << "The " << number << " number was not found in any array!" << endl;
}
}

cout << endl;
return 0;
}
Last edited on
closed account (LE8Cko23)
My problem is that I'm not being able to get the last occurrence if the number is repeated more than once in an array,
and another problem is when there's a number that is in both arrays my output is not:
n was found in both arrays
Location of n in Array #1: location (last occurrence)
Location of n in Array #2: location (last occurrence)
My output is:
n was found in 1 array
Location of n in Array #1: location (last occurrence)
n was found in 1 array
Location of n in Array #2: location (last occurrence)
Last edited on
> I'm not being able to get the last occurrence
That's because you are too eager to print to screen.
Also, there is no need to do it all at once, traverse each array separately.
1
2
3
4
5
int found1 = -1;
for(int K=0; K<n; ++K)
   if(list1[K] == number)
      found1 = number;
//similar for list2 
Then you simply check the value of found{1,2} to see if they were found and where.
Topic archived. No new replies allowed.