Home

Programming Tips

C++ is used for all the examples.

Repeatedly ask for user input

Ask for user input, validate it, and if it isn’t correct ask again.

int input;
while (true) {
  cout << "User input: ";
  if (!(cin >> input) || !(/*Check if input is valid*/)) {
    cout << "Please try again.\n";
    cin.clear(); // Clear error flags
    continue;
  }
  break;
}

Swapping variables without a temp variable

// Swap a and b
int a = 50, b = 10;

a = a ^ b;
b = a ^ b;
a = a ^ b;

cout << "a: " << a << endl;
cout << "b: " << b << endl;

Getting each digit of an int

int var = 12345;
vector<int> digits;

int temp = var;
for (int i = 0; temp != 0; i++) {
  digits.push_back(temp % 10);
  temp /= 10;
}

Comparing floats

Getting random numbers

Getting a random integer from a function that generates numbers from 0 to 1.

int getRandomNum(int start, int end) { // End is exclusive
  return (rand() * (end - start)) + start; // Truncating when converting back into an int
}

Two D arrays

int arr[rows][cols];

for (int row = 0; row < arr.size(); row++) {
  for (int col = 0; col < arr[0].size(); col++) {
    auto element = arr[row][col];
  }
}

Convolutional 2d array

void nearestNeighbor(int array[rows][cols], int rIndex, int cIndex) {
  int startCol = cIndex - 1;
  int endCol = startCol + 2;
  if (startCol < 0) startCol = 0;
  if (endCol > cols) endCol = cols;

  int startRow = rIndex - 1;
  int endRow = startRow + 2;
  if (startRow < 0) startRow = 0;
  if (endRow > rows) endRow = rows;

  for (int row = startRow; row < endRow; row++) {
    for (int col = startCol; col < endCol; col++) {
      std::cout << array[row][col] << " ";
    }
  }
}

void convolute(int array[rows][cols], int index) {
  for (int row = 0; row < rows; row++) {
    for (int col = 0; col < cols; col++) {
      nearestNeighbor(array, index);
    }
  }
}

Rounding with truncation