Reputation: 1
I'm new to C++ and I'm trying to learn it for an entrance test at my school in order to take the computer science class I want. I had to write a program that would create an array and use the values they give me for rows and column. The program uses a function to find the sum of the largest row of integers.
#include <iostream>
using namespace std;
int findMaxSumArray (int arr[3][3])
{
int sum1, sum2 = 0;
int i, j = 1;
int row = 3;
int col = 3;
for (i = 0; i < row; ++i)
{
sum1 = sum1 + arr[1][i];
}
for (j = 2; j < col; ++j)
{
for (i = 0; i < row; ++i)
{
sum2 = sum2 + arr[j][i];
}
if (sum2 > sum1)
{
sum1 = sum2;
}
}
return sum1;
}
int main ()
{
int arr[3][3] = { {1, 2, 3}, {2, 3, 4}, {5, 6, 7} };
cout << findMaxSumArray(arr);
}
At this point I've gotten my code to return the correct answer on other online compilers, but the one for the test keeps giving me this error. I looked into causes for the error and they all seem unrelated, involving two files referencing main together. These are the errors I'm getting:
Syntax Error(s)
prog.cpp: In function 'int main()':
prog.cpp:46:5: error: redefinition of 'int main()'
int main() {
^
prog.cpp:38:5: note: 'int main()' previously defined here
int main ()
^
I'm a little lost about why I might be getting this error on some, but not all compilers. I don't fully understand C++ as I'm learning it. Could any of you shed some light on the issue?
Upvotes: 0
Views: 229
Reputation: 19
It is not related to your question, but there is another problem in your code - you are using uninitialized local variable.
Despite what it might look like, this line of code won't initialize sum1, it will only declare it:
int sum1, sum2 = 0;
To make it more clear we could rewrite it like this, meaning would be the same:
int sum1;
int sum2 = 0;
Local variables are not getting zero initialized by default (like global variables are), it means that they will have some value, but we can't predict it.
As you can guess using var1 won't yield expected results.
sum1 = sum1 + arr[1][i]; //!!
It will cause weird bugs instead.
Upvotes: 1