Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 2 Arrays and strings – example programs.

Similar presentations


Presentation on theme: "Module 2 Arrays and strings – example programs."— Presentation transcript:

1 Module 2 Arrays and strings – example programs.
Two dimensional arrays – matrix operations. Structure, union and enumerated data types.

2 Arrays An array is a collection of data that holds fixed number of values of same type. can store group of data of same data type in an array. Array might be belonging to any of the data types Array size must be a constant value. Contiguous (adjacent) memory locations are used to store array elements in memory. Example for C Arrays: int a[10];       // integer array char b[10];    // character array   i.e. string

3 Types of C arrays: There are 2 types of C arrays.
One dimensional array Multi dimensional array Two dimensional array Three dimensional array Four dimensional array etc…

4 declare an array in C data_type array_name[array_size]; For example,
float mark[5]; Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.

5 access array elements can access elements of an array by indices.
float mark[5]; The first element is mark[0], second element is mark[1] and so on.

6 Few key notes: Arrays have 0 as the first index not 1. In this example, mark[0] If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4] Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

7 initialize an array It's possible to initialize an array during declaration. int mark[5] = {19, 10, 8, 17, 9}; int mark[] = {19, 10, 8, 17, 9};

8 insert and print array elements
int mark[5] = {19, 10, 8, 17, 9} mark[3] = 9; ​scanf("%d", &mark[2]); // print first element of an array printf("%d", mark[0]); // print ith element of an array printf("%d", mark[i-1]);

9 find the average of n numbers using arrays
#include <stdio.h> int main() { int marks[10], i, n, sum = 0, average; printf("Enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) printf("Enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; } average = sum/n; printf("Average marks = %d", average); return 0;

10 Deletion of an element from an array
Searching an element in an array

11 C Program to Find the Largest Number in an Array
#include <stdio.h> int main() { int array[50], size, i, largest; printf("\n Enter the size of the array: "); scanf("%d", &size); printf("\n Enter %d elements of the array: ", size); for (i = 0; i < size; i++) { scanf("%d", &array[i]);} largest = array[0]; for (i = 1; i < size; i++) { if (largest < array[i]) largest = array[i]; } printf("\n largest element present in the given array is : %d", largest); return 0;

12 Two Dimension Matrix 2D arrays are generally known as matrix. Syntax :
type arrayName [ x ][ y ]; Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −

13 Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row. 1. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ }; 2. int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

14 Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. int val = a[2][3];

15 #include<stdio.h> int main() { int i, j; int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 }}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); return 0;

16 2. Uninitialized elements will get default 0 value.
#include <stdio.h> int main() { int i, j; int a[3][2] = { { 1 }, { 5, 2 }, { 6 }}; for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { printf("%d ", a[i][j]); } printf("\n"); return 0;

17 Programs Matrix Addition Matrix Subtraction Matrix Multiplication
Matrix Transpose

18 String array of characters ended with null character (‘\0’).
 null character indicates the end of the string Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C. EXAMPLE FOR C STRING: 1. char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘\0’}; 2. char string[20] = “fresh2refresh”; 3. char string []    = “fresh2refresh”;

19 char greeting[] = "Hello";

20 Reading Strings from user
use the scanf() function to read a string the scanf() function only takes the first entered word. The function terminates when it encounters a white space (or just space). #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.

21 Reading a line of text Use getchar() to read a line of text
#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;

22 to read line of text using gets() and puts()
#include <stdio.h> 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; }

23 Example #include <stdio.h> int main () {
int main () {    char string[20] = “welcome";    printf("The string is : %s \n", string );    return 0; }

24 Function & Purpose strcpy(s1, s2); strcat(s1, s2); strlen(s1);
Copies string s2 into string s1. strcat(s1, s2); Concatenates string s2 onto the end of string s1. strlen(s1); Returns the length of string s1. strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

25 Strcmp() example #include <stdio.h> #include <string.h> int main( ) { char str1[ ] = "fresh" ; char str2[ ] = "refresh" ; int i, j, k ; i = strcmp ( str1, "fresh" ) ; j = strcmp ( str1, str2 ) ; k = strcmp ( str1, "f" ) ; printf ( "\n%d %d %d", i, j, k ) ; return 0; }

26 #include<stdio.h> #include<string.h> int main() {
strrev() strrev( ) function reverses a given string in C language. #include<stdio.h> #include<string.h> int main() {    char name[30] = "Hello";     printf("String before strrev( ) : %s\n",name); printf("String after strrev( )  : %s",strrev(name));    return 0; }

27 Structure C Structure is a collection of different data types which are grouped together each element in a C structure is called member. To access structure members in C, structure variable should be declared. Many structure variables can be declared for same structure and memory will be allocated for each separately. User defined data type used to represent a record

28 Defining a Structure struct [structure tag] { member definition; ... } [one or more structure variables];

29 Example Struct student { char name[50]; int rollno; float mark1,mark2,total; }st;

30 Accessing Structure Members
use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that wish to access Example st.name=“Arun” st.rollno=15; st.mark1=45.2; st.mark1=47.2;

31 ANOTHER WAY OF DECLARING C STRUCTURE
#include<stdio.h> #include<string.h> Struct student { char name[50]; int rollno; float mark1,mark2,total; } main() struct student st; strcpy(st.name,”Arun”); st.rollno=23; ….

32 #include <stdio. h> #include <string
#include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; } record; main() record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); }

33 Difference between array & structure
Structures 1. An array is a collection of related data elements of same type. 1. Structure can have elements of different  types 2. An array is a derived data type 2. A structure is a programmer-defined data type 3. Any array behaves like a built-in data types. All we have to do is to declare an array variable and use it. 3. But in the case of structure, first we have to design and declare a data structure before the variable of that type are declared and used. 4. Array allocates static memory and uses index / subscript for accessing elements of the array. 4. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure. 5. Array is a pointer to the first element of it 5. Structure is not a pointer 6. Element access takes relatively less time. 6. Property access takes relatively large time.

34 Union A union is a special data type available in C that allows to store different data types in the same memory location Union and structure in C  are same in concepts, except allocating memory for their members. Structure allocates storage space for all its members separately. Whereas, Union allocates one common storage space for all its members

35 can access only one member of union at a time
can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately.

36 DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:
C Structure C Union Structure allocates storage space for all its members separately. Union allocates one common storage space for all its members. Union finds that which of its member needs high storage space over other members and allocates that much space Structure occupies higher memory space. Union occupies lower memory space over structure. We can access all members of structure at a time. We can access only one member of union at a time. Structure example: struct student { int mark; char name[6]; double average; }; Union example: union student { int mark; char name[6]; double average; };

37 Defining a Union union [union tag] { member definition; ... } [one or more union variables];

38 Example union Data { int i; float f; char str[20]; } data;

39 Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member. Example data.i=10;

40 #include <stdio. h> #include <string
#include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; main( ) { union Data data; data.i = 10; printf( "data.i : %d\n", data.i); data.f = 220.5; printf( "data.f : %f\n", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str); }


Download ppt "Module 2 Arrays and strings – example programs."

Similar presentations


Ads by Google