Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming and Data Structures

Similar presentations


Presentation on theme: "Programming and Data Structures"— Presentation transcript:

1 Programming and Data Structures
Debasis Samanta Computer Science & Engineering Indian Institute of Technology Kharagpur Spring-2017

2 Lecture #4 Arrays and Strings
CS : Programming and Data Structures Lecture #04: © DSamanta

3 Today’s Discussion… Arrays Strings Basic concept 1-Dimensional Arrays
Declaration of 1-D arrays in C programs Initialization of 1-D arrays Some C programs dealing with 1-D arrays 2-Dimensional Arrays Declaration of 2-D arrays in C programs Initialization of 2-D arrays Strings Basic concepts Declaration of strings in C Initialization of a string C-library functions for strings Some C-programs with strings CS : Programming and Data Structures Lecture #04: © DSamanta

4 Arrays CS 11001 : Programming and Data Structures
Lecture #04: © DSamanta

5 Some Examples of Arrays
CS : Programming and Data Structures Lecture #04: © DSamanta

6 Basic Concept Many applications require multiple data items that have common characteristics. In mathematics, we often express such groups of data items in indexed form x1, x2, x3, …, xn Why are arrays essential for some applications? Reading some numbers from the keyboard and then Sort them in ascending order. To find the mode and standard deviation. etc. How such a set of data can be stored in computer and subsequently process them? CS : Programming and Data Structures Lecture #04: © DSamanta

7 Basic Concept 1-D array 3-D array 2-D array
CS : Programming and Data Structures Lecture #04: © DSamanta

8 1-D Arrays CS 11001 : Programming and Data Structures
Lecture #04: © DSamanta

9 x is a 10-element one dimensional array
Arrays Homogenous data types All the data items constituting the group share the same name. int x[10]; Individual elements are accessed by specifying the index. x[0] x[1] x[2] x[9] x is a 10-element one dimensional array CS : Programming and Data Structures Lecture #04: © DSamanta

10 Declaring Arrays Like variables, the arrays that are used in a program must be declared before they are used. General syntax: type array-name [size]; type specifies the type of element that will be contained in the array (int, float, char, etc.) size is an integer constant which indicates the maximum number of elements that can be stored inside the array. Example int marks[5]; Here, marks is an array containing a maximum of 5 integers. CS : Programming and Data Structures Lecture #04: © DSamanta

11 Examples Examples: Be careful! int n; int x[10]; char line[80];
float points[150]; char name[35]; Be careful! If we are not sure of the exact size of the array, we can define an array of a large size. int marks[50]; there is no element like x[50], x[-1], x[100], etc. The following kind of usage is illegal: int n; int marks[n]; CS : Programming and Data Structures Lecture #04: © DSamanta

12 How an array is stored in memory?
Starting from a given memory location, the successive array elements are allocated space in consecutive memory locations. Here, x is the starting address of the array in memory The array index starts at zero. That is, the location of a[0] is at x Let k is the number of bytes allocated per array element Element a[i] is allocated at the memory location having address x + i*k a x x+k x+2k CS : Programming and Data Structures Lecture #04: © DSamanta

13 A Warning In C, while accessing array elements, array bounds are not checked. Example: int marks[5]; : marks[8] = 75; The above assignment would not report any error; however, execution will fail. Rather, it may result in unpredictable program results. CS : Programming and Data Structures Lecture #04: © DSamanta

14 Initialization of Arrays
General form type array_name[size] = { list of values }; Examples int marks[5] = {72, 83, 65, 80, 76}; char name[4] = {‘A’, ‘m’, ‘i’, ‘t’}; Some special cases If the number of values in the list is less than the number of elements, then the remaining elements are automatically set to zero. float total[5] = {24.2, -12.5, 35.1}; total[0]=24.2, total[1]=-12.5, total[2]=35.1, total[3]=0, total[4]=0 CS : Programming and Data Structures Lecture #04: © DSamanta

15 Initialization of Arrays
If the size declares is less than the elements in the initialization, then the excess elements will be ignored float total[5] = {2.2, -1.5, 3.5, 0.1, 0.2, 0.4}; The last element namely 0.4 will be ignored! The size may be omitted. In such cases the compiler automatically allocates enough space for all initialized elements. int flag[] = {1, 1, 1, 0}; char name[] = {‘A’, ‘m’, ‘i’, ‘t’}; CS : Programming and Data Structures Lecture #04: © DSamanta

16 Example 1: Find the minimum of a Set of 10 Numbers
#include <stdio.h> main() { int a[10], i, min; for (i=0; i<10; i++) scanf (“%d”, &a[i]); min = 99999; if (a[i] < min) min = a[i]; } printf (“\n Minimum is %d”, min); Array declaration Reading array element Assessing array element CS : Programming and Data Structures Lecture #04: © DSamanta

17 Alternate Version #1 Change only one line to change the problem size.
#include <stdio.h> #define size 10 main() { int a[size], i, min; for (i=0; i<size; i++) scanf (“%d”, &a[i]); min = 99999; if (a[i] < min) min = a[i]; } printf (“\n Minimum is %d”, min); CS : Programming and Data Structures Lecture #04: © DSamanta

18 Alternate Version #2 Define an array of large size and use only the required number of elements. #include <stdio.h> main() { int a[100], i, min, n; scanf (“%d”, &n); /* Number of elements */ for (i=0; i<n; i++) scanf (“%d”, &a[i]); min = 99999; if (a[i] < min) min = a[i]; } printf (“\n Minimum is %d”, min); CS : Programming and Data Structures Lecture #04: © DSamanta

19 Example 2: Computing GPA
Handling two arrays at the same time. #include <stdio.h> #define nsub 6 main() { int grade_pt[nsub], cred[nsub], i, gp_sum=0, cred_sum=0, gpa; for (i=0; i<nsub; i++) scanf (“%d %d”, &grade_pt[i], &cred[i]); gp_sum += grade_pt[i] * cred[i]; cred_sum += cred[i]; } gpa = gp_sum / cred_sum; printf (“\n Grade point average: is %d”, gpa); CS : Programming and Data Structures Lecture #04: © DSamanta

20 Things You Cannot Do You cannot Suppose, a and b are two array names.
They cannot be used as ordinary variables use = to assign one array variable to another is not possible a = b; /* a and b are arrays */ use == to directly compare array variables is not allowed if (a == b) ……… directly scanf or printf arrays is not possible printf (“……”, a); CS : Programming and Data Structures Lecture #04: © DSamanta

21 Accessing Array int a[25], b[25];
How to copy the elements of one array to another? By copying individual elements for (j=0; j<25; j++) a[j] = b[j]; By reading them one element at a time scanf (“%f”, &a[j]); The ampersand (&) is necessary. Note: The elements can be entered all in one line or in different lines. CS : Programming and Data Structures Lecture #04: © DSamanta

22 Accessing Array int a[25]; Printing Array (array elements)
By printing them one element at a time. for (j=0; j<25; j++) printf (“\n %f”, a[j]); The elements are printed all in one line (starting with a new line). printf (“\n”); printf (“%f”, a[j]); CS : Programming and Data Structures Lecture #04: © DSamanta

23 2-D Arrays CS 11001 : Programming and Data Structures
Lecture #04: © DSamanta

24 Two Dimensional Arrays
Many applications require us to store a table of values. The table contains a total of 20 values, five in each line. The table can be regarded as a matrix consisting of four rows and five columns. C allows us to define such tables of items by using 2-D arrays. Subject 1 Subject 2 Subject 3 Subject 4 Subject 5 Student 1 75 82 90 65 76 Student 2 68 80 70 72 Student 3 88 74 85 Student 4 50 40 CS : Programming and Data Structures Lecture #04: © DSamanta

25 Declaring 2-D Arrays General form:- Examples
type array_name [row_size][column_size]; Examples int marks[4][5]; float sales[12][25]; double matrix[100][100]; CS : Programming and Data Structures Lecture #04: © DSamanta

26 Accessing Elements of a 2-D Array
Similar to that for 1-D array, but use two indices. Examples x[m][n] = 0; c[i][k] += a[i][j] * b[j][k]; First indicates row, second indicates column. Both the indices may be expressions which would evaluate to integer values. x = sqrt (a[j*3][k+2]); CS : Programming and Data Structures Lecture #04: © DSamanta

27 Storing a 2-D Array in Memory
Starting from a given memory location, the elements are stored row- wise in consecutive memory locations. x: starting address of the array in memory c: number of columns k: number of bytes allocated per array element a[i][j] :: is allocated memory location at address x + (i * c + j) * k a[0]0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] Row 0 Row 1 Row 2 CS : Programming and Data Structures Lecture #04: © DSamanta

28 Reading the Elements of a 2-D Array
By reading them one element at a time. for (i=0; i < nrow; i++) for (j=0; j < ncol; j++) scanf (“%f”, &a[i][j]); The ampersand (&) is necessary. Note: The elements can be entered all in one line or in different lines. CS : Programming and Data Structures Lecture #04: © DSamanta

29 Printing the Elements of a 2-D Array
By printing them one element at a time. for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) printf (“\n %f”, a[i][j]); The elements are printed one per line. printf (“%f”, a[i][j]); Till Slide 30 of ISG CS : Programming and Data Structures Lecture #04: © DSamanta

30 Printing the Elements of a 2-D Array
The elements are printed nicely in matrix form. for (i=0; i<nrow; i++) { printf (“\n”); for (j=0; j<ncol; j++) printf (“%f ”, a[i][j]); } Till Slide 30 of ISG CS : Programming and Data Structures Lecture #04: © DSamanta

31 Example 1: Reading a Matrix Amxn
Read the element of a matrix of integers of size mxn Till Slide 30 of ISG CS : Programming and Data Structures Lecture #04: © DSamanta

32 Example 2: Matrix Addition
Find the sum of two matrix amxn and bmxn anddtore the result in cmxn Till Slide 30 of ISG CS : Programming and Data Structures Lecture #04: © DSamanta

33 Example 3: Matrix Multiplication
Find the product of two matrices amxp and bpxn and store the result in cmxn Till Slide 30 of ISG CS : Programming and Data Structures Lecture #04: © DSamanta

34 Arrays Beyond 2-D C language allows arrays of three or more dimensions. The general form of a multi-dimensional array is type array_name[s1][s2][s3]…[sn]; Here, si is the size of the i-th dimension. Examples. int rainFall [day][month][city]; will store the rainfall data for each day in a year and for a number of cities. float table[2][3][4] = {{{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}},……}; declares a 3-D array table with 24 float values and initialize the first and second rows of the first entries in the third dimension. CS : Programming and Data Structures Lecture #04: © DSamanta

35 Strings CS 11001 : Programming and Data Structures
Lecture #04: © DSamanta

36 Introduction A string is an array of characters.
Individual characters are stored in memory in ASCII code. A string is represented as a sequence of characters terminated by the null (‘\0’) character. ‘\0’ l e H o “Hello”  CS : Programming and Data Structures Lecture #04: © DSamanta

37 Character Arrays and Strings
char C[8] = {‘d',‘e',‘b',‘a',‘s',‘i',‘s','\0'}; C[0] gets the value ‘d', C[1] the value ‘e', and so on. The last (7th) location receives the null character ‘\0’. Null-terminated character arrays are also called strings. Strings can be initialized in an alternative way. The last declaration is equivalent to char C[16] = “India is great!"; The trailing null character is missing here. C automatically puts it at the end. Note also that for individual characters, C uses single quotes, whereas for strings, it uses double quotes. CS : Programming and Data Structures Lecture #04: © DSamanta

38 Declaring String Variables
A string is declared like any other array: char string-name [size]; Here, size determines the number of characters in string_name (including for null character ‘\0’) When a character string is assigned to a character array, it automatically appends the null character (‘\0’) at the end of the string. char C[16] = “India is great!"; CS : Programming and Data Structures Lecture #04: © DSamanta

39 Examples A string may be initialized at the time of declaration.
char name[30]; char city[15]; char dob[11]; A string may be initialized at the time of declaration. char city[15] = “Calcutta”; char city[15] ={‘C’,‘a’,‘l’,’c’,‘u’,‘t’,’t’,‘a’}; char dob[] = “ ”; Equivalent CS : Programming and Data Structures Lecture #04: © DSamanta

40 Reading Strings from the Keyboard
Two different cases will be considered Reading words Reading an entire line CS : Programming and Data Structures Lecture #04: © DSamanta

41 Reading “words” scanf can be used with the “%s” format specification.
char name[30]; : scanf (“%s”, name); The ampersand (&) is not required before the variable name with “%s”. The problem here is that the string is taken to be upto the first white space (blank, tab, carriage return, etc.) If we type “Debasis Samanta” name will be assigned the string “Debasis”! CS : Programming and Data Structures Lecture #04: © DSamanta

42 Reading a “line of text”
In many applications, we need to read in an entire line of text (including blank spaces). We can use the getchar() function for the purpose. CS : Programming and Data Structures Lecture #04: © DSamanta

43 Reading a “line of text”
char line[81], ch; int c=0; : do { ch = getchar(); line[c] = ch; c++; } while (ch != ‘\n’); c = c – 1; line[c] = ‘\0’; Read characters until CR (‘\n’) is encountered Make it a valid string CS : Programming and Data Structures Lecture #04: © DSamanta

44 Reading a line :: Alternate Approach
Reads a string containing uppercase characters and blank spaces char line[81]; : scanf (“%[ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line); Reads a string containing any characters: char line[81]; : scanf (“%[^\n]”, line); CS : Programming and Data Structures Lecture #04: © DSamanta

45 Writing Strings to the Screen
We can use printf with the “%s” format specification. printf (“\n %s”, name); Alternatively, we can use printf with the “%c” format and each character one after another. i = 0; while (name[i++] !=‘\0’) printf(“%c”, name[i]); CS : Programming and Data Structures Lecture #04: © DSamanta

46 Processing Character Strings
There exists a set of C library functions for character string manipulation. strcpy :: string copy strlen :: string length strcmp :: string comparison strtcat :: string concatenation It is required to add the line. #include <string.h> CS : Programming and Data Structures Lecture #04: © DSamanta

47 strcpy() Works very much like a string assignment operator.
strcpy (string1, string2); Assigns the contents of string2 to string1. Examples: strcpy (city, “Calcutta”); strcpy (city, mycity); Warning: Assignment operator do not work for strings. city = “Calcutta”; -> INVALID CS : Programming and Data Structures Lecture #04: © DSamanta

48 strlen() Counts and returns the number of characters in a string.
len = strlen (string);/* Returns an int */ The null character (‘\0’) at the end is not counted. Counting ends at the first null character. char city[15]; int n; : strcpy (city, “Calcutta”); n = strlen (city); n is assigned 8 CS : Programming and Data Structures Lecture #04: © DSamanta

49 strcmp() Compares two character strings. Examples:-
int strcmp (string1, string2); Compares the two strings and returns 0 if they are identical; non-zero otherwise. Examples:- if (strcmp (city, “Delhi”) = = 0) { …… } if (strcmp (city1, city2) ! = 0) CS : Programming and Data Structures Lecture #04: © DSamanta

50 strcat() Joins or concatenates two strings together. Example:-
strcat (string1, string2); string2 is appended to the end of string1. The null character at the end of string1 is removed, and string2 is joined at that point. Example:- strcpy (name1, “Amit “); strcpy (name2, “Roy“); strcat (name1, name2); i m A ‘\0’ t y o R ‘\0’ i m A t y o R ‘\0’ CS : Programming and Data Structures Lecture #04: © DSamanta

51 Example 2: Page Statistics
/* Read a line of text and count the number of uppercase in the text */ #include <stdio.h> #include <string.h> main() { char line[81]; int i, n, count=0; scanf (“%[^\n]”, line); n = strlen (line); for (i=0; i<n; i++) if (isupper (line[i]) count++; } printf (“\n The no. of uppercase ltr in the str %s is %d”,line, count); CS : Programming and Data Structures Lecture #04: © DSamanta

52 Example 1: Upper Case Counting
/* Read a text and count the number of uppercase letters */ #include <stdio.h> #include <string.h> #define MAX 1000; main() { char myText[MAX]; int i, n, wCount=0; lCount = 0; while ((c=getchar()) != 0) myText[i++] = c; myText[i] = ‘\0’; n = strlen (myText); for (i=0; i<n; i++) switch(myText[i]){ case ‘ ‘: wCount++; break; case ‘\.’ :lcount++; break; } printf (“\n The number of words is %d and sentences is %d”,wCount, lCount); CS : Programming and Data Structures Lecture #04: © DSamanta

53 Any question? You may post your question(s) at the “Discussion Forum” maintained in the course Web page. CS : Programming and Data Structures Lecture #04: © DSamanta

54 Problems for Ponder… An array of integer of size 10 is declared. Compiler then allocate memory for it In which memory (cache, main memory, secondary memory) the memory is allocated? If it is stored in maim memory, then in which part of the memory (data area, heap area or instruction area) it is stored? How much memory (in Bytes), usually it will take? Are they stored in contagious locations or distributed at random thorough the entire memory available? Two arrays x and y are declared as follows. float x[100] ; double y [100]; Which would take more amount? Why? Suppose, you have declared an array long x[100]; Assume that the word size of the memory is 2 bytes. If the starting location of the array (i.e., the location of x[0]) in the memory is 1124, then what will be the memory location of x[8]? CS : Programming and Data Structures Lecture #04: © DSamanta

55 Problems for Ponder… Suppose, we want to store the following data into an array, which is declared as char a2z [100]; 11, 0, A, a, -1, 55, * Is it possible to store them? If not, why? What will be the memory location of a[i][j] in memory, if the starting location of the array is x and the 2-D array is stored in column major order? Assume, each element of the array needs w words of the memory. What should be the memory locations in (a) row-major and (b) column major order of any non-zero elements of the following diagonal matrices. CS : Programming and Data Structures Lecture #04: © DSamanta

56 Problems for Ponder… Assume that array A and B are declared as follows: int A[5][4]; int B[4]; Find the errors (if any), in the following program segments for (i=1; i<4; i++) scanf(“%f”, B[i]); for (i=1; i<=5; i++) for (j=1; i<=4; j++) A[i][j] = 0; for (i=4; i>=0; i--) scanf(“%d”, &B[i]); CS : Programming and Data Structures Lecture #04: © DSamanta

57 Problems for Ponder… String variables can be assigned values in the following four ways: During type declaration a) char name[] = “India”; b) char name [ ] = {‘I’, ‘n’, ‘d’, ‘i’, ‘a’, ‘\0’};\ Using strcpy function strcpy(aString, name); Reading-in a string using scanf function scanf(%s”, name); Reading using gets function gets(name); What is the advantages and limitations in the above ways of initializing a string variable. Explain your answers with appropriate C programs. It is required to store the name of 20 cities. Assume that name of a city should not exceed 20 characters. Give an idea how the data can be stored in a string matrix say myCities, tht is, myCity[i] will stored the name of the i-th city. CS : Programming and Data Structures Lecture #04: © DSamanta

58 Problems for Practice…
You can check the Moodle course management system for a set of problems for your own practice. Login to the Moodle system at Select “PDS Spring-2017 (Theory) in the link “My Courses” Go to Topic 4: Practice Sheet #04 : Arrays and Strings Solutions to the problems in Practice Sheet #04 will be uploaded in due time. CS : Programming and Data Structures Lecture #01: © DSamanta

59 Spend few minutes and then enjoy the study.
If you try to solve problems yourself, then you will learn many things automatically. Spend few minutes and then enjoy the study. CS : Programming and Data Structures Lecture #01: © DSamanta


Download ppt "Programming and Data Structures"

Similar presentations


Ads by Google