In: Computer Science
Write a C++ program that declares three one-dimensional arrays named miles, gallons and mpg. Each array should be capable of holding 10 elements. In the miles array, store the numbers 240.5, 300.0 189.6, 310.6, 280.7, 216.9, 199.4, 160.3, 177.4 and 192.3. In the gallons array, store the numbers 10.3, 15,6, 8.7, 14, 16.3, 15.7, 14.9, 10.7 , 8.3 and 8.4. Each element of the mpg array should be calculated as the corresponding element of the miles array divided by the equivalent element of the gallons array: for example mpg[0]=miles[0]/gallons[0]. Use pointers when calculating and displaying the elements of the mpg array. |
CODE with proper comments :
#include<iostream>
using namespace std;
int main() {
//declaring miles array of 10 float elements
float miles[10];
//assigning values to miles array
miles[0] = 240.5;
miles[1] = 300.0;
miles[2] = 189.6;
miles[3] = 310.6;
miles[4] = 280.7;
miles[5] = 216.9;
miles[6] = 199.4;
miles[7] = 160.3;
miles[8] = 177.4;
miles[9] = 192.3;
//declaring gallons array of 10 float elements
float gallons[10];
//assigning values to gallons array
gallons[0] = 10.3;
gallons[1] = 15.6;
gallons[2] = 8.7;
gallons[3] = 14;
gallons[4] = 16.3;
gallons[5] = 15.7;
gallons[6] = 14.9;
gallons[7] = 10.7;
gallons[8] = 8.3;
gallons[9] = 8.4;
float mpg[10]; //declaring mpg array of 10 elements
//assigning values to mpg using pointer (array of acts as a pointer
in c++)
for(int i=0; i<10; i++){
*(mpg + i) = miles[i] / gallons[i];
}
//printing the values of mpg using pointer
for(int i=0; i<10; i++){
cout << "mpg[" << i << "] : " << *(mpg + i)
<< endl;
}
}
SCREENSHOTS :
1. Program (1 of 2)
2. Program (2 of 2)
3. Result/Output (1 of 1)