0% found this document useful (0 votes)
29 views29 pages

Unit 2 PC Notes

Uploaded by

mathibm92
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)
29 views29 pages

Unit 2 PC Notes

Uploaded by

mathibm92
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/ 29

UNIT II ARRAYS AND STRINGS

Introduction to Arrays: Declaration, Initialization – One dimensional array – Two


dimensional arrays - String operations: length, compare, concatenate, copy – Selection sort, linear
and binary search

2.1 INTRODUCTION TO ARRAYS


Definition : An array is a collection of similar data items that are stored under acommon name . In
array, each element is located in separate memory locations.
DECLARATION: The array variable has to be declared before they are used.
SYNTAX :
data_type array_name[size];

Where, data_type: e.g int, char, float. . .array_name it is a valid variable name
size is the Number of elements the array
Example : int r[7];

int r[7];
r[0] r[1 r[2] r[3] r[4] r[5] r[6]
ARRAY INITIALIZATION

The values can be initialized to an array when they are declared like ordinaryvariables, otherwise
they holdgarbage values.
SYNTAX: data_type array_name[size]={list of values};

Example: int i[7]={2,4,1,17,49,5,11}; (OR) int i[]={2,4,1,17,49,5,11};

NAME i[0] i[1] i[2] i[3] i[4] i[5] i[6]


ELEMENT 2 4 1 17 49 5 11
ADDRESS 2000 2002 2004 2006 2008 2010 2012

CHARACTERISTICS (Properties) OF ARRAY


 All the elements of an array share the same name, and they are distinguishedfrom one
another with the help of subscript value or index value.
 String array always terminates with null character ('\0').
 In array the elements are stored in continuous memory locations.
 Array index in C starts with 0 i.e., Index of the first element of an array
 Array elements are stored in continuous memory locations. For example, 1st element of i is
stored at memory location 2000, then the successive elements in 2002,2004, etc
 The type of the array is the data type of its elements
 The length of the array is the no. of data elements in the array
 The amount of storage required for holding elements of the array depends on its type and
size.
The total size in bytes for a single dimensional array is computed as

Total bytes = sizeof(data_type) × number of elements


Example: int a2[8];
Total bytes occupied by array a2 is 2×8=16 (i.e. Total bytes =sizeof (int)×8 )

Types of array :
1. One Dimensional array
2. Two Dimensional array
3. Multi Dimensional array

Programming in C 1
2.2 ONE DIMENSIONAL ARRAY

An array with a single subscript is called One Dimensional array. A One-Dimensional Array is
also known as 1D Array
It occupies continuous memory location.
DECLARATION AND INITIALIZATION OF 1D ARRAY
Declaration of 1 D Array :
Syntax: datatype variable_name[size];
Eg : int a[5];

a[0] a[1] a[2] a[3] a[4]


A one dimensional array can be initialized in several ways. Let’s see the differentways of
initializing a 1D array.
Ex1: int a[3]={12,18,6};
Ex2: int a[]={7,12,9};
Ex3: int a[3]={5}; //stores 5,0,0
Ex4: int a[3]={}; //stores 0,0,0
Ex5: array_name[index]=value;
a[0]=26;
a[1]=15;
a[2]=34;
Access Numbers in a 1D Array
We can access any number stored in a 1D array using the following syntax.
Syntax: array_name[index];
Ex2 : printf("%d %d %d",a[0],a[1],a[2]);

Store and Access the Numbers in a 1D Array using Loops


#include<stdio.h>
#include<conio.h>
int main()
{
int a[5], i;
printf("Enter 5 numbers\n");
for(i=0; i<5; i++)
{
scanf("%d",&a[i]);
}
printf("List of even numbers\n");
for(i=0; i<5; i++)
{
if(a[i]%2==0)
{
printf("%d ",a[i]);
}
}
return 0;
}
Enter 10 numbers
10
15
28
Programming in C 2
31
49
List of even numbers10
28

2.3 TWO – DIMENSIONAL ARRAY


Arrays with two subscripts are called Two dimensional array
A 2D array is also known as a matrix or a table of rows and columns.
Two dimensional arrays are used in situation where a table of values need to bestores in an
array.
The elements of a Two-dimensional array can be accessed by using a row subscript(number)
andcolumn subscript (number).
Declaring 2D array
SYNTAX: data_type array_name[row_size][column_size];

Eg: int i[3][4]; //3 Rows and 4 columns

Initialising a 2D array
To create a 2D array of integers, take a look at the following example: int
matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

The first dimension represents the number of rows [2], while the second dimensionrepresents the
number of columns [3]. The values are placed in row-order, and canbe visualized like this:
Column 1 Column 1 Column 1
Row 1 1 4 2
Row 2 3 6 8

The pictorial representation of x[3][4] is

Access the Elements of a 2D Array

To access an element of a two-dimensional array, you must specify the indexnumber of


both the row and column.
This statement accesses the value of the element in the first row (0) and thirdcolumn (2) of
the matrix array.

Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2

Change Elements in a 2D Array

To change the value of an element, refer to the index number of the element in each ofthe dimensions:
The following example will change the value of the element in the first row (0) and firstcolumn (0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
printf("%d", matrix[0][0]); // Now outputs 9 instead of 1

Programming in C 3
Reading, Storing and accessing elements of a 2-D array(Loop
through a 2D Array)
The elements of a 2D array can be read and stored using nested loops. To loop through a multi-
dimensional array, you need one loop for each of the array's dimensions. The following example gets
and prints all elements in the matrix or 2 D array

Example
// 2 D array Output :
#include <stdio.h>
void main() 1234
{ 1 2
int x[2][2],i,j; 3 4
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&x[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t",x[i][j]);
}
printf(“\n”);
}
}
MULTI – DIMENSIONAL ARRAY
If the dimension are three or more , they are called as multidimensional array. ieArrays with
more than 3 or more subscripts are caller Multi dimensional arrays
Multidimensional arrays are slower than the single dimensional array

ARRAY DECLARATION:
data_type array_variable[size_1][size_2] .............. [size_n];
SYNTAX:
E.g: float b[4][4][4][4];

INITIALISING A MULTI-DIMENSIONAL ARRAY:


A multi dimensional array can be initialized as

SYNTAX: data_type array_variable[size_1][size_2] ............... [size_n]={list of values};

Eg: int m[3][3][3] = {11,12,13},{14,15,16},{17,18,19}},


{{21,22,23}, {24,25,26},{27,28,29}},
{{31,32,33},{34,35,36},{37,38,39}}};

Eg: Program for Multidimensional array


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k;
Programming in C 4
int a[3][3][3]={{{1,2,3},{4,5,6},{7,8,9}},
{{1,4,7},{2,5,8},{3,6,9}},
{{1,4,4},{2,4,7},{6,6,3}}};

clrscr();
printf("Elements of
an array \n");for 1 2 3
(i=0;i<3;i++) 4 5 6
{ 7 8 9
for (j=0;j<3;j++)
{ 1 4 7
for(k=0;k<3;k++) 2 5 8
{ 3 6 9
printf("%d\t",a[i][j][k]);
} 1 4 4
printf("\n"); 2 4 7
} 6 6 3
printf("\n");
}
getch();
}
Advantages of an Array
Allow random access of elements
Capable of storing many elements at a time
The direct indexing supported by array is their biggest advantage. Direct indexing
the time required to access any element in an array
Limitations of arrays:
The memory to an array is allocated at the compile time
Arrays are static in nature. The size of an array can’t be expanded or can’tbe changed at the
runtime.
The size of an array has to be kept big enough to accommodate the worstcases.
Therefore, memory usage in case of arrays is inefficient

2.4 STRING
String is a sequence characters enclosed within double quotes.
The string is always declared as character arrays, In other words, characterarrays are
called as strings.
NULL (‘\0’ ) character is used at the end of the string.

Ex : 1. “God Bless!!”
2. “A”
3. “ ”
char edu[ ]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’\0’};

MEMORY ALLOCATION OF THE ABOVE STRING


C O L L E G E \0
2001 2002 2003 2004 2005 2006 2007 2008
DECLARATION AND INTIALIZATION OF STRING
Declaration :
Syntax : char string_name[10];Eg :
char name[10]
The string can be initialized as follows
char name[] =”INDIA”;

Programming in C 5
DISPLAY OF STRING WITH DIFFERENT FORMATS
The printf() function with %s format specifier is used to display the string on thescreen.
Variousformats is shown below
Example ; char a[15]="STRINGHANDLING";

Example: Program to display string in different formats.


#include <stdio.h>
void main()
{
char a[15]="STRINGHANDLING"; OUTPUT
printf("\n %s",a); STRINGHANDLING
printf("\n %.5s",a); STRIN
printf("\n %.8s",a); STRINGHA
printf("\n %-10.4s",a); STRI
}

STRING ARRAY
A string is a collection of characters. A string constant is a one dimensionalarray
ofcharacters terminated by a null („\0‟) character.
Example: char name[] = {‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’,’\0’};
Terminating the string with null „\0‟ is important, because it is the only waythe
functions that work with a string can know where the string ends.
The last character is called ‘\0’ null character, it occupies one byte memoryand the last
character is always
Example: char name[]=”COMPUTER”;

C O M P U T E R \0

Example: Program to read and print the character string from the array

#include<stdio.h>
void main()
{
char str[20]; 17
printf(“Enter string:\n”);
scanf(“%s”,str);
printf(“String is:%s”,str);
}

Example: Program to read a line of text


#include<stdio.h>
main()
{
char line[100];
clrscr();
printf(“Enter the text:\n”);
scanf(“%s”,line);
printf(“Entered line is:%s”,line);
getch();
}

2.5 STRING OPERATIONS / STRING HANDLING FUNCTIONS


The header file #include<string.h> is to be initialized whenever standard library function is used.

Programming in C 6
The commonly used C string library functions are given in following table
S.NO FUNCTION SYNTAX PURPOSE
1. strlen() var = strlen(string); To calculate length of the
string.
2. strcpy() strcpy(string1,string2); To copy string2 in to string1.
3 strncpy() strncpy(str1,str2); To copy n characters of a str2into
str1
4 strcat() strcat(string1,string2); To combine two strings
5 strncat() strncat(string1,string2); To concatenate a portion of
one string with Another
6 strcmp() strcmp(string1,string2); To compare character of two
string
7 strncmp() strncmp(str1,str2,n); To compare a position of two
strings
8. strcmpi() strcmpi(string1,string2); To compare character of two
string without case sensitivity.

a. String length – strlen()


strlen() function is used to find the number of characters in a string. Syntax :
strlen(string)
Example : x=strlen(str) , where str is a string variable
b. String compare - strcmp()
strcmp() function is used to compare two strings and returns 0 if they are equal.Syntax :
strcmp(string1,string2)
Example : x=strcmp(str1,str2) , where str1,str2 are string variables
c. String concatenate - strcat()
strcat() function is used to join two strings together.Syntax :
strcat(string1,string2)
Example : strcat(str1,str2) , where str1,str2 are string variables. The joined stringis stored in
str1.
d. String Copy – strcpy()
strcpy() function is used to copy one string to another string.Syntax :
strcpy(string1,string2)
Example : strcpy(str1,str2) , where str1,str2 are string variables. The content ofstr2 is copied to
str1.

Programs for the string operations


// string operations strlen , strcpy, strcat, strcmp
#include<stdio.h>
#include<string.h>
void main()
{
int n=3;
char name[ 50] = "C Program";
char str1[20];
char str2[20] = "Computer";
char rev[20];
int length;
length = strlen(name);
strcpy(str1,str2);
strcat(name,str2);
printf("Length of the name is: %d",length);

Programming in C 7
printf("\nCopy of the string is: %s",str1);
printf("\nStrcat [concatenated] is %s",name);
if(strcmp(str1,str2)==0)
{
printf("\nstring 1 and string 2 are equal");
}
else
{
printf("\nstring 1 and string 2 are not equal");
}}
Output:
Length of the name is: 9
Copy of the string is: Computer
Strcat [concatenated] is C ProgramComputerstring 1
and string 2 are equal

2.6 SELECTION SORT IN C


Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest
element from the unsorted portion of the list and moving it to the sorted portion of the list.
Let us consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass: For the first position in the sorted array, the whole array is traversed from index 0 to
4 sequentially. The first position where 64 is stored presently, aftertraversing whole array it is
clear that 11 is the lowest value.
64 25 12 22 11
Thus, replace 64 with 11. After one iteration 11, which happens to be the least value in the
array, tends to appear in the first position of the sorted list.
11 25 12 22 64
Second Pass: For the second position, where 25 is present, again traverse the rest of the array in
a sequential manner.
11 25 12 22 64
After traversing, we found that 12 is the second lowest value in the array and it should
appear at the second place in the array, thus swap these values.
11 12 25 22 64
Third Pass: Now, for third place, where 25 is present again traverse the rest ofthe array and
find the third least value present in the array.
11 12 25 22 64
While traversing, 22 came out to be the third least value and it should appear atthe third place
in the array, thus swap 22 with element present at third position.
11 12 22 25 64
Fourth pass: Similarly, for fourth position traverse the rest of the array and find the fourth
least element in the array
As 25 is the 4th lowest value hence, it will place at the fourth position.
11 12 22 25 64
Fifth Pass: At last the largest value present in the array automatically get placedat the last
position in the array
The resulted array is the sorted array.
11 12 22 25 64
Follow the below steps to solve the problem:
Initialize minimum value to location 0.
Traverse the array to find the minimum element in the array.
While traversing if any element smaller than minimum is found then swap bothvalues.
Then, increment minimum to point to the next element.
Repeat until the array is sorted.
Programming in C 8
Program for selection sort
#include <stdio.h>
#include <conio.h>
int main()
{
int a[100], n, i, j, min_index, temp;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d Numbers \n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++) Output :
{ Enter number of elements
min_index =i; 5
Enter 5 Numbers
for(j = i + 1; j < n; j++)
64 25 12 22 11
{ Sorted Array:
if(a[min_index] > a[j]) 11 12 22 25 64
min_index =j;
}
if (min_index!=i)
{
temp=a[i];
a[i]=a[min_index];
a[min_index] =temp;
}
}
printf("Sorted Array: \n");
for(i = 0; i < n; i++)
printf("%d\t", a[i]);
getch();
return 0;
}
2.7 SEARCHING
Searching is the process of finding the location of the specified element in the list. The specified
element is often called the search key. The two most commonly used searching techniques are
1. Sequential or Linear search
2. Binary search
1 Sequential or Linear search
It is the simplest searching technique.
Linear Search is defined as a sequential search algorithm that starts at one end and goes through
each element of a list until the desired element is found, otherwise the search continues till the
end of the data set.
Consider searching for a given value v in an array of size N.
Sequential search involves looking at each value in turn (i.e., start with the value inarray[0], then
array[1], etc.)
If the current value is v, the algorithm quits and returns its index value;
The linear search do not require the elements to be in sorted order.
Program
#include <stdio.h>
void main()
{
int array[100], search, i, n;
printf("Enter number of elements in array\n");
Programming in C 9
scanf("%d", &n);
printf("Enter %d integers one be one", n);
for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
printf("Enter a number to search\n");
scanf("%d", &search);
for (i = 0; i < n; i++)
{
if (array[i] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array.\n", search);
}
Output
Enter number of elements in array 5
Enter 5 integers one be one
4 8 9 12 16
Enter a number to search 12
12 is present at location 4

Advantages of Linear Search


Linear search is simple to implement and easy to understand.
Linear search can be used irrespective of whether the array is sorted or not.
It can be used on arrays of any data type.
Does not require any additional memory.
It is a well suited algorithm for small datasets.

2 Binary Search
Binary Search is defined as a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity.
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.
0 1 2 3 4 5 6 7 8 9
First Step:
o Initially the search space is from 0 to 9.
o Let’s denote the boundary by L and H where L = 0 and H = 9 initially.
o Now mid of this search space is M = 4.
o So compare target with arr[M].
Second Step:
o As arr[4] is less than target, switch the search space to the right of 16, i.e.,[5, 9].
o Now L = 5, H = 9 and M becomes 7.
o Compare target with arr[M].
Third Step:
o arr[7] is greater than target.
o Shift the search space to the left of M, i.e., [5, 6].
o So, now L = 5, H = 6 and M = 6.
o Compare arr[M] with target.
o Here arr[M] and target are the same.
Programming in C 10
So, we have found the target.

Program
// binary search
#include<stdio.h>
int main()
{
int c, start, stop, mid, n, search, a[100];
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter %d integers:\n", n); Output :
for (c = 0; c < n; c++) Enter number of elements:
scanf("%d",&a[c]); 5
Enter 5 integers:
printf("Enter the value to find:\n");
4 6 8 10 12
scanf("%d", &search); Enter the value to find:
start = 0; 10
stop = n - 1; element found at 4
while(start<=stop)
{
mid=(start+stop)/2;
if(search==a[mid])
{ printf("element found at %d",mid+1);
break;}
else
if(search<a[mid])
stop=mid-1;
else
start=mid+1;
}

Programming in C 11
if (start > stop)
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
Comparison between Linear Search and Binary Search

S.No. Linear Search Binary Search

1 In linear search input data need not In binary search input data need to be in
to be in sorted. sorted order.
2 It is also called sequential search. It is also called half-interval search.

3 The time complexity of linear The time complexity of binary


search O(n). search O(log n).
4 Multidimensional array can be used. Only single dimensional array is used.
5 It is less complex. It is more complex.
6 It is very slow process. It is very fast process.

EXAMPLE PROGRAMS for 1 D array

1 COMPUTING MEAN
The mean (average) of a data set is found by adding all numbers in the data set and thendividing by the
number of values in the set.

#include<stdio.h>
#include<conio.h>
void main() OUTPUT
{
int a[100],n,i;
float sum=0,mean;
clrscr();
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the elements one by one");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0; i<n; i++)
sum=sum+a[i];
mean=sum/n;
printf("the mean of given array number is %f",mean);getch();
}

2. COMPUTING MEDIAN
The median is the middle value when a data set is ordered from least to greatest.
#include<stdio.h>
void main( )
{
int i,j,n,a[10],t;
float median;
clrscr();
printf("Enter the number of items\n");
scanf("%d", &n); /* Reading items into array a */

Programming in C 12
printf("Input %d values \n",n);
for (i = 0; i < n ; i++)
scanf("%d", &a[i]);
/* Sorting begins */
for (i = 0 ; i < n ; i++)
{
for (j = i+1 ; j <n ; j++)
{
if (a[i] > a[j])
{
t = a[j];
a[j] = a[i];
a[i] = t;
}
}
}
for (i = 0 ; i <n ; i++)
printf("%d ", a[i]);
/* calculation of median */
if ( n % 2 == 0)
median = (a[n/2] + a[(n-1)/2])/2.0 ;
else
median = a[(n-1)/2];
/* Printing */
printf("\n\nMedian is %f\n", median);
getch();
}
OUTPUT

3. COMPUTING MODE
The mode is the number that occurs most often in a data set.
#include<stdio.h>
void main()
{
int maxValue = 0, maxCount = 0, i, j,n=5,a[10];
clrscr();
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for (i = 0; i < n; ++i)
{
int count = 0;
for (j = 0; j < n; ++j)
{
if (a[j] == a[i])

Programming in C 13
++count;
}
if (count > maxCount)
{
maxCount = count;
maxValue = a[i];
}
}
printf("Mode = %d ", maxValue);
getch();
}

OUTPUT

EXAMPLE PROGRAMS for 2 D array

Matrix Operations (Addition, Scaling, Determinant and Transpose)

1. MATRIX ADDITION
#include <stdio.h>int
main()
{
int rowCount, columnCount, i, j;
int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10];
printf("Number of rows of matrices to be added : ");
scanf("%d", &rowCount);
printf("Number of columns matrices to be added : ");
scanf("%d", &columnCount);
printf("Elements of first matrix : \n");
for (i = 0; i < rowCount; i++)
for (j = 0; j < columnCount; j++)
scanf("%d", &firstMatrix[i][j]);
printf("Elements of second matrix : \n");
for (i = 0; i < rowCount; i++)
for (j = 0; j < columnCount; j++)
scanf("%d", &secondMatrix[i][j]);
printf("Sum of entered matrices : \n");
for (i = 0; i < rowCount; i++)
{
for (j = 0; j < columnCount; j++)
{
resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j];

Programming in C 14
printf("%d\t",resultMatrix[i][j]);
}
printf("\n");
}
return 0;}

OUTPUT
Number of rows of matrices to be added : 2
Number of columns matrices to be added : 2
Elements of first matrix :
5
5
5
5
Elements of second matrix :11
1
1
Sum of entered matrices :6 6
6 6

2. MATRIX DETERMINANT
#include<stdio.h>int
main()
{
int a[3][3], i, j;
long determinant;
printf("Enter the 9 elements of matrix: ");
for(i = 0 ;i < 3;i++)
for(j = 0;j < 3;j++)
scanf("%d", &a[i][j]);

printf("\nThe matrix is\n");


for(i = 0;i < 3; i++){
printf("\n");
for(j = 0;j < 3; j++)
printf("%d\t", a[i][j]);
}
determinant = a[0][0] * ((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1] * (a[1][0]
* a[2][2] - a[2][0] * a[1][2]) + a[0][2] * (a[1][0] * a[2][1] - a[2][0] * a[1][1]);

printf("\nDeterminant of 3X3 matrix: %ld", determinant);


return 0;
}
Output:
Enter the elements of matrix:1 2 3 4
51234

The Matrix is1 2


3
4 5 1
2 3 4
Determinant of matrix is -5

Programming in C 15
3. MATRIX TRANSPOSE
#include <stdio.h>
void main() OUTPUT:
{
static int array[10][10];
int i, j, m, n;
printf("Enter the order of the matrix \n");
scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
}

3 MATRIX SCALING
#include <stdio.h>
void main()
{
int a[3][3],num,i,j;
printf(“ENTER A 3*3 Matrix\n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("Enter any number to multiply with matrix A: ");
scanf("%d", &num);
for(i=0; i<3; i++)
{ output :
for(j=0; j<3; j++)
16
{
a[i][j] = num * a[i][j];
}
}
printf("\nResultant matrix c.A = \n");
for(i=0; i<3; i++)
{
for(j=0; j<3;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
}

PROGRAMS FOR UNIVERSITY EXAMINATION


Programs on One dimensional array or list
1. Sum of array elements
2. Program to print an array in a reverse order
3. Remove the redundant element in an array
4. Delete a particular element in an array
5. Find the maximum and minimum element in a set of n elements
6. Program to find max, min, second largest, second smallest element in an array
7. Linear search
8. Binary search
9. Program for sorting in ascending and descending order
Programs on two dimension array or matrix
1. Matrix addition
2. Matrix subtraction
3. Matrix multiplication
4. Transpose of a matrix
5. Sum of diagonal element in an array
6. Sorting names in alphabetical order
Programs on strings
1. All string library functions program
2. Find the number of vowel(s) present in the string
3. To check the given string is palindrome or not
4. Count the number of sentences, words and characters in a given paragraph
5. To do string functions without using library functions

1 Sum of array elements


#include<stdio.h>
#include<conio.h>
void main( )
{
int a[100],i,sum=0, n;
printf("Enter size of an array: ");
scanf("%d",&n);
printf("Enter array elements:\n”);
for(i=0;i<n; i++)
scanf("%d",&a[i]);
for(i=0; i<n; i++)
{
sum=sum+a[i];
17
}
printf(“\nThe sum of array elementsis %d”,sum);
getch();
}
Sample Output:
Enter size of an array 5
Enter array elements
28190
The sum of array elements is 20

2. Program to print an array in a reverse order


#include<stdio.h>
#include<conio.h>
void main( )
{
int a[100],i, n ;
printf("Enter size of an array: ");
scanf("%d",&n);
printf("Enter array elements:\n”);
for(i=0; i<n; i++)
scanf("%d",&a[i]);
printf(“The array in a reverse order”);
for(i=n-1;i>=0;i--)
{
printf(“%d\t”,a[i]);
}
getch();
}
Sample Output:
Enter size of an array 5
Enter array elements
28190
The array in a reverse order
0 9 1 8 2

3. Program to remove redundant element in an array


#include<stdio.h>
#include<conio.h>
void main()
{
int n,a[10],i,j,k;
clrscr();
printf("\n Enter array size:");
scanf("%d",&n);
printf("\n Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(j=0;j<n;j++)
{
for(i=0;i<n;i++)
{
if(a[i]==a[i+1])
{
for(k=i+1;k<n;k++)
18
a[k]=a[k+1];
n--;
}
}
}
printf("\n Resultant Array:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}

Sample Output:
Enter array size: 5
Enter array elements: 6 2 2 7 9
Resultant Array:
6279

4. Delete a particular element in an array


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],n,i,pos;
clrscr();
printf("\n Enter array size:");
scanf("%d",&n);
printf("\n Enter array Elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter position to delete element from array:");
scanf("%d",&pos);
if(pos>=n+1)
printf("\n Deletion not possible");
else
{
for(i=pos-1;i<n-1;i++)
a[i]=a[i+1];
printf("\n Resultant Array:");
for(i=0;i<n-1;i++)
printf("%d",a[i]);
}
getch();
}
Sample Output:
Enter array size: 5
Enter array elements: 6 2 0 7 9
Enter position to delete element from array:1
Resultant Array: 6 0 7 9
6.Program to find maximum, minimum, second largest and second smallest element in an array
#include<stdio.h>
#include<conio.h>
void main( )
19
{
int a[100],i, j, temp, n ; Sample output:
clrscr(); Enter size of an array: 5
printf("Enter size of an array: ");
scanf("%d",&n); Enter array elements: 6 2 0 7 9
printf("\nEnter array elements:”); The greatest element is 9
for(i=0; i<n; i++) The smallest element 0
scanf("%d",&a[i]); The second largest element is 7
for(i=0;i<n-1;i++) The second smallest element is 2
{
for(j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}}}
printf ( "\nThe greatest element is %d", a[n-1]) ;
printf ( "\nThe smallest element is %d", a[0]) ;
printf ( "\nThe second largest element is %d", a[n-2]) ;
printf ( "\nThe second smallest element is %d", a[1]) ;
getch();
}
Sample output:
Enter size of an array: 5
Enter array elements: 6 2 0 7 9
The greatest element is 9
The smallest element 0
The second largest element is 7
The second smallest element is 2
7. Program for sorting in ascending and descending order
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[100],i, j, temp, n ;
clrscr();
printf("Enter size of an array:\t ");
scanf("%d",&n);
printf("\nEnter array elements”);
for(i=0; i<n; i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
for(j=i+1; j<n; j++)
{
if(a[i]>a[j])
{
temp=a[i];a[i]=a[j];
a[j]=temp;
}
}
}
20
printf ( "\nArray after sorting in ascending order:\t ");
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
printf ( "\nArray after sorting in descending order:\t ") ;
for ( i = n-1 ; i>=0 ; i-- )
printf ( "%d\t", a[i] ) ;
}
Sample Output:
Enter size of an array: 5
Enter array elements: 6 2 1 7 9
Array after sorting in ascending order1 2 6 7 9
Array after sorting in descending order9 7 6 2 1

Programs on two dimensions array or matrix


1. Matrix subtraction
#include<stdio.h>
#include<conio.h>
void main()
{
int m1[10][10],m2[10][10],sub[10][10]={0};
int i,j,r,c;
clrscr();
printf("Enter the row and column of two matrix:\n");
scanf("%d%d",&r,&c);
printf("Enter first matrix:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&m1[i][j]); Sample Output:
} Enter the row and column of two matrix:
} 22
printf("Enter second matrix:\n");
Enter first matrix:
for(i=0;i<r;i++)
{ 1234
for(j=0;j<c;j++) Enter second matrix:
{ 5678
scanf("%d",&m2[i][j]); The subtraction of two matrix:
} -4 -4
}
-4 -4
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sub[i][j]= m1[i][j]-m2[i][j];
}
}
printf("\nThe subtraction of two matrix:\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("\t%d",sub[i][j]);
}
21
printf("\n");
}
2.Sum of Diagonal Element
#include<stdio.h>
#include<conio.h>
void main()
{
int mat[10][10],i,j,r,c,sum=0;
clrscr();
printf("Enter the row and column value:\n");
scanf("%d%d",&r,&c);
printf("Enter the elements of the matrix:\n");
for(i=0;i<r;i++){
for(j=0;j<c;j++){
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++) sample output:
{ Enter row and column value:
if(i==j) 2
{ 2
sum=sum+mat[i][j]; Enter the elements of the matrix:
} 12
}
} 34
printf("Sum of diagonal element : %d”, sum);getch(); Sum of diagonal element: 5
}

Programs on String operations


1. Program to sort names
#include<stdio.h>
#include<string.h>
void main()
{
char a[20][20], temp[20];
Sample Output:
int i, j,n;clrscr();
printf(“Enter no of names to sort\n”); Enter no of names to sort
scanf(“%d”,&n); 3
printf("\nEnter names:\n "); Enter names
for (i = 0; i < n; i++) YOGI
scanf("%s", a[i]); AHANA
for (i = 0; i < n-1; i++) KANI
{
Strings in order are
for (j = i+1; j < n; j++)
{ AHANA
if (strcmp(a[i], a[j]) > 0) KATI
{ YOGI
strcpy(temp, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], temp);
}}}
printf("Strings in order are :\n ");
22
for (i = 0; i < n; i++)
printf("%s\n", a[i]);
getch();
}
2. Find the number of vowel(s) present in the string
#include<stdio.h>
#include<conio.h>void main()
{
char string[200];
int count=0,i=0;
printf("Enter a string:\n");
gets(string);
while(string[i]!='\0')
{
switch(string[i])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
count++;
}
i++;
}
if(count==0)
printf("\n No vowel is present in the string");
else
printf("\n%d vowels are present in the string", count);
getch();
}
Sample output:
Enter a string:
Hello How are you
7 vowels are present in the string

3. To check whether the given string is palindrome or not


#include <stdio.h>
#include <string.h>
#include<conio.h>
int main()
{
char str[100], rev[100];
clrscr();
printf("Enter the string to check if it is a palindrome\n");
gets(str);
strcpy(rev,str);
strrev(rev);
if( strcmp(str,rev) == 0 )
23
printf("Entered string is a palindrome\n");
else
printf("Entered string is not a palindrome\n");
getch();
}
Sample Output:
Enter the string to check if it is a palindrome: liril
Entered string is a palindrome
Sample Output:
Enter the string to check if it is a palindrome: lux
Entered string is not a palindrome
4. Program to count no of occurrence of particular character in a string
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20], ch;int
count = 0, i;
clrscr();
printf("\n Enter a string : ");
gets(str);
printf("\n Enter the character to be searched : ");
scanf("%c", &ch);
for (i = 0; str[i] != '\0'; i++)
{
if (str[i] == ch)
count=count+1;
}
if (count == 0)
printf("\n Character is not present");else
printf("\n Occurrence of character is %d", count);
getch();
}

Sample Output:
Enter a string : Hello
Enter the character to be searched : l
Occurrence of character is 2

5 . Program to count no of blank spaces in the string


#include<stdio.h>
#include<conio.h>
void main()
{
char str[200], ch;
int count = 0, i=0;
clrscr();
printf("\nEnter a string : ");
gets(str);
while(str[i]!=’\0’)
{
if(str[i]==’ ‘)
count++;
i++;
24
}
printf("\nNumber of blank spaces in the given string are %d", count);getch();
}
Sample Output:
Enter a string
People resent a joke if there is some truth in it- TagoreNumber
of blank spaces in the given string are 11

6. Program to count spaces, digits, vowels, consonants in a line

#include<stdio.h>
#include<conio.h>
void main()
{
char line[150];int
i,v,c,d,s;
v=c=d=s=0;
printf("Enter a line of string:\n");
gets(line); for(i=0;line[i]!='\0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' ||line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U') v=v+1;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))c=c+1;
else if(line[i]>='0'&&c<='9')
d=d+1;
else if (line[i]==' ')
s=s+1;
}
printf("Vowels: %d",v);
printf("\nConsonants: %d",c);
printf("\nDigits: %d",d); printf("\nWhite spaces: %d",s);getch();
}
Sample output: Enter a
line of string :god is
love1
Vowels: 4
Consonants: 5
Digits:1
White spaces: 2
7. To concatenate two strings without using library function
void main(void)
{
char str1[25],str2[25];int
i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
25
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

Output:
Enter First String:HELLO
Enter Second String:GIRL
Concatenated String is HELLOGIRL

8. To compare 2 strings without using strcmp


#include<stdio.h>
#include<string.h>
int main()
{
int i;
char s1[] = "Hello";
char s2[] = "Hell"; int j
= strlen(s1); int k =
strlen(s2); int flag=1;
if (j == k)
{
for (i = 0; i < j; i++)
{
if (s1[i] == s2[i])
continue;
else
{
printf("\nThe Strings are not equal\n");
flag=0;
break;
}
}
}
else
{
flag=0;
}
if (flag==0)
printf("\nThe Strings are not equal\n");
else
printf("\nThe Strings are equal\n");
return (0);
}

Output:
The Strings are equal

9. Program to copy string without using strcpy()*/


#include <stdio.h>
int main()
{
char s1[100] = "computer", s2[100],i;
for(i = 0; s1[i] != '\0'; ++i)
26
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}

Output:
String s2: computer

10. reverse a string without strrev()


#include <stdio.h>
#include <string.h>
void main()
{
char string[20],temp; int
i,length; printf("Enter
String : ");
scanf("%s",string);
length=strlen(string)-1;
printf("Reverse string ");
for(i=length;i>=0;i--)
{
printf("%c",string[i]);
}
}

Output : Enter
String : gel
Reverse string leg

`Unit 2 - Important Questions


Q.No Part - A
1. List out the features of Arrays.
2. Define a float array of size 5 and assign 5 values to it.
3. Identify the main elements an array declaration.
4. What are the drawbacks of Initialization of arrays in C?
5. What will happen when you access the array more than its dimension?
6. Point out an example code to express two dimensional arrays.
7. How to create a two dimensional array?
8. What is the starting index of an array?
9. Distinguish between one dimensional and two dimensional arrays.
10. What are the different ways of initializing array?
11. What is the use of '\0' and '%s'?

27
12. Is address operator used in scanf() statement to read an array? Why?
13. What is the role of strrev()?
14. Discover the meaning of a String.
15. How to initialize a string? Give an example.
16. Differentiate between Linear search and Binary search.
17. Specify any two methods of sorting.
18. Design a C program for compare any two string
19. Sort the following elements using selection sort method 23, 55, 16, 78, 2
20. List out the any four functions that are performed on character strings.
21. Given an array int a [10] = {101, 012, 103, 104, 105, 106, 107, 108, 109, 110}. Show thememory
representation and calculate its length.
22. Name any two library functions used for string handling.
Write the output of the following Code:
main()
{
static char name[ ]="Engineering” int
23. i=0;
while (name[i]!='\0')
{
printf("%c" name[i]);
i++;
}
}
24. Define an array? How do you initialize array
25. How do you assign an array to another array

Part B
Explain the need for array variables. Describe following with respect to arrays:
1.  Declaration of array
 Accessing an array element.
2. Write a C program to re-order a one-dimensional array of numbers in descending order.
3. Write a C program to multiply two matrices (2D array) by getting input from the user.
Write a C program to perform the following matrix operations:
4.  Addition
 Subtraction
 Scaling
5. Write the C program to median and mode for an array of numbers and explain.
6. Write a C program to calculate mean, median and mode for an array of elements.
7. Write a C program for Determinant and transpose of a matrix.
Describe the following with suitable examples.
8.  Initializing a 2 Dimensional Array
 Memory Map of a Dimensional Array.
9. Explain about the String Arrays and its manipulation in detail.
28
10. Write a C program to find average marks obtained by a 30 students in a test.
11. What are the different types of string functions? Describe with their purpose.
12. Write short notes on Reading and Writing string.
13. Write a C program to sort the n numbers using selection sort.
14. Develop a C program to search an element from the array.
15. Differentiate binary search from linear search.
16. Write a C program to find whether the given string is palindrome or not without using
string functions.
Describe the following functions with examples.
 strlen()
17.  strcpy()
 strcat()
 strcmp()
18. Write the C program to find the number of Vowels, Consonants, Digits and white spacein a
string.
19. Write a C program to count the number of characters, spaces, vowels, constants andothers
using string functions.
Discuss about the following --
20.  Advantages and disadvantages of linear and binary search.
 Discuss briefly runtime initialization of a two dimensional array.
Explain about the following:
21.  String and character array.
 Initializing string variables.
 String input and output.
22. Explain binary search procedure. Write a C program to perform binary search andexplain.

23. Write a C Program to take 5 values from the user and store them in a array

29

You might also like