Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Programming in C - Structures

Structures in C - A comprehensive note

Uploaded by

leninantony2008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Programming in C - Structures

Structures in C - A comprehensive note

Uploaded by

leninantony2008
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Programming in C

Module II

Contents:
Arrays – definition, initialization and processing of arrays – Searching algorithms – Linear search,
Binary Search, Sorting algorithms – Selection sort, Quick sort, Passing arrays to functions - Strings –
Representation of strings in C – String input and output - String processing – copy, concentrate,
length, comparison, pattern searching etc - builtin String functions – Implementation of string
functions.

Ref: Let us C - Yashawant Kanetkar - 5Ed


________________________________________________________________________________

Arrays:
● An array is a collective name given to a group of ‘similar elements’.
● It is a fixed-size sequenced collection of elements of the same data type, which can be any
primitive or user defined data types..
● Eg: Marks of 100 students can be represented by an integer array, salary of 200 employees by a
float array.
● An array is also known as a subscripted variable or indexed variable.
● The first element in the array is said to be at index 0, so the last element is at index 1 less than
the size of the array.

S3 CT, GPTC Cherthala 1


● Before using an array its type and dimension must be declared.
● The array elements are always stored in contiguous memory locations.

● Array Declaration: datatype array_name[array_size];


○ Eg:
■ int marks[100];
■ float salary[200];
● The first example declares an integer array named marks having 100 integer elements.
● The array elements can be accessed by using an index value which ranges from 0 to
(array_size-1).
● In the first example, the first mark can be accessed with marks[0], second by marks[1],.. And
the last mark by marks[99].
● Since the array is not being initialized, all the values present in it would be garbage values.
● If the storage class is declared to be static then all the array elements would have a default
initial value as zero.
● The array name itself is a pointer to the first element.
● The following code reads and prints the marks of 100 students.
int i, marks[100];
for ( i = 0 ; i < 100 ; i++ )
{
printf ( "\nEnter the mark " ) ;
scanf ( "%d", &marks[i] ) ;
}
printf ( "\nThe marks are \n" ) ;
for ( i = 0 ; i < 100 ; i++ )
{
printf ( "%d\n", marks[i] ) ;
}

● The arrays can be single dimensional or multidimensional.


○ Single dimensional arrays have only one subscript.
■ Eg: int marks[100];
○ Multidimensional arrays can have more than one subscript.
■ Eg: int matrix[5][3];
● It declares a two dimensional array named matrix with 5 rows , each
having 3 columns.

● Array initialization: An array can be initialized with values during the declaration also.
● Eg:
○ int num[6] = { 2, 4, 12, 5, 45, 5 } ;
○ int n[ ] = { 2, 4, 12, 5, 45, 5 } ; // automatically allocates 6 locations
○ float pressure[ ] = { 12.3, 34.2, -23.4, -11.3 } ;

Reading and printing a 2D array:


● For a 2D array, we need two subscripts; one for row and the other for column.
● Eg: arr[4][3]; represents an array with maximum 4 rows, each with maximum 3
columns/elements.

S3 CT, GPTC Cherthala 2


● Thus, for accessing the array elements, we need to use two variables, say i and j in nested
iterations.
● The following program reads and prints a 2D array with maximum order 10x10.

int main()
{
int arr[10][10], i, j, m, n;
printf("Enter the number of elements in the row:");
scanf("%d", &m);
printf("Enter the number of elements in the column:");
scanf("%d", &n);
printf("Enter the elements:");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &arr[i][j]);
}
}

printf("The elements are: \n");


for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d\t", arr[i][j]);
}
printf("\n");
}

return 0;
}

Initialization of a 2D array
● The following matrix can be initialized as given below.

int arr[3][2] = { {1,2}, {2,3}, {3,4} };

Program for Matrix Transpose:


#include<stdio.h>
int main()
{
int a[10][10]={{1,2}, {3,4}, {5,6}},i,j,rows=3,cols=2;

printf("Matrix is\n");
for(i=0;i<rows;i++)
{
S3 CT, GPTC Cherthala 3
for(j=0; j<cols; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("Transpose is\n");
for(i=0;i<cols;i++)
{
for(j=0; j<rows; j++)
{
printf("%d ", a[j][i]);
}
printf("\n");
}
}

Output will be;

Matrix is
1 2
3 4
5 6
Transpose is
1 3 5
2 4 6

Features of Arrays
1. Contiguous Memory Allocation
2. Fixed Size
3. Zero-Based Indexing
4. Direct Access to Elements
5. Initialization
6. Array Name as a Pointer
7. Multi-Dimensional Arrays

Passing Array elements into a function


● Array elements can be passed to a function by calling the function by value, or by reference.
In the call by value we pass values of array elements to the function, whereas in the call by
reference we pass addresses of array elements to the function. These two calls are illustrated
below:

/* Demonstration of call by value */


void display ( int m )
{
printf ( "%d ", m ) ;
}

int main( )
{

S3 CT, GPTC Cherthala 4


int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
display ( marks[i] ) ; //call by value
return 0;
}

And here’s the output…


55 65 75 56 78 78 90
● Here, we are passing an individual array element at a time to the function display( ) and getting
it printed in the function display( ). Note that since at a time only one element is being passed,
this element is collected in an ordinary integer variable m, in the function display( ).

/* Demonstration of call by reference */


void disp ( int *n )
{
printf ( "%d ", *n ) ;
}

int main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
disp ( &marks[i] ) ; //call by reference
return 0;
}

And here’s the output...


55 65 75 56 78 78 90

● Here, we are passing addresses of individual array elements to the function display( ).
Hence, the variable in which this address is collected (n) is declared as a pointer variable.
And since n contains the address of array element, to print out the array element we are using
the ‘value at address’ operator (*).
● If the value at the pointer n is changed, the actual array element also will be changed.

Passing an Entire Array to a Function


An entire array can be passed into the function along with its size.
void display ( int arr[], int n )
{
int i ;
for ( i = 0 ; i < n ; i++ )
{
printf ( "element = %d\n", arr[i] ) ;
}
}

S3 CT, GPTC Cherthala 5


int main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
display ( num, 6 ) ; // the array num is passed to arr
return 0;
}

Divide and Conquer Method of Problem Solving


The "divide and conquer" method is a fundamental algorithmic technique used in programming
and computer science. It involves breaking down a complex problem into smaller, more manageable
subproblems, solving each subproblem individually, and then combining their solutions to solve the
original problem. This approach is particularly useful for solving problems that can be recursively
divided into similar subproblems.
Eg: Binary Search, Quick Sort

Searching Algorithms
Linear Search
Linear search is a straightforward searching algorithm that sequentially checks each element in
a list or array until a match is found or all elements have been checked.
Steps:
1. Start from the beginning of the list.
2. Compare each element of the list with the target value sequentially.
3. If a match is found, the search stops, and the index of the matched element is returned (or the
element itself, depending on the implementation).
4. If the end of the list is reached without finding the target value, the search concludes with a
message indicating that the target value is not in the list.

Program:
#include <stdio.h>
int main()
{
int arr[10], i, key, n, index=-1;
printf("Enter the number of elements:");
scanf("%d", &n);
printf("Enter the elements:");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}

printf("Enter the element to be searched: ");


scanf("%d", &key);

// steps for linear search


for (i = 0; i < n; ++i)
{
if (arr[i] == key)
{
index=i; // stores the index where the element is found
break;
S3 CT, GPTC Cherthala 6
}
}

if (index == -1)
{
printf("Element is not found in the array\n");
}
else
{
printf("Element is found at index %d\n", index);
}

return 0;
}

Binary Search
Binary Search is a search algorithm that is used to find the position of an element in a sorted
array. The binary search algorithm works by comparing the element to be searched by the middle
element of the array and based on this comparison follows the required procedure.
Case 1: if element == middle, the element is found and returns the index.
Case 2: if element < middle, search for element in the left sub-array starting from index 0 to
middle-1.
Case 3: if element > middle, search for the element in the right sub-array starting from
middle+1 index to the last element (index n-1).
This division and searching continues until the search element is found (successful search) or
the lower and upper indexes cross each other (unsuccessful search).
After every cycle of search, the algorithm divides the size of the array into half hence in the
next iteration it will work only in the remaining half of the array.
Binary search works efficiently on sorted data whatever be the size of the data.

Example 1.
Array of 10 elements: 3 5 7 9 12 15 18 20 23 25
Key to be searched is 20
first = 0, last =9
middle=(first+last)/2 = 4
Compare the element at middle and the key, ie, 12 and 20
Since 20 is greater than 12, take the right sub-array starting from index middle+1 to last, ie, 5
to 9.
Continue searching until the key is found or interval is zero.

Example 2.
Here L represents first, H represents end and M represents middle.

S3 CT, GPTC Cherthala 7


Program:
int binarySearch(int a[], int beg, int end, int val)
{
int mid;
if(beg <= end) //check for boundary crossing. If FALSE, search
stops.
{
mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid;
}

/* if the item to be searched is smaller than middle,


then it can only be in left subarray */
else if(val < a[mid])
{
return binarySearch(a, beg, mid-1, val);
}

/* if the item to be searched is larger than middle,


then it can only be in right subarray */
else
{
return binarySearch(a, mid+1, end, val);
}
}
return -1; // search stops unsuccessfully and returns -1
}

int main()
{
int a[10] ; // array with max size 10
int val; // value to be searched
int n; // size of array
int i;
int res; // stores the result
printf( "Enter number of items: ");
scanf("%d",& n);
S3 CT, GPTC Cherthala 8
printf( "Enter the sorted items: \n");
for(i = 0; i< n; i++)
{
scanf("%d",& a[i]);
}
printf( "Enter key to be searched: ");
scanf("%d",& val);

res = binarySearch(a, 0, n-1, val); // Store result

if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at index %d of the array", res);
return 0;
}

Sorting algorithms
Selection Sort
The algorithm repeatedly selects the smallest element from the unsorted portion of the list and
swaps it with the first element of the unsorted part. Then it becomes part of the sorted list. This
process is repeated for the remaining unsorted portion until the entire list is sorted.
Steps:
1. Initialization: Start with the entire array considered as unsorted.
2. Find Minimum: Iterate through the unsorted part of the array to find the minimum element.
3. Swap: Swap the minimum element with the first element of the unsorted part (or place it
directly at the end of the sorted part).
4. Repeat: Move the boundary between the sorted and unsorted parts one element to the right and
repeat steps 2 and 3 until the entire array is sorted.
5. End: The array is now sorted.
Eg:

Program:
#include <stdio.h>
S3 CT, GPTC Cherthala 9
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, minposition, swap;

// steps for selection sort


for (i = 0; i < (n - 1); i++)
{
minposition = i; // let it be the minimum in this iteration
for (j = i + 1; j < n; j++)
{
if (arr[minposition] > arr[j])
minposition = j;
}
if (minposition != i) // check for swapping
{
swap = arr[i];
arr[i] = arr[minposition];
arr[minposition] = swap;
}
}

for (i = 0; i < n; i++)


printf("%d ", arr[i]);
return 0;
}

Quick Sort
● Quick sort is a commonly used sorting algorithm that is often preferred over other sorting
algorithms due to its efficiency and effectiveness.
● Uses a divide-and-conquer approach to sort elements.
● Quick Sort divides the array into smaller parts (sub-arrays) and recursively sorts these parts. It
then combines these sorted parts to produce the final sorted array.
● The core idea of Quick Sort is to select a 'pivot' element from the array. This pivot element is
used to partition the array into two sub-arrays: elements less than the pivot and elements
greater than the pivot.
● The array is rearranged so that all elements less than the pivot come before the pivot and all
elements greater than the pivot come after it. The pivot is then placed in its correct position in
the sorted array.
● Quick Sort is then applied recursively to the sub-arrays formed by the partitioning step. This
process continues until the base case is reached (usually when the sub-array has one or zero
elements, which is inherently sorted).

Program:
void quicksort(int number[],int first,int last)
{
int i, j, pivot, temp;
if(first<last)

S3 CT, GPTC Cherthala 10


{
pivot=first; // choose a pivot
i=first;
j=last;
while(i<j)
{
while(number[i]<=number[pivot] && i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j) // swapping
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1); // partitioning
quicksort(number,j+1,last);
}
}

int main(){
int i, count, number[25];
printf("How many elements are you going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: \n", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);

quicksort(number,0,count-1);

printf("Order of Sorted elements: ");


for(i=0;i<count;i++)
printf("%d ",number[i]);
return 0;
}

Strings
● A string is a one-dimensional array of characters terminated by a null ( ‘\0’ ).
● ‘\0’ is called the null character and its ASCII value is 0.
● Each character in the array occupies one byte of memory and the last character is always ‘\0’.
● ‘\0’ is the only way for the program to understand that the string has ended.
● Eg:
○ char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;

S3 CT, GPTC Cherthala 11



● The above example can also be simply initialized as follows.
○ char name[ ] = "HAESLER" ;
○ Here ‘\0’ is automatically added.
● A string can be printed in many ways.
(1) i=0;
while(name[i] != ’\0’)
{
printf(“%c”, name[i]);
i++;
}
(2) printf(“%s”, name);
(3) puts(name);

● Reading a string:
(1) scanf(“%s”, name”);
○ Here the characters are stored in the variable name till it reaches a delimiter such as
Space or Enter.
○ The number of characters must not be greater than the memory space allocated for the
string when declared.
○ Eg: if “good morning” is entered, only “good” is stored.
(2) gets(name);
● Here all the characters including space are stored until Enter key is reached. This can
be used to enter a line of characters.
○ if “good morning” is entered, “good morning” is stored.
(3) scanf ( "%[^\n]s", name ) ;
● Similar to gets(). All characters until a ‘\n’ is reached are stored in the array.

S3 CT, GPTC Cherthala 12


Standard Library String Functions
● Some standard string functions are defined in the header file string.h.

S3 CT, GPTC Cherthala 13


● String length - strlen( )
○ Syntax: strlen(string_name);
■ Returns the length of the string excluding ‘\0’.
■ Eg: strlen(“hai”);
■ it returns 3.
○ For a string s, its implementation is similar to the following.
int i = 0 ;
while ( s[i] != '\0' )
{
i++ ;
}
return ( i ) ;

● String Copy - strcpy( )


○ Syntax: strcpy(target, source);
○ It copies the contents of the string source into target and returns the target string.
○ The target should be big enough to hold the source string.
○ This function copies the characters in the source string into the target string till it
reaches the end of the source string (‘\0’). ‘\0’ is also copied.
○ Eg:
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "source string = %s \n", source ) ;
printf ( "target string = %s \n", target ) ;
○ The output will be
source string = Sayonara
target string = Sayonara
○ The implementation of the function is similar to the following.
int i = 0 ;
while ( source[i] != '\0' )
{
target[i]=source[i];
i++ ;
}
target[i]=’\0’;

● String Concatenation - strcat( )


○ Syntax: strcat(target, source);
○ This function concatenates the source string at the end of the target string and returns
the target string.
○ The target should be large enough to hold the appended string also.
○ Eg:
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;

S3 CT, GPTC Cherthala 14


printf ( "source string = %s \n", source ) ;
printf ( "target string = %s \n", target ) ;
○ The output will be,
source string = Folks!
target string = HelloFolks!
○ The implementation is similar to the following.
int i = 0, j=0 ;
while ( target[i] != '\0' ) // finding the end of target string
{
i++ ;
}
while ( source[j] != '\0' )
{
target[i]=source[j]; // adding source characters to the target
i++;
j++;
}
target[i]='\0'; // putting the end of target string
● String Comparison - strcmp( )
○ Syntax: strcmp(str1, str2);
○ This function compares two strings to find out whether they are the same or different.
The two strings are compared character by character until there is a mismatch or end of
one of the strings is reached, whichever occurs first. If the two strings are identical,
strcmp( ) returns a value zero. If they’re not, it returns the numeric difference
between the ASCII values of the first non-matching pairs of characters.
○ Eg:
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ; // i will be 0
j = strcmp ( string1, string2 ) ; // j will be 4. Difference of J and F is 4
k = strcmp ( string1, "Jerry B" ) ; // k will be -32. Difference of ‘\0’ and ‘space’ is -32

Example Program: To check whether a string is palindrome or not using standard string functions.

#include<stdio.h>
#include<string.h>

int main()
{
char source[10], reverse[10];
int length,i;
printf("Enter the string in lowercase: ");
scanf("%s",source);

S3 CT, GPTC Cherthala 15


length = strlen(source);

// to reverse the string


i=0;
while(i<length)
{
reverse[i]= source[length-1-i];
i++;
}
reverse[i]= '\0';

printf("Reverse is %s\n",reverse);
if(strcmp(source,reverse)==0)
{
printf("The given string is palindrome\n");
}
else
{
printf("The given string is not palindrome\n");
}
return 0;
}

***************************************

Questions from Module II

Nov 2022
1. Write the initialization statement of the following matrix. (1)

2. List any two built-in functions to manipulate strings. (1)


3. Write the features of an array. (3)
4. #include<stdio.h>
int main()
{
int a[5] = {5, 1, 15, 20, 25};
int i, j, m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf(“%d, %d, %d”, i, j, m);
return 0;
}
Write the output and explain.

S3 CT, GPTC Cherthala 16


5. How to find whether two strings are equal or not using the built-in function? Illustrate with
examples. (3)
6. Write notes on passing an array into a function as arguments. (3)
7. Explain steps in the Binary Search method. (7)
8. Explain how to
a) read a string 1 Mark
b) find length of the string 2 Marks
c) copy the string 2 Marks
d) find the reverse of string. 2 Marks

Nov 2023
1. The library function used to find the length of a string is ......... (1)
2. Write a C statement to initialize an array with values 3,7,2,4,1. (1)
3. Illustrate the steps to solve problems using divide and conquer methods. (3)
4. (a)Differentiate between one dimensional and two dimensional arrays. (3 Marks)
(b)Write a C program to find the transpose of a given matrix. (4 Marks)
5. Write a C program to implement binary search algorithm. (7)
6. Explain any four string manipulation functions with examples. (7)
7. Write a C program to check whether a given string is palindrome or not. (7)

S3 CT, GPTC Cherthala 17

You might also like