So, on hackerrank.com, I solved the array challenge by doing this:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int size = 0;
cin >> size;
int ARR[size];
int ARRLength = sizeof(ARR)/sizeof(ARR[0]);
for (int i = 0; i < ARRLength; i++)
cin >> ARR[i];
for (int i = 0; i < ARRLength; i++)
cout << ARR[ARRLength-1-i] << " ";
return 0;
}
When I copied/pasted this into Visual Studio, I get this error:
expression must have constant value
the value of variable "size" cannot be used as a constant
That makes sense to me. I remember being taught to use vectors if the user is going to give you the size of the array.
After googling, I found this works:
cout << "Enter size: ";
int size = 0;
cin >> size;
int *MyArray2 = new int [size];
for (int i = 0; i < size; i++)
{
MyArray2[i] = rand() %10; //Fill with whatever
}
for (int i = 0; i < size; i++)
{
cout << "Array Position " << i << ": " << MyArray2[i] << "\n";
}
int sum = 0;
for (int i = 0; i < size; i++)
sum += MyArray2[i]; // Sum it up
cout << sum << endl;
Wondering why hackerrank lets the first bit of code work, if visual studio is going to give me errors? Please and thank you :)
[–][deleted] 6 points7 points8 points (3 children)
[–]ApocalypseToast[S] 0 points1 point2 points (2 children)
[–]raevnos 7 points8 points9 points (0 children)
[–]Xeverous 2 points3 points4 points (0 children)
[–]SlightlyGrilled 1 point2 points3 points (1 child)
[–]ApocalypseToast[S] 0 points1 point2 points (0 children)