6. Calculate 1-2 + 3-4 + ·-100

Source: Internet
Author: User
(1) Use the for statement and separate the calculation and summation with odd and even numbers # include <iostream>
Using namespace STD;

Int main ()
{
Int I, J;
Int sum = 0, sum1 = 0, sum2 = 0; // The value must be initialized to 0 before summation. Otherwise, a strange value is returned.
For (I = 1; I <= 100; I ++, I ++) // the original for statement can be used in this way
{
Sum1 + = I;
}
For (j =-2; j> =-100; j --, j --) // the original for statement can be used in this way.
{
Sum2 + = J;
}
Sum = sum1 + sum2;
Cout <sum <Endl;

Return 0;
}
(2) combined with the if statement, use a judgment to separate addition and subtraction: # include <iostream>
Using namespace STD;

Int main ()
{
Int sum = 0;
For (INT I = 1; I <= 100; I ++)
{
If (I % 2 = 1)
{
Sum + = I;
} Else
{
Sum-= I;
}
}
Cout <sum <Endl;
Return 0;
} (3) Simpler Method # include <iostream>
Using namespace STD;

Int main ()
{
Int sum = 0;
For (INT I = 1; I <= 100; I ++)
{
If (I % 2 = 1)
{
I =-I;
}
Sum + = I;
}
Cout <sum <Endl;
Return 0;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.