Contents on Derived Data Types Arrays: Arrays declaration, Initialization and access of one-dimensional and two-dimensional arrays, Programs using one- and two-dimensional arrays, sorting and searching arrays Strings: Declaring and initializing string variables, reading strings from terminal, writing strings to screen, Arithmetic operations on characters, String handling functions - strlen, strcmp, strcpy, and strcat , Character handling functions - toascii, toupper, tolower, isalpha, isnumeric . Pointers: Understanding pointers, accessing the address of a variable, declaring and initializing pointers, accessing a variable through its pointer, pointer expression, pointer increments and scale factor, pointers and arrays, pointer and strings. 2
Arrays 3
What is Array? Array is a collection of homogeneous data items which are stored in a contiguous memory location and data can be accessed randomly using indexes of an array. The size of the array should be mentioned while declaring it. Array elements are always counted from zero (0) onward. Array elements can be accessed using the position of the element in the array. The array can have one or more dimensions. There are three types of array One dimensional Array Two Dimensional Array Multi dimensional Array 4
The ‘datatype’ indicates whether your array is integer type, float type or any other type. ‘name of array’ is a name given to array, and ‘size’ indicates the no. of elements in your array. Syntax: Ex: int num [10]; It means out array name is ‘num’ of int type and it contains different 10 elements. Here the valid subscript range is 0-9. float n[20]; It means out array name is ‘n’ of float type and it contains different 20 elements. Here the valid subscript range is 0-19 int roll_no[50]; It means out array name is ‘roll_no’ of int type and it contains different 50 elements. Here the valid subscript range is 0-49 Declaration of Array(One dimensional array) datatype name of array[size]; 5
Array Initialization The general syntax of the initialization of array is: To initialize your array you have to give list of the values separated by comma in curly bracket. datatype arrayname[size]={ list of values separated by comma}; Eg1: int X[5] = { 10, 20, 30, 40, 50}; The array variable of size 5 ‘x’ is initialized by five different values 10, 20, 30, 40 and 50 respectively that means X[0] = 10; X[1] = 20; X[2] = 30; X[3] = 40; X[4] = 50; 6
Eg2:- long int gdp[10]; Note that gdp[ ] has auto storage class and it has not been initialized, so it contains garbage values. If we declare it as static array, all its elements would be set to 0. Eg3:- char name[5] = “Well” ; Eg4:- int x[5] = {10, 50}; 7
Access the Elements of an Array To access an array element, refer to its index number . Array indexes start with : [0] is the first element. [1] is the second element, etc. Example int bca[] = { 25 , 50 , 75 , 100 }; printf("%d", bca[0]); Output : 25 8
Eg: WAP to accept ‘n’ no. to store it in an one dimensional array and to display the contents of that array. #include<stdio.h> void main() { int a[100],i,n; printf(“How many no. in the array”); scanf (“%d”,&n); printf(“Enter the elements”); for(i=0;i<=n-1;i++) { scanf(“%d”,&a[i]); } printf(“Contents of the array”); for(i=0;i<=n-1;i++) { printf(“%d”, a[i]); } } 9
Two-dimensional Array Two-dimensional array can store the table of values. “An array with two subscript is known as the two-dimensional array of double-subscripted variable.” The two-dimensional array can be represented by the matrix in mathematics. The matrix elements can be represented by v i j where ‘i’ value indicates the row number and ‘j’ value indicated the column number. 10
We can declare the two-dimensional array by using following format: Eg: int x[2][2]; Means your array ‘x’ contains 2 rows and 2 columns. OR int a[2][2] = {{2,4}, {5,6}}; datatype arrayname[row size][column size]; 11
Eg : void main( ) { int a[5][5]; // Declaration of array with the size = 5 int i, j; // Read the Array elements value for(i = 0 ; i < 5 ; i ++) { for(j = 0 ; j < 5 ; j++) { scanf(“%d”, &a[i][j]); } } // Print the array elements value for(i = 0 ; i < 5 ; i ++) { for(j = 0 ; j < 5 ; j++) { printf(“%d”, a[i][j]); } } } 12
Advantages of Arrays Efficient storage: Arrays allow storing multiple elements of the same data type in a single continuous memory block. Easy to access elements using an index. Random access: Any element can be directly accessed using its index in constant time O(1). Code simplicity: Reduces the need for multiple variables (e.g., instead of declaring 100 variables, one array of size 100 is enough). Iterative operations: Arrays work smoothly with loops, making operations like searching, sorting, and traversing easier. 13
Disadvantages of Arrays Fixed size: Once declared, the size of an array cannot be changed during runtime. May cause memory wastage if the declared size is too large or overflow if it’s too small. Same data type only: Arrays can only hold elements of the same data type (e.g., all integers or all floats). Insertion and deletion are costly: Inserting or deleting elements in the middle requires shifting other elements, which is inefficient (O(n) time complexity). Memory consumption for large arrays: Declaring very large arrays may lead to stack overflow if memory exceeds system limits. 14
Multidimensional Arrays A multi-dimensional array in C can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Syntax type arrName [size1][size2]....[ sizeN ]; type : Type of data to be stored in the array. arrName : Name assigned to the array. size1, size2,..., sizeN : Size of each dimension. 15
Eg : #include < stdio.h > int main() { int arr [2][3][2]; // 3D array: 2 blocks, 3 rows, 2 columns // Input elements printf ("Enter elements of the 3D array:\n"); for ( int i = 0; i < 2; i ++) { // blocks for ( int j = 0; j < 3; j++ ) { // rows for ( int k = 0; k < 2; k++) { // columns printf ("Element [%d][%d][%d]: ", i , j, k); scanf ("%d", & arr [ i ][j][k]); } } } // Display elements printf ("\n3D Array elements are:\n"); for ( int i = 0; i < 2; i++) { printf ("Block %d:\n", i); for ( int j = 0; j < 3; j++) { for ( int k = 0; k < 2; k++) { printf ("%d\t", arr [i][j][k]); } printf ("\n"); } printf ("\n"); } return 0; } 16
Transpose of matrix using array #include<stdio.h> int main() { int r,c,a[10][10],i,j; printf("Enter row and column for matrix:"); scanf("%d %d",&r,&c); printf("Enter the values for matrix\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&a[i][j]); } } 17
printf("the matrix is \n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",a[i][j]); } printf("\n"); } printf("the transpose of matrix is \n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",a[j][i]); } printf("\n"); } } Output of Transpose Matrix 18
Searching in array Searching is the process of finding some particular element in the list. If the element is present in the list, then the process is called successful, and the process returns the location of that element. Otherwise, the search is called unsuccessful. There are two types Linear search Binary search 19
Linear search Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. Working of the linear search 20
Binary Search Binary search is the search technique that works efficiently on sorted lists. Binary Search is a searching technique used in C to find the position of a target element in a sorted array by repeatedly dividing the search interval in half. It starts by comparing the target element with the middle element of the array: If they are equal, the search is successful. If the target is smaller, the search continues in the left half. If the target is larger, the search continues in the right half. 21
Sorting Sorting refers to ordering data in an increasing or decreasing order according to some linear relationship among the data items. Bubble sort Selection sort Insertion sort 22
Bubble sort Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. 23
Selection sort The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. 24
Insertion sort The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. 25
End of Array concepts 26
Strings A String in C programming is a sequence of characters terminated with a null character ‘\0’. A string is an array of characters. Any group of characters enclosed in double quotes is a string constant. E.g.: “Hello” The common operations performed on strings are, 1. Reading/Writing 2. Combining strings 3. Copying one string to another 4. Comparing two strings 5. Find the length of the string 27
Declaring string variables Declaring a string in C is as simple as declaring a one-dimensional array. Syntax: char string_name [size]; str_name is any name given to the string variable. size is used to define the length of the string, i.e the number of characters strings will store. When a character string is assigned to a character array, the compiler automatically supplies a null character (‘\0’) at the end of the string. Hence the size should always be equal to the maximum number of characters plus one. 28
Initializing string variables Assigning a string literal without size Assigning a string literal with a predefined size Assigning character by character with size Assigning character by character without size 29
Assigning a string literal without size String literals can be assigned without size. Here, the name of the string str acts as a pointer because it is an array. char str [] = “Hello"; 30
Assigning a string literal with a predefined size String literals can be assigned with a predefined size. But we should always account for one extra space which will be assigned to the null character. If we want to store a string of size n then we should always declare a string with a size equal to or greater than n+1. char str [15] = “Hello World"; 31
Assigning character by character with size We can also assign a string character by character. But we should remember to set the end character as ‘\0’ which is a null character. char str [6] = {‘H’,’e’,’l’,’l’,’o’,'\0'}; 32
Assigning character by character without size We can assign character by character without size with the NULL character at the end. The size of the string is determined by the compiler automatically. char str [] = {‘H’,’a’,’ i ’,'\0'}; 33
Reading strings from terminal Words can be read using the scanf function with %s as the format specifier. But the problem with scanf statement is that it terminates its input when it encounters a white space. For example, char city[15]; scanf (“%s”, city); If New York is given as input at the terminal then, only New will be assigned to the variable city. 34
Writing strings to screen The format %s can be used to display an array of characters that is terminated by a null character. For example: Consider the following statement printf (“%s”, name); The above statement can be used to display the entire contents of the array, name. 35
Access Strings Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets []. Example char greetings[] = "Hello World!"; printf ("%c", greetings[0]); 36
Modify Strings To change the value of a specific character in a string, refer to the index number, and use single quotes: Example char greetings[] = "Hello World!"; greetings[0] = 'J'; printf ("%s", greetings); // Outputs Jello World! instead of Hello World! 37
String handling functions C library supports a large number of built-in string functions in a header file called string.h . The most important string handling functions are tabulated as follows: 1. strcat () 2. strcmp () 3. strcpy () 4. strlen () 38
Putting Strings together (Concatenation): The process of combining 2 strings together is known as concatenation. In C, we cannot directly combine two strings. The characters from string1 and string2 should be copied to string3 one after another. But, the size of string3 should be large enough to accommodate both string1 and string2. 39
strcat () Function: This function is used to concatenate or join 2 strings together. It takes the following form: strcat (string1,string2); where string1 and string2 are character arrays. When this function is executed string2 is appended to string1, It does so by removing the null character at the end of string1 and placing string2 from there. The contents of string2 remain unchanged. Example: char str1[20] = "Hello "; char str2[] = "World!"; // Concatenate str2 to str1 (result is stored in str1) strcat (str1, str2); // Print str1 printf ("%s", str1); 40
Eg : Write a C program to illustrate concatenation of strings using string handling function. #include< stdio.h > #include< string.h > void main() { char str1[31]="New"; char str2[32]="Mangalore"; printf ("\n First String is: %s\n",str1); printf ("Second String is: %s\n",str2); strcat (str1,” “) ; strcat (str1,str2); printf ("Resultant String: %s \n",str1); } 41 Output: First String is: New Second String is: Mangalore Resultant String: New Mangalore
Comparison of Two strings: Strings cannot be compared directly. We have to compare the two strings character by character. The comparison is done till there is a mismatch or one of the strings terminates to a null character, whichever occurs first. 42
strcmp () Function: This function compares two strings identified by arguments and has value 0 if they are equal. If they are not, it has the numeric difference between the first non-matching characters in the string. It takes the following form, strcmp (string1,string2); where string1 and string2 may be string variables or string constants. E.g.: strcmp (“their”, “there”); The above statement will return a value -9 which is a numeric difference between ASCII “ i ” and ASCII “r”. If the value is negative, it means that string1 is alphabetically above string2. 43
Eg : #include < stdio.h > #include < string.h > int main() { char str1[] = "Hello, World!"; char str2[] = "Hello, C!"; int result = strcmp (str1, str2); if (result == 0) { printf ("The strings are equal.\n"); } else if (result < 0) { printf ("The first string is less than the second string.\n"); } else { printf ("The first string is greater than the second string.\n"); } return 0; } 44 Output: The first string is greater than the second string.
To copy One string to another strcpy () Function: The general format of this function is : strcpy (string1,string2); The above statement assigns the content of string2 to string1. String2 may be character array or a string constant. E.g.: strcpy (city, “DELHI”); This statement will assign the string “DELHI” to string variable city. If city1= “DELHI” and city2= “CHENNAI”. The statement strcpy (city1,city2); will assign the contents of string variable city2 to city1. The size of array city1 should be large enough to contain the contents of city2. 45
Eg : #include< stdio.h > #include< string.h > void main() { char str1[31]=“Hello"; char str2[32]=“C Program"; printf ("\ nFirst String is: %s\n",str1); printf ("Second String is: %s\n",str2); strcpy (str1,str2); printf ("Resultant String: %s\n",str1); } 46 First String is: Hello Second String is: C Program Resultant String: C Program
To find the Length of a string: strlen () Function: This function counts and returns the number of characters in the specified string. The general format of this function is n= strlen (string); where n is an integer variable which receives the value of the length of the string. The argument in this function can be a string constant also. Eg : city= “DELHI”; m= strlen (city); The above statement assigns 5 to the variable m. 47
Eg : #include< stdio.h > #include< string.h > void main() { char str [31]; int len ; printf ("\ nEnter any String:\n"); gets( str ); len = strlen ( str ); printf ("\ nNumber of Characters in %s=%d\n", str,len ); } 48 Output: Enter any String: Hello World Number of Characters in "Hello World" = 11
Reversing a String: strrev (string) function for reversing the given string. The C standard library does not contain the strrev () function, which is not a standard library function. However, it has long been a well-liked utility function for C programmers to reverse strings. The strrev (string) function returns reverse of the given string. 49
Character handling functions Character functions need ctype.h header file to be included in the program. Different character functions provided by C Language are: toascii , toupper , tolower , isalpha , isnumeric 51
1. isalpha (): This function checks whether the character variable/constant contains alphabet or not. 2. isdigit (): This function checks whether the character variable/ constant contains digit or not. 3. isupper (): This function checks whether the character variable/constant contains an capital letter alphabet or not. 4. islower (): This function checks whether the character variable/constant contains a lowercase alphabet or not. 52
Cont … 5. toupper (): This function converts lowercase alphabet into uppercase alphabet. 6. tolower (): This function converts an uppercase alphabet into lowercase alphabet. 7. isalnum (): This function checks whether the character variable/constant contains an alphabet or digit. 53
Eg : #include < stdio.h > #include < ctype.h > // For isalpha (), isalnum (), isdigit () int main() { char ch ; printf ("Enter a character: "); scanf ("%c", & ch ); if ( isalpha ( ch )) { printf ("'%c' is an alphabetic character.\n", ch ); } else if ( isdigit ( ch )) { printf ("'%c' is a digit.\n", ch ); } else if ( isalnum ( ch )) { printf ("'%c' is alphanumeric (either alphabet or digit).\n", ch ); } else { printf ("'%c' is neither alphabetic nor digit.\n", ch ); } return 0; } 54
Eg : #include < stdio.h > #include < ctype.h > // For isupper , islower , toupper , tolower int main() { char ch ; printf ("Enter a character: "); scanf ("%c", & ch ); // Check if the character is uppercase if ( isupper ( ch )) { printf ("'%c' is an uppercase letter.\n", ch ); printf ("Its lowercase form is: %c\n", tolower ( ch )); } 55 Output: Enter a character: A 'A' is an uppercase letter. Its lowercase form is: a
Cont ….. // Check if the character is lowercase else if ( islower ( ch )) { printf ("'%c' is a lowercase letter.\n", ch ); printf ("Its uppercase form is: %c\n", toupper ( ch )); } else { printf ("'%c' is not an alphabetic character.\n", ch ); } return 0; } 56
End of STRING concepts 57
Pointers A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator. There are a number of advantages of using pointers. They are, • It enables us to access a variable that is defined outside a function. • More efficient in handling arrays • Reduce the length and complexity of a program • Increase the execution speed 58
Accessing the address of a variable When a variable is declared, the system allocates memory location suitable to hold the variable value. The memory location is called the address. Consider the following statement: int qty ; qty =179; 59
Declaring pointers The declaration of a pointer variable takes the following form: data type * pt -name; This informs the compiler that • The asterisk(*) tells that pt -name is a pointer variable • pt -name needs memory location • pt -name points to a variable of type data type Example: int *p; 60
Pointer Initialization Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( & ) addressof operator to get the memory address of a variable and then store it in the pointer variable. int var = 10; int * ptr ; ptr = & var ; We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time. Example, int * ptr = & var ; 61
#include < stdio.h > int main() { int a = 10; // Variable declaration and initialization int * ptr ; // Pointer declaration ptr = &a; // Initializing pointer with address of 'a' printf ("Value of a: %d\n", a); printf ("Address of a: %p\n", &a); printf ("Pointer ptr stores: %p\n", ptr ); printf ("Value pointed by ptr : %d\n", * ptr ); return 0; } 62 OUTPUT: Value of a: 10 Address of a: 0x7ffcc3b24a9c Pointer ptr stores: 0x7ffcc3b24a9c Value pointed by ptr : 10
Accessing a variable through pointer Once a pointer is assigned the address of a variable, the value of the variable can be accessed using a unary operator (*) asterisk. It is also known as indirection operator. Consider the following statements: int qty ,*p, n; qty =150; p=& qty ; n=*p; Here n gets the value 150 63
Pointer expression Pointer expressions are used to manipulate the memory address directly, rather than the value stored at that address. Pointers themselves hold the memory address of a variable, and pointer expressions use this address to perform various operations. Key Concepts of Pointer Expressions: Pointer Declaration : Pointers are used to point to address the location of a variable. A pointer is declared by preceding the name of the pointer by an asterisk(*). Syntax:datatype * pointer_name ; 64
Dereferencing: The dereference operator * is used to access the value stored at the memory address that the pointer is pointing to. Ex: int x = 10; int * ptr = &x; // ptr stores the address of x printf ("%d", * ptr ); // Dereference ptr to access the value of x, outputs 10 Pointer Arithmetic : Pointers can be incremented or decremented, which moves the pointer by the size of the type it points to. Example: int arr [3] = {1, 2, 3}; int * ptr = arr ; printf ("%d\n", * ptr ); // 1 ptr ++; // Pointer moves to next element printf ("%d\n", * ptr ); // 2 65
Pointer increments and scale factor Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int ), and the new address will point to 1004. While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will be 1004. 66
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int ), and the new address will point to 996. While if a float type pointer is decremented then it will decrement by 4(size of a float) and the new address will be 996. 67
Pointers and arrays When an array is declared, the compiler allocates the base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations. The base address is the location of the first element in the array. Example: int a[10]; int *p; p=a; The above statement p=a makes p to point to the array a. i.e. p will point to the base address of a. 68
Feature Array Pointer Definition A collection of elements in memory A variable that holds a memory address Memory Allocation Fixed, statically allocated Can be dynamically allocated (heap) Size Fixed, determined at compile-time Can change, dynamically allocated Access Use array indexing ( arr [0]) Use dereferencing (*ptr) Pointer Arithmetic Can perform pointer arithmetic on the array name Can perform pointer arithmetic on the pointer Change Address Cannot change the address Can change the address by reassigning the pointer 69
Pointer and strings A string is a sequence of characters which we save in an array. And in C programming language the \0 null character marks the end of a string. Creating a string: In the following example we are creating a string str using char character array of size 6. char str [6] = "Hello"; 70