I have to find the sum of all integer numbers lying between 1 and N inclusive.
Input
The input consists of a single integer N that is not greater than 10000 by it's absolute value.
Output
Write a single integer number that is the sum of all integer numbers lying between 1 and N inclusive.
Sample
input -3
Output -5
And this is my code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
int a,b;
cin >>a;
if (a>0 && a<=10000){
for (int i=1;i<=a;i++){
b=b+i;
}
}
elseif (a<1 && a>= -10000){
for (int i=1;i>=a;i--){
b=b+i;
}
}
cout<<b;
}
my problem is , when i submit it , it says wrong answer. but when i tested it, it seems work. Anyone can Help me?
To be fair in addition to what Peater87 said you should initialize all variables before they are used, its just good practice.
When the variable is created, memory is set aside for the variable, but it contains whatever was last stored at that memory location. So, when you first use "b" it starts with whatever garbage that was at that memory location which throws the final sum off.
When you initialize "b" to zero when it is defined then the for loop will start adding to zero and not some garbage value like -8+ million as I have seen on my computer.
these will help you in the long run, they are easier to type and you will see them a lot in others' code.
for adding 1,
b++;
and more generally, adding a value to a variable's existing value:
b += x;
-- exists for subtracting 1 and all the operators exist including logical for the self assignment:
--b;
b ^= 3; //xor example
b *= 3; //multiply example
etc.