C++ Project

Hey guys

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.
hope this will help you....all you need to do is use a for loop to get the sum of the even numbers.

#include<iostream.h>
#include<conio.h>
class calculate
{
int i,a,sum;
public:
void accept()
{
cout<<"\n\t Enter the number";
cin>>a;
}
void add()
{
sum=0;
for(i=2;i<=a;i=i+2)
{
sum=sum+i;
}
}
void display()
{
cout<<"\n\t Sum = "<<sum;
}
};
void main()
{
calculate ob;
clrscr();
ob.accept();
ob.add();
ob.display();
getch();
}
1
2
3
4
5
6
7
#include <iostream>
int main()
{
    int n = 0;
    std::cin >> n;
    std::cout << 2*n/4*(n/2+1) << '\n';
}

Algebra for the win! ;^)
closed account (o1vk4iN6)
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++).
@Bazzy that may not work; the output doesn't get flushed by you adding a newline character to the stream. Use std::endl please :)
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).
Topic archived. No new replies allowed.