-1

This program I wrote is supposed to print some numbers:

#include <iostream>
using namespace std;
int main()
{
    int hitung(int A[], int n) 
    {
        int jumlah = 0;
        for (int i = 0; i < n; i++) 
        {
            jumlah = jumlah + A[i];
            if (i % 2 == 1) 
            {
                cout << A[i];
            }
        }
        return jumlah;
    }
}

However, when I try to compile it I get these error messages:

main.cpp: In function 'int main()':
main.cpp:6:5: error: a function-definition is not allowed here before '{' token
     {
     ^
main.cpp:18:1: error: expected '}' at end of input
 }
 ^

While the first error is understandable since function definition can't be in other function, I don't understand the 2nd error since all my brackets are closed.

Why is the compiler producing the second error?

SHR
  • 7,940
  • 9
  • 38
  • 57

1 Answers1

1

You have defined the function hitung into main(). You cannot do that. What you can do however is this:

#include <iostream>
using namespace std;

int hitung(int A[], int n) 
{
    int jumlah = 0;
    for (int i = 0; i < n; i++) 
    {
        jumlah = jumlah + A[i];
        if (i % 2 == 1) 
        {
            cout << A[i];
        }
    }
    return jumlah;
}

int main()
{
   int a[] = {1, 2, 3};
   cout << hitung(a, 3) << endl;

   return 0;
}

Alternatively, you could declare your function before main(), and define it afterwards.

gsamaras
  • 71,951
  • 46
  • 188
  • 305