I'm beginner in C++, and I've got a question about a simple sum code in c++.
Here is my code :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
int sum;
int arr_i = 0;
cin >> n;
vector<int> arr(n);
while (arr_i != n)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
arr_i++;
}
return 0;
}
The output doesn't print the correct answer without "cout << sum" before the if condition.
How can I solve this problem ?
2 Answers 2
You forget to initialize sum
to 0.
int sum = 0;
As the previous post mentioned, sum was not initialized to 0. In terms of good practices and styles its a good idea to initialize any variables that are modified within a loop right before the loop body so that someone reading the code can easily grasp the context of your variables.
int main()
{
int n;
int sum;
int arr_i;
cin >> n;
vector<int> arr(n);
sum = 0;
arr_i = 0;
while (arr_i != n)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
arr_i++;
}
return 0;
}
or as I prefer a "for" loop...
int main()
{
int n;
int sum;
int arr_i;
cin >> n;
vector<int> arr(n);
for (sum = 0, arr_i = 0; arr_i != n; arr_i++)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
}
return 0;
}
-
Even better, initialize them at declaration, and reduce scope of the variable.Jarod42– Jarod422016年04月08日 22:37:19 +00:00Commented Apr 8, 2016 at 22:37
-
@Jarod42 Good point. Yes, i didn't want to deviate too much from his original post, but definitely declaring and initializing the variable in a block of code where it is only used is even better. So a "for (int sum = 0; int array_i = 0; arr_i != n; arr_i++)" would be best in this case.Art Solano– Art Solano2016年04月08日 22:51:24 +00:00Commented Apr 8, 2016 at 22:51
-
A for loop would actually be the preferred method as you know how many times the loop is iterating because they are having the user enter "n" times of iterations. Even though a while loop is justifiable, a for loop seems more proper.user2277872– user22778722016年04月08日 23:22:42 +00:00Commented Apr 8, 2016 at 23:22
cmath.h
for a simple sum.math.h
orcmath
, notcmath.h
cout << accumulate(arr.begin(), arr.end(), 0);