Logical operators short-circuit evaluation

Very useful in some situations:
int arr[max_size];
//search for value x in array
i = 0;
while (i< max_size && arr[i]!=x)  //order is vital
if (i < max_size)
  cout << "Found at index: " << i;
  cout << "Not in array";
The short-circuit feature of the && is critical to the correctness of this code. If x is not in the array, i will eventually equal max_size and then in the evaluation of the && i< max_size is evaluated first, it will be False and thus arr[i]!=x will not be evaluated, which we wouldn't want because i is max_size and so arr[max_size] doesn't exist and would cause an error.

A row of a 2D array is a 1D array.

float mat[max_rows][max_cols];  //using global constants

//sum a row.  Function with 2D array argument
cout << "Which row to sum: ";
cin >> row_num;
sum = sum_row(mat, row_num);

float sum_row (float M[][max_cols], int row) {
  float sum=0;
  int i;
  for (i=0; i< max_cols; i++)
    sum += M[row][i];
  return sum;

Alternatively: function with 1D array of floats to sum

float sum_array (float V[]) {
  float sum=0;
  int i;
  for (i=0; i< max_cols; i++)
    sum += V[i];
  return sum;

float mat[max_rows][max_cols];  //2D array

Calling this function with one row of a 2D array as the actual argument:

sum = sum_array(mat[row_num]);

Use this function to sum each row of the 2D array:

float sum[max_rows];

for (i=0; i< max_rows; i++)
  sum[i] = sum_array(mat[i]);

Next (C strings)

©David Wills