C Programming

Practise Exercise 7: Arrays

1. The statement which declares a character based array called letters of ten elements is,

letters : char[10];
char[10] letters;
char letters[10];
char array letters[0..9];


2. Assign the character value 'Z' to the fourth element of the letters array

letters[4] := "Z";
letters[3] = 'Z';
letters[3] = 'z';
letters[4] = "Z";


3. Use a for loop to total the contents of an integer array called numbers which has five elements. Store the result in an integer called total.

Statement 1

	for( loop = 0, total = 0; loop >= 4; loop++ )
		total = total + numbers[loop];
Statement 2

	for( loop = 0, total = 0; loop < 5; loop++ )
		total = total + numbers[loop];
Statement 3

	for( loop = 0, total = 0; loop <= 5; loop++ )
		total = total + numbers[loop];

4. Declare a multidimensioned array of floats called balances having three rows and five columns.

float balances[3][5];
balances[3][5] of float;
float balances[5][3];
array of float balances[0..2][0..5];

5. Write a for loop to total the contents of the multidimensioned float array balances, as declared in question 4.

Statement 1

	for( row = 0, total = 0; row < 3; row++ )
		for( column = 0, total = 0; column < 5; column++ )
			total = total + balances[row][column];
Statement 2

	for( row = 0, total = 0; row < 3; row++ )
		for( column = 0; column < 5; column++ )
			total = total + balances[row][column];
Statement 3

	for( row = 0, total = 0; row < 3; row++ )
		for( column = 0; column < row; column++ )
			total = total + balances[row][column];

6. Assign the text string "Hello" to the character based array words at declaration time.

char words[10] = 'Hello';
static char words[] = "Hello";
static char words["hello"];
static char words[] = { Hello };

7. Assign the text string "Welcome" to the character based array stuff (not at declaration time)

strcpy( stuff, 'Welcome' );
stuff = "Welcome";
stuff[0] = "Welcome";
strcpy( stuff, "Welcome" );

8. Use a printf statement to print out the third element of an integer array called totals

printf("%d\n", &totals[3] );
printf("%d\n", totals[3] );
printf("%c\n", totals[2] );
printf("%d\n", totals[2] );

9. Use a printf statement to print out the contents of the character array called words

printf("%s\n", words);
printf("%c\n", words);
printf("%d\n", words);
printf("%s\n", words[2]);

10. Use a scanf statement to read a string of characters into the array words.

scanf("%s\n", words);
scanf(" %c", words);
scanf("%c", words);
scanf("%s", words);

11. Write a for loop which will read five characters (use scanf) and deposit them into the character based array words, beginning at element 0.

Statement 1

	for( loop = 0; loop < 5; loop++ )
		scanf("%c", &words[loop] );
Statement 2

	for( loop = 0; loop <= 5; loop++ )
		scanf("%c", words );
Statement 3

	for( loop = 0; loop < 5; loop++ )
		scanf("%c", &words[0] );

ęCopyright B Brown. 1984-1999. All rights reserved.