Home > Back-end >  The question asks to print the sum of all integers in an array. Why cant I run the following code?
The question asks to print the sum of all integers in an array. Why cant I run the following code?

Time:01-06

The program crashes after asking for array values. I am new to programming. Please help me out!

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int number_of_elements;
    cin >> number_of_elements;
    int sum_of_array = 0;
    vector <int> ar(number_of_elements);
    for(int i = 0; i < number_of_elements; i  ){
       cin >> ar[i];
       sum_of_array  = ar[i];
    }
    cout << sum_of_array;
    return sum_of_array;
}

CodePudding user response:

You can use cout to print out the answer, but int main() should ALWAYS return 0

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    
    int number_of_elements;
    cin >> number_of_elements;
    int sum_of_array = 0;
    vector <int> ar(number_of_elements);
    for(int i = 0; i < number_of_elements; i  ){
       cin >> ar[i];
       sum_of_array  = ar[i];
    }
    cout << sum_of_array;
    return 0;
}

CodePudding user response:

Remember, in main(), ALWAYS return 0.

  •  Tags:  
  • Related