A. Write program in C++ (Print distinct numbers, file input, test eof, array, li
ID: 3686584 • Letter: A
Question
A. Write program in C++
(Print distinct numbers, file input, test eof, array, linear search)
Write a program that reads in up to 100 integer numbers from file, and displays distinct numbers (i.e. if a number appears multiple times, it is displayed only once.)
[Hint:
1. Read a number and store it to an array if it is new. Otherwise, discard it.
2. The array can be defined with the maximum size 100.
3. But, it may not be full. So, you need a count to record the actual number of digits stored in the array.
4. After the input, the array contains distinct numbers.
]
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
//function to search, whether a key is present or not
bool search(int arr[], int n, int key);
int main(){
//openiong file
char fileName[20];
cout<<"Enter input filename: ";
cin>>fileName;
ifstream read(fileName);
// creating array
int arr[100];
int count = 0;
int num;
while(!read.eof()){ // read one by one
read>>num;
if(!search(arr,count,num)) // if not in array, then add
arr[count++] = num;
}
//printing
for(int i=0; i<count; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
bool search(int arr[], int n, int key){
for(int i=n-1; i>=0; i--)
if(arr[i]==key)
return true;
return false;
}
/*
input file:
numbers.txt
12 34 5 6 8 9 12 15 16 20 23
25 6 9 16 12
Output:
Enter input filename: numbers.txt
12 34 5 6 8 9 15 16 20 23 25
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.