Monday, August 1, 2016

C++ Array

One of the most used things on competitive programming is array, here's how to create it on C++

// lets say we want to create an array of 5
int num = 5;
// this part creates the array with number of 5
int *array = new int[num];
// this part sets the value
for (int i = 0; i < num; i++) {
  array[i] = i;
}
pretty easy huh.. and here's the complete codes
#include 
#include 

using namespace std;

int main() {
  int num = 0;
  cout << "Please enter number of array : " << endl;
  cin >> num;

  int *array = new int[num];
  // set the value
  for (int i = 0; i < num; i++) {
    array[i] = i;
  }

  // print the array
  for (int i = 0; i < num; i++) {
    cout << array[i] << " ";
  }
  cout << endl;

  // delete array when done
  delete[] array;

  return 0;
}

! deleting the array is necessary since it will safe spaces in memory

No comments :

Post a Comment