Header Ads

You need to write a C++ program that has

When an object falls
because of gravity, the following formula can be used to determine the distance
the object falls in a specific time period:



` d = 1/2 gt^2`                                                                   



Where d is the distance in
meters, g
 is 9.8(constant of gravity) and t is the amount of time, in seconds, that the
object has taken to fall.



You need to write a C++ program that
has:



1.      A
function fallingDistance which:



v  Accepts
an object’s falling time (in seconds) as an argument.



v  Calculates
the distance, in meters, that the object has fallen in that time.



v  Returns
this calculated distance.



2.      In
the main() function there is a:



Ø  A
loop struct in which:



v  the
function fallingDistance is called passing data given in the table.



v  Sum
of all these distances is calculated.



Ø  Average
distance is calculated and displayed.



3.      Following
is the time data:























Time(seconds)



1



3



5



7



9




 



4.      You
can use any of the loop structs like…for-loop, while or do-while loop.



5.      The
formula to calculate average is:



              Average = (sum of values) / number of values



 Sample screenshot of the program is given below:


 Solution:

#include <iostream>


double fallingDistance(double time) {

    const double g = 9.8;

    double distance = 0.5 * g * time * time;

    return distance;

}


int main() {


    double times[] = {1, 3, 5, 7, 9};

    int numTimes = sizeof(times) / sizeof(times[0]);

    double sum = 0;


    for (int i = 0; i < numTimes; i++) {

        double distance = fallingDistance(times[i]);

        sum += distance;

    }


    double average = sum / numTimes;

    /*std::cout << "Sum of distances covered = " << sum << "m\n";*/

    std::cout << "Average distance covered = " << average << "m";


    return 0;

}


No comments

Powered by Blogger.