Arrays and Strings

Chapter: Arrays and Strings

If you declare

int a[20], b[10];
you are reserving space for 20 ints called a[0] .. a[19], and 10 ints called b[0] .. b[9]. As in many languages, you can work through an array with a for loop such as:
for (i = 0; i < 20; i++) {
  do something with a[i];
}
A shortcut way to initialize arrays is this:
int b[] = {2, 4, 6, 8, 10, 9, 7, 5, 3, 1};

Exercise 1

Complete the following program so that it correctly prints the largest and smallest members of the array:
 
#include < stdio.h  >
main() {
  int i,min,max;
  int arr[] = {2, 4, 6, 8, 10, 9, 7, 5, 3, 1};
  min = max = 0;
  for // insert code here
    if (arr[i] > arr[max]) // and here
    if (arr[i] < arr[min]) // and here
  }
  printf("Max %d Min %d\n", arr[max], arr[min]);
}


A string in C is just an array of char. The final entry of the array needs to be the special char '\0'.

Try the following program:

#include < stdio.h >
main() {
  char c[] = {'a', 'b', 'c', '\0'};
  printf("%s\n", c);
}

Now change that last character to something other than '\0'.


Exercise 2

What happens?

If you use the syntax below, the terminator will be placed there for you. Work with the following program and see if you can answer the questions below:

#include < stdio.h >
main() {
  int i,min,max;
  char carr[] = "To be or not to be";
  min = max = 0;
  i = 0;
  while (carr[i] != '\0') {
    if (carr[i] > carr[max]) max = i;
    if (carr[i] < carr[min]) min = i;
    i++;
  }
  printf("Max %d Min %d\n", carr[max], carr[min]);
}


Exercise 3

  1. Why do we not use a for loop to go through the array?
  2. Explain the output of this program



rhyspj@gwu.edu