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

Write a program that calculates the distance a car travels based on the time and

ID: 3807770 • Letter: W

Question

Write a program that calculates the distance a car travels based on the time and speed provided in a file. This program should use the parallel arrays in the main function provided and follow the specifications a-d below. const int SIZE = 5; int main () { int time[SIZE] ; int speed [SIZE]; int distance [SIZE]; load_arrays (time, speed); calculate_dist (time, speed, distance); print (time, speed, distance); : : } a) Write a function that will open an input file, gets the time and speed from a file and store them in the respective arrays. The format of the file is 2 integer values separated by a space on each line b) Write a function that will calculate the distance from the values in the time and speed arrays and place the answer in the distance array. c) Write a function that will print out the input data from a) and the calculated items from b) above (print the file data to the screen, and the calculated distance values in the format of 3 on one line.

Explanation / Answer

// C++ code
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

const int SIZE = 5;


void load_arrays(int time[], int speed[])
{
   int i = 0;
   ifstream inFile ("input.txt");
   if (inFile.is_open())
   {
   while (true)
   {
       inFile >> time[i] >> speed[i];
       i++;
       if(inFile.eof())
           break;
   }
   inFile.close();
   }

   else cout << "Unable to open file";
}

void calculate_dist (int time[], int speed[], int distance[])
{
   for (int i = 0; i < SIZE; ++i)
   {
       distance[i] = speed[i]*time[i];
   }
}

void print (int time[], int speed[], int distance[])
{
   cout << " Time Speed ";
   for (int i = 0; i < SIZE; ++i)
   {
       cout << time[i] << " " << speed[i] << endl;
   }

   cout << " Distance: ";
   for (int i = 0; i < SIZE; ++i)
   {
       if(i == 3)
           cout << endl;

       cout << distance[i] << " ";
   }
   cout << endl;
}

int main ()
{
   int time[SIZE] ;
   int speed [SIZE];
   int distance [SIZE];
   load_arrays (time, speed);
   calculate_dist (time, speed, distance);
   print (time, speed, distance);

   return 0;
}

/*
input.txt
4 5
5 6
3 4
4 5
3 4


output
Time   Speed
4   5
5   6
3   4
4   5
3   4


Distance:
20 30 12
20 12
*/

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