A more optimal version of solution 1 code could be:
#include <iostream>
using namespace std;
int main ()
{
double s = 0;
cout << "Sum of :";
for (int i = 1; i <= 6; ++i)
{
double sign = 1.0;
if (i % 4 == 0)
{
cout << " - "; sign = -1.0;
}
else if (i > 1) {
cout << " + ";
}
int q = 2 * i;
cout << 1 << "/" << q;
s += sign / q;
}
cout << "\n" << "Result = " << s;
}
Corrections have been made in above code in
bold so that 1/8 get substracted from the result.
That code is more optimal for mainly for the time it take to write or read it. At execution time, there won't be much difference. It is more typical of expert code that know what they do. For example, we only check once the modulo and skip first sign only if positive.
One could simplify code like that:
if (i > 1)
{
cout << (i % 4 == 0 ? " - " : " + ");
}
But that code is slightly less maintainable if first number is negative as more change would be required. Thus I would not recommend that change in this case.