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

UNIT III CProgramming

cprograming

Uploaded by

samrudhsgowda097
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)
11 views22 pages

UNIT III CProgramming

cprograming

Uploaded by

samrudhsgowda097
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/ 22

UNIT III Arrays, Strings

Arrays & Strings


Arrays in C
When we work with a large number of data values we need that any number of different
variables. As the number of variables increases, the complexity of the program also increases
and so the programmers get confused with the variable names. There may be situations where
we need to work with a large number of similar data values. To make this work easier, C
programming language provides a concept called "Array".
An array is a special type of variable used to store multiple values of same data type at a
time.
An array can also be defined as follows...
An array is a collection of similar data items stored in continuous memory locations with
single name.
Declaration of an Array
In C programming language, when we want to create an array we must know the datatype of
values to be stored in that array and also the number of values to be stored in that array.

We use the following general syntax to create an array...


datatype arrayName [ size ] ;
Syntax for creating an array with size and initial values
datatype arrayName [ size ] = {value1, value2, ...} ;
Syntax for creating an array without size and with initial values
datatype arrayName [ ] = {value1, value2, ...} ;
In the above syntax, the datatype specifies the type of values we store in that array
and size specifies the maximum number of values that can be stored in that array.
Example Code
int a [3] ;
Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and
tells the compiler to store three different integer values (each in 2 bytes of memory) into that 6
bytes of memory. For the above declaration, the memory is organized as follows...

In the above memory allocation, all the three memory locations have a common name 'a'. So
accessing individual memory location is not possible directly. Hence compiler not only
allocates the memory but also assigns a numerical reference value to every individual memory

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

location of an array. This reference number is called "Index" or "subscript" or "indices". Index
values for the above example are as follows...

Accessing Individual Elements of an Array


The individual elements of an array are identified using the combination of 'arrayName' and
'indexValue'. We use the following general syntax to access individual elements of an array...
arrayName [ indexValue ] ;
For the above example the individual elements can be denoted as follows...

For example, if we want to assign a value to the second memory location of above array 'a', we
use the following statement...
Example Code
a [1] = 100 ;
The result of the above assignment statement is as follows...

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Types of Arrays in C
In c programming language, arrays are classified into two types. They are as follows...
1. Single Dimensional Array / One Dimensional Array
2. Multi Dimensional Array
Single Dimensional Array
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called
as one-dimensional arrays, Linear Arrays or simply 1-D Arrays.
Declaration of Single Dimensional Array
We use the following general syntax for declaring a single dimensional array...
datatype arrayName [ size ] ;
Example Code
int rollNumbers [60] ;
The above declaration of single dimensional array reserves 60 continuous memory locations of
2 bytes each with the name rollNumbers and tells the compiler to allow only integer values
into those memory locations.
Initialization of Single Dimensional Array
We use the following general syntax for declaring and initializing a single dimensional array
with size and initial values.
datatype arrayName [ size ] = {value1, value2, ...} ;
Example Code
int marks [6] = { 89, 90, 76, 78, 98, 86 } ;
The above declaration of single dimensional array reserves 6 contiguous memory locations of
2 bytes each with the name marks and initializes with value 89 in first memory location, 90 in

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

second memory location, 76 in third memory location, 78 in fourth memory location, 98 in


fifth memory location and 86 in sixth memory location.
We can also use the following general syntax to intialize a single dimensional array without
specifying size and with initial values...
datatype arrayName [ ] = {value1, value2, ...} ;
The array must be initialized if it is created without specifying any size. In this case, the size
of the array is decided based on the number of values initialized.
Example Code
int marks [] = { 89, 90, 76, 78, 98, 86 } ;

char studentName [] = "btechsmartclass" ;


In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler stores one
exttra character called \0 (NULL) at the end.
Accessing Elements of Single Dimensional Array
In c programming language, to access the elements of single dimensional array we use array
name followed by index value of the element that to be accessed. Here the index value must be
enclosed in square braces. Index value of an element in an array is the reference number given
to each element at the time of memory allocation. The index value of single dimensional array
starts with zero (0) for first element and incremented by one for each element. The index value
in an array is also called as subscript or indices.

We use the following general syntax to access individual elements of single dimensional array...
arrayName [ indexValue ]
Example Code
marks [2] = 99 ;
In the above statement, the third element of 'marks' array is assinged with value '99'.
Multi Dimensional Array
An array of arrays is called as multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array. Multi dimensional array
can be of two dimensional array or three dimensional array or four dimensional array or
more...

Most popular and commonly used multi dimensional array is two dimensional array. The 2-
D arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Declaration of Two Dimensional Array


We use the following general syntax for declaring a two dimensional array...
datatype arrayName [ rowSize ] [ columnSize ] ;
Example Code
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2
bytes each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array
We use the following general syntax for declaring and initializing a two dimensional array with
specific number of rows and coloumns with initial values.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;
Example Code
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2
bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values 1,
2 & 3 and second row is initialized with values 4, 5 & 6.
We can also initialize as follows...
Example Code
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing Individual Elements of Two Dimensional Array
In a c programming language, to access elements of a two-dimensional array we use array name
followed by row index value and column index value of the element that to be accessed. Here
the row and column index values must be enclosed in separate square braces. In case of the
two-dimensional array the compiler assigns separate index values for rows and columns.

We use the following general syntax to access the individual elements of a two-dimensional
array...
arrayName [ rowIndex ] [ columnIndex ]
Example Code
matrix_A [0][1] = 10 ;

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

In the above statement, the element with row index 0 and column index 1 of matrix_A array
is assinged with value 10.
Code to read two dimensional Array elements
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
scanf(“%d”,&a[i][j]);
}
}

Code to print/output two dimensional Array elements


for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf(“%d”,a[i][j]);
}
}

Applications of Arrays in C
In c programming language, arrays are used in wide range of applications. Few of them are as
follows...
● Arrays are used to Store List of values
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.
● Arrays are used to Perform Matrix Operations
We use two dimensional arrays to create matrix. We can perform various operations on matrices
using two dimensional arrays.
● Arrays are used to implement Search Algorithms
We use single dimensional arrays to implement search algorihtms like ...

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

1. Linear Search
2. Binary Search
● Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting algorihtms like ...
1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort, etc.,
● Arrays are used to implement Datastructures
We use single dimensional arrays to implement datastructures like...
1. Stack Using Arrays
2. Queue Using Arrays
● Arrays are also used to implement CPU Scheduling Algorithms

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Concept Structure :

Stepwise Procedure:
Linear Search Method:
In the Linear Searching method, the elements in the list are scanned from the first element till either the
required key element is found or the list is over. The Key element is compared with every element. This
is also called as sequential search method. The list elements are not required to be in specific order.
The advantage of the method is its simplicity. But it is efficient only for small sized lists. The maximum
iterations required will be the size of the list ‘N’.
Pictorial Description:
Let us consider a list of integer elements with N = 12 as:

A[0] 1 2 3 4 5 6 7 8 9 10 A[11] Index

18 89 11 45 24 40 32 15 231 7 48 59 Elements

1. If search Key is 40 :
Starting with index = 0, the current element is compared with key. The Key 40 is found at index position
6. This is depicted pictorially as below:

A[0] 1 2 3 4 5 6 7 8 9 10 A[11] Index

18 89 11 45 24 40 32 15 231 7 48 59 Elements

Current element A[0], 18 = 40, go to next element ----- Comparison 1

A[0] 1 2 3 4 5 6 7 8 9 10 A[11]
18 89 11 45 24 40 32 15 231 7 48 59

Current element A[1], 89 =40, go to next element ----- Comparison 2

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

A[0] 1 2 3 4 5 6 7 8 9 10 A[11]

18 89 11 45 24 40 32 15 231 7 48 59

Current element A[2], 11 = 40, go to next element ----- Comparison 3

A[0] 1 2 3 4 5 6 7 8 9 10 A[11]
18 89 11 45 24 40 32 15 231 7 48 59

Current element A[3], 45 = 40, go to next element ----- Comparison 4

A[0] 1 2 3 4 5 6 7 8 9 10 A[11]

18 89 11 45 24 40 32 15 231 7 48 59

Current element A[4], 24 = 40, go to next element ----- Comparison 5

A[0] 1 2 3 4 5 6 7 8 9 10 A[11]

18 89 11 45 24 40 32 15 231 7 48 59

Current element A[4], 40 = 40, key found ----- Comparison 6


Thus Key 40 found at position 6
The result of the Linear search is:
The key element 40 is Found in the list at position6.
The number of comparisons required = 6.
Similarly,
2. If search Key is 89, then:
The result of the Linear search will be as :
The key element 89 is Found in the list at position 2.
The number of comparisons required = 2.
3. If search Key is 64, then:
The result of the Linear search will be as :
The key element 64 is Not Found in the list.
The number of comparisons required = 12 i.e. N.

IMPLEMENTATION OF LINEAR SEARCH

WAP C Pgm to search an element using sequential search .

#include<stdio.h>
#include<conio.h>

int linear(int key,int a[],int n) /algorithm begin/


{
int i;
for(i=0;i<n;i++)
{

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

if(a[i]==key)
return i+1;
}
return 0;
} /algorithm ends/

void main()
{
int i,n, key,pos,a[20];
clrscr();
printf("enter the number of elements n\n");
scanf("%d",&n);
printf("enter the values\n"); /reading array elements/
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the key element\n");
scanf("%d",&key);
pos=linear(key,a,n);
if(pos==0)
printf("unsucessful\n");
else
printf("key found at position =%d\n",pos);
getch();
}

OUTPUT:

What is Search?
Search is a process of finding a value in a list of values. In other words, searching is the process
of locating given value position in a list of values.
Binary Search Algorithm
Binary search algorithm finds a given element in a list of elements with O(log n) time
complexity where n is total number of elements in the list. The binary search algorithm can be
used with only a sorted list of elements. That means the binary search is used only with a list
of elements that are already arranged in an order. The binary search can not be used for a list
of elements arranged in random order. This search process starts comparing the search element
with the middle element in the list. If both are matched, then the result is "element found".
Otherwise, we check whether the search element is smaller or larger than the middle element
in the list. If the search element is smaller, then we repeat the same process for the left sublist
of the middle element. If the search element is larger, then we repeat the same process for the
right sublist of the middle element. We repeat this process until we find the search element in
the list or until we left with a sublist of only one element. And if that element also doesn't match
with the search element, then the result is "Element not found in the list".

Binary search is implemented using following steps...


• Step 1 - Read the search element from the user.
• Step 2 - Find the middle element in the sorted list.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

• Step 3 - Compare the search element with the middle element in the sorted list.
• Step 4 - If both are matched, then display "Given element is found!!!" and terminate
the function.
• Step 5 - If both are not matched, then check whether the search element is smaller or
larger than the middle element.
• Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5
for the left sublist of the middle element.
• Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5
for the right sublist of the middle element.
• Step 8 - Repeat the same process until we find the search element in the list or until
sublist contains only one element.
• Step 9 - If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.
REFER LAB RECORD FOR PROGRAM
Example
Consider the following list of elements and the element to be searched.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Arranging the data in either ascending or descending manner based on certain key in the record
is known as SORTING.
Arranging the data in either ascending or descending manner based on certain key in the record
is known as SORTING. Suppose we want to search for the telephone number of a person in the
telephone directory. if the telephone directory is not sorted in alphabetical order, we may have
to search for the entire telephone directory. just to know whether the telephone number of a
person exists or not. Since the telephone directory is sorted, we know how easy is to search for
telephone number.so,it is required to arrange the names in alphabetical order.

There are different types of sorting techniques, among few of them are listed below

✓ Bubble Sort
✓ Selection Sort
✓ Insertion Sort
✓ Quick Sort
✓ Merge Sort
✓ Shell Sort
✓ Radix Sort
✓ Heap Sort

Bubble Sort-
Bubble sort is the easiest sorting algorithm to implement.
It is inspired by observing the behavior of air bubbles over foam.
It is an in-place sorting algorithm.
It uses no auxiliary data structures (extra space) while sorting.

How Bubble Sort Works?


Bubble sort uses multiple passes (scans) through an array.
In each pass, bubble sort compares the adjacent elements of the array.
It then swaps the two elements if they are in the wrong order.
In each pass, bubble sort places the next largest element to its proper position.
In short, it bubbles down the largest element to its correct position.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Bubble Sort Example-

Consider the following array A-

Now, we shall implement the above bubble sort algorithm on this array.

Step-01:

• We have pass=1 and i=0.


• We perform the comparison A[0] > A[1] and swaps if the 0th element is greater than the
1th element.
• Since 6 > 2, so we swap the two elements.

Step-02:

• We have pass=1 and i=1.


• We perform the comparison A[1] > A[2] and swaps if the 1th element is greater than the
2th element.
• Since 6 < 11, so no swapping is required.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Step-03:

• We have pass=1 and i=2.


• We perform the comparison A[2] > A[3] and swaps if the 2nd element is greater than the
3rd element.
• Since 11 > 7, so we swap the two elements.

Step-04:

• We have pass=1 and i=3.


• We perform the comparison A[3] > A[4] and swaps if the 3rd element is greater than the
4th element.
• Since 11 > 5, so we swap the two elements.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Finally after the first pass, we see that the largest element 11 reaches its correct position.

Step-05:

• Similarly after pass=2, element 7 reaches its correct position.


• The modified array after pass=2 is shown below-

Step-06:

• Similarly after pass=3, element 6 reaches its correct position.


• The modified array after pass=3 is shown below-

Step-07:

• No further improvement is done in pass=4.


• This is because at this point, elements 2 and 5 are already present at their correct
positions.
• The loop terminates after pass=4.

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

• Finally, the array after pass=4 is shown below-

REFER LAB RECORD FOR PROGRAM.

Program to compute transpose of a matrix.


#include <stdio.h>
void main()
{ int rows, cols;
printf("Enter the number of rows and column: ");
scanf("%d %d", &rows,&cols);
int matrix[rows][cols], transpose[cols][rows];
printf("Enter elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
transpose[j][i] = matrix[i][j];
}
}

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

printf("\nOriginal Matrix:\n");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

printf("\nTranspose of the Matrix:\n");


for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
printf("%d\t", transpose[i][j]);
}
printf("\n");
}
getch();
}

Strings in C
String is a set of characters that are enclosed in double quotes. In the C programming language,
strings are created using one dimension array of character datatype.
There are two methods to create strings and they are as follows...
1. Using one dimensional array of character datatype ( static memory allocation )
2. Using a pointer array of character datatype ( dynamic memory allocation )

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

Creating string in C programming language


In C, strings are created as a one-dimensional array of character datatype. We can use
both static and dynamic memory allocation. When we create a string, the size of the
array must be one more than the actual number of characters to be stored. That extra
memory block is used to store string termination character NULL (\0). The following
declaration stores a string of size 5 characters.
char str[6] ;
The following declaration creates a string variable of a specific size at the time of
program execution.
char *str = (char *) malloc(15) ;
Assigning string value in C programming language
String value is assigned using the following two methods...
1. At the time of declaration (initialization)
2. After declaraation

Reading string value from user in C programming language


We can read a string value from the user during the program execution. We use the
following two methods...
1. Using scanf() method - reads single word
2. Using gets() method - reads a line of text
Using scanf() method we can read only one word of string. We use %s to represent
string in scanf() and printf() methods.
Examples of reading string value using scanf() method
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome !!", name);
return 0;
}

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

When we want to read multiple words or a line of text, we use a pre-defined


method gets(). The gets() method terminates the reading of text with Enter character.
Examples of reading string value using gets() method
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
printf("Please enter your name : ");
gets(name);
printf("Hello! %s , welcome!!", name);
return 0;
}

C Programming language provides a set of pre-definied functions called String


Handling Functions to work with string values. All the string handling functions are
defined in a header file called string.h.
String Handling Functions in C
C programming language provides a set of pre-defined functions called string
handling functions to work with string values. The string handling functions are
defined in a header file called string.h. Whenever we want to use any string handling
function we must include the header file called string.h.
The following table provides most commonly used string handling function and their
use

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

To find the length of a string without using built in function


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
char str[100],i=0;
clrscr();
printf("\nEnter the string:\n");
scanf("%s",str);
while(str[i]!='\0')
{
i++;

SWETHA C V, DCA, Presidency College (Autonomous)


UNIT III Arrays, Strings

}
printf("\nThe length of the string = %d",i);
getch();
}
To find the length of a string using built in function
#include <stdio.h>
#include <string.h>
void main()
{
char str1[100], str2[100], str3[100];
clrscr();
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
printf("\nLength of first string: %d", strlen(str1));
printf("\nLength of second string: %d", strlen(str2));
strcpy(str3, str2);
printf("\n\nAfter copying, str3: %s", str3);
strcat(str1, str2);
printf("\nAfter concatenation, str1: %s", str1);
getch();
}
*****Kindly read all programs taught in Class*****

SWETHA C V, DCA, Presidency College (Autonomous)

You might also like