Sie sind auf Seite 1von 36

Arrays and more I/O

EE1503 Programming and Design

2010/2011
In this chapter …

o Concept of arrays
o Arrays and strings
o Character input and output
o Reading strings using scanf()
o Strings with gets() and puts()
o Multi-dimensional arrays
o Common pitfalls with arrays in C

2
Concept of arrays

A standard variable looks like this:

int x; // Declare a standard integer


// variable called x
x=53; // Assign a value to x.

X 53
Variable name
Memory
Location
Contents

3
Concept of arrays
o Whilst standard variables are of course very useful,
there are applications where they are not practical.
o Arrays are most useful when the data are naturally
expressed as a contiguous sequence of values.
• Example: Write a program which inputs a number between 0-10
and displays the equivalent page number of that section in a book.

Index
0 1 2 ….. 8 9 10
X 0 1 16 ….. 66 81 93

Variable name
Memory locations
Contents
4
Declaration and assignment

o Like any other variable in C, Arrays must be declared


before it is used.
o Name: the rules used to define a variable apply for
array too.
o No special data type for the declaration. The data
type used is the type of the data in the array.
• For example: Let’s declare an array which can hold all
the letters of the alphabet.
char Alphabet[26];
o The index or sub-script must be an integer

5
Declaration and assignment
o Very important: An array index starts at 0.
The first element of the array corresponds to index 0,
the second one to index 1, more generally the nth
element corresponds to index n-1.
o To assign a value to a particular element of the array:
Alphabet[2]=‘C’;
o Note: the array is not initiliazed by default.
o The brackets are similar to function call operator and
has precedence over most operators.
o It is possible to have an expression inside the
brackets.
6
Initialization

Declare array called Odd of the appropriate type and size


to store odd numbers

int Odd[5]=
Odd[5];
Odd[ /* Initialize
]= {1,3,5,7,9}
{1,3,5,7,9}; /* array array
; Initialize */ */
Odd[0]=1;
int
// Ifindex=0,value; // Option 1
the array is Initialized at Declaration
Odd[1]=3;
// The number
Option of //
3 Initialize Simple
elements
array atassignment
need not be specified.
Declaration
Odd[2]=5;
for(value=1;value<11;value+=2,index++)
//Have
// Compiler will assign
to initialize correct
every array size.
element
Odd[3]=7;
Odd[index]=value; // Option 2: Use for loop to
Odd[4]=9;
// The number of element //simplify assignment.
in the list should be equal
// to the size of the array
// If you specify less element in the list, the
// remaining cell of the array will be initialized
to 0
// If you specify more, a syntax error would appear
7
Initialization

o Another possibility is to use a symbolic constant


o E.g.:
#include <stdio.h>
#define size 5
{
float arr [size];
}

o Very practical way of defining the size of an array


because it makes the program scalable, i.e. easy
to change the size of the array by only changing
one value.

8
Examples using arrays

#include <stdio.h>
void main (void) {
float amounts[10];
int i;
printf (“US Dollar to UK Pound converter: \n\n”);
printf (“%10s %10s\n”, “Dollars”, “Pounds”);
for (i = 0; i < 10; i++) {
amounts[i] = (i+1)*5.00;
printf (“%10.2f %10.2f\n”, amounts[i], (amounts[i] /
1.66));}
}

9
Example using array

10
Strings and character arrays

o By creating an array of characters, you can create


a string
o Two important differences between character
arrays and other array types
• Storing a string in a character array always
requires an extra element
This extra, final element stores the terminating NULL
character (‘\0’), which marks the end of a string

• Character arrays for strings must be assigned a


value using double quotation marks
e.g. Name[7] = “Basil”;

11
Strings and character arrays
o C gives an easier way to initialize an array
without counting the elements by using an
unsized array by automatically calculating the
dimensions of array big enough to hold all the
characters including the terminating ‘\0’
o Bad practice example
char word [10];
word[0] = ‘H’;
word[1] = ‘e’;
word[2] = ‘l’;
word[3] = ‘l’;
word[4] = ‘o’;
word[5] = ‘\0’;
printf(“%s”, word);
12
Strings and character arrays

o Better practice?

// Declare and initialize an array of char access as


// separate characters
char Name1[ ] = {‘D’,’a’,’v’,’i’,’d’};

/* Declare and initialize an array of char access as a string*/


char Name2[ ] = “David”;

13
Strings and character arrays

o Example 1: Show how the contents of each array


can be displayed

#include<stdio.h>
void main(void)
{
char Name1[ ] = {‘D’,’a’,’v’,’i’,’d’};
char Name2[ ] = {“David”};
int x;
for(x=0;x<5;x++) printf(“%c”,Name1[x]);
printf(“%s”,Name2);
}

14
Strings and character arrays

15
Strings and character arrays
o Example 2: Create an array which can store a
string of five characters inputted from the
keyboard.
#include<stdio.h>
void main()
{
char Text[6];
int x;

for(x=0;x<6;x++) scanf(“%c”,&Text[x]);
for(x=0;x<6;x++) printf(“%c”,Text[x]);

} It is much simpler if we treat the array of


char as a single string.
16
Strings and character arrays

17
Strings and character arrays

#include<stdio.h>
void main(void)
{

char Text[6];
scanf(“%s”, &Text);
printf(“%s”,Text);

}
Note: When using an array of char as a string
we do not use index.

18
Reminder: Character I/O

o getchar() Read a single character from the


keyboard.
o Returns next key pressed as an integer

Example
{
char Key;
do
Key=getchar();
while(Key!=‘Q’);
}

19
Reminder: Character I/O

o putchar() Display single character to the screen

Example
{
int i = 0;
char line [] ={“Hello\n”};
while(line [i] ! = ‘\0’) {
putchar (line [i]);
i++;
}
}
20
Reading strings using scanf( )

o It has already been shown that scanf can be used


to input strings (slide 18).
o But as scanf uses white spaces as an end of string
markers this can prove a problem.
o This is a limitation if
• more than one word is required to be inputted.
• the number of words to be inputted is not known.
o Problem if number of letters is larger than array.
o However, the maximum number of characters
inputted can be specified: e.g. scanf(“%10s”,&x);

21
More problems with scanf

o Compiler does not check automatically if the


variable specified to hold input value(s) is
compatible with the format type specified
o Example:
int x
scanf(“%f”,&x);

i.e. using %f format to read a float value into an


integer variable
o It does not inform the user if the input is invalid –
such problems will remain undetected

22
gets() and puts()

o gets() is an efficient way to input strings


from the keyboard (Standard input).

Reads a string into named array and


append the null character

General Form: gets(Array name)


o puts() is an efficient way to display strings
on the screen (Standard Output).
Displays the contents of the named array on
the screen.
General Form: puts(Array name)

23
gets() and puts()

o Example

#include<stdio.h>

void main(void)
{
char Input_String[40];
gets(Input_String); // Read string
puts(Input_String); // Display string

24
gets() and puts()

25
Multidimensional array

o So far, we only look at one dimension arrays


o Arrays can have two dimensions or more

0 1 2 ….. 23 24 25
char X[26]; X A B C ….. X Y Z
char X[2][26]; X a b c ….. x y z
X α β χ ….. ξ ψ ζ
char X[n][26];

26
Multidimensional array
o Example
void main ()
{
Char text[][13]={“first text\n”,
“second text\n”,
“third text\n”,
“last text\n”};
int counter1;
/*print complete strings*/
for (counter1=0; counter1<4; counter1++)
printf(“%s”, text[counter1]);
}

27
Example
# include <stdio.h>
void main ()
{
double amounts[2][10];
char titles[2][7] = {"Pounds", "Euros"};
double rates[] = {0.6078, 0.6654};
int i, j;

printf("US Dollar amounts converted to British "


"Pounds and Euros: \n\n");
for (i = 0; i < 2; i++) {
printf("%10s %10s\n", "Dollars", titles[i]);

for (j = 0; j < 10; j++) {


amounts[i][j] = (j+1)*5.00;
printf ("%10.2f %10.2f\n", amounts[i][j],
(amounts[i][j]*rates[i])); }
printf ("\n\n"); }
}

28
Example

29
Exercise 1

o Declare and initialize an array to hold the


following cities and their corresponding countries.
The array should be able to be accessed either by
City or Country :

Britain, London, Coventry, Birmingham,


Manchester, France, Paris, Marseille, Toulouse,
Lyon, Sweden, Malmo, Stockholm, Germany,
Berlin, Frankfurt, Dresden, Spain, Barcelona,
Vigo, Madrid, Seville.

30
Exercise 1

o Start by deciding upon the number of dimensions


and size of the array.
• How many dimensions will be required?
• How many elements for each dimension?
o How many dimensions?:
• Country, city, “string” 3 dimensions
o How many elements?:
• Country: 5
• City: maximum 4
• “string”: maximum 10 letters

31
Exercise 1
#include<stdio.h>
void main()
{
char Place[5][5][15]={“Britain”, “London”, “Coventry”, “Birmingham”,
“Manchester”, “France”, “ Paris”, “Marseille”, “Toulouse”, “Lyon”,
“Sweden”,”Malmo”, “Stockholm”, “” ,“”,“Germany”, ”Berlin”,
“Frankfurt”, “Dresden”, “”, “Spain”, “ Barcelona”, “Vigo”, “Madrid”,
“Seville”};

int C;
for(C=1;C<5;C++)
printf(“%s ”,Place[C][0]);
}
What is display on the screen?

32
Exercise 1

33
Exercise 1
#include<stdio.h>

void main()

char Place[5][5][15]={“Britain”, “London”, “Coventry”, “Birmingham”,


“Manchester”, “France”, “ Paris”, “Marseille”, “Toulouse”, “Lyon”,
“Sweden”,”Malmo”, “Stockholm”, “” ,“”,“Germany”, ”Berlin”,
“Frankfurt”, “Dresden”, “”, “Spain”, “ Barcelona”, “Vigo”, “Madrid”,
“Seville”};

int C;

printf(“%s is a city in %s\n”,Place[4][1], Place[4][0]);

What is display on the screen?

34
Exercise 1

35
Common pitfalls with arrays in C

o C does not provide protection against exceeding


the size of an array.
o Arrays must be of a fixed size. Once defined the
array size is fixed.
o The size of an array containing a string should be
greater by 1 than the number of letters.
o An array index starts at 0.

36

Das könnte Ihnen auch gefallen