// A program that takes in an array of a given length and swaps the first and // the last elements of that array. // Sasha Vassar Week 5, Lecture 9 #include // PROBLEM: Read in an array of numbers (user will specify how many numbers // they plan to read in). Then the first number and the last number in the // array will be swapped, and the modified array printed out again. // How shall we solve this? // 1. Read in numbers // - User specifies how many numbers they will enter // - User then provides the numbers // 2. Print out the original array // 3. Swap the first and the last number in the array // 4. Print out the modified array #define MAX_SIZE 100 void print(int array[], int size); int read_size(int array[]); void swap(int *number1_ptr, int *number2_ptr); int main (void) { //Declare an array int array[MAX_SIZE]; //Find out size of the array, by calling the function read_size(array) int size = read_size(array); //Print out original array, by calling the function print printf("The original array is:\n"); print(array, size); //Swap the first and the last element of the array, by calling the function //swap. Notice that swapping is best done with pointers to the specific //array indexes. swap(&array[0], &array[size-1]); //Print out modified array, by calling the function print again printf("The array with the first and last numbers swapped is:\n"); print(array, size); return 0; } int read_size(int array[]) { int counter = 0; printf("How many numbers would you like to enter? "); scanf("%d", &counter); int i = 0; while (i < counter) { printf("Enter a number for the array: "); scanf("%d", &array[i]); i++; } return counter; } // 1, 2, 3, 4, 5 // *1, *5 void swap(int *number1_ptr, int *number2_ptr) { // temp = 1 int temp = *number1_ptr; //address at pointer 1 = 5 *number1_ptr = *number2_ptr; //address at pointer 2 = 1 *number2_ptr = temp; } void print(int array[], int size) { int i = 0; while (i < size) { printf("%d ", array[i]); i++; } printf("\n"); }