I am trying to write a program to find prefix sum. It is showing error: invalid types 'int[int] for array subscript for single dimensional array code1
#include <bits/stdc++.h>
using namespace std;
long long a[(int)1e5 + 50];
int n;
void buildPrefixSum() { // O(n)
for(int i = 1; i < n; i++) {
a[i] += a[i - 1];
}
}
int getSum(int i, int j) { // O(1)
int sum = a[j];
if(i > 0) sum -= a[i - 1];
return sum;
}
int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t,a,b;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
buildPrefixSum();
cin >> t;
while(t--)
{
cin >> a >> b;
cout << getSum(a,b) << "\n";
}
}
But when I change the main function to this, the code runs properly.code2
int main() {
cin >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
buildPrefixSum();
int q;
cin >> q;
while(q-- > 0) {
int a, b;
cin >> a >> b;
cout << getSum(a, b) << endl;
}
return 0;
}
I don't understand the difference between the two codes. Can anyone please clarify the mistake I made in the main function of the first code?
aand what types you're declaring.main():int t,a,b;The local variableaeclipses the global variable with same name. (The global is still there but you cannot access it in the local scope.)