Reputation: 15
For some reason I am not getting the desired answer and I can't fathom where the error is.
For example, given the array ar = [1,2,3]
, 1+2+3 = 6
, so return 6
, but I am getting 650462183
instead.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
int arr[i];
cout << "enter the value of yout arr\n";
cin >> arr[i];
int count = 0;
for (int j = 0; j <= i; j++)
{
count += arr[j];
}
cout << count << endl;
return 0;
}
Upvotes: 1
Views: 297
Reputation: 75062
The array int arr[i];
has only i
elements: arr[0]
to arr[i-1]
.
Therefore, the condition of the loop should be j < i
, not j <= i
.
cin >> arr[i];
is also wrong. You should use another loop to read i
elements instead of readling only one to an out-of-range element like this.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
int arr[i];
cout << "enter the value of yout arr\n";
for (int j = 0; j < i; j++)
{
cin >> arr[j];
}
int count = 0;
for (int j = 0; j < i; j++)
{
count += arr[j];
}
cout << count << endl;
return 0;
}
Note that variable-length arrays (VLA) like int arr[i];
is not supported in the standard C++. You should use std::vector
instead. You can do this by changing int arr[i];
to std::vector<int> arr(i);
in this case.
Another choice is not using arrays and summing what are entered directly:
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <cstdlib>
#include <cctype>
using namespace std;
int main ()
{
int i;
cout << "enter the value of i" << endl;
cin >> i;
cout << "enter the value of yout arr\n";
int count = 0;
for (int j = 0; j < i; j++)
{
int element;
cin >> element;
count += element;
}
cout << count << endl;
return 0;
}
Upvotes: 8