Share this:


DECLARING ARRAYS
Arrays may consist of any of the valid data types. Arrays are declared along with all other variables in the declaration section of the program.
/* Introducing array’s */
#include
main()
{
int numbers[100];
float averages[20];
numbers[2] = 10;
–numbers[2];
printf(“The 3rd element of array numbers is %dn”, numbers[2]);
}
Sample Program Output
The 3rd element of array numbers is 9
The above program declares two arrays, assigns 10 to the value of the 3rd element of array numbers, decrements this value ( –numbers[2] ), and finally prints the value. The number of elements that each array is to have is included inside the square brackets.
ASSIGNING INITIAL VALUES TO ARRAYS
The declaration is preceded by the word static. The initial values are enclosed in braces, eg,
#include
main()
{
int x;
static int values[] = { 1,2,3,4,5,6,7,8,9 };
static char word[] = { ‘H’,’e’,’l’,’l’,’o’ };
for( x = 0; x < 9; ++x )
printf(“Values [%d] is %dn”, x, values[x]);
}
Sample Program Output
Values[0] is 1
Values[1] is 2
….
Values[8] is 9
The previous program declares two arrays, values and word. Note that inside the squarebrackets there is no variable to indicate how big the array is to be. In this case, C initializes the array to the number of elements that appear within the initialize braces. So values consist of 9 elements (numbered 0 to 8) and the char array word has 5 elements.
The following program shows how to initialise all the elements of an integer based array to the value 10, using a for loop to cycle through each element in turn.
#include
main()
{
int count;
int values[100];
for( count = 0; count < 100; count++ )
values[count] = 10;
}
MULTI DIMENSIONED ARRAYS
Multi-dimensioned arrays have two or more index values which specify the element in the array.
multi[i][j]
In the above example, the first index value i specifies a row index, whilst j specifies a column index.
Declaration and calculations
int m1[10][10];
static int m2[2][2] = { {0,1}, {2,3} };
sum = m1[i][j] + m2[k][l];
NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the braces are,
{ 0, 1 },
{ 2, 3 }
Remember that arrays are split up into row and columns. The first is the row, the second is the column. Looking at the initial values assigned to m2, they are,
m2[0][0] = 0
m2[0][1] = 1
m2[1][0] = 2
m2[1][1] = 3
EXERCISE C13
Given a two dimensional array, write a program that totals all elements, printing the total.
CLASS EXERCISE C14
What value is assigned to the elements which are not assigned initialised.
EXERCISE C13
Given a two dimensional array write a program that totals all elements printing the total.
#include
main()
{
static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} };
int row, column, sum;
sum = 0;
for( row = 0; row < 4; row++ )
for( column = 0; column < 3; column++ )
sum = sum + m[row][column];
printf(“The total is %dn”, sum );
}
CLASS EXERCISE C14
They get initialised to ZERO.
CHARACTER ARRAYS [STRINGS]
Consider the following program,
#include
main()
{
static char name1[] = {‘H’,’e’,’l’,’l’,’o’};
static char name2[] = “Hello”;
printf(“%sn”, name1);
printf(“%sn”, name2);
}
Sample Program Output
Helloxghifghjkloqw30-=kl`’
Hello
The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in name2[5], whilst name1 has not. This can often result in garbage characters being printed on the end. To insert a null at the end of the name1 array, the initialization can be changed to,
static char name1[] = {‘H’,’e’,’l’,’l’,’o’,’’};
Consider the following program, which initialises the contents of the character based array word during the program, using the function strcpy, which necessitates using the include file string.h
#include
#include
main()
{
char word[20];
strcpy( word, “hi there.” );
printf(“%sn”, word );
}
Sample Program Output
hi there.
SOME VARIATIONS IN DECLARING ARRAYS
int numbers[10];
static int numbers[10] = { 34, 27, 16 };
static int numbers[] = { 2, -3, 45, 79, -14, 5, 9, 28, -1, 0 };
static char text[] = “Welcome to New Zealand.”;
static float radix[12] = { 134.362, 1913.248 };
double radians[1000];
READING CHARACTER STRINGS FROM THE KEYBOARD
Character based arrays are often refered to in C as strings. C does not support a string type, so character based arrays are used in place of strings. The %s modifier to printf() and scanf() is used to handle character based arrays. This assumes that a 0 or NULL value is stored in the last element of the array. Consider the following, which reads a string of characters (excluding spaces) from the keyboard.
char string[18];
scanf(“%s”, string);
NOTE that the & character does not need to precede the variable name when the formatter %s is used! If the users response was
Hello
then
string[0] = ‘H’
string[1] = ‘e’
….
string[4] = ‘o’
string[5] = ‘’
Note how the enterkey is not taken by scanf() and the text string is terminated by a NULL character ‘’ after the last character stored in the array.

Practice Exercise 7: Arrays

2. Assign the character value ‘Z’ to the fourth element of the letters array
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.
4. Declare a multidimensioned array of floats called balances having three rows and five columns.
5. Write a for loop to total the contents of the multidimensioned float array balances.
6. Assign the text string “Hello” to the character based array words at declaration time.
7. Assign the text string “Welcome” to the character based array stuff (not at declaration time)
8. Use a printf statement to print out the third element of an integer array called totals
9. Use a printf statement to print out the contents of the character array called words
10. Use a scanf statement to read a string of characters into the array 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.
Answers: Practice Exercise 7: Arrays
1. Declare a character based array called letters of ten elements
char letters[10];
2. Assign the character value ‘Z’ to the fourth element of the letters array
letters[3] = ‘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.
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];
5. Write a for loop to total the contents of the multidimensioned float array balances.
for( row = 0, total = 0; row < 3; row++ )
for( column = 0; column < 5; column++ )
total = total + balances[row][column];
6. Assign the text string “Hello” to the character based array words at declaration time.
static char words[] = “Hello”;
7. Assign the text string “Welcome” to the character based array stuff (not at declaration time)
char stuff[50];
strcpy( stuff, “Welcome” );
8. Use a printf statement to print out the third element of an integer array called totals
printf(“%dn”, totals[2] );
9. Use a printf statement to print out the contents of the character array called words
printf(“%sn”, words);
10. Use a scanf statement to read a string of characters into the array 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, begin
ning at element 0.
for( loop = 0; loop < 5; loop++ )
scanf(“%c”, &words[loop] );
FUNCTIONS
A function in C can perform a particular task, and supports the concept of modular programming design techniques.
We have already been exposed to functions. The main body of a C program, identified by the keyword main, and enclosed by the left and right braces is a function. It is called by the operating system when the program is loaded, and when terminated, returns to the operating system.
Functions have a basic structure. Their format is
return_data_type function_name ( arguments, arguments )
data_type_declarations_of_arguments;
{
function_body
}
Answer: EXERCISE C15

LOCAL AND GLOBAL VARIABLES

Functions and Arrays

CLASS EXERCISE C17

Practise Exercise 8: Functions

Modifier
Meaning
b
backspace
f
form feed
n
new line
r
carriage return
t
horizontal tab
v
vertical tab
\
backslash
double quote
single quote
line continuation
nnn
nnn = octal cha
racter value
xnn
nn = hexadecimal value (some compilers only)
Modifer
Meaning
d
read a decimal integer
o
read an octal value
x
read a hexadecimal value
h
read a short integer
l
read a long integer
f
read a float value
e
read a double value
c
read a single character
s
read a sequence of characters, stop reading when
an enter key or whitespace character [tab or space]
[…]
Read a character string. The characters inside the
brackets indicate the allow-able characters that
are to be contained in the string. If any other
character is typed, the string is terminated. If the
first characteris a ^, the remaining characters
inside the brackets indicate that typing them
will terminate the string.
*
this is used to skip input fields
Example of scanf() modifiers

PRINTING OUT THE ASCII VALUES OF CHARACTERS

Operation
Operator

Comment
Value of Sum before
Value of sum after
AND
&
sum = sum & 2;
4
0
OR
|
sum = sum | 2;
4
6
Exclusive OR
^
sum = sum ^ 2;
4
6
1’s Complement
~
sum = ~sum;
4
-5
Left Shift
<<
sum = sum << 2;
4
16
Right Shift
>>
sum = sum >> 2;
4
1


EcoleBooks | COMPUTER FORM  6 - C PROGRAMMING

subscriber

Leave a Reply

Your email address will not be published. Required fields are marked *

Accept Our Privacy Terms.*