0% found this document useful (0 votes)
11 views126 pages

Unit 3

Uploaded by

Niraj Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
11 views126 pages

Unit 3

Uploaded by

Niraj Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 126

Unit 3

Arrays
Syllabus
• Introduction to Arrays (1-D, 2-D),
• Character arrays and Strings,
• Basic Algorithms:
– Searching,
– Basic Sorting Algorithms (Bubble, Insertion and
Selection),
– Finding roots of equations,
– notion of order of complexity through example programs
(no formal definition required).
Introduction to Array
• The variables that we have used till now are capable of storing
only one value at a time. Consider a situation when we want to
store and display the age of 100 employees. For this we have to
do the following-
• Declare 100 different variables to store the age of employees.
• Assign a value to each variable.
• Display the value of each variable.
• Although we can perform our task by the above three steps but
just imagine how difficult it would be to handle so many
variables in the program and the program would become very
lengthy.
• The concept of arrays is useful in these types of situations where
we can group similar type of data items.
Definition

• An array is a collection of similar type of data items and each data item is
called an element of the array.
• The data type of the elements may be any valid data type like char, int or float.
• The elements of array share the same variable name but each element has a
different index number known as subscript.
• For the above problem we can take an array variable age[100] of type int. The
size of this array variable is 100 so it is capable of storing 100 integer values.
The individual elements of this array are-
• age[0], age[l], age[2], age[3], age[4], age[98], age[99] In C. The subscripts
start from zero, so age[0] is the first element, age[1] is the second element of
array and so on.
• Arrays can be single dimensional or multidimensional. The number of
subscripts determines the dimension of array. A one-dimensional array has one
subscript, two dimensional array has two subscripts and so on. The one-
dimensional arrays are known as vectors and two-dimensional arrays are
known as matrices.
Array

 One-Dimensional array
 Two-Dimensional array
 Multi-Dimensional array
One-Dimensional Array

 collection of elements of same data type that


are stored contiguous in memory.
 int a[10];

data

10 20 30 25 35 6 50 45 28 14

1000 1002 1004 1006 1008 1010 1012 1014 1016 1018

Address
One-Dimensional Array

 The subscript, or the index of each array


element is determined based on the number
of offset positions it is from the starting
position. The starting offset is taken as 0.

offset

0 1 2 3 4 5 6 7 8 9

10 20 30 25 35 6 50 45 28 14

1000 1002 1004 1006 1008 1010 1012 1014 1016 1018
One-Dimensional Array
Syntax:
datatype variablename [size];

Example:
int a[10];
block of 10 contiguous elements in memory.

Array name (Starting address of the array)


a

offset

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
One-Dimensional Array

Initialization

 A character array needs a string terminator, the NULL character („\0‟) as


the last character, whereas integer and float arrays do not need a
terminator.

 Examples:
char array1[] = {'A','R','R','A','Y','\0'};
char array2[ ] = {“ARRAY”};
char array1[] = {'M', 'T', 'W', 'T', 'F', 'S', 'S'};
float values[ ] = {100.56, 200.33, 220.44, 400.22, 0};
int marks[5] = { 99, 78};
One-Dimensional Array

Initialization
int a[5]={7,3,8,2,25};
(or)
int a[5];
a[0]=7;
a[1]=3;
a[2]=8;
a[3]=2;
a[4]=25;
Input To Array

Normal Variable: Array Variable:


Array offset
inta[20],i; always
int a; start with 0
scanf(“%d”,&a); for(i=0;i<20;i++)
{
Array Variable: scanf(“%d”,
&a[ i ]);
int a[20];
}
scanf(“%d”,&a[0]);
--- 4 lines
---
scanf(“%d”,&a[19]);
Which one is best ?
20 lines
Program 1
//Program to input values into an array and display them.
#include<stdio.h>
main( )
{
int arr[5], i; Output:
for(i=0;i<5;i++)
{
printf ("Enter the value for arr[%d]",i);
scanf("%d",&arr[i]) ;
}
printf ("The array elements are\n");
for(i=0;i<5;i++)
{
printf("%d\t",arr[i]);
printf ("\n");
}}
Program 2
//Program to add the elements of an array
#include<stdio.h>
int main()
{
Output:
int arr[10],i,sum=0;
for(i=0;i<10;i++)
{
printf ("Enter the value for arr [%d]",i);
scanf("%d",&arr[i]);
sum=sum+arr[i];
}
printf ("Sum = %d\n", sum) ;
}
Program 3
//Program to count the even and odd numbers in a array.
#include<stdio.h>
int main()
{
int arr[10],i,even=0,odd=0; Output:
for(i=0;i<10;i++)
{
printf ("Enter the value for arr[%d]",i);
scanf("%d",&arr[i]);
if(arr[i]%2==0)
even++;
else
odd++;
}
printf("Even numbers %d, Odd numbers =%d\n", even, odd);
}
Program 4
//Program to find the maximum and minimum number in an array.
#include<stdio.h>
int main( )
{
int i, j , arr[ 10] = { 2 , 5, 4, 1, 8, 9, 11 , 6, 3 , 7} ;
int min, max;
min=max=arr[0] ;
for(i=1;i<10;i++)
{
if(arr[i]<min)
min=arr[i] ;
if(arr[i]>max)
max=arr[i] ;
}
printf("Minimum =%d,maximum =%d\n" ,min, max) ;
}

Output:
Program 5
//program to find sum of elements of arrays
#include<stdio.h>
void main()
{
int a[5],sum=0,i;
printf("enter the five elements of array");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
sum=sum +a[i];
}
printf("sum of elements of array is :");
printf("%d\n",sum);
}
Output:
Program 6
//Write a program to take marks of 10 students in the class and print the average of the
class.
#include<stdio.h>
void main()
{
int a[10],sum=0,avg,i;
printf("enter the marks of 10 students");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
sum=sum +a[i];
}
avg=sum/10;
printf("Average percentage of the class:");
printf("%d\n",avg);
}
Program 7
//Write a program to take two array from user and display sum of two arrays.

for(i=0;i<5;i++)
#include<stdio.h> {
void main() scanf("%d",&b[i]);
{ }
int a[5],b[5],sum[5],i; for(i=0;i<5;i++)
printf("enter the first array"); {
for(i=0;i<5;i++) sum[i]=a[i]+b[i];
}
{
scanf("%d",&a[i]); printf("sum of two array is");
} for(i=0;i<5;i++)
{
printf("%d\n",sum[i]);
printf("enter the second array"); }
}
SEARCHING
• Searching refers to the operation of finding the location of
a given item in a collection of items.

• The search is said to be successful if ITEM does appear in


DATA and unsuccessful otherwise.

19
Linear search
• Suppose DATA is a linear array with n elements.
• Given no other information about DATA, the most intuitive
way to search for a given ITEM in DATA is to compare ITEM
with each element of DATA one by one.
• That is , first we test whether DATA[1]= ITEM, and then we
test whether DATA[2]= ITEM, and so on.
• This method is called linear search or sequential search.

20
Example

21
Linear search program
#include<stdio.h>
int main()
{
int arr[10]={1,5,7,8,9,45,2,6,98,99};
int item,i;
printf("enter the item to be search");
scanf("%d",&item);
for(i=0;i<10;i++)
{
if(arr[i]==item)
{
printf("item is at location %d",i+1);
break;
}}}
Output:
Binary Search
• Search a sorted array by repeatedly dividing the search
interval in half.
• Begin with an interval covering the whole array.
• If the value of the search key is less than the item in the
middle of the interval, narrow the interval to the lower half.
• Otherwise narrow it to the upper half.
• Repeatedly check until the value is found or the interval is
empty.

23
Example

24
Binary search program
while (low <= high)
{
if(arr[mid] < item)
#include<stdio.h> {
#define SIZE 5 low = mid + 1;
int main() }
{ else if(arr[mid] == item)
int i, arr[SIZE], item, low, high, mid; {
printf("Enter 5 numbers"); printf("%d found at location %d\n", item,
for (i=0; i<SIZE; i++) mid+1);
{ break;
scanf("%d",&arr[i]); }
} else
printf("Enter a number to find :"); {
high = mid - 1;
scanf("%d", &item);
}
low = 0;
mid = (low + high)/2;
high =SIZE -1;
}
mid = (low+high)/2;
if(low > high)
{
printf("Not found! %d is not
present in the list.",item);
Bubble Sort
• Bubble Sort is the simplest of the sorting techniques.
• In the bubble sort technique, each of the elements in
the list is compared to its adjacent element. Thus if
there are n elements in list A, then A[0] is compared
to A[1], A[1] is compared to A[2] and so on.
• After comparing if the first element is greater than
the second, the two elements are swapped then.
• Larger elements move or ‘bubble’ up to the top of the
list.

30
31
32
33
Bubble sort program
for(i=0; i<n-1; i++)
for(j=0; j<n-1-i; j++)
#include<stdio.h> {
int main() if(a[j]>a[j+1])
{ {
int a[10],i,j,temp,n; temp=a[j];
printf("\n Enter the max no.of a[j]=a[j+1];
Elements to Sort: \n"); a[j+1]=temp;
}
scanf("%d",&n);
}
printf("\n Enter the Elements : \n");
printf("sorted array is");
for(i=0; i<n; i++) for(i=0; i<n; i++)
{ {
scanf("%d",&a[i]); printf("%d\t",a[i]);
} }
return 0;
}
Selection Sort
• In this sorting we find the smallest element
in this list and put it in the first position.
• Then find the second smallest element in
the list and put it in the second position.
And so on.

35
36
Selection Sort program
#include <stdio.h> temp = a[i];
int main() a[i] = a[min];
{ a[min] = temp;
int a[10], n, i, j, min, temp; }

printf("Enter number of elements\n");


scanf("%d", &n); printf("Sorted list in ascending
printf("Enter %d integers\n", n); order:\n");
for (i = 0; i < n; i++)
{ for (i = 0; i < n; i++)
scanf("%d", &a[i]); printf("%d\n", a[i]);
}
for (i = 0; i < n - 1; i++) // finding minimum return 0;
element (n-1) times }
{
min = i;
for (j = i + 1; j < n; j++)
{
if ( a[j]<a[min])
min= j;
}
Insertion Sort
• The insertion sort works just like its name suggest-it inserts
each item its proper place in the final list.
• During the first iteration, the element position 2nd is
compared with the element at the 1st position.
• During the second iteration, the element at the position 3rd is
compared with the element at the 2nd and 1st positions.
• This process is repeated for all the elements in the array up
to (n-1) iterations.
• This method is widely used by card players.

38
Example

39
Insertion Sort program
#include <stdio.h> for (i = 1; i < n; i++)
{
int main()
temp=a[i];
{ j=i-1;
int n, i, j, temp; while(j>=0 && a[j]>temp)
int a[10]; {
printf("Enter number of elements\ a[j+1]=a[j];
n"); j=j-1;
scanf("%d", &n); }
a[j+1]=temp;
printf("Enter %d integers\n", n);
}
for (i = 0; i < n; i++) printf("sorted array is\n");
{ for (i = 0; i < n; i++)
scanf("%d", &a[i]); {
} printf("%d\n", a[i]);
}
}
Character arrays and Strings
Introduction
• Strings are array of characters i.e. they are
characters arranged one after another in memory. Thus, a
character array is called string.
Each character within the string is stored within one element
of the array successively.
• A string is always terminated by a null character (i.e. slash
zero \0).
Arrays and Strings…
• Operations performed
on character strings include:
– Reading and writing strings
– Copying one string to another
– Combining strings together
– Comparing strings for equality
– Extracting a portion of a string
String Declaration
• A string variable is declared as an array of characters.
• Syntax:
• char string_name[size];
• E.g. char name[20];
• When the compiler assigns a character string to a character
array, it automatically supplies a null character (‘\0’) at the
end of the string
Initializing String Variables
• Strings are initialized in either of the following two forms:
• char name[4]={‘R’,‘A’,‘M’, ‘\0’};
char name[]={‘R’,‘A’,‘M’, ‘\0’};

char name[4]=“RAM”;
char name[]=“RAM”;
• When we initialize a character array by listing its elements, the
null terminator or the size of the array must be provided
explicitly.

R A M \0
name[0] name[1] name[2] name[3]
Program 8
#include<stdio.h>
int main()
{
char str[]="welcome";
printf("%s",str);
}

Output
Program 9
Using printf() and scanf()
include<stdio.h>
int main ()
{
char name[20];
printf("Enter name:");
scanf("%s",name);
printf("Your name is %s.", name);
return 0;
}
output:

Note: scanf( ) stops reading as soon as it encounters a whitespace.


Program 10
Using gets() and puts()
#include<stdio.h>
int main ()
{
char name [20];
printf("Enter name:");
gets(name);
printf("Your name is:”);
puts(name);
}
Output
String handling functions
• Strings need to be manipulated by programmer.
• It can be done manually but is time consuming.
Program 11
//Counting length of the string
#include <stdio.h>
void main()
{
char input_string[50];
int i=0;
printf("\nEnter your text:");
gets(input_string);
while(input_string[i]!='\0')
{
i++;
}
printf("\nThe length of your text
is: %d character(s)", i);
}
Program 12

//Copying one string to another


#include <stdio.h>
void main()
{
char string1[50], string2[50]; int i;
printf("\nEnter your name:");
gets(string1);
for(i=0;string1[i]!='\0';i++)
{
string2[i]=string1[i];
}
string2[i]='\0';
printf("\nThe name is:"); puts(string2);
}
String Handling Functions

• C supports a number of string handling function.


• These function are defined in the header file string.h.
• Therefore, whenever, the string handling functions are used in
a C program, the preprocessor statement #include<string.h>
should be included in the program.
Sl. No. String Functions Operation Performed

1 strcat() Appends the characters of second argument at the end


of first string variable.
2 strncat() Appends first n character of second argument at the
end of first variable.
3 strcmp() Compares two strings (Comparison is case sensitive).
4 strncmp() Compares first n characters of source string constant
or variable to destination string variable. (Comparison
is case sensitive).
5 strcpy() Copies character of source string constant or variable
to destination string variable.
6 strncpy() Copies first n characters of source string constant or
variable to destination string variable.
7 strlen() Finds length of a string.
8 strlwr() Converts a string to lowercase.
9 strupr() Converts a string to uppercase.
10 strrev() Reverses the string. Only supported by Turbo C
11 strset() Sets all characters of a string to a given character.
strcat( )
This function is used for concatenation of two strings. If first
string is "King" and second string is “size” then after using this
function the first string becomes "Kingsize".
Syntax:
strcat(stringl, string2); /*concatenates string2 at the end of
stringl */

The null character from the first string is removed, and the
second, string is added at the end of first string.
The second string remains unaffected.
This function ,takes pointer to two strings as arguments and
returns a pointer to the first(concatenated) string.
Program 13
//Program to understand the work of strcat ( ) function.
#include<stdio.h>
#include<string.h>
int main()
{
char strl[20],str2[20];
printf ("Enter the first string: ") ;
scanf("%s",strl);
printf ("Enter the second string: ") ;
scanf("%s",str2) ;
strcat(strl,str2);
printf( "First string: %s \t Second string: %s\n", strl, str2) ;
return 0;
}
14
strncat()
This appends first n-character of second string to the end of the
first string.
• Syntax:
• strncat(string1, string2, n);
Program 14
// Program to understand the work of
strncat ( ) function.

#include<stdio.h>
#include<string.h>
int main()
{
char str1[20]="Subhash ";
char str2[10]="Chandra ";
strncat(str1,str2,3);
printf("str1: %s\n",str1);
return 0;
}
strcmp( )
• This function is used for comparison of two strings.
• Syntax:
• strcmp(string1, string2)
• If the two strings match, it returns value 0, otherwise it returns
a non-zero(1 or -1) value. This function compares the strings
character by character.
Program 15
//Program to understand the work of strcmp() function.

#include<stdio.h>
#include<string.h>
int main( )
{
char strl [10], str2 [10];
printf ("Enter the first string: ");
scanf("%s",strl);
printf ("Enter the second string :");
scanf("%s",str2);
if ((strcmp(strl,str2) )==0)
printf ("Strings are same\n");
else
printf ("Strings are not same\n");
return 0;
}
strncmp()
• This function compares the first n character of two input
strings.
• Syntax:
• strncmp(String1, String2, n); /*where, n is an integer.*/
• The comparison stops when either the end of string is
reached or the corresponding characters in two strings are
not same. The non-zero value returned on mismatch is the
difference of the ASCII value of the non-matching
characters of the two string
Program 16
//Program to understand the work of strncmp() function.

#include<stdio.h>
#include<string.h>
int main( )
{
char str1[10], str2 [10];
int a;
printf ("Enter the first string: ");
scanf("%s",str1);
printf ("Enter the second string :");
scanf("%s",str2);
a=strncmp(str1,str2,4);
printf("%d",a);
return 0;
}
strcpy( )
• This function is used for copying one string to another string.
• Syntax:
• strcpy( strl, str2 )
• It copies str2 to strl. Here str2 is the source string and strl is
destination string. If str2 = "suresh" then this function copies
“suresh" into strl. This function takes pointers to two strings
as arguments and returns the pointer to first string.
Program 17
//Program to understand the work of strcpy () function.

#include<stdio.h>
#include<string.h>
int main()
{
char str1[10],str2[10];
printf ("Enter the first string:");
scanf("%s",str1);
printf ("Enter the second string:");
scanf("%s",str2) ;
strcpy(str1,str2);
printf ("First string ; %s\t\t Second string : %s\n",str1,str2);
}
Output:
strncpy()
• This copies first n characters of second string to the first string.
• Syntax:
• strncpy(string1, string2, n);
Program 18
//Program to understand the work of strncpy () function.
#include<stdio.h>
#include<string.h>
int main()
{
char str1[]="sachine";
char str2[]="Tendulkar";
strncpy(str1, str2, 6);
printf (" %s",str1);
}

Output:
strlen( )
• This function returns the length of the string i.e. the
number of characters in the string excluding the
terminating null character. It accepts a single argument,
which is pointer to the first character of the string.
• Syntax:
• strlen(string);
Program 19
Program to understand the work of strlen () function.

#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
int length;
printf ("Enter the string:") ;
scanf ("%s",str);
length=strlen(str) ;
printf ("Length of the string is %d", length) ;
}

Output:
strlwr()

This function is used to convert an uppercase letters in the


string to the lowercase.
• Syntax:
• strlwr(string);
Program 20

//Program to understand the work of strlwr () function.

#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="SPArk";
strlwr(string1);
printf("%s is in lower case",string1);
}
Output:
strupr()
It converts any lowercase letters that appear in the input string to
the input string to the uppercase.
• Syntax:
• strupr(string);
Program 21
//Program to understand the work of strupr () function.

#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="SPArk";
strupr(string1);
printf("%s is in upper case",string1);
}

Output:
strrev ()
• This function accepts single string as parameter and
reverse that string.
• Syntax:
• strrev (string)
Program 22
//Program to understand the work of strrev () function.

#include <stdio.h>
#include <string.h>
void main(void)
{
char string[]="spark";
strrev(string);
printf("reverse string is %s",string);
}

Output:
strset()
This function replace a string str1 with specified character char.
• Syntax:
• strset(string1, char)
Program 23
//Program to understand the work of strset () function.

#include<stdio.h>
#include<string.h>
int main()
{
char str1[]="sachine";
strset(str1, 'b');
printf (" %s",str1);
}

Output:
Program 24
//Program to find the number of vowels in a given string.

#include <stdio.h>
int main()
{
char str[10];
int j, n=0, i;
printf("enter the string");
gets(str);
for(j=0; str[j]!='\0';j++)
{
if(str[j]=='a'||str[j]=='e'||str[j]=='i'||str[j]=='o'||str[j]=='u'||str[j]=='A'||str[j]=='E'||str[j]=='I'||
str[j]=='O'||str[j]=='U')
n=n+1;
}
printf(" total no of vowels is %d",n);
return 0;
}
Program 25
//Program to add one string after
another string. for(i=0;str1[i]!='\0';i++)
#include<stdio.h> {
int main()
str[l]=str1[i];
{
l++;
char str[10], str1[10];
int l,n=0,i; }
printf("enter the string"); str[l]='\0';
gets(str); printf("%s",str);
printf("enter the second string"); }
gets(str1);
for(l=0;str[l]!='\0';l++)
{
n++;
}
Program 26
//Program to check the entered for(i=0;i < length ;i++)
string is palindrome or not. {
#include <stdio.h> if(string1[i] != string1[length-i-1])
#include <string.h> { flag = 1; break;
int main() }
}
{
if (flag==1)
char string1[20]; { printf("%s is not a palindrome",
int i, length; string1);
int flag = 0; }
else
printf("Enter a string:");
{ printf("%s is a palindrome", string1);
scanf("%s", string1); }
length = strlen(string1); return 0;
}
Program 26
//Program to check the entered string is palindrome or not.
#include <stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
printf("enter a string ");
gets(str1);
strcpy(str2,str1);
strrev(str1);
if((strcmp(str1,str2))==0)
printf("Strings are palindrone\n");
else
printf("Strings are not palindrome\n");
}
Program 27
//Program to convert upper case
to lower case and vice versa. if(str[i]>=65 && str[i]<=90)
{
#include<stdio.h> str[i]=str[i]+32;
#include<string.h> continue;
}
void main() if(str[i]>=97 && str[i]<=122)
{ {
str[i]=str[i]-32;
char str[10]; continue;
int i; }
}
printf("enter the string"); printf("%s",str);
gets(str); }

for(i=0;str[i]!='\0';i++)
{
Program 28
• //Program to input any string and then reverse the string.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20], len=0,i;
printf("enter any string");
gets(str);
len=strlen(str);
for(i=len-1;i>=0;i--)
{
printf("%c",str[i]);

}
Arrays of Strings
• String is array of characters.
• Thus an array of string is 2-D array
of characters.
• E.g.
• char names[5][10];
• Here, names[5][10] means 5 names having 10 characters each.

19
Program 24
//WAP to read name of 5 persons using array of strings and
display them
#include<stdio.h>
int main()
{
char names[5][10];
int i;
printf("\nEnter name of 5 persons:");
for(i=0;i<5;i++)
scanf("%s", names[i]);
printf("\nThe names are:");
for(i=0;i<5;i++)
printf("\n%s", names[i]);
getch();
}

21
Program 25
#include<stdio.h>
void main()
{
char names[5][10],temp[10];
int i, j;
printf("\nEnter name of 5 persons:");
for(i=0;i<5;i++)
gets(names[i]);
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(strcmp(names[i], names[j])>0)
{
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}
}
}
printf("\nNames in ascending order:\n");
for(i=0;i<5;i++)
puts(names[i]); 22
Two-Dimensional Array
Two-Dimensional Array
It is also possible for arrays to have two or more dimensions. The two dimensional array
is also called matrix.
Syntax:
datatype variablename [rowsize] [columnsize];

Example:
int a[4][3];

Means that a -> is a two dimensional array, which contains 4 rows and 3 columns( total
12 elements). Each element is access by their row and column position.

0 1 2 Column offset
a[0][0] value
Address 0
1000
Of a[0][0]
1006 1 a[0][2]
2 1004
Row offset
value 3
?
Two-Dimensional Array

Initialization

Example:
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5,6 };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
Input To 2-D Array

1-D Array: 2-D Array:

int a[20],i; int a[2][3],i,j;


Increment
for(i=0;i<20;i++) for(i=0;i<2;i++) row
{ { index
scanf(“%d”, &a[ i ]); for(j=0;j<3;j++)
Increment
} { column index
scanf(“%d”,&a[i][j]);
}
}

Note:
In this 2-D array example we will get input row by row. That means get
rows
value one by one using inner for loop. Increment row using outer loop.
Representation of Two-Dimensional Arrays in Memory

• Specifically, the programming languages will store the array A in


either,
– Column by column, called column-major order, or
– Row by row, called row-major order.
a[0][0]=1000
Find out address of a[0][3]=?
Representation of Two-Dimensional Arrays in Memory
Address of an element in 2D
Address of an element of any array say “A[ I ][ J ]” is calculated in
two forms as given:
Row Major System:
• The address of a location in Row Major System is calculated
using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
• Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given
assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not
given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
Address of an element in 2D
Column Major System:
• The address of a location in Column Major System is calculated
using the following formula:
Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )]
• Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given
assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not
given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
Problem 1

93
Solution

94
Important
• Usually number of rows and columns of a matrix are given (like
A[20][30] or A[40][60] ) but if it is given as
• A[Lr- – – – – Ur, Lc- – – – – Uc].
• In this case number of rows and columns are calculated using the
following methods:
• Number of rows (M) will be calculated as = (Ur – Lr) + 1
Number of columns (N) will be calculated as = (Uc – Lc) + 1
• And rest of the process will remain same as per requirement (Row
Major Wise or Column Major Wise).
Problem 2
• An array X [-15……….10, 15……………40] requires one
byte of storage. If beginning location is 1500 determine the
location of X [15][20].
Solution
Number or rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1 = 26
Number or columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26
(i) Column Major Wise Calculation of above equation
The given values are:
• B = 1500,
• W = 1 byte,
• I = 15,
• J = 20,
• Lr = -15,
• Lc = 15,
• M = 26
• Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)] = 1500 + 1 * [30 + 26 * 5] =
1500 + 1 * [160] = 1660 [Ans]
Solution
ii) Row Major Wise Calculation of above equation
The given values are:
• B = 1500,
• W = 1 byte,
• I = 15,
• J = 20,
• Lr = -15,
• Lc = 15,
• N = 26
• Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
• = 1500 + 1* [26 * (15 – (-15))) + (20 – 15)] = 1500 + 1 * [26 * 30 + 5] = 1500
+ 1 * [780 + 5] = 1500 + 785
= 2285 [Ans]
Problem 3

99
Program 26
//Program to input and display a matrix.
#include<stdio.h>
int main( )
{
int mat[2][3],i,j;

printf("Enter the elements of matrix");


for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&mat[i][j]);
printf ("The matrix that you have entered is ; \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%5d",mat[i][j]);
}
printf("\n") ;
}
Program 27
//Program to find the sum of all matrix elements.
#include<stdio.h>
int main( )
{
int mat[2][3],i,j, s=0;
for(i=0;i<2;i++)
for(j=0;j<3;j++)
{
printf("Enter the elements of matrix [%d][%d]",i,j);
scanf("%d",&mat[i][j]);
s=s+mat[i][j];
}
printf ("The matrix that you have entered is ; \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%5d",mat[i][j]);
}
printf("\n") ;
}
printf ("The sum of matrix element is %d",s);
}
Program 28
//Program to add the diagonal of square matrix.
#include<stdio.h>
int main( )
{
int mat[3][3],i,j, s1=0,s2=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
printf("Enter the elements of matrix [%d][%d]",i,j);
scanf("%d",&mat[i][j]);
if(i==j)
s1=s1+mat[i][j];
if((i+j)==2)
s2=s2+mat[i][j];
}
printf ("The matrix that you have entered is ; \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%5d",mat[i][j]);
}
printf("\n") ;
}
printf ("The sum of matrix element is %d and %d",s1,s2);
}
Program 29
//Program to add the upper and lower triangle of square matrix.
#include<stdio.h>
int main( )
{
int mat[3][3],i,j, s1=0,s2=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
printf("Enter the elements of matrix [%d][%d]",i,j);
scanf("%d",&mat[i][j]);
if(i>j)
s1=s1+mat[i][j];
if(i<j)
s2=s2+mat[i][j];
}
printf ("The matrix that you have entered is ; \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%5d",mat[i][j]);
}
printf("\n") ;
}
printf ("The sum of matrix element is %d and %d",s1,s2);
}
Program 28
//Program for addition of two matrices.
for(i=0;i<2;i++)
#include<stdio.h> for(j=0;j<2;j++)
int main() mat3[i][j]=mat1[i][j]+mat2[i][j];
{ printf ("The resultant matrix mat3 is :\n");
int i,j,mat1[2][2],mat2[2][2],mat3[2][2]; for(i=0;i<2;i++)
printf("Enter matrix matl”); {
for(j=0;j<2;j++)
for(i=0;i<2;i++)
printf ("%5d" ,mat3[i][j]);
for(j=0;j<2;j++) printf("\n");
scanf("%d",&mat1[i][j]); }
printf ("Enter matrix mat2”); }
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf ("%d",&mat2[i][j]);
Matrix Multiplication

• In order to multiply two matrices, A and B, the


number of columns in A must equal to the number of
rows in B. Thus, if
• Matrix A =m X n and
• Matrix B = r X s then n=r.

• Result of matrix includes =m X s


Example

We have (2×4) × (4×3) and since the number of columns


in A is the same as the number of rows in B , we can go ahead
and multiply these matrices.

Our result will be a (2×3) matrix.


Steps
Program 29
//Program to read a 2d array and find sum of elements for each row and each column.
for (i = 0; i < m; ++i)
#include <stdio.h>
{
void main () for (j = 0; j < n; ++j)
{ {
int array[10][10]; sum = sum + array[i][j] ;
}
int i, j, m, n, sum = 0; printf("Sum of the %d row is = %d\n", i, sum);
printf("Enter the order of the matrix\n"); sum = 0;
scanf("%d %d", &m, &n); }
sum = 0;
printf("Enter the elements of the matrix\n"); for (j = 0; j < n; ++j)
for (i = 0; i < m; i++) {
{ for (i = 0; i < m; ++i)
{
for (j = 0; j < n; j++) sum = sum + array[i][j];
{ }
scanf("%d", &array[i][j]); printf("Sum of the %d column is = %d\n", j, sum);
sum = 0;
}
}
} }
Program 30
//Program to find the transpose of matrix.
#include<stdio.h>
#define ROW 3
#define COL 4
int main ( )
{
int mat1[ROW][COL] ,mat2[COL][ROW], i, j;
printf ("Enter matrix. matl (%dx%d) row-wise \n" ,ROW, COL) ;
for(i=0;i<ROW;i++)
for(j=0;j<COL;j++)
scanf("%d",&mat1[i][j]);
for(i=0;i<COL;i++)
for(j=0;j<ROW;j++)
mat2[i][j]=mat1[j][i];
printf ("Tranpose of matrix is; \n") ;
for(i=0;i<COL;i++)
{
for(j=0;j<ROW;j++)
printf ("%5d" ,mat2[i][j]) ;
printf ("\n");}}
//Program for multiplication of two matrices.
Program 31
#include<stdio.h> for(i=0;i<ROW1;i++)
#define ROW1 3 for(j=0;j<COL2;j++)
#define COLl 4 {
#define ROW2 4 mat3[i][j]=0;
#define COL2 2 for(k=0;k<COLl;k++)
int main() mat3[i][j]+=matl[i][k]*mat2[k][j];
{ }
int matl[ROW1][COLl],
printf ("The Resultant matrix mat3 is : \n") ;
for(i=0;i<ROW1;i++)
mat2[ROW2][COL2],
{
mat3[ROW1][COL2];
for(j=0;j<COL2;j++)
int i,j,k; printf ("%5d",mat3[i][j]);
printf("Enter matrix matl(%dx%d) row-wise : \ printf("\n");
n", ROW1, COLl) ; }
for(i=0;i<ROW1;i++) }
for(j=0;j<COLl;j++)
scanf("%d",&matl[i][j]) ;
printf("Enter matrix mat2 (%dx%d) row-wise :
\n" ,ROW2, COL2);
for(i=0;i<ROW2;i++)
for(j=0;j<COL2;j++)
scanf("%d",&mat2[i][j]) ;
Program 32
Program to find greatest value from the matrix
#include<stdio.h>
int main()
{
int i,j,a[2][2],g=0;
printf("Enter matrix matl");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
if(a[i][j]>g)
g=a[i][j];
}
printf("greatest value in the matrix=%d",g);
}
Write a Program( assignment)
To Find roots of quadratic equations
Notion of order of complexity through example
programs
Time Complexity
• Time Complexity of algorithm/code is not equal to the actual
time required to execute a particular code but the number of
times a statement executes.

• Now, the question arises if time complexity is not the actual


time require executing the code then what is it?

• The answer is : Instead of measuring actual time required in


executing each statement in the code, we consider how many
times each statement execute.
Example 1
#include <stdio.h>
int main()
{
printf("Hello World");
}
Output: Hello World
• In above code “Hello World!!!” print only once on a screen.
So, time complexity is constant: O(1) i.e. every time constant
amount of time require to execute code, no matter which
operating system or which machine configurations you are
using.
Example 2
#include <stdio.h>
void main()
{
int i, n = 4;
for (i = 1; i <= n; i++) {
printf("Hello Word !!!\n");
}
}
• Output:
• Hello Word !!!
• Hello Word !!!
• Hello Word !!!
• Hello Word !!!
• In above code “Hello World!!!” will print N times. So, time complexity of
above code is O(N).
Continued….
• Each operation in an algorithm (or a program) has a cost.
 Each operation takes a certain amount of time.

count = count + 1;  take a certain amount of time, but it is


constant

A sequence of operations:

count = count + 1; Cost: c1


sum = sum + count; Cost: c2

 Total Cost = c1 + c2
117
Continued….
Example: Simple If-Statement
Cost Times
if (n < 0) c1 1
absval = -n c2 1
else
absval = n; c3 1

Total Cost <= c1 + max(c2,c3)

118
Continued….
Example: Simple Loop
Cost Times
i = 1; c1 1
sum = 0; c2 1
while (i <=n) { c3 n+1
i = i + 1; c4 n

sum = sum + i; c5 n
}

Total Cost = c1 + c2 + (n+1)*c3 + n*c4 + n*c5


 The time required for this algorithm is proportional to n

119
Continued….
Example: Nested Loop
Cost Times
i=1; c1 1
sum = 0; c2 1
while (i <= n) { c3 n+1
j=1; c4 n
while (j <= n) { c5 n*(n+1)
sum = sum + i; c6 n*n
j = j + 1; c7 n*n
}
i = i +1; c8 n
}
Total Cost = c1 + c2 + (n+1)*c3 + n*c4 + n*(n+1)*c5+n*n*c6+n*n*c7+n*c8
 The time required for this algorithm is proportional to n 2

120
Time Complexity

You might also like