Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads in non-negative integers and stores and displays dist

ID: 3767443 • Letter: W

Question

Write a program that reads in non-negative integers and stores and displays distinct numbers (i.e., if a number appears multiple times, it is stored and displayed only once). Your program should allow up to 1000 distinct numbers to be stored and displayed. Use the following algorithm (this is required!): Read each number and store it in an array if it is new. If the number is already in the array, ignore it. The user will indicate that they are done entering numbers by entering a negative number. Here is a sample run:

To get credit for this assignment you must use appropriate decomposition! You should have a function to read the numbers and a function to print the resulting array. The function that reads the numbers should call an additional function that returns a bool value indicating whether a number is already in the array. At the conclusion of the call to the function that reads the numbers, the array MUST contain only distinct numbers.

Additionally, you must not sort the array. The numbers must appear in the same order in which they were typed.

Explanation / Answer

#include <iostream>

using namespace std;

#define MAX 1005

bool already_present(int data[MAX], int input, int size)
{
   int i;
   for(i=0;i<size;i++)
       if(data[i] == input)
           return true;
   return false;
}

int read_stdin(int data[MAX])
{
   int input;
   int size=0;
   while(true)
   {
       cout<<"Enter a non-negative integer (negative to quit): ";
       cin>>input;
       if(input<0)
           break;

       if(!already_present(data,input,size))
           data[size++] = input;
   }
   return size;
}

void print_stdout(int data[MAX],int size)
{
   int i;
   cout<<"You entered ";
   for(i=0;i<size;i++)
       cout<<data[i]<<" ";

   cout<<endl;
}

int main()
{
   int data[MAX],size;
   size = read_stdin(data);
   print_stdout(data,size);
   return 1;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote