Unit-IV
Unit-IV
Unit-IV
Module – 4: (Arrays & Basic Algorithms)
Arrays: Array notation and representation, manipulating array elements, using multi dimensional arrays. Character
arrays and strings, Structure, union, enumerated data types, Array of structures, Passing arrays to functions.
Basic Algorithms: Searching &Basic Sorting Algorithms (Bubble, Insertion and Selection), Finding roots of equations,
Notion of order of complexity.
Introduction
• The fundamental data types, namely char, int, float, double are used to store only one value at any
given time.
• Hence these fundamental data types can handle limited amounts of data.
• In some cases, we need to handle large volume of data in terms of reading, processing and printing.
• To process such large amounts of data, we need a powerful data type that would facilitate efficient
storing, accessing and manipulation of data items.
• “C” supports a derived data type known as array that can be used for such applications.
Arrays:
Types of Arrays:
float b[7];
char c[7];
• Like any other variables, arrays must be declared before they are used. The general
Ver 2.0
• The datatype specifies the type of element that will be contained in the array, such as int, float, or char.
• The size indicates the maximum number of elements that can be stored inside the array.
• Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid.
int group[10];
• To represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable num. We may declare
the variable num as
int num[5];
• Hence the computer reserves five storage locations as shown
num[0] num[1] num[2] num[3] num[4]
num 35 40 20 57 19
num[1] = 40;
num[2] = 20;
num[3] = 57;
num[4] = 19;
Valid Statements:
• a = number[0] + 10;
• number[4] = number[0] + number[2];
Example-1: Write a program using a single dimensional array to read and display the array elements.
#include<stdio.h>
#include<conio.h> void
main( )
{
int i,x[10];
printf("Enter 10 real numbers: \n"); for
(i=0; i <10; i++)
{
scanf(" %d ", &x[i]);
Ver 2.0
}
printf("The array elements are:"); Output:
Enter 10 real numbers: 1 2 3 4 5 6 7 8 9 10
for(i=0; i < 10; i++)
The array elements are: 1 2 3 4 5 6 7 8 9 10
{
printf("%d \t", x[i]);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,sum=0;
float a[10], large, small,avg ;
printf(“ \n Array elements are \n”);
for(i=0; i<=9; i++)
scanf(“ %f ”, &a[ i ]);
large = a[0];
small = a[0]; Output:
Array elements are: 1 2 3 4 5 6 7 8 9 10
for(i=1; i<=9; i++)
Average is 5.5
{ Largest element in array is 10 Smallest element in array is 1
sum=sum+a[i];
if(a[ i ] > large)
large = a[ i ];
else if( a[ i ] < small)
small = a[ i ];
}
avg=sum/10.0;
printf(“\n Average is %f \n”, avg);
printf(“\n Largest element in array is %f\n”, large);
printf(“ \n smallest element in array is %f \n”, small);
getch( );
}
Ver 2.0
Example 3: Given an array of 20 integers. Write a program in C to search for a given integer in that array.
#include<stdio.h> Output:
#include<conio.h> Enter the elements of the
int main() array: 1
{ 2
int a[10],i,n,c=0; 3
printf("\nEnter the elements of the array: 4
"); for(i=0; i<=19; i++) 5
{ 5
scanf("%d",&a[i]); 6
} 6
printf("\nEnter the number to be search: 7
"); scanf("%d",&n); 8
for(i=0; i<=19; i++) 65
{ 1
if(a[i]==n) 2
{ 2
c=1; 3
break; 3
} 3
} 5
if(c==0) 9
printf("\nThe %d number is not in the 4
list",n); else Enter the number to be search: 65
printf("\nThe %d number is found at postion %d",n,i+1); The 65 number is found at position 11
return 0;
getch();
}
• A two-dimensional array has its elements in a rectangular grid of rows and columns.
• The elements of a two-dimensional array can be accessed by using a row index (i.e. row number)
and column index (i.e. column number).
• Both the number index and column index are required to select an element of a two-dimensional
array.
• A two-dimensional array is popularly known as a matrix.
int a[4][5]={1,5,4,7,5,8};
Ver 2.0
• Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
1 2 3
int table[2] [3] = {1,2,3,4,5};
4 5 0
• This initializes the elements of first row to zero and the second row to one.
• This initialization is done row by row.
• The above statement can be equivalently written as int table [2][3] = {{1,2,3}, {4,5}};
(2) Write a program in C to read the elements of the matrix of 3x3 & transpose its element.
# include<stdio.h>
# include<conio.h> void
main( )
{
int i,j, a[3][3], b[3][3];
clrscr( );
printf(“\n Enter Elements of matrix A: \n”);
for( i=0; i < 3; i++)
{
for( j=0; j<3; j++)
{
scanf(“ %d ”, &a[ i ][ j ]);
Ver 2.0
}
}
/* transposing logic simply copying one matrix elements to another in reverse order */
for( i=0; i < 3; i++)
{
Output:
for( j=0; j < 3; j++)
{ Enter Elements of matrix A:
b[ j ][ i ]=a[ i ][ j ]; 3 5 8
} 4 8 5
} 8 5 4
printf(“ \n The Matrix Transpose is \ n”); The Matrix Transpose is
for( i=0; i<3; i++) 3 4 8
{ 5 8 5
for( j=0; j<3; j++) 8 5 4
{
printf(“%d”, b[ i ][ j ]);
}
printf (“ \ n”);
}
getch( );
}
(3) Write a program in C to perform addition and subtraction of two matrices of 3X3.
# include<stdio.h>
# include<conio.h> void
main( )
{
int i,j, a[3][3], b[3][3],sum[3][3]={0},subt[3][3]={0};
clrscr( );
printf(“Enter Elements of Matrix of A: \n”);
for( i=0; i < 3; i++)
{
Output:
for( j=0; j<3; j++)
{ Enter Elements of Matrix of A:
scanf(“ %d ”, &a[i][j]); 4 5 8
} 2 9 8
} 2 9 4
Enter Elements of Matrix of B:
printf(“Enter Elements of Matrix of B: \ n”);
1 3 5
for( i=0; i < 3; i++) 0 5 4
{ 6 7 2
for( j=0; j < 3; j++)
{
scanf(“ %d ”, &b[i][j]);
}
}
printf(“\n Matrix Addition \n”);
for( i=0; i < 3; i++)
{
for( j=0; j < 3; j++)
{
sum[i][j]= a[i][j] + b[i][j];
printf(“%d\t”,sum[i][j]);
Ver 2.0
}
printf (“ \n”); Matrix Addition
}
5 8 13
printf(“n Matrix Subtraction/Difference \n”);
for( i=0; i < 3; i++) 2 14 12
{ 8 16 6
for( j=0; j < 3; j++)
{ Matrix Subtraction
Subt[i][j]= a[i ][j] – b[i][j]; 3 2 3
printf(“%d\t”,subt[i][j]); 2 4 4
} -4 2 2
printf(“\n”);
}
getch( );
}
}
MULTI – DIMENSIONAL ARRAY:
A list of items can be given one variable name using more than two subscripts and such
a variable is called Multi – dimensional array.
Three-Dimensional Array:
A list of items can be given one variable name using three subscripts and such a variable
is called Three – dimensional array.
strlen( ) Function: strlen( ) function is used to find the length of a character string.
Ex: int n;
char st[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable n.
• Note that the null charcter ‘\0’ available at the end of a string is not counted.
strcpy( ) Function: strcpy( ) function is used to copy from one string to another string.
Ex :
char city[15];
strcpy(city, “BANGALORE”) ;
• This will assign the string “BANGALORE” to the character variable city.
Note that character value like
city = “BANGALORE”; cannot be assigned in C language.
strcat( ) Function: strcat( ) function is used to join character, Strings. When two characters strings are
joined, it is referred as concatenation of strings.
Ex:
char city[20] = “BANGALORE”; char pin[8] = “-560001”;
strcat(city,pin);
• This will join the two strings and store the result in city as “BANGALORE – 560001”.
• Note that the resulting string is always stored in the left side string variable.
int n;
char city[20] = “Madras”;
char town[20] = “Mangalore”;
n=strcmp(city, town);
• This will return an integer value “- 1‟ which is the difference in the ASCII values of the first
mismatching letters “d” and “n”
Note: that the integer value obtained as the difference may be assigned to an integer variable
as follows:
int n;
n =strcmp(city, town);
Example: 1 Write a program in C to find length of string without using string function.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100]; int i=0;
printf("\nEnter the String : ");
gets(str);
while (str[i] != '\0')
{
i++;
}
printf("\nLength of the String is : %d", length);
}
Example: 2 Write a program in C to copy one string to another without using string function.
#include<stdio.h>
#include<conio.h> void main() {
char s1[100], s2[100]; int i;
printf("\nEnter the string:"); gets(s1);
i = 0;
while (s1[i] != '\0')
{
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("\nCopied String is %s ", s2);
getch();
}
#include<stdio.h>
Ver 2.0
#include<conio.h>
void main()
{
char str[50];
char rev[50];
int i=-1,j=0;
printf("Enter any string : ");
gets(str);
while(str[++i]!='\0');
while(i>=0)
rev[j++] = str[--i];
rev[j]='\0';
printf("Reverse of string is : %s",rev);
getch();
}
Example: 4 Write a C program to test whether a given string is palindrome string
• Consider the string “LIRIL” when it is reversed, it reads again as “LIRIL”. Any string of this kind is called
a palindrome string.
• Few other palindrome strings are
DAD, MOM, MADAM, MALAYALAM
Structures
Initialization of a Structure
• Struct student s1={1211,”Rahul”,25};
• Here 1211 is rollno of student, “Rahul” is name of student which is string or array of characters and 25
is marks of student.
Accessing and Processing a Structure
Example: Write a program in C to make a student structure and display 10 students information as rollno,
name, and marks.
#include<stdio.h>
#include<conio.h>
struct student
Ver 2.0
{
int rollno;
char name[30];
int marks;
};
void main()
{
struct student s[10];
int i;
printf(“Enter information of students:\n”);
for(i=0;i<10;i++)
{
s[i].roll=i+1;
printf(“\n For roll number %d\n”,s[i].roll);
printf(“Enter name:”);
scanf(“%s”,s[i].name);
printf(“Enter Marks”);
scanf(“%d”,&s[i].marks);
printf(“\n”);
}
printf(“Displaying information of students:\n\n”);
for(i=0;i<10;i++)
{
s[i].roll=i+1;
printf(“\n Information for roll number %d\n”,i+1);
printf(“Name: %s”, s[i].name);
printf(“Marks : %d”,&s[i].marks);
}
getch();
}
Union
• Just like structures, unions are used to create user defined types.
• A union is a collection of one or more variables, possibly of different types.
• The only difference between structures and unions is in the terms of storage of their numbers.
• In structures, a separate memory is allocated to each member while in unions, all the members
of an object share same memory.
• A union objects are used only if one of its constituting members is to be used at a time.
Defining a union
• Same as structure, with only difference is keyword union.
Syntax
union name_of_union
{
type variable1; type variable2;
};
Example:
union var
Ver 2.0
{
char a;
int b;
float c;
};
Example:
#include<stdio.h>
#include<conio.h>
union var
{
char a;
int b;
float c;
};
void main()
{
union var A={‘A’};
printf(“The values of member a is :%c”,A.a);
getch();
}
Output:
The values of member a is: A
• Here, type_name is the name of enumerated data type or tag. And value1, value2,....,valueN are
values of type type_name.
• By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the
default value.
Example
// Changing the default value of enum elements
enum suit{ club=0, diamonds=10, hearts=20, spades=3};
• Above code defines the type of the data but, no any variable is created. Variable of type enum can be
created as:
enum boolean { false,true};
enum boolean check;
• Here, a variable check is declared which is of type enum boolean. Example of enumerated type
Ver 2.0
#include <stdio.h>
#include <conio.h>
enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday};
void main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
getch();
}
Output:
4 day
Searching
Searching is an operation or a technique that helps finds the place of a given element or value in the list. Any
search is said to be successful or unsuccessful depending upon whether the element that is being searched is
found or not. Some of the standard searching technique that is being followed in the data structure is listed
below:
Linear Search
This is the simplest method for searching. In this technique of searching, the element to be found in searching
the elements to be found is searched sequentially in the list. This method can be performed on a sorted or an
unsorted list (usually arrays). In case of a sorted list searching starts from 0th element and continues until the
element is found from the list or the element whose value is greater than (assuming the list is sorted in
ascending order), the value being searched is reached.
Example: Linear Search to find the element “20” in a given list of numbers
Binary Search
Binary search is a very fast and efficient searching technique. It requires the list to be in sorted order. In this
method, to search an element you can compare it with the present element at the center of the list. If it
matches, then the search is successful otherwise the list is divided into two halves: one from the 0th element
to the middle element which is the center element (first half) another from the center element to the last
element (which is the 2nd half) where all values are greater than the center element.
Ver 2.0
Example: Binary Search to find the element “23” in a given list of numbers.
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator on
the elements. The comparison operator is used to decide the new order of element in the respective data
structure.
For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the
character with lesser ASCII value will be placed first than the character with higher ASCII value.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if
they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap
them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura First Year (CS-A & CS-B) 15 | Page
Ver 2.0
Example:
Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending
order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given
array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura First Year (CS-A & CS-B) 16 | Page
Ver 2.0
Ω-notation:
To denote asymptotic lower bound, we use Ω-notation. For a given function g(n), we denote
by Ω(g(n))(pronounced “big-omega of g of n”) the set of functions:
Ω(g(n))= { f(n) : there exist positive constants c and n0 such that 0≤c∗g(n)≤f(n) for all n≥n0 }
Θ-notation:
To denote asymptotic tight bound, we use Θ-notation. For a given function g(n), we denote
by Θ(g(n))(pronounced “big-theta of g of n”) the set of functions:
Θ(g(n))= { f(n) : there exist positive constants c1,c2 and n0 such that 0≤c1∗g(n)≤f(n)≤c2∗g(n) for all n>n0 }
PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura First Year (CS-A & CS-B) 17 | Page