Skip over navigation

1D Arrays

Problems and Solutions 2

Looping Constructs for One-Dimensional Arrays

How to Cite This SparkNote

Problem : You are given a character array word of size n. Write C code that will reverse the order of the characters in this array.


int i;
char ch;

/* A loop to reverse the array word. */
for (i = 0; i < n / 2; i++) {
	/* Swap word[i] with word[n - (i + 1)]. */
	ch = word[i];
	word[i] = word[n - (i + 1)];
	word[n - (i + 1)] = ch;
}
This code switches each of the characters in the first half of the array with the corresponding ones from the second half of the array. If there are an odd number of elements in the array, the middle element does not need to get switched.

Problem : Write a function that takes in an array of type card_t and length n and shuffles it. Assume that you have a function called RandomInteger(x, y) which returns an integer greater than or equal to x and less than y.


void shuffle (card_t deck[], int n) 
{
	int switch, tmp, i;

	/* 
	 * A deck with 0 cards or 1 card can't be 
	 * shuffled any  more than it already is.
	 *
	 */
	if (n == 0 || n == 1) return;

	for(i = 0; i < n; i++)
	{
		/* 
		 * Swap element i of deck with a 
		 * random element. 
		 *
		 */
		switch = RandomInteger(0, n - 1);
		tmp = deck[switch];
		deck[switch] = deck[i];
		deck[i] = tmp;
	}
}
This function uses a loop to step through the array deck. On each pass it switches element i of deck with a random element. After we finish stepping through the array it will be shuffled. Many other solutions are possible.

Problem : Write a function that is passed an array of integers sorted in ascending order and returns with all of the duplicate entries removed.


int remove(int arr[], int n)
{
	int ins_pt, last, i;

	if (n == 0) return;

	last = arr[0];
	ins_pt = 1;
	for (i = 1; i < n; i) {

		/* 
		 * If the current element is greater than the last, 
		 * insert it into the first empty spot in the array.
		 *
		 */
		if (arr[i] > last) {
			last = arr[i];
			arr[ins_pt] = last;
			ins_pt;
		}
	}
	return ins_pt;
}
This function achieves this removal process using only the original array. Basically it steps through the original array and every time it encounters a previously unseen integer it inserts it into the next open spot in the array. Notice that it must return the new size of the array at the end because otherwise the caller would not know where the array ends.

Follow Us