Upload
meljun-cortes
View
58
Download
1
Tags:
Embed Size (px)
Citation preview
Exploring Arrays and Exploring Arrays and StringsStrings
C Programming C Programming LanguageLanguage
MELJUN CORTESMELJUN CORTES
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 2
ObjectivesObjectives
WeWe’’ll learnll learn Declare one-dimensional arraysDeclare one-dimensional arrays Use stringsUse strings Create multidimensional arraysCreate multidimensional arrays Initialize arraysInitialize arrays Build arrays of stringsBuild arrays of strings
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 3
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
Arrays ?Arrays ? A list of variables that are all of the same type and are accessed A list of variables that are all of the same type and are accessed
through a common name.through a common name. Form a convenient way to handle groups of related data.Form a convenient way to handle groups of related data.
The general form of one-dimensional ArrayThe general form of one-dimensional Array
typetype : data type : data type var_namevar_name : array name : array name sizesize : the number of elements : the number of elements
type var_name[size]; type var_name[size];
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 4
Declaration of ArrayDeclaration of Array type var_name[size];type var_name[size];
ex) int grade[5];ex) int grade[5];
grade[0], grade[1], . . . , grade[4]grade[0], grade[1], . . . , grade[4]
Index : Index : 00 ~ ~ Size Size –– 1 1 var_name[index]var_name[index] corresponds to a variable. corresponds to a variable. index range of array[n] : ( index range of array[n] : ( 0 ~ n-10 ~ n-1 ) )
Often mistake for ( Often mistake for ( 1 ~ n1 ~ n ) )
⇒ It can have an fatal effect on the program.It can have an fatal effect on the program.
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 5
Declaration of ArrayDeclaration of Array
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 6
Usually using arrayUsually using array for ( i = 0 ; i < N ; i++ )for ( i = 0 ; i < N ; i++ )
a[i] = 0 ;a[i] = 0 ; /* clear a *//* clear a */
for ( i = 0 ; i < N ; i++ )for ( i = 0 ; i < N ; i++ )
scanf("%d", &a[i]) ;scanf("%d", &a[i]) ; /* reads data into a *//* reads data into a */
for ( i = 0 ; i < N ; i++ )for ( i = 0 ; i < N ; i++ )
sum += a[i] ;sum += a[i] ; /* sums the elements of a *//* sums the elements of a */
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 7
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
The scores arrayThe scores array
int scores[9];int scores[9];
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 8
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
#include <stdio.h> int main(void) {
int sqrs[10];int i;
for(i=1; i<11; i++) sqrs[i-1] = i*i;for(i=0; i<10; i++) printf("%d ", sqrs[i]);
return 0; }
#include <stdio.h> int main(void) {
int sqrs[10];int i;
for(i=1; i<11; i++) sqrs[i-1] = i*i;for(i=0; i<10; i++) printf("%d ", sqrs[i]);
return 0; }
Using arrayUsing array This program loads theThis program loads the sqrs sqrs array with the squares of the array with the squares of the
numbers 1 through 10 and then displays them.numbers 1 through 10 and then displays them.
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 9
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
Using arrayUsing array When you want to use scanf() to input a numeric value into an When you want to use scanf() to input a numeric value into an
array element, simply put the & in front of the array name. array element, simply put the & in front of the array name. Ex) This call to scanf() reads an integer into count[9]Ex) This call to scanf() reads an integer into count[9]
In C, you may not assign one entire array to anotherIn C, you may not assign one entire array to another Ex) This fragment is incorrectEx) This fragment is incorrect
scanf("%d", &count[9]) ;scanf("%d", &count[9]) ;
char a1[10], a2[10] ; : : a2 = a1 ; /* this is wrong */
char a1[10], a2[10] ; : : a2 = a1 ; /* this is wrong */
for(t=0; t<SIZE; t++)
a2[t] = a1[t];
for(t=0; t<SIZE; t++)
a2[t] = a1[t];
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 10
Example 1.Example 1. Arrays are very useful when lists of information need to be managed.Arrays are very useful when lists of information need to be managed.
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 11
Example 2.Example 2. This program loads This program loads a1a1 with the numbers 1 through 10 and then copies with the numbers 1 through 10 and then copies
them into them into a2a2..
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 12
Example 3.Example 3. The user first enters the message, which is stored in a character array. The user first enters the message, which is stored in a character array.
When the user presses When the user presses ENTERENTER, the entire message is then encoded by , the entire message is then encoded by adding 1 to letter.adding 1 to letter.
1.1. Declare one-dimensional arraysDeclare one-dimensional arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 13
2. Initialize Arrays2. Initialize Arrays
You can give the elements of arrays initial values. You can give the elements of arrays initial values.
Integer arrayInteger array int i[5] = { 1, 4, 9, 16, 25 } ;int i[5] = { 1, 4, 9, 16, 25 } ;
Character arrayCharacter array char a[3] = { 'A', 'B', 'C' } ; char a[3] = { 'A', 'B', 'C' } ;
char i[5] = "Herb" ;char i[5] = "Herb" ;
type array-name[size] = {value-list} ;
• value-list : a comma-separated list of constants that are type compatible with the base type of the array.
type array-name[size] = {value-list} ;
• value-list : a comma-separated list of constants that are type compatible with the base type of the array.
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 14
2. Initialize Arrays2. Initialize Arrays
You can give the elements of arrays initial values. You can give the elements of arrays initial values.
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 15
2. Initialize Arrays2. Initialize Arrays
/* Squares array */#include <stdio.h>#define ARY_SIZE 5
void main () {int i;int sqrAry[ARY_SIZE];
for (i = 0; i < ARY_SIZE; i++) sqrAry[i] = i * i;
printf("Element\tSquare\n");printf("=======\t======\n");for (i = 0; i < ARY_SIZE; i++) printf("%5d\t%4d\n", i, sqrAry[i]);
}
Result Element Square
======= ====== 0 0 1 1 2 4 3 9 4 16
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 16
2. Initialize Arrays2. Initialize Arrays
ExercisesExercises
Write a program that reads ten numbers entered by the user
and reports if any of them match.
Write a program that reads ten numbers entered by the user
and reports if any of them match.
====== Mapping Checking Program ======Enter ten numbers : 1 2 3 4 5 6 7 8 9 10Enter a mapping number : 55 is in your array[4].Enter a mapping number : 1212 is not in your array.Enter a mapping number : 0===== Good Bye ~~!! =====
====== Mapping Checking Program ======Enter ten numbers : 1 2 3 4 5 6 7 8 9 10Enter a mapping number : 55 is in your array[4].Enter a mapping number : 1212 is not in your array.Enter a mapping number : 0===== Good Bye ~~!! =====
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 17
3. Use String3. Use String
StringString The most common use of the one-dimensional array in C is the The most common use of the one-dimensional array in C is the
string.string. A string is defined as a null-terminated character array.A string is defined as a null-terminated character array.
The size of array must have one byte larger than the largest string.The size of array must have one byte larger than the largest string.
String constantString constant A series of characters is surrounded by double quotation A series of characters is surrounded by double quotation
markmark((“”“”)) ““This is a stringThis is a string””, , ““HelloHello””, , ““xyz 123xyz 123””
End of a string mark : null character End of a string mark : null character ‘‘\0\0’’ ASCII value is 0. ASCII value is 0.
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 18
3. Use String3. Use String
Storing string and charactersStoring string and characters
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 19
3. Use String3. Use String
String and character arrayString and character array
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 20
3. Use String3. Use String
String and charactersString and characters
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 21
3. Use String3. Use String
String variablesString variables C language doesnC language doesn’’t have string type.t have string type. String variables use char array.String variables use char array.
char str[11];char str[11]; char str[11] = char str[11] = ““Good DayGood Day””;; char month[] = char month[] = ““JanuaryJanuary””;; char *pStr = char *pStr = ““Good Day!Good Day!””;; char str[10] = {char str[10] = {‘‘GG’’,,’’oo’’,,’’oo’’,,’’dd’’,,’’ ’’,,’’DD’’,,’’aa’’,,’’yy’’,,’’!!’’,,’’\0\0’’};};
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 22
3. Use String3. Use String
CC’’s standard library functions for strings standard library functions for string gets(str)gets(str) : reads characters until you press ENTER.: reads characters until you press ENTER. strcpy(to, from)strcpy(to, from) : is used copy the contents : is used copy the contents fromfrom into into toto.. strcat(to, from)strcat(to, from) : concatenates a copy of: concatenates a copy of from from to to toto and and
terminates terminates fromfrom with a null. with a null. strcmp(s1, s2)strcmp(s1, s2) : lexicographically compares two strings and: lexicographically compares two strings and
returns an integer based on the outcomereturns an integer based on the outcome
- - s1 is less than s2 s1 is less than s2 less than 0less than 0
- s1 is equal to s2 - s1 is equal to s2 00
- s1 is greater than s2 - s1 is greater than s2 greater than 0greater than 0 strlen(str)strlen(str) : returns the length of the string pointed to by str: returns the length of the string pointed to by str
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 23
3. Use String3. Use String
String inputString input
#include <stdio.h> int main(void) {
char str[80];int i;
printf("Enter a string (less than 80 chars) : \n");gets(str); /* input the string */for(i=0; str[i]; i++) printf("%c", str[i]); /* output the string */
return 0; }
#include <stdio.h> int main(void) {
char str[80];int i;
printf("Enter a string (less than 80 chars) : \n");gets(str); /* input the string */for(i=0; str[i]; i++) printf("%c", str[i]); /* output the string */
return 0; }
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 24
3. Use String3. Use String
String inputString input
#include <stdio.h> int main(void) {
char str[80];int i;
printf("Enter a string (less than 80 chars) : \n");gets(str); /* input the string */printf(str); /* output the string */
return 0; }
#include <stdio.h> int main(void) {
char str[80];int i;
printf("Enter a string (less than 80 chars) : \n");gets(str); /* input the string */printf(str); /* output the string */
return 0; }
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 25
3. Use String3. Use String
String input/output functionString input/output function Using gets() and puts()Using gets() and puts()
gets() reads characters until you press ENTER.gets() reads characters until you press ENTER. scanf() reads characters until you press blank, space or ENTER.scanf() reads characters until you press blank, space or ENTER.
puts(message); printf(“%s”, message);gets(message); ≠ scanf(“%s”, message);
puts(message); printf(“%s”, message);gets(message); ≠ scanf(“%s”, message);
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 26
3. Use String3. Use String
String input functionString input function
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 27
3. Use String3. Use String
String output functionString output function
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 28
3. Use String3. Use String
String output functionString output function
#include <stdio.h>#define MAXCHARS 81
void main(void) { char message[MAXCHARS]; /* enough storage for a complete line */
printf("Enter a string:\n"); gets(message); printf("The string just entered is:\n"); puts(message);}
#include <stdio.h>#define MAXCHARS 81
void main(void) { char message[MAXCHARS]; /* enough storage for a complete line */
printf("Enter a string:\n"); gets(message); printf("The string just entered is:\n"); puts(message);}
Enter a string:This is a test input of a string.The string just entered is:This is a test input of a string.
Enter a string:This is a test input of a string.The string just entered is:This is a test input of a string.
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 29
3. Use String3. Use String
String manipulation functionString manipulation function String manipulation library : String manipulation library : <string.h><string.h>
String Length : String Length : strlen()strlen() function function
Returns the length, in characters, of a stringReturns the length, in characters, of a string
str… (parameters)
strlen(str) : 8char str[12];
int strlen(str)
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 30
3. Use String3. Use String
String manipulation functionString manipulation function String Copy : String Copy : strcpy()strcpy() function function
Copys the contents of Copys the contents of fromfrom to to toto..
strcpy(to, from) ;
char str[80];
strcpy(str, “hello”);printf(str);
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 31
3. Use String3. Use String
String Copy String Copy
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 32
3. Use String3. Use String
String manipulation functionString manipulation function String Concatenation : String Concatenation : strcat()strcat() function function
Adds the contents of Adds the contents of fromfrom to the contents of to the contents of toto..
strcat(to, from) ;
char str[80];
strcpy(str, “hello”);strcat(str, “ there”);printf(str);
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 33
3. Use String3. Use String
String Concatenation String Concatenation
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 34
3. Use String3. Use String
String Compare : String Compare : strcmp()strcmp() function function
Returns the result of comparison two strings.Returns the result of comparison two strings.
strcmp(s1, s2) ;
string1 str ing2 Size Results Returns
“ABC123”
“ABC123”
“ABC123”
“ABC123”
“ABC123”
“ABC”
“ABC123”
“ABC123”
“ABC456”
“ABC456”
“ABC”
“ABC”
“ABC123”
“123ABC”
8
3
4
3
4
3
-1
equal
equal
String1<string2
equal
String1>string2
equal
equal
0
0
< 0
0
> 0
0
0
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 35
3. Use String3. Use String
Return : 0
Return : < 0
Return : > 0
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 36
Example Example –– String manipulation functionString manipulation function
3. Use String3. Use String
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 37
Example Example –– String manipulation functionString manipulation function
3. Use String3. Use String
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 38
3. Use String3. Use String
ExercisesExercises
Write a program that repeatedly inputs string.
Each time a string is input, concatenate it with a second string
called bigstr.
Add newlines to the end of each string.
If the user types quit, stop inputting and display bigstr(which will
contain a record of all strings input).
Also stop if bigstr will be overrun by the next concatenation.
Write a program that repeatedly inputs string.
Each time a string is input, concatenate it with a second string
called bigstr.
Add newlines to the end of each string.
If the user types quit, stop inputting and display bigstr(which will
contain a record of all strings input).
Also stop if bigstr will be overrun by the next concatenation.
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 39
4. Multidimensional Arrays4. Multidimensional Arrays
Multidimensional ArrayMultidimensional Array You can create arrays of two or more dimensions`You can create arrays of two or more dimensions` `̀
ex) 10 X 12 two-dimensional integer arrayex) 10 X 12 two-dimensional integer array
Two-dimensional arrayTwo-dimensional array 5 X 4 two-dimensional array5 X 4 two-dimensional array
int count[10][12] ; int count[10][12] ;
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 40
4. Multidimensional Arrays4. Multidimensional Arrays
Two-dimensional ArrayTwo-dimensional Array This program loads a 4X5 This program loads a 4X5
array with the products of array with the products of
the indices, then displays the indices, then displays
the array in row, column the array in row, column
format.format.
0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12
0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 41
4. Multidimensional Arrays4. Multidimensional Arrays
Initialization of Multidimensional Array Initialization of Multidimensional Array int table[5][4] = int table[5][4] = {0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, {0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23,
30, 31, 32, 33, 40, 41, 42, 43}; 30, 31, 32, 33, 40, 41, 42, 43}; int table[5][4] = int table[5][4] = {{0, 1, 2, 3}, {10, 11, 12, 13},{{0, 1, 2, 3}, {10, 11, 12, 13},
{20, 21, 22, 23}, {30, 31, 32, 33}, {20, 21, 22, 23}, {30, 31, 32, 33}, {40, 41, 42, 43} {40, 41, 42, 43} };};
int table[ ][4] = int table[ ][4] = {{0, 1, 2, 3}, {10, 11, 12, 13},{{0, 1, 2, 3}, {10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}, {20, 21, 22, 23}, {30, 31, 32, 33}, {40, 41, 42, 43}{40, 41, 42, 43} };};
int table[5][4] = int table[5][4] = {0}; {0}; All zero All zero
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 42
4. Multidimensional Arrays4. Multidimensional Arrays
Three-Dimensional ArrayThree-Dimensional Array Add the size of the additional dimension.Add the size of the additional dimension.
ex) 5 X 4 X 3 three-dimensional arrayex) 5 X 4 X 3 three-dimensional array
float values[5][4][3] ; float values[5][4][3] ;
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 43
ExampleExample
4. Multidimensional Arrays4. Multidimensional Arrays
MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS
School of Computer InformationSchool of Computer Information 44
4. Multidimensional Arrays4. Multidimensional Arrays
ExercisesExercises
Write a program that defines a 3X3X3 three-dimensional array,
and load it with the numbers 1 to 27.
And display the sum of its elements.
Write a program that defines a 3X3X3 three-dimensional array,
and load it with the numbers 1 to 27.
And display the sum of its elements.