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 a list of integers in to an array with base type i

ID: 3878799 • Letter: W

Question

Write a program that reads in a list of integers in to an array with base type int . Read this array from the input file, called infile.txt . (The program should read in the data into an array calle d, numbers [ ], which can store all data from the input file.) You may as sume that there are fewer than 20 entries in the array. Your program de termines how many entries there are. The output is to be a two-column list. The first column is a list of the distinct array elements; the secon d column is the count of the number of occurrences of each element. The list should be sorted on entries in the first column, largest to smallest. USE only function calls in the main program. (Only minimum implementation will be allowed in the main program.) (C++)

Explanation / Answer

Dear Student,

Please find the following code. This may work in any compiler.

#include<iostream>

#include<fstream>

#include<stdlib.h>

int count = 0; //For maintaining no. of elements

using namespace std;

void read_Elements(int []);

void sort_Array(int []);

void display_Array(int []);

int main()

{

int arr[20]={0}; //Initializing all elements to dummy values

read_Elements(arr);

sort_Array(arr);

display_Array(arr);

}

void read_Elements(int a[])

{

ifstream fin("infile.txt"); //opening file in read mode

char str[80];

int num,i = 0;

if(!fin.is_open()) //Checking for file opening

{

cout<<"File Cannot open ";

return ;

}

while(fin.getline(str, 80) != 0) //taking one line at a time

{

num = atoi(str); //converting string to integer

a[i] = num; //Storing in an array

i++;

count++; //Incrementing no. of elements

}

fin.close(); //Closing the file

}

void sort_Array(int a[])

{

int i, j, temp;

for(i=0;i<count;i++)

{

for(j=0;j<count-i;j++)

{

if(a[j] < a[j+1]) //Soring array elements in descending order

{

temp = a[j];

a[j] = a[j+1];

a[j+1] = temp;

}

}

}

}

void display_Array(int a[])

{

int b[count], c[count], i=1,j=1, num, n;

b[0] = a[0];

while(i<count) //Loop for copying only unique values to b array

{

if(a[i] != a[i-1])

{

b[j] = a[i];

j++;

}

i++;

}

for(i=0;i<j;i++) //Loop for finding no. of occurnces of element

{

num = b[i];

n = 0;

for(int k = 0;k<count;k++)

{

if(num == a[k])

{

n++;

}

}

c[i] = n;

}

for(i=0;i<j;i++) //Loop for printing

{

cout<<b[i]<<" "<<c[i]<<" ";

}

}

Contents of infile.txt is

10
20
30
40
50
60
60
70
60
50
40
30
20
10

OUTPUT:

70 1

60 3

50 2

40 2

30 2

20 2

10 2

Hoping you understand. In case of any doubts comment below.

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