Anda di halaman 1dari 46

ARRAYS AND STRINGS

One Dimensional Arrays Initialization of Arrays

ARRAYS
Arrays are used to store collections of related data.

ONE DIMMENSIONAL ARRAYS


In an array multiple values of the same data type can be stored with one variable name.

ARRAY - NAME
When we declare variables to be arrays, we can use the name of the variable to access all the elements in the collection.

SAMPLE ARRAY
Suppose an array named test_scores will be used to store the scores on a test. This array might be visualized as follows test_scores 89 75 93 68 77 83 0 1 2 3 4 5

SAMPLE ARRAY
test_score is the variable name the collection of the 5 data object each data object occupies one cell of the array the numbers below are indices into the array

EXAMPLE
test_scores [ 2 ] the variable name test_score and an index 2 inside a pair of brackets [ ] are used to access the contents of the cell of an array test_score [ 2] refers to 93 that is stored

WHAT YOU NEED TO KNOW ABOUT ARRAYS IN C


You have to 1. How to declare arrays 2. How individual cells are addressed 3. How to initialize arrays.

void main( void ) { int test_scores[10]; int i;

/* Note 1*/

printf( "Please enter the ten test scores now.\n" ); for ( i = 0; i < 10; i++ ) { /* Note 2 */ printf( "#%2d > ", i+1 ); /* Note 3 */ scanf( "%d", &test_scores[i] ); /* Note 4 */ } printf( "Thank you.\n" ); }

Note 1:
The variable test_scores is defined as an array of 10 elements of type int. The indicies will be the integers 0 through 9

void main( void ) { int test_scores[10]; int i;

/* Note 1*/

printf( "Please enter the ten test scores now.\n" ); for ( i = 0; i < 10; i++ ) { /* Note 2 */ printf( "#%2d > ", i+1 ); /* Note 3 */ scanf( "%d", &test_scores[i] ); /* Note 4 */ } printf( "Thank you.\n" ); }

Note 2:
In the for loop, the variable i will act as an index into the array It will consecutively take on the values 0 through 9. The loop terminates when i is incremented to 10.

Note 3:
The printf ( ) call outputs a prompt for each of the test scores. For the users convenience, the test scores are numbered 1 through 10 instead of the index values of 0 through 9.

ARRAY DECLARATION
Contains the following information: 1. Type of elements that will be stored 2. Name of the array 3. Fact that this variable is an array 4. number of cells must be stated ( only when the declaration is also a definition - memory must be allocated)

ARRAY DECLARATION
int test_scores [10] Type Variable Name Number of Cells Indices
int test_score 10 0, 1, 2, 3,9

ARRAY INDEX (INDICES)


In C integers are the only choice for array indices The first cell will always have index 0 The last cell will always have index one less than the total number of cells

I=n-1

ARRAY MEMORY
When an array is defined a contiguous (array cells are placed in adjacent memory locations) block of memory is allocated that is large enough to hold all elements. The elements will be stored in order of the indices.

Sizeof( ) an ARRAY
The operations allowed on an array element are those allowed on any expression with the same underlying type. There is only one (1) operator that can act on the array as a whole: sizeof ( ) This operator indicates the total amount of memory used by the array.

Sizeof ( ) array
int example [ 4 ] assume that an int occupies 2 bytes the value of the expression sizeof ( example ) 4 x 2 = 8 bytes

INITIALIZATION OF ARRAYS
When arrays are initialized at the time of declaration, the initial values are placed in a commaseparated list enclosed in braces char name [6] = { S, a, L, L, y, \O};

INITIALIZATION OF ARRAYS
char name [6] = { S, a, L, L, y, \O}; variable name name number of elements 6 element type char range 0 to 5 initial values constants

ASSIGNMENT STATEMENTS
char name [6] = { S, a, L, L, y, \O}; establishing the values in the array names can also be done with 6 assignment statements name [0] = S; name [1] = a; name [2] = L; name [3] = L; name [4] = y; name [5] = \O;

INITIALIZING EXAMPLE
int numbers [8] = { 4, 0, 5, 6}; variable name numbers type int number of cells 8 indices 0 to 7

INITIALIZING EXAMPLE
int numbers [8] = { 4, 0, 5, 6}; contents of array 40560000 01234567 The number of initial values was less than the number of cells in the array.

INITIALIZATION OF ARRAYS
float dollars [ ] = { 1.37, 45.68, 3.45 } ; variable name dollars type float number of cells missing number of initial values 3

INITIALIZATION OF ARRAYS
float dollars [ ] = { 1.37, 45.68, 3.45 } ; 1.37 45.68 3.45 0 1 2 Because 3 initial values were given, the array will have 3 cells Each cell will contain one of the initial values.

VARIABLE DECLARATIONS
char float chararray [12]; floatvals [20];

OPERATORS
sizeof ( ) operator used with an array returns the number of bytes in that array

A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns one
dimension two dimensions

Two-Dimensional Arrays

29

A two-dimensional array is declared by specifying the size of each dimension separately:


int[][] scores = new int[12][50];

Two-Dimensional Arrays

A two-dimensional array element is referenced using two index values


value = scores[3][6]

The array stored in one row or column can be specified using one index
30

Multidimensional Arrays
An array can have many dimensions

If it has more than one dimension, it is called a multidimensional array


Each dimension subdivides the previous one into the specified number of elements Each array dimension has its own length constant

Int a[10][10]

31

Scan n For (i=0;i<n;i++) scan a[i] Big=a[0] Small=a[0]; For (i=1;i<n;i++) if (a[i]>big) big =a[i] if (a[i]<small small=a[i];

12 7 10 2 5 If (a[i]>aa[j] swapping

t=a[i] a[i]=a[i+1] a[i+1]=t

Matrix
Read number of rows (n) number of columns (m) For I = 1 to n for j=1 to m read a[i][j]; For I = 1 to n for j=1 to n write a[i][j];

Matrix addition and substraction


For I = 1 to n for j=1 to m read a[i][j]; For I = 1 to n for j=1 to m read b[i][j]; C[i][j]=a[i][j] + b[i][j]; D[i][j]= a[i][j] + b[i][j];

Matrix multiplication
n m 1 2 3 4 p q 5 2 2 2 n q 9 6 23 14

For I = 1 to n { for j=1 to q { c[i][j]=0; for k = 1 to p { C[i][j]=a[I,k] * b[k][j] + c[i][j];

Strings

Strings
Strings are a group of characters. Called as character arrays String must be terminated by NULL character \0. Char name[] = {M,C,A} Any sequence or set of characters defined within double quotation symbols is a constant string. Normally each character is stored in one byte, successive characters are stored in successive bytes.

Reading Strings from the terminal: The function scanf with %s format specification is needed to read the character string from the terminal. Example: char address[15]; scanf(%s,address); Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space, suppose if we type the string new york then only the string new will be read and since there is a blank space after word new it will terminate the string. /*String.c string variable*/ #include < stdio.h > main() { char month[15]; printf (Enter the string); gets (month); printf (The string entered is %s, month); }

String operations (string.h)


C language recognizes that string is a different class of array by letting us input and output the array as a unit and are terminated by null character. C library supports a large number of string handling functions that can be used to array out many o f the string manipulations such as:
Length (number of characters in the string). Concatentation (adding two are more strings) Comparing two strings. Substring (Extract substring from a given string) Copy(copies one string over another)

strlen() function: This function counts and returns the number of characters in a string. The length does not include a null character. Syntax n=strlen(string); Where n is integer variable. Which receives the value of length of the string. Example length=strlen(Hollywood); The function will assign number of characters 9 in the string to a integer variable length. /*writr a c program to find the length of the string using strlen() function*/ #include < stdio.h > include < string.h > void main() { char name[100]; int length; printf(Enter the string); gets(name); length=strlen(name); printf(\nNumber of characters in the string is=%d,length); }

strcat() function: when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat() function joins 2 strings together. It takes the following form strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1. the string at string2 remains unchanged. Example

strcpy(string1,sri); strcpy(string2,Bhagavan); Printf(%s,strcat(string1,string2);

strcmp function: In c you cannot directly compare the value of 2 strings in a condition like if(string1==string2) Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp() is given below: Strcmp(string1,string2) String1 & string2 may be string variables or string constants. String1, & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second. Example: strcmp(Newyork,Newyork) will return zero because 2 strings are equal. strcmp(their,there) will return a 9 which is the numeric difference between ASCII i and ASCII r. strcmp(The, the) will return 32 which is the numeric difference between ASCII T & ASCII t.

strcmpi() function This function is same as strcmp() which compares 2 strings but not case sensitive. Example strcmpi(THE,the); will return 0. strcpy() function: C does not allow you to assign the characters to a string directly as in the statement name=Robert; Instead use the strcpy(0 function found in most compilers the syntax of the function is illustrated below. strcpy(string1,string2);

Strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant.
strcpy(Name,Robert); In the above example Robert is assigned to the string called name.

strlwr () function: This function converts all characters in a string from uppercase to lowercase.

syntax strlwr(string); For example: strlwr(EXFORSYS) converts to Exforsys.

strrev() function: This function reverses the characters in a string. Syntax


strrev(string); For ex strrev(program) reverses the characters in a string into margrop.

strupr() function: This function converts all characters in a string from lower case to uppercase. Syntax strupr(string);

Arithmetic operations on characters: We can also manipulate the characters as we manipulate numbers in c language. When ever the system encounters the character data it is automatically converted into a integer value by the system. We can represent a character as a interface by using the following method. X=a; Printf(%d\n,x); Will display 97 on the screen. Arithmetic operations can also be performed on characters for example x=z-1; is a valid statement. The ASCII value of z is 122 the statement the therefore will assign 121 to variable x.