I got this assignment and the way it is worded is confusing to me. If anyone can explain it better it would be a great help also how to approach the problem

Use a one dimensional array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print it only if it is not a duplicate of a number already read. Provide for the “worst case” in which all 20 numbers are different. Use the smallest possible array to solve this problem.

Should I use an array of 20 and what does it mean by use the smallest possible array?

Recommended Answers

All 5 Replies

The smallest possible array size would be 19 because the last number read does not need to be placed in the array.

Ok I understand that this is what i got so far

//Alejandro Hernandez Reding 20 numbers between 10 and 100
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

int main()
{
	int num[20];
	int i;
	srand((unsigned)time(0)); 
	int random_integer;
	for(i=0;i<20;i++)
	{random_integer=(rand()%90+10);
	num[i]=random_integer;}


cin.get();
return 0;
}

But I'm not sure on what to use for the logic to find duplicate numbers.

before adding the new number to the array you need to search the array to see if its already there. A simple for loop will suffice.

Would an if and else-if statement work as well??

Would an if and else-if statement work as well??

No because you need a loop to look at all the items in the array. You will need an if statement inside the loop. Something like this:

int j;
bool found = false;
for(j = 0; j < i; j++)
{
   if( array[j] == random_integer)
   {
         found = true;
         break;
   }
}
if( found == false)
{
    // add new item to the array
}
Be a part of the DaniWeb community

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