0% found this document useful (0 votes)
2 views

Unit-IV

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit-IV

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Ver 2.

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:

• An array is a collection of similar data type or homogenous.


• It allocates sequential memory locations.
• Individual values are called as elements.
• It is simply grouping of like type data such as list of numbers, list of names

Some examples where arrays can be used are


1) List of temperatures recorded every hour in a day, or a month, or a year.
2) List of employees in an organization.
3) List of products and their cost sold by a store.
4) Test scores of a class of students
5) List of customers and their telephone numbers.

Types of Arrays:

• One – dimensional arrays


• Two – dimensional arrays
• Multidimensional arrays

ONE – DIMENSIONAL ARRAY(1-D)


A list of items can be given one variable name using only one subscript and such a variable is called a single
– subscripted variable or a one – dimensional array.
int a[5];

float b[7];

char c[7];

Declaration of One-Dimensional Arrays:

• Like any other variables, arrays must be declared before they are used. The general
Ver 2.0

form of array declaration is


Syntax:

<datatype> <array_name>[size of array];

• 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.

• The size of array should be a constant value

Examples: float height[50];

• Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid.

int group[10];

• Declares the group as an array to contain a maximum of 10 integer constants.

• 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

• The values to the array elements can be assigned as


num[0] = 35;

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();
}

Initialization of One – Dimensional Arrays:


• After an array is declared, its elements must be initialized. Otherwise they will contain “garbage”
value.
• The elements of an array can be initialized by using an initialization list (comma separated list).
• An initializer is an expression that determines the initial value of elements of array.

The general form of initialization of array is

datatype array_name[size] = {list of values};


Example: int number[3] = {1,2,4};
i.e. we will declare the variable number as an array of size 3 and will assign 1,2 and 4 to number[0],
number[1] and number[2] respectively0.
Example-2: Write a C program to read in 10 integer number and print their average, minimum and maximum
numbers.

#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();
}

TWO DIMENSIONAL ARRAYS:

• 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

Declaration of a two-dimensional Array:


• A two-dimensional array declaration consists of a type specifier (i.e. element type) and identifier (i.e. name
of an array), row size specifier (i.e. number of rows in an array) and column size specifier (i.e. number of
columns in each row).
• The size specifier are enclosed within square brackets.
Example

int arr[2][3]; //arr is an integer type array of 2 rows and 3

columns. float ab[5][1];// ab is floating point type array of 5X1.

Char name[2][3]; //name is a character type array of 2 rows and 3 columns.

Initialization of two–Dimensional Arrays:

• 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}};

(1) Write a program to display the elements of two-dimensional array.


#include<stdio.h>
void main( )
{ Output:
int i,j;
int a[3][3] ={{1,2,3},{4,5,6},{7,8,9}}; Elements of an Array
printf("elements of an array \n \n");
for( i=0; i<3; i++) 1 2 3
{
for ( j=0; j<3; j++) 4 5 6
{
printf ("%d\t", a[i][j]); 7 8 9
}
printf("\n");
}
}

(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( );
}

(3) Write a program in C to perform multiplication of two matrices of 3x3.


# include<stdio.h>
# include<conio.h> void
main( )
{
int i,j,k,a[3][3], b[3][3],multi[3][3]={0};
clrscr( );
printf(“Enter Elements of Matrix of A: \n”);
for( i=0; i < 3; i++) Output:
{ Enter Elements of Matrix of A:
for( j=0; j<3; j++) 4 5 8
{ 2 9 8
scanf(“ %d ”, &a[i][j]); 2 9 4
} Enter Elements of Matrix of B:
} 1 3 5
printf(“Enter Elements of Matrix of B: \ n”); 0 5 4
for( i=0; i < 3; i++) 6 7 2
{ Matrix Multiplication
for( j=0; j < 3; j++) 52 93 56
{ 50 107 62
scanf(“ %d ”, &b[i][j]); 26 79 54
}
}
printf(“\n Matrix Multiplication \n”);
for( i=0; i < 3; i++)
{
for( j=0; j < 3; j++)
{
for( k=0; k < 3; k++)
{
multi[i][j]=multi[i][j]+a[i][k]*b[k][j];
printf(“%d\t”,multi[i][j]);
}
}
printf(“\n”);
}
getch();
Ver 2.0

}
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.

Example: int a[3][4][6];

STRINGS AND THEIR OPERATIONS IN C

• In C language, an array of characters is known as a string.


Example: char st[80];
• This statement declares a string array with 80 characters.
• The control character ‘\0’ which represents a null character is placed automatically at the end
of any string used.
STRING HANDLING FUNCTIONS IN C:
There are four important string Handling functions in C language.
• strlen( ) function
• strcpy( ) function
• strncpy( ) function
• strcat( ) function
• strncat( ) function
• strcmp( ) function
• strrev() function

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.

strcmp( ) Function: strcmp( ) function is used to compare two character strings.


• It returns a 0 when two strings are identical. Otherwise it returns a numerical value which is the
different in ASCII values of the first mismatching character of the strings being compared.
Ver 2.0

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);

READING / WRITING STRINGS:


• We use scanf ( ) function to read strings which do not have any white spaces.
Ex: scanf(“ %s ”, city );
• When this statement is executed, the user has to enter the city name (eg “NEWDELHI”) without any white
space (i.e not like “NEW DELHI”).
• The white space in the string will terminate the reading and only “NEW” is assigned to city.
• To read a string with white spaces gets( ) function.

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();
}

Example: 3 Write a program in C to reverse a string without using string function.

#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

/* program to check for palindrome string */


# include<stdio.h>
# include<conio.h>
# include<string.h>
void main( )
{
char st[20], rst[20];
int i,j;
clrscr( );
printf(„\n Enter the string:”);
scanf(“%s”, st);
/* loop to reverse the string */
i=0;
j=strlen(st)-1;
while( j >= 0 )
{
rst[ i ] = st[ j ];
i++;
j--;
}
rst[ i ] = ‘\0’;
if(strcmp(st,rst)==0)
printf(“\n %s is a palindrome string”, st);
else
printf(“\n %s is not a palindrome string”, st);
getch();
}
Ver 2.0

Structures

• It is a user defined data type.


• A structure is a collection of variables under a single name and provides a convenient way of grouping
several pieces of related information together. (Data of Different Types).
Defining a structure
• First, we use struct keyboard followed by name of structure then curly braces.
• We must specify the names and types of each of the fields of the structure and declare variables of
that types.
Example
struct student
{
int rollno;
char name[30];
int marks;
};
• It contains three members:
o rollno integer type
o 30 element character array of name
o marks integer type
• The variable of type student can be declared as
o struct student s1,s2,s3;

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

• The members of a structure can be accessed and processed as separate entities.


• Structure members can be accessed by using dot(.), also called period operator. Syntax
Variable.member
Example for student structures
s1.rollno s1.name s1.marks

Accessing and Processing a Structure

• The members of a structure can be accessed and processed as separate entities.


• Structure members can be accessed by using dot(.), also called period operator. Syntax
Variable.member

Example for student structures


s1.rollno s1.name s1.marks

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

enumerated data types

• An enumeration is a user-defined data type consists of integral constants.


• Each integral constant is given a name.
• Keyword enum is used to define enumerated data type.
Syntax
enum type_name{ value1, value2,...,valueN };

• 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};

Declaration of enumerated variable:

• 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 or Sequential Search


• Binary Search

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

Notion of Order of Complexity


Algorithmic complexity is concerned about how fast or slow particular algorithm performs. We define
complexity as a numerical function T(n) - time versus the input size n. We want to define time taken by an
algorithm without depending on the implementation details. But you agree that T(n) does depend on the
implementation! A given algorithm will take different amounts of time on the same inputs depending on such
factors as: processor speed; instruction set, disk speed, brand of compiler and etc
We use different notation to describe limiting behavior of a function.
O-notation:
To denote asymptotic upper bound, we use O-notation. For a given function g(n), we denote
by O(g(n))(pronounced “big-oh of g of n”) the set of functions:
O(g(n))= { f(n) : there exist positive constants c and n0 such that 0≤f(n)≤c∗g(n) for all n≥n0 }

Ω-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

You might also like