Before tackling the matter at hand, I would like to note some things:
I would advice against including the entirety of the standard namespace since the names inside it are bound to eventually clash with any identifiers declared in your code. Instead, provide
using
declarations for any names inside
std
that you need, for instance
using std::vector; using std::cout; using std::cin; // So on, and so forth.
When you defined
liczba
and
suma
, you initialized only
suma
to
0. It may be tempting to expect both objects to be initialized to
0 but that is not the case.
I'd like to comment on the missing
<<
(bitwise left shit operator) between
"Sum of "
and
l[i]
in the final output stream.
Finally, the type of
l_size
should not be
int
, but rather
std::vector<int>::size_type
. The
size_type
member is guaranteed to hold the size of any vector in memory. It is considered to be tedious to write by some, so why not let
auto
deduce the type from the initializer for you?
auto l_size = l.size(); // l_size is a std::vector<int>::size_type
Alright, to the matter of hand:
The problem is in the
for
loop of your code. You're decrementing
l_size
twice each iteration.
You also happen to be using a postfix decrement operator. It decrements your objects value by 1 but it is the unchanged value that forms the subexpressions in each iteration.
Consider this example:
1 2
|
int i = 5;
std::cout << i-- << std::endl; // Prints 5 but the value of i is 4!
|
Now consider this example:
1 2
|
int i = 5;
std::cout << --i << std::endl; // Prints 4 and the value of i is 4.
|
The latter example used the prefix operator which decrements the value of its operand and returns the modified value.
The output of the first iteration looks perfectly valid because it decrements the value of
l_size
twice but does so with the postfix decrement operator and therefore makes it look like the value is only changed once. That is not the case since the value of
l_size
is
l_size - 2
after each iteration.
You should be able to solve it yourself now if you followed along. I'll respond with the answer if you can't. I also suggest looking into iterators, they simplify this kind of operations greatly.
This is probably just a throw-away account, but in the future, consider naming your objects in English when posting code to forums.