Oct 15, 2012 at 9:56am UTC
I'm beginner in C++ and I'm working in Eclipse (MinGW Compiler) and need to make a program, sum of odd numbers that will collect only the second number.
Ex. You type 10 and then the program automatically will
2+4+6+8+10 = 30
or if you type 16
2+4+6+8+10+12+14+16 and then it'll give you the result of 72.
Somebody can help me with this ? Need to know the formula of that, I really appreciate your help guys.
Oct 15, 2012 at 10:43am UTC
hope this will help you....all you need to do is use a for loop to get the sum of the even numbers.
cout<<"\n\t Enter the number";
cout<<"\n\t Sum = "<<sum;
Oct 16, 2012 at 12:14pm UTC
Way to explain the algebra :-C.
Well the way I figured you got that is:
Well to make it short we can see it is just 2(1+2+...+n), if you took high school math you should know summation from 1 to n is just n(n+1)/2. So we want to multiple that by 2 and make n = n / 2 as the input is a multiple of 2, we want the input to be from 1,2,..,n instead. Which turns into 2*( (n/2)(n/2+1)/2 ) along with some simplifying and clever organization you get what Bazzy has (n/4 isn't a fraction for integral types in C++).
Oct 16, 2012 at 1:30pm UTC
@Bazzy that may not work; the output doesn't get flushed by you adding a newline character to the stream. Use std::endl please :)
Oct 16, 2012 at 2:57pm UTC
Actually the output stream probably does get flushed when you add a newline, as well as when input is requested and when the program ends.
Having said that, it's still usually a good idea to do a std::flush before the end of the program and before requesting input (replace std::flush with std::endl if you want a newline as well).