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

Problem 3. Dynamic Memory Allocation (10 points) Re-do Problem 2, but this time

ID: 3835176 • Letter: P

Question

Problem 3. Dynamic Memory Allocation (10 points) Re-do Problem 2, but this time you cannot assume an array size of 20. Instead ask the user for the size of the array and using dynamic memory allocation, create an array of the appropriate size. Assume that the user knows the exact of the array the program will need to process. HINT: This is the same as dynamic memory allocation that we saw in Chapter 9. Remember, what we use in dynamic memory allocation--a data type, a corresponding pointer, and an array size. Think what should be the data type and array size for your program.

Explanation / Answer

/* Assuming a file contains employee information. Each line is id name salary.

#include<iostream.h>
#include<string>

struct Employee {
public:
    int id;
    string name;
    int salary;
};


void main(){
   int size;
   int i,j;
   Employee temp;

   cout << "Enter size" << endl;
   cin >> size;    //Assuming user has enetred 20
   Employee *array = new Employee[size];
  
   ifstream infile;

   infile.open("Input.txt");
   index = 0;
   while (infile >> array[index].id >> array[index].name >> array[index].salary){
       index++;
       if (index == size)
          break;
   }
   infile.close();
   /* Sorting as per salary */

   for ( i = 0; i<size; ++i){
      for (j=0; j<size - i - 1; ++j){
          if (array[j].salary > array[j+1].salary){
                 temp = array[j];
                 array[j] = array[j+1];
                 array[j+1] = temp;             
          }
      }
   }
}

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