unit 6. arrays

38
UNIT 6 ARRAYS

Upload: ashim-lamichhane

Post on 13-Jan-2017

281 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Unit 6. Arrays

UNIT 6ARRAYS

Page 2: Unit 6. Arrays

Ashim Lamichhane 2

Arrays• An array is used to store a collection of data, but it is often more useful to think of an array

as a collection of variables of the same type.

• Array is a data structure that store a number of data items as a single entity (object) .

• The individual data items are called elements and all of them have same data types.

• Array is used when multiple data items have common characteristics are required.

Page 3: Unit 6. Arrays

Ashim Lamichhane 3

• Instead of declaring, • such as number0, number1, ..., and number99, • We declare one array variable such as numbers and use numbers[0],

numbers[1], and ..., numbers[99] to represent individual variables. • A specific element in an array is accessed by an index.

• All arrays consist of contiguous memory locations.

• The lowest address corresponds to the first element and the highest address to the last element.

Page 4: Unit 6. Arrays

Ashim Lamichhane 4

How to Define an Array?• An Array is defined as following

<storage_class> <type-of-array> <name-of-array> [<number of elements in array>];

• storage_class: it may be auto, register, static and extern. [Optional]

• type-of-array: It is the type of elements that an array stores. E.x. ‘char’, ‘int’.

• name-of-array: This is the name that is given to array. At least the name should be in context with what is being stored in the array.

• [number of elements]: This value in subscripts [] indicates the number of elements the array stores.

Page 5: Unit 6. Arrays

Ashim Lamichhane 5

For example (ONE DIMENSIONAL ARRAY)• an array of five characters can be defined as :• char arr[5];

• to declare a 10-element array called balance of type double:• double balance[10];

• int num[35]; /* An integer array of 35 elements */

• char ch[10]; /* An array of characters for 10 elements */

Page 6: Unit 6. Arrays

Ashim Lamichhane 6

Initializing Array• You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

• The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].

• If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

• Ex: balance[4] = 50.0;

• The above statement assigns the 5th element in the array with a value of 50.0.

Page 7: Unit 6. Arrays

Ashim Lamichhane 7

• All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1.

• Shown below is the pictorial representation of the array we discussed earlier:

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

Page 8: Unit 6. Arrays

Ashim Lamichhane 8

Accessing Array Elements• An element is accessed by indexing the array name. • This is done by placing the index of the element within square

brackets after the name of the array. For example −double salary = balance[4];

• The above statement will take the 10th element from the array and assign the value to salary variable.

Page 9: Unit 6. Arrays

Ashim Lamichhane 9

example#include <stdio.h> int main () {

int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100; /* set element at location i to i + 100 */ }

/* output each array element's value */ for (j = 0; j < 10; j++ ) {

printf("Element[%d] = %d\n", j, n[j] ); }

return 0; }

Page 10: Unit 6. Arrays

Ashim Lamichhane 10

[IMP] WAP to sort n numbers in ascending order.#include <stdio.h>int main(void){

int nums[50],i,j,n,temp;printf("How many Numbers are there?\t");scanf("%d",&n);printf("\nEnter %d numbers: \n",n);for(i=0;i<n;i++){

scanf("%d",&nums[i]);}for (i = 0; i < n-1; ++i){

for (j=i+1; j < n;j++) {if(nums[i]>nums[j]){

temp=nums[i];nums[i]=nums[j];nums[j]=temp;}

}}

printf("\nThe numbers in ascending order:\n");for(i=0; i<n;i++){

printf("\t%d",nums[i]);}

printf("\n");}

Page 11: Unit 6. Arrays

Ashim Lamichhane 11

Characteristics Of An Array• The declaration of int a[5] is nothing but creation of 5 variables of integer

type in the memory.

• All the elements of an array share the same name. distinguished from one another by element number or array index.

• Any element can be modified separately without disturbing another element.

• Element basis operation should be carried out rather than taking as a whole.

Page 12: Unit 6. Arrays

Ashim Lamichhane 12

Questions (Classwork)• WAP to read 10 integers from keyboard and display entered numbers

on the screen.

• WAP that reads mark’s percentage in an examination of 10 students and deviation percentage from average of students.

• [IMP] WAP to find the highest and second last smallest number of an element.

Page 13: Unit 6. Arrays

Ashim Lamichhane 13

Multi Dimensional Array• Have more than one dimensions.

• Separate pair of square brackets is required for each subscript or dimension or index.

• Two dimensional arrays will require two pairs of square brackets; three dimensional with three pairs and so on.

• Two dimensional is also called matrix.

Page 14: Unit 6. Arrays

Ashim Lamichhane 14

storage_class data_type array_name[dim1] [dim2] … [dimn];

• Here, dim1,dim2…dimn are positive valued integer expressions that indicate the number of array elements associated with each subscript.

• m*n two dimensional array can be thought as tables of values having m rows and n columns.

• For ex int x[3][3] can be shown as follows:

Col 1 Col 2 Col 3

ROW 1 X[0][0] X[0][1] X[0][2]

ROW 2 X[1][0] X[1][1] X[1][2]

ROW 3 X[2][0] X[2][1] X[2][2]

Page 15: Unit 6. Arrays

Ashim Lamichhane 15

Declaration of two-dimensional array• Like one dimensional array, two dimensional arrays must also be

declared before using it.

• The syntax:[storage_class] data_type array_name[row_size][col_size];

• Example:• int matrix[2][3]; /* matrix is 2-D array which has 2 rows and 3 columns */• float m[10][20];• char students[10][15];

Page 16: Unit 6. Arrays

Ashim Lamichhane 16

Initialization of 2-D array• int marks[2][3]={ {2,4,6}, {8,10,12} }; //is equivalent to

• marks[0][0]=2;marks[0][1]=4;marks[0][2]=6;• marks[1][0]=8;marks[1][1]=10; marks[1][2]=12;

• int marks1[ ][3]= { {2,4,6}, {8,10,12} }; // is equivalent to• marks1[0][0]=2; marks1[0][1]=4; marks1[0][2]=6;• marks1[1][0]=8; marks1[1][1]=10; marks1[1][2]=12;

• int marks2[2][3]={2,4,6,8,10,12};

• Int marks3[][3]={2,4,6,8,10,12};

ERRORS:

• Int marks[3][]={2,4,6,8,10,12}; int marks[ ][ ]={2,4,6,8,10};

Page 17: Unit 6. Arrays

Ashim Lamichhane 17

Accessing 2-D array elements• In 2-D array, the first dimension specifies number of rows and second

specifies columns.

• A row is 1-D array. 2-D array contains multiple rows(i.e. 1-D arrays). Thus 2-D array is an array of 1-D arrays.

• 2-D array is traversed row by row(i.e. every column elements in first row are traversed first and then column elements of second row are traversed and so on.)

• Nested loop is used to traverse the 2-D array.

Page 18: Unit 6. Arrays

Ashim Lamichhane 18

• Let us consider following 2-D array marks of size 4*3 • i.e. matrix having 4 rows and 3 columns

• The Array is traversed in the following order:35 ->10 ->11 ->34 ->90 ->76 ->13 ->8 ->5 ->76 ->4 ->1

• i.e marks[0][0] -> marks[0][1] -> marks[0][2] -> marks[1][0] -> marks[1][1] -> marks[1][2] -> marks[2][0] -> marks[2][1] -> marks[2][2] -> marks[3][0] -> marks[3][1] -> marks[3][2].

35 10 11

34 90 76

13 8 5

76 4 1

Page 19: Unit 6. Arrays

Ashim Lamichhane 19

#include <stdio.h>int main(void){int matrix[2][3],i,j;for(i=0;i<2;i++){for(j=0;j<3;j++){printf("Enter Matrix[%d][%d]: ",i,j); scanf("%d",&matrix[i][j]);}}printf("The Entered Matrx\n");for(i=0;i<2;i++){for(j=0;j<3;j++){printf("%d\t",matrix[i][j]);}printf("\n");}

}

Page 20: Unit 6. Arrays

Ashim Lamichhane 20

WAP: Sum of matrix//FOR FIRST MATRIX Afor(i=0;<m;i++){for(j=0;j<n;j++){

scanf(“%d”,&a[i][j]);}}

//FOR FIRST MATRIX B

for(i=0;<m;i++){for(j=0;j<n;j++){scanf(“%d”,&b[i][j]);}}

//FOR sumfor(i=0;<m;i++){

for(j=0;j<n;j++){sum[i][j]=a[i][j]+b[i][j];}}

Page 21: Unit 6. Arrays

Ashim Lamichhane 21

Passing arrays to function• It is possible to pass the value of an array element and even an entire

array as an argument to a function.

• To pass an entire array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument in function call statement.

• When declaring a one-dimensional array as a formal argument, the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration.

Page 22: Unit 6. Arrays

Ashim Lamichhane 22

• Syntax for function call passing array as argument,function_name(array_name)

• Syntax for function prototype which accepts arrayreturn_type function_name(data_type array_name[]);Orreturn_type function_name(data_type *pointer_variable);

• When array is passed to a function, the values of the array elements are not passed to the function rather the array name is interpreted as the address of the first array element.

• The address assigned to the corresponding formal argument when the function is called.

• The formal argument therefore becomes a pointer to the first array element.

Page 23: Unit 6. Arrays

Ashim Lamichhane 23

#include <stdio.h>void display(int n){

printf("%d\t", n );}

int main(void){int nums[5]={100,23,44,3,65},i;printf("\nThe content of array is: \n");for (int i = 0; i < 5; i++){

display(nums[i]);}

}

Page 24: Unit 6. Arrays

Ashim Lamichhane 24

WAP to illustrate passing an entire array to a function#include <stdio.h>void change(int a[]){

a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50;}

int main(void){int nums[5]={100,23,44,3,65},i;printf("\nBEFORE FUNCTION CALL: \n");for (int i = 0; i < 5; i++) {printf("\t%d",nums[i]);}printf("\n");change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */printf("\nAFTER FUNCTION CALL\n");for (int i = 0; i < 5; i++) {printf("\t%d",nums[i]);

} printf("\n");}

Page 25: Unit 6. Arrays

Ashim Lamichhane 25

Arrays and Strings• In C programming, array of character are called strings. A string is terminated by null

character \0. For example:Ex. "c string tutorial"

• Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character at the end of string.

• Strings are actually one-dimensional array of characters terminated by a null character '\0'.

• If you follow the rule of array initialization then you can write the above statement as follows −char greeting[] = "Hello";

c s t r i n g t u t o r i a l \0

Page 26: Unit 6. Arrays

Ashim Lamichhane 26

char greeting[] = "Hello";Following is the memory presentation of the above defined string in C −

Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '\0' at the end of the string when it initializes the array.

INDEX 0 1 2 3 4 5

VARIABLE H e l l o \0

ADDRESS 0x23452 0x23453 0x23454 0x23455 0x23456 0x23457

Page 27: Unit 6. Arrays

Ashim Lamichhane 27

Initialization of strings• In C, string can be initialized in different number of ways.

char c[]="abcd"; OR,

char c[5]="abcd"; OR,

char c[]={'a','b','c','d','\0'}; OR;

char c[5]={'a','b','c','d','\0'};

C[0] C[1] C[2] C[3] C[4]

a b c d \0

Page 28: Unit 6. Arrays

Ashim Lamichhane 28

Declaration of strings• Strings are declared in C in similar manner as arrays. Only difference is

that, strings are of char type.char s[5];

• Strings can also be declared using pointer. char *p

(will be discussed in future chapters)

s[0] s[1] s[2] s[3] s[4]

Page 29: Unit 6. Arrays

Ashim Lamichhane 29

• Let us try to print the above mentioned string −

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

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0;

}

OUTPUT:Greeting message: Hello

Page 30: Unit 6. Arrays

Ashim Lamichhane 30

Write a C program to illustrate how to read string from terminal.

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

char name[20]; printf("Enter name: "); scanf("%s",name); printf("Your name is %s.",name); return 0;

}OUTPUT:Enter name: Dennis Ritchie Your name is Dennis.

NOTE: Here, program will ignore Ritchie because, scanf() function takes only string before the white space.

Page 31: Unit 6. Arrays

Ashim Lamichhane 31

C program to read line of text manually.#include <stdio.h> int main(){

char name[30],ch; int i=0; printf("Enter name: "); while(ch!='\n') // terminates if user hit enter { ch=getchar(); name[i]=ch; i++; } name[i]='\0'; // inserting null character at end printf("Name: %s",name);return 0;

}

This process to take string is tedious. There are predefined functions gets() and puts in C language to read and display string respectively.

Page 32: Unit 6. Arrays

Ashim Lamichhane 32

int main(){ char name[30]; printf("Enter name: "); gets(name); //Function to read string from user. printf("Name: "); puts(name); //Function to display string. return 0;

}• Both, the above program has same output below:

• OutputEnter name: Tom Hanks Name: Tom Hanks

Page 33: Unit 6. Arrays

Ashim Lamichhane 33

Passing Strings to Functions#include <stdio.h> void Display(char ch[]); int main(){

char c[50]; printf("Enter string: "); gets(c); Display(c); // Passing string c to function. return 0;

} void Display(char ch[]){

printf("String Output: "); puts(ch);

}• Here, string c is passed from main() function to user-defined function Display(). In function declaration, ch[] is

the formal argument.

Page 34: Unit 6. Arrays

Ashim Lamichhane 34

C supports a wide range of functions that manipulate null-terminated strings −

S.N. Function & Purpose(these functions are defined in header file string.h)

1 strcpy(s1, s2);Copies string s2 into string s1.

2 strcat(s1, s2);Concatenates string s2 onto the end of string s1.

3 strlen(s1);Returns the length of string s1.

4 strcmp(s1, s2);Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);Returns a pointer to the first occurrence of character ch in string s1.

6 strrev(s1);Returns reverse of a string s1

Page 35: Unit 6. Arrays

Ashim Lamichhane 35

#include <stdio.h> #include <string.h> int main () {

char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; /* copy str1 into str3 */ strcpy(str3, str1); printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */ strcat( str1, str2); printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */ len = strlen(str1); printf("strlen(str1) : %d\n", len ); return 0;

}

Strcpy(str3,str1) Hello

Strcat(str1,str2) HelloWorld

Strlen(str1) 10

Page 36: Unit 6. Arrays

Ashim Lamichhane 36

Please do check Google Drive for Assignment

Page 37: Unit 6. Arrays

Ashim Lamichhane 38

Reference• http://www.thegeekstuff.com/2011/12/c-arrays/• http://www.tutorialspoint.com/cprogramming/c_arrays.htm• http://c.learncodethehardway.org/book/ex10.html• http://beginnersbook.com/2014/01/c-arrays-example/• A Textbook Of C programming by Ram Datta Bhatta• http://www.cprogramming.com/tutorial/c/lesson9.html• http://www.programiz.com/c-programming/c-strings

Page 38: Unit 6. Arrays

Ashim Lamichhane 39

END