0% found this document useful (0 votes)
132 views36 pages

PSP Module-3-Notes

This document discusses arrays in C programming. It begins by explaining why arrays are needed and defines arrays as collections of homogeneous elements of the same data type that are accessed using indexes. It then covers: 1) Types of arrays including one-dimensional, two-dimensional, and multidimensional arrays. 2) Declaration, initialization, reading, and writing of one-dimensional arrays. 3) Examples of C programs that work with arrays, including reading/printing array elements, finding the sum/largest element of an array, generating Fibonacci numbers using arrays, and evaluating polynomials using Horner's method.

Uploaded by

loxx
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)
132 views36 pages

PSP Module-3-Notes

This document discusses arrays in C programming. It begins by explaining why arrays are needed and defines arrays as collections of homogeneous elements of the same data type that are accessed using indexes. It then covers: 1) Types of arrays including one-dimensional, two-dimensional, and multidimensional arrays. 2) Declaration, initialization, reading, and writing of one-dimensional arrays. 3) Examples of C programs that work with arrays, including reading/printing array elements, finding the sum/largest element of an array, generating Fibonacci numbers using arrays, and evaluating polynomials using Horner's method.

Uploaded by

loxx
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/ 36

SUBJECT:

PROBLEM-SOLVING THROUGH PROGRAMMING


(21PSP13)

MODULE-3

Prepared by:
CHANDANA D.C
Assistant professor
Dept. Of ISE
21PSP13 Module 3

ARRAYS
1. WHY DO WE NEED ARRAYS?
Arrays are used to represent multiple data items of the same type using single name.

2. DEFINITION OF ARRAYS

 The array is a collection of homogeneous elements of same data type.


 The array index starts with 0.
 Arrays are called as subscripted variables because; it is accessed using subscripts/indexes.
 Ex: 1. List of employees in an organization.
2. List of products and their cost sold by a store.
3. Test scores of a class of students.

 Here marks[0]=10, marks[1]=20, marks[2]=30 and marks[3]=40. This subscript/index notation is


borrowed from Mathematics where we have the practice of writing: marks4, marks3, marks2 and so on.

Properties of Array
Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored at the
smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each element of the
array with the given base address and the size of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So,
it doesn't grow the size dynamically like Linked List which we will learn later

1 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

3. TYPES OF ARRAYS

I. One dimensional array/ Single-Subscripted Variable


II. Two dimensional array/ Double-Subscripted Variable
III. Multidimensional array

I. One-Dimensional Array:
A list of items can be given one variable name using only one subscript and such a variable is called as one
dimensional array.

Ex: int marks[4];


 Here marks is the name of the array which is capable of storing 4 integer values. The first value will
be stored in marks[0], the second value will be stored in marks[1] and so on and the last value will be in
marks[3].
Declaration of One-Dimensional Array: Here is general syntax for array declaration along with examples.

Syntax: data_type array_name[array_size];


Examples: int marks[4];
float temperature[5];
Note: Declaration specifies the data type of array, its name and size.

Initialization of One-Dimensional Array: After array is declared, next is storing values in to an array is
called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is called compile
time initialization. There are 4 different methods:
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero

a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[array_size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[3]={29.5, 30.7, 35.6};

2 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

b) Initialization without size:

 In the declaration the array size will be set to the total number of initial values specified.

 The compiler will set the size based on the number of initial values.

 Syntax: data_type array_name[ ]={list of values};


Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
a) Partial initialization:

 If we not specify the all the elements in the array, the unspecified elements will be
initialized to zero.
 In such a case elements are initialized in the order from 0th element.
 The remaining elements will be initialized to zero automatically by the compiler.
Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.

a) Initializing all the elements zero: If we want to store zero to all the elements in the array we can do.
Examples: int marks[4]={0};
e) String Initialization
 Sequence of characters enclosed within double quotes is called as string.
 The string always ends with NULL character (\0)

Assigning values to arrays


Using assignment operators, we can assign values to individual elements of arrays.
For example:
int a[3];
a[0]=10;

3 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
a[1]=20;
a[2]=30;

2. Run time initialization: Run time initialization is storing values in an array when program is
running or executing.
Example:
printf(“Enter 4 marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
Reading and writing single dimensional arrays.

To read array elements from keyboard we can use scanf() function as follows:
To read 0th element: scanf(“%d”,&a[0]);
To read 1st element: scanf(“%d”,&a[1]);
To read 2nd element: scanf(“%d”,&a[2]);
……
…….
To read nth element : scanf(“%d”,&a[n-1]);
In general
To read ith element:

scanf(“%d”,&a[i]); where i=0; i<n; i++

To print array elements we can use printf() function as follows:


To print 0th element: printf(“%d”,a[0]);

To print 1st element: printf(“%d”,a[1]);


To print 2nd element :printf(“%d”,a[2]);
To nth element : printf(“%d”,&a[n-1]);
In general
To read ith element:

printf(“%d”,a[i]); where i=0; i<n; i++

4 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

Write a C program to read N elements from keyboard and to print N elements on screen.

#include <stdio.h>
void main()
{
int a[10],i,n;
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\nElements in array are: ");
for(i=0;i<n;i++)
{
printf("%d ", a[i]);
}
}

Output
Enter size of array: 5
Enter 5 elements in the array : 3 7 5 6 7
Elements in array are: 3 7 5 6 7

Write a C program to find sum of n array elements.


#include <stdio.h>
void main()
{
int a[10],i,n, SUM=0;
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\nElements in array are: ");
for(i=0;i<n;i++)
{
SUM=SUM+a[i];
}
printf(" sum %d ",SUM);
}

5 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

Write a c program to find largest of n elements stored in an array a.

#include <stdio.h>
void main()
{
int a[10],i,n, big;
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\nElements in array are: ");
big=a[0];
for(i=0;i<n;i++)
{
if(a[i]>big)
big=a[i];
}
printf(" big %d ",big);
}

OUTPUT
Enter size of array: 5
Enter 5 elements in the array : 12 45 7 1 7
Elements in array are: big 45

Write a C program to generate Fibonacci numbers using arrays.

#include <stdio.h>
void main()
{ int fib[24];
int i,n;
printf("Enter size of array: ");
scanf("%d",&n);
fib[0] = 0;
fib[1] = 1;
for(i = 2; i < n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for (i = 0; i < n; i++)
{
printf("%d \t", fib[i]);
}
}

OUPUT

6 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

Write a C program to evaluate the polynomial using Horners method.


#include <stdio.h>
void main()
{
float a[100],sum=0,x;
int n,i;

printf("\nEnter degree of the polynomial X :: ");


scanf("%d",&n);
printf("\nEnter coefficient's of the polynomial X :: \n");
for(i=n;i>=0;i--)
{
printf("\nEnter Coefficient of [ X^%d ] :: ",i);
scanf("%f",&a[i]);
}
printf("\nEnter the value of X :: ");
scanf("%f",&x);
for(i=n;i>0;i--)
{
sum=(sum+a[i])*x;
}
sum=sum+a[0];
printf("\nValue of the polynomial is = [ %f ]\n",sum);
}

OUT PUT
Enter degree of the polynomial X :: 3
Enter coefficient's of the polynomial X ::
Enter Coefficient of [ X^3 ] :: 1
Enter Coefficient of [ X^2 ] :: 3
Enter Coefficient of [ X^1 ] :: 2
Enter Coefficient of [ X^0 ] :: 5
Enter the value of X :: 4
Value of the polynomial is = [ 125.000000 ]

7 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

II. Two-Dimensional Array:


 A list of items can be given one variable name using two subscripts and such a variable is called a
single subscripted variable or one dimensional array.
 It consists of both rows and columns. Ex: Matrix.

Declaration of Two-Dimensional Array: Here is general syntax for array declaration along with examples.

Syntax: data_type array_name[row_size][column_size];


Examples: int marks[4][4];
float city_temper[3][3];
Note: Declaration and definition specify the data type of array, its name and size.

Initialization of Two-Dimensional Array: After array is declared, next is storing values in to an array is
called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is called compile
time initialization. Following are the different methods of compile time initialization.

Syntax: data_type array_name[row_size][column_size]={list of values};


Examples: int marks[3][4]={ 1,2,3, 4, 5, 6, 7,8,9,10,11,12};
float city_temper[2][2]={29.5, 30.7, 35.6, 45.7};
Note: In the above examples we are storing values in marks array and temperature array respectively.
The pictorial representation is also given below

 After initialization the arrays appear as follows:

1 2 3 4 29.5 30.5
marks city_temp
35.6 45.7
5 6 7 8

8 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

2. Run time initialization: Run time initialization is storing values in an array when program is
running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);
for(i=0; i<3; i++)
for(j=0;j<3;j++)
{
scanf(“ %d”, &marks[i][j]);
}
More Examples: Other way of initialization:
int a[ ][3]= { 0, 1, 2, 3,4,5,6,7,8};
int b[ ][4] ={1,2,3,4,5,6,7,8,9,10,11,12};

012 1234
a b
345 5678
67 8 9 10 11 12

Example for Invalid initialization


int A[3][ ]={1,2,3};
Note: Never have column size undeclared in two dimension array.

III. Multi-Dimensional Array: It can have 3, 4 or more dimensions. A three dimensional array is an
array of 2D arrays. It has row, columns, depth associated with it.

NOTE:
USING ARRAYS WITH FUNCTIONS:
In large programs that use functions we can pass Arrays as parameters. Two ways of passing arrays to
functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter

Pass individual elements of array as parameter Pass complete array as parameter


Here, each individual element of array is passed to Here, the complete array is passed to the function.
function separately.
Example: Example:

#include<stdio.h> #include<stdio.h>
int square(int); int sum(int [ ]);

9 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

int main( ) int main( )


{ {
int num[5], i; int marks[5], i;
num[5] ={1, 2, 3, 4, 5}; marks[5] ={10, 20, 30, 40, 50};
for(i=0; i<5; i++) sum(marks);
{ }
square(num[i]); int sum(int n[ ])
} {
} int i, sum=0;
int square(int n) for(i=0; i<5; i++)
{ {
int sq; sum = sum+n[i];
sq= n * n; }
printf(“%d ”, sq); printf(“Sum = %d ”, sum);
} }

Write a c program to read & print 2d array as a Array.

#include<stdio.h>
void main()
{
int m, n , i, j , a[3][3];
printf(“Enter number of Rows and Columns\n”);
scanf(“%d %d”, &m, &n);
printf(“Enter array Elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“Array Elements are\n”);
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
printf(“%d”, a[i][j]);
}
printf(“\n”);
}
}

10 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

Write a c program to Add Two Matrices of m*n dimension.


#include<stdio.h>
#include<conio.h>
void main()
{
int m, n, i, j, a[3][3], b[3][3] , c[3][3];
printf(“Enter number of rows and columns\n”);
scanf(“%d %d”,&m, &n);
//Reading the Array A Elements
printf(“Enter array A elements\n”);
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
scanf(“%d”, &a[i][j]);
}
}
//Reading Array B Elements
printf(“Enter Array B Elements\n”);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf(“%d”,&b[i][j]);
}
}
//Logic to Perform Addition of m*n matrix
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
printf(“Resultant Matrix C is \n”);
for(i=0;i<m;i++)
{
11 Prof. Chandana D C, Dept. of ISE 2021-22
21PSP13 Module 3
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}

Write a c program to find biggest element in a matrix or 2D array.


#include<stdio.h>
void main()
{
int m, n, i, j, a[3][3];
printf(“Enter Number of Rows and Columns\n”);
scanf(“%d %d”, &m, &n);
printf(“Enter Array Elements\n”);
for(i=0; i<m; i++)
{
for(j=0;j<n; j++)
{
scanf(“%d”,&a[i][j]);
}
}

big = a[0][0];
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
if(big > a[i][j])
big = a[i][j];
}
}
printf(“Big is %”, big);
}

12 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

Matrix Multiplication Programs


#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p,q;
printf("Enter the order of matrix A\n");
scanf("%d%d",&m,&n);
printf("Enter the order of matrix B\n");
scanf("%d%d",&p,&q);

if(n!=p)
{
printf("Matrix multiplication is not possible\n");
exit(0);
}
printf("Enter the elements of matrix A\n");
for(i = 0 ; i < m; i++)
{
for(j = 0 ; j < n; j++)
{
scanf("%d",&a[i][j]);
}

}
printf("Enter the elements of matrix B\n");

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


{
for(j = 0 ; j < q; j++)
{
scanf("%d",&b[i][j]);
}

}
for(i=0 ; i < m ; i++)
{
for(j=0 ; j < q ; j++)
{
c[i][j] = 0;
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}

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

13 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
printf("\n");
}
printf("Matrix B is\n");

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


{
for(j = 0 ; j < q; j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
printf("The Product od two Matrix is\n");
for(i = 0 ; i < m; i++)
{
for(j = 0 ; j < q; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}

C Program To check whether matrix is Identiy matrix or Not


#include<stdio.h>
void main()
{
int i, j, rows, columns, a[10][10], Flag = 1;

printf("\n Please Enter Number of rows and columns : ");


scanf("%d %d", &i, &j);

printf("\n Please Enter the Matrix Elements \n");


for(rows = 0; rows < i; rows++)
{
for(columns = 0; columns < j; columns++)
{
scanf("%d", &a[rows][columns]);
}
}

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


{
for(columns = 0; columns < j; columns++)
{
if(a[rows][columns] != 1 && a[columns][rows] != 0)
{
Flag = 0;
break;
}
}
}

14 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
if(Flag == 1)
{
printf("\n The Matrix that you entered is an Identity Matrix ");
}
else
{
printf("\n The Matrix that you entered is Not an Identity Matrix ");
}
}

C program to find Transpose of a Matrix

#include <stdio.h>
void main()
{
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
}

15 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

III SEARCHING ALGORITHMS


The process of finding a particular item in the large amount of data is called searching.
The element to be searched is called key element.
There are two methods of searching:
1] Linear search.
2] Binary search

1. Linear Search:
• Linear search also called sequential search is a simple searching technique.
• In this technique we search for a given key item in linear order i.e,one after the other from first
Element to last element.
• The search may be successful or unsuccessful.
• If key item is present, the search is successful, otherwise unsuccessful search.

Program to implement linear search.


#include<stdio.h>
void main ( )
{
int i, n, a[10],
key;
printf(“Enter Number of Elements to be stored in an array\n”);
scanf(“%d”, &n);
printf(“Enter Array Elements \n”);

16 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
for(i=0; i<n; i++)
{
scanf(“%d”, &a[i]);
}
printf(“Enter The Key Element
\n”); scanf(“%d”,, &key);
for(i=0; i<n; i++)
{
if(key = = a[i])
{
printf(“Successful search\n”);
printf(“Key =%d Element Found at Pos=%d \n”,key,i+1)
break;
}
}
printf(“un successful search\n”);
}

Advantages of Linear Search


• Very simple Approach.
• Works well for small arrays.
• Used to search when elements are not sorted.
Disadvantages of Linear Search
• Less efficient if array size is large
• If the elements are already sorted, linear search is not efficient.

17 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

2. Binary Search:
• Binary search is a simple and very efficient searching technique which can be applied if the items are
Arranged in either ascending or descending order.
• In binary search first element is considered as low and last element is considered as high.
• Position of middle element is found by taking first and last element is as follows.
mid=(low+high)/2
• Mid element is compared with key element, if they are same, the search is successful.
• Otherwise if key element is less than middle element then searching continues in left part of the array.
• If key element is greater than middle element then searching continues in right part of the array.
• The procedure is repeated till key item is found or key item is not found.
• Note: Elements in the array Need to in Sorted Order otherwise Binary Search is not
Going to work properly

Advantages of binary search


• Simple technique
• Very efficient searching technique Disadvantages
• The elements should be sorted.
• It is necessary to obtain the middle element, which are stored in array. If the elements are stored in
Linked list, this method cannot be used .
Disadvantages
Elements Need to be kept in sorted order before applying the Binary Search Algorithm

18 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

C program to search a key in a list of names using Binary searching technique*/

#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[20],low,mid,high,i,n,k;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("%d\n",n);
printf("Enter the elements\n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("Enter the element to be searched\n");
scanf("%d",&k);
low = 0;
high = n - 1;
while(low <= high)
{
mid = (low + high)/2;
if(a[mid] == k)
{
printf("Successful search, element %d found at %d\n",k,mid+1);
exit(0);
}
else if(a[mid] > k)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
printf("Unsuucessful search\n");

19 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

SORTING
SORTING: It is the process of arranging elements in the list according to their values in ascending or
descending order. A sorted list is called an ordered list.
Ex: Bubble Sort, Selection Sort, Insertion Sort, Shell Sort, Merge Sort, Quick Sort.

1. Bubble Sort
 This is the simplest and easiest sorting technique.
 In this technique two successive elements of an array such as a[j] and a[j+1] are compared.
 If a[j]>=a[j+1] the they are exchanged, this process repeats till all elements of an array are arranged in
ascending order.
 After each pass the largest element in the array is sinks at the bottom and the smallest element in the array
is bubble towards top. So this sorting technique is also called as sinking sort and bubble sort.

 The comparison Operations goes for N-1 times


Bubble sort will start by comparing the first element of the array with the second element, if the first element
is greater than the second element, it will swap both the elements, and then move on to compare the second
and the third element, and so on.
#include<stdio.h>
void main( )
{
int n, a[100], i, j, temp;;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
for(j=0;j<(n-i)-1;j++)
{
if( a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}

20 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

2. Selection Sort
 It is an another technique for Sorting the elements in the array
 Here it considers the first element as minimum
 It Compares the Next Element with the Minimum Position Element
 If it is less than the Minimum Position Element it changes the default position of minimum to current
 Minimum value position.
 Whereas in bubble sort it was comparing the neighbor elements and swap was taking place but in
 Selection sort swap happens from maximum value to the minimum value.
o It reduces the Number of swap time

o This is illustrated as shown below

Selection sort will start by comparing the first element with other elements and finds minimum element and
swaps, then it starts comparing by taking second element with other elements and so on.

#include<stdio.h>
void main( )
{
int n, a[100], i, j, temp, pos;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
pos=j;
}
if(pos !=i )
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}

21 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

STRINGS

1. INTRODUCTION
 A group of characters together is called String.
 String is always enclosed within double quotes (“ “)
 String always ends with delimiter (NULL – ‘\0’ )
 Ex: a = “CBIT”

Operations on string:

 Reading and writing a string


 Combining string together
 Copying one string to another
 Comparing string for equality
 Extracting a portion of string
2. DECLARATION OF A STRING
A String is declared like an array of character.
Syntax: data_type string_name[size];
Example: char name[20];
String size 20 means it can store upto 19 characters plus the NULL character.

3. INITIALIZATION OF A STRING
Syntax: data_type string_name[size] = value;
Example: The String can be initialized in two ways:
i. char name[30] = “SUVIKA”;
ii. char name[30] = {‘S’, ‘U’, ‘V’, ‘I’, ‘K’, ‘A’, ‘\0’};

NOTE:
i. char a[2] = “CPPS”;
The above initialization is invalid because, the size is less.
ii. char a[5];
a = “CPPS”;
The above initialization is invalid because, in string the declaration and initialization should
be done together.

4. LIMITATION OF STRINGS
One string variable cannot be directly assigned to another variable as shown below:
char name1[10] = “Hello”;

22 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
char name2[10];
name2 = name1; //Invalid
But, this initialization can be done using a loop and assigning a individual character as shown below:
#include<stdio.h>
void main( )
{
char name1[10] = “Hello”;
char name2[10];
int i;
for(i=0; i<5; i++)
{
name2[i] = name1[i];
}
name2[i] = ‘\0’;
}

5. READING AND WRITING A STRING

i. Reading a String: To read a string we use %s specifier.

Ex: char name[10];


printf(“Enter the name\n”);
scanf(“%s”, name);

While reading strings we need not specify address operator because, character array itself is an
address.

NOTE:

Edit set conversion code %[ ]

It is used to specify the type of character that can be accepted by scanf function.

Ex 1: char name[20];
scanf(“%[0123456789]”, name);

Example 1 specifies that it accepts only numbers.

Ex 2: char name[20];
scanf(“%[^0123456789]”, name);

Example 2 specifies that it accepts only alphabets, special symbols, space but it does not accept any
number.

Ex 3: char name[20];
scanf(“%[A-Z]”, name);

Example 3 specifies that it accepts only upper case alphabets.

ii. Writing/Printing a String: We can use print function with %s format specifier to print a string. It
prints the character until NULL character.

Ex 1: char name[10] = “SUVIKA”;

23 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
printf(“The name is %s”, name);

Output: The name is SUVIKA

Ex 2: char name[10] = “SUVIKA”;


printf(“%s”, name);
printf(“%9.3s”, name);
printf(“%-10.3s”, name);

Output:

S U V I K A

S U V

S U V

A program illustrating strings or char arrays, accept your name and print it

#include<stdio.h>
#include<conio.h>
main()
{
char name[10];
printf("\n Enter Your name");
scanf("%s", name);
printf("\n Your name is %s", name);
}

6. STRING MANIPULATION FUNCTIONS

 C library supports a large number of string handling functions that can be used to carry out many of
string manipulation and are stored in header file <string.h>
 There are mainly 6 string handling functions:

Function Name Description


strcpy( ) String Copy Copies one string to another
strlen( ) String Length Finds the length of a string
strcmp( ) String Compare Compares two strings
strcat( ) String Concatenation It concatenates (combines) two strings.
strncpy( ) String ‘n’ Copy Copies left most ‘n’ characters from source to destination.
strncmp( ) String ‘n’ Compare Compares left most ‘n’ characters from source to destination.

24 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
I. strcpy( ) – String Copy

It is possible to assign the value to a string variable using strcpy( ). It allows us to copy one string
from one location to another.

Syntax: strcpy(destination, source);

This function has two parameters:


i. destination: A string variable whose value is going to be changed.
ii. source: A string variable which is going to be copied to destination.

Ex: char a[10], b[10];


strcpy(a, “ABC”);
strcpy(b, a);

After two calls to strcpy( ) a, b contains ABC.

//A program to illustrate the use of string copy strcpy() functions


#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10], str2[10];
int len=0;
clrscr();
printf(“Enter the String \n”);
scanf(“%s”, str1);
strcpy(str1, str2);
printf(“Copied String =%s”, str2);
getch();
}

II. strlen( ) – String Length

The string length function can be used to find the length of the string in bytes.

Syntax: length = strlen(str);

String length function has one parameter str which is a string. It returns an integer value.

Ex: char str[10] = “ABC”;


int length;
length = strlen(str); //3

Note: str = ‘\0’


length = strlen(str); //0
25 Prof. Chandana D C, Dept. of ISE 2021-22
21PSP13 Module 3

A program to illustrate the use of string length strlen() functions


#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str[10];
int len=0;
clrscr();
printf(“Enter the String \n”);
scanf(“%s”, str);
len = strlen(str);
printf(“Length of the String =%d”, len);
}

III. strcmp( ) – String Compare

It is used to compare two strings. It takes the two strings as a parameter and returns an integer
value.
Syntax: result = strcmp(first, second);

result = 0  first = second


result > 0  first > second
result < 0  first < second

Example: int res;


res = strcmp(“cat”, “car”); //res > 0res
= strcmp(“pot”, “pot”); //res = 0res =
strcmp(“big”, “small”); //res < 0

A program to illustrate the use of string Comparison strcmp() functions


#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10], str2[10];
int len=0;
clrscr();
printf(“Enter the First String \n”);
scanf(“%s”, str1);
printf(“Enter the Second String \n”);\
scanf(“%s”, str2);

26 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
if(strmp(str1,str2)== 0)
printf(“Both the strings are Equal”);
else if(strcmp(str1,str2)>0)
printf(“String 1 is greater then String 2”);
else
printf(“String 1 is less than string 2”);
getch();
}

IV. strcat( ) – String Concatenate

It is used to concatenate or join two strings together. It has two parameters where the combined
string will be stored in the (destination) first parameter.

Syntax: strcat(destination, source);

Example: char first[30] = “Computer”;


char last[30] = “Programming”;
strcat(first, last);

Note: strcat( ) stops copying when it finds a NULL character in the second string.

A program to illustrate the use of string concatenation strcat() functions


#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10], str2[10];

int len=0;
clrscr();
printf(“Enter the First String \n”);
scanf(“%s”, str1);
printf(“Enter the Second String \n”);
scanf(“%s”, str2);
printf(“Concatenated String=%s \n”, strcat(str1,str2);
getch();
}

27 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
V. strncmp( ) – String ‘n’ Compare

It compares upto specify number of characters from the two strings and returns integer value.

Syntax: result = strncmp(first, second, numchars);

result = 0  first = second


result > 0  first > second  w.r.t number of characters
result < 0  first < second

Example: int res;


res = strncmp(“string”, “stopper”, 4); //res > 0
res = strncmp(“string”, “stopper”, 2); //res = 0
res = strncmp(“stopper”, “string”, 4); //res < 0

VI. strncpy( ) – String ‘n’ Copy

This function allows us to extract a substring from one string and copy it to another location.

Syntax: strncpy(dest, source, numchars);

The strncpy( ) takes three parameters. It copies the number of characters (numchars) from source
string to destination string.
Since, numchars doesn’t include NULL character we have to specify explicitly.

Ex: char a[10] = “CBIT”;


char b[10];
strncpy(b, a, 2);
b[2] = ‘\0’

VII. strrev() To reverse the given string

A program to illustrate the use of string copy strrev() functions


#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10], rev[10];
int len=0;
clrscr();
printf(“Enter the String \n”);
scanf(“%s”, str1);
strcpy(strrev(str), rev);
printf(“Reversed String =%s”, rev);
getch();
}

28 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

VIII. strupr() Converts from Lower case to Upper Case


IX. strlwr() Coverts from Upper Case to Lower Case

A program to illustrate the use of string upper strupr() and string lower strlwr() functions
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10], rev[10];
int len=0;
clrscr();
printf(“Enter the String \n”);
scanf(“%s”, str1);
printf(“Upper String =%s \n”, strupr(str1));
printf(“Lower String=%s \n”, strlwr(str1);
getch();
}

Write functions to implement string operations such as compare, concatenate, string length. Convince
the parameter passing techniques

#include<stdio.h>
#include<string.h>
void stringlength(char a[100],char b[100]);
void concatenate(char a[100],char b[100]);
void stringcompare(char a[100],char b[100]);
void main()
{
char p[100],q[100],ch[100];
int len1,len2;
printf("Enter the first string:\n");
gets(p);
printf("Enter the second string:\n");
gets(q);
stringlength(p,q);
stringcompare(p,q);
concatenate(p,q);
}
void stringlength(char a[100], char b[100])
{
int len1,len2;
len1=strlen(a);
len2=strlen(b);

29 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

printf("First string length is :%d \n Second string lenght is: %d",len1,len2);


}
void concatenate(char a[100], char b[100])
{
printf("The concatenated String is :%s ", strcat(a,b));
}
void stringcompare(char a[100], char b[100])
{
if(strcmp(a,b)==0)
printf("\nSTRINGS ARE EQUAL\n");
else
printf("\nSTRINGS ARE NOT EQUAL\n");
}

7. ARRAY OF STRINGS
It is an array of 1D character array which consists of strings as its individual elements.

Syntax: char name[size1][size2];


Ex: char days[7][10] = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”,
“Saturday”};

Write a program to check whether a given string is palindrome or not. (without using any built-in string
function
#include <stdio.h>
#include <string.h>

int main(){
char string1[20];
int i, length;
int flag = 0;

printf("Enter a string:");
scanf("%s", string1);

length = strlen(string1);

for(i=0;i < length ;i++){


if(string1[i] != string1[length-i-1]){
flag = 1;
break;
}
}

if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}

30 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

Write a ‘C’ function to count the number of vowels and consonants in a string.

#include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,vowels=0,consonants=0;
printf("Enter the string : ");
gets(s);
for(i=0;s[i];i++)
{
if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 && s[i]<=122))
{

if(s[i]=='a'|| s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O' ||s[i]=='U')


vowels++;
else
consonants++;
}
}
printf("vowels = %d\n",vowels);
printf("consonants = %d\n",consonants);
return 0;
}

Write a C program to swap two strings


#include <stdio.h>
#include <string.h>
void main()
{
char first[100], second[100], t[100];
printf("Enter first string\n");
gets(first);
printf("Enter second string\n");
gets(second);
printf("\nBefore Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n\n", second);
strcpy(t, first);
strcpy(first, second);
strcpy(second, t);
printf("After Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n", second);
}

31 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

QUESTION BANK

1 What is an array? How a s ingle dimension and two dimension arrays are declared and initialized?
8M

2 Write a C program that reads N integer numbers and arrange them in ascending order using
selection Sort. Trace the steps for the input: 9, 1, 6, 3, 2, 0, 5 10M

3 Write a C program to search an integer from N numbers in ascending order using binary searching
technique 6M

4 Write a ‘C’ program to implement matrix multiplication and ensure if the rules for multiplication
are checked. 8M

5 Write a ‘C’ Program to read N numbers into an array & perform Linear search 5M

6 Write a ‘C’ program to find the sum of rows and sum of columns of a matrix 5M

7 Write a C program to input N integers in a single dimensional array & sort them in ascending order
using bubble sort. 6M

8 Explain searching, and techniques to implement searching. List their advantages and disadvantages
8M

9 List the difference between linear search and binary search. 4M

10 Write a C program to read matrix of M x N and prints its transpose. 5M

11 For a array declared as int a[50], compute the address of a[35] if a’s base address is 1000 and
word size=2. 2M CO3

12 How 1D and 2D integer arrays are represented in memory? Explain with the help of suitable
example the declaration and initializing the array elements. 10M

Strings (module 3)

12 Explain string input/output functions with examples. 8M

13 Explain any five string manipulation functions with example. 10M

14 Write a program to check whether a given string is palindrome or not. (without using any built-in
string function). 5M

15 Write a ‘C’ function to count the number of vowels and consonants in a string. 5M

16 Write a C program to swap two strings. 5M

17 Mention the purpose of a Null Character in C strings 2M

32 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

VTU SOLVED QUESTIONS

1 WACP to find the transpose of a given matrix.

#include<stdio.h>
void main( )
{
int m, n, I, j, a[100][100], t[100][100];
printf(“Enter the order of matrix\n”);
scanf(“%d%d”, &m, &n);
printf(“Enter the elements of matrix\n”);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
scanf(“%d”, &a[i][j]);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
t[j][i] = a[i][j];
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf(“%d”, t[i][j]);
}
printf(“\n”);
}
}
2 WACP to copy a string (combination of digits and alphabets) to another string (only alphabets).

#include<stdio.h>
#include<ctype.h>
void main()
{
char s1[100], s2[100];
int i=0, j=0;
printf("Enter String1\n");
scanf("%s",s1);
while(s1[i] != '\0')
{
if(isalpha(s1[i]))
{
s2[j] = s1[i];
j++;
}
i++;
}
s2[j] = '\0';
printf("The copied string is %s\n", s2);
}

WACP to find biggest of n numbers using arrays.

#include<stdio.h>
void main()
{

33 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3
int n, a[100], i, large=0;
printf("Enter size of array\n");
scanf("%d", &n);
printf("Enter elements of array\n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=0; i<n; i++)
{
if(a[i] > large)
large = a[i];
}
printf("Large number = %d", large);
}

WACP to concatenate two strings without using built in functions.

#include<stdio.h>
void main()
{
char s1[100], s2[100];
int i=0, j=0;
printf("Enter String1\n");
scanf("%s", s1);
printf("Enter String2\n");
scanf("%s", s2);
while(s1[i] != '\0')
i++;
while(s2[j] != '\0')
{
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0';
printf("The concatenated string is %s", s1);
}

Differentiate between Linear Search and Binary Search.

Linear Search Binary Search


The elements may be in sorted or unsorted order. The elements must be in sorted order.
It is preferred for small size arrays. It is preferred for large size arrays.
It is less efficient in case of large size arrays. It is less efficient in case of small size arrays.
It is based on sequential approach. It is based on divide and conquer approach.
It finds the position of the searched element by It finds the position of the searched element by
comparing each element. finding the middle element of the array.

******************"If you want to shine like a sun, first burn like the sun."*****************

34 Prof. Chandana D C, Dept. of ISE 2021-22


21PSP13 Module 3

35 Prof. Chandana D C, Dept. of ISE 2021-22

You might also like