Calculating work using dot product in C++ Write a C++ program fulfilling the following task: The user should enter the 3 dimensional force vector F and a 3 dimensional length vector s. The force is assumed to be constant. The program then calculates the work W = F (dot) s and prints the result on the screen.


#include &lt;iostream&gt;

using namespace std;

int main()
{
    //I decided to try and declare my variables locally to make it easier for readers.
    double F[3];
    int i;

    cout &lt;&lt; "Enter in components of the force vector F:\n";

    for(i=0; i&lt;3; i++)
    {
        cout &lt;&lt; "Component " &lt;&lt; i+1 &lt;&lt; ": ";
        cin &gt;&gt; F[i];

    }

    double s[3];

    cout &lt;&lt; "Enter in the components of the length vector s:\n";

    for(i=0; i&lt;3; i++)
    {
        cout &lt;&lt; "Component " &lt;&lt; i+1 &lt;&lt; ": ";
        cin &gt;&gt; s[i];
    }

    double W = 0.0;

    for(i=0; i&lt;3; i++)
    {
       W = W + (F[i] * s[i]);
    }

    cout &lt;&lt; "The work done is: " &lt;&lt; W &lt;&lt; " J";

    return 0;
}


Does "The force is assumed to be constant" change anything about the code. I don't see how that makes a difference? Is it included for completeness?
using namespace std should be avoided

Not much more to say than that. Just don't do it. The worst case is putting it into a header. Next is using it outside any namespace, so you've done the second worst possible incarnation of this particular problem.

Typing std::cout instead of cout really isn't going to cause you a lot of problem, I promise.

Don't Repeat Yourself

You have essentially identical code for entering the two input vectors. You probably want to use a function to enter the values for a vector, and just call it once for each input vector.

Use the Library

As a general rule, I'd avoid using built-in arrays when at all reasonable. In this case, you can use std::array instead:

std::array&lt;double, 3&gt; F;
std::array&lt;double, 3&gt; s;


The standard library already provides std::inner_product to do exactly the calculation you're doing. You might as well use it:

double W = std::inner_product(F.begin(), F.end(), s.begin(), 0.0);