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

Unit III

Uploaded by

justabhi148
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

Uploaded by

justabhi148
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 AND STRINGS

Arrays – Initialization – Declaration – One dimensional and Two dimensional arrays. String-
String operations – String Arrays. Simple programs- sorting- searching – matrix operations.

ARRAYS
Definition :
Array is a collection of same data type elements under the same variable name
referenced by index number. Arrays allow you to store group of data of a single type.
Characteristics:
 An array is a derived data type. It is used to represent a collection of elements of the
same data type.
 The elements can be access with base address (index) and the subscripts define the
position of the element.
 In array the elements are stored in continuous memory location, the starting memory
location is represented by the base address of the array
 It is easier to refer the array elements by simply incrementing the value of the
subscript
 Array is a linear and homogeneous data structure
Ex: int a[5];
 It tells the compiler that ‘a’ is an integer type of array and can store 5 integers.

Advantages:
 An array is a derived data type. It is used to represent a collection of elements of the
same data type.
 The elements can be access with base address (index) and the subscripts define the
position of the element.
 In array the elements are stored in continuous memory location, the starting memory
location is represented by the base address of the array
 It is easier to refer the array elements by simply incrementing the value of the
subscript

GE 6151 Unit – III 1


Rules of Array:
 It does not check the boundary.
 Processing time will increase when working with large data because of increased memory.
 The array element start with zero not 1.
 Character array size must be one element greater than data for NULL value.
 One variable for control structure is required to assign and read value to one
dimensional array.
 Two variable for control structures are required to assign and read value to two
dimensional arrays.
 No two arrays can have the same name but arrays and ordinary variable can be assigned
the same name.
Classification of arrays:
 One dimensional Array
 Two Dimensional Array
 Multi-Dimensional Array
One Dimensional Array:
A list of items can be given one variable name using only one subscript and a variable
is called one dimensional array or single subscripted variable.
Declaration:
Arrays are declared in the same manner as an ordinary variables except that array
name must have the size of an array
Syntax:
Data_type Array_name[size];
Description:
Data type-> specifies the type of the data
Array name -> specify the name of the array
Size -> specify the maximum number of elements that the array can hold
Ex:
int a[5]; //Here a is integer array with 5 subscript
a[0]
a[1]
a[2]

GE 6151 Unit – III 2


a[3]
a[4]

Initializing an array:
 The values can be initialized to an array when they are declared like ordinary variables
otherwise they hold garbage values.
 The array can be initialized in the following two types:
o At compile time(static Initialization)
o At run time(Dynamic Initialization)

static Initialization:
Syntax:
Data_type Array_name[size] = {list of values}
The list of values must be separated by commas.
Ex:
Int marks[5]= {70,80,98,35,56};

70 marks[0]
80 marks[1]
98 marks[2]
35 marks[3]
56 marks[4]

int age[]={2,4,34,3,4};
 The elements can be used like ordinary variables
 Character array can also initialized in similar manner
 Ex:

char name[10]={‘R’,’A’,’J’};

The above statements declare the name variables as an array of character with the string
“LAK”.

Dynamic Initialization:

The array can be explicitly initialized at run time.

GE 6151 Unit – III 3


Ex:

int sum[5];

for(int i=0;i<5;i++)

sum[i]=i;

Like the array can also be initialized by reading data from the user.

Ex:

int sum[5];

for(int i=0;i<5;i++)

scanf(“%d”,&a[i]);

Accessing Array Elements:


In C programming, arrays can be accessed and treated like variables in C.
Example:
#include <stdio.h>
void main()
{
int marks[10],i, n, sum=0;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
}
Output:
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45

Example: Program to accept 5 numbers and print whether the number is even or odd.

#include <stdio.h>
#include<conio.h>
GE 6151 Unit – III 4
void main()
{
int array[5], I;
clrscr();
printf("Enter the elements of the array \n");
for (i = 0; i <5; i++)
{
scanf("%d", &array[i]);
}
printf("Even numbers in the array are - ");
for (i = 0; i < 5; i++)
{
if (array[i] % 2 == 0)
{
printf("%d \t", array[i]);
}
}
printf("\n Odd numbers in the array are -");
for (i = 0; i <5; i++)
{
if (array[i] % 2 != 0)
{
printf("%d \t", array[i]);
}
}
getch();
}
Two dimensional array:
 Two dimensional arrays are used in situation where a table of values need to be
stored in an array.
 These can be defined in the same manner as in one dimensional array except a
separate pair of square brackets are required for each subscript
Syntax:
Data_type Array_name[row_size][column_size];
Two dimensional arrays are stored in a row column matrix where the left index
indicated the row and the right index indicated the column.
Example:

GE 6151 Unit – III 5


Void main()
{
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
printf(“Array Elements and Address\n”);
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%d[%d]\t”,a[i][j],&a[i][j]);
}
printf(“\n”);
}
}

Output:
1[2000] 2[2002] 3[2004]
4[2006] 5[2006] 6[2007]
7[2009] 8[2011] 9[2013]

Example: Transpose of Matrix


#include<stdio.h>
#include<conio.h>
void main()
{
int r,c,i,j,m[10][10];
clrscr();
printf("Enter number of rows and columns:");
scanf("%d %d",&r,&c);
for(i=0;i<r;i++) for(j=0;j<c;j++)
scanf("%d",&m[i][j]);
printf("\nThe Transpose matrix");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
printf(" %d",m[j][i]);
}
getch();
}

GE 6151 Unit – III 6


Matrix Addition:
#include <stdio.h>
#include<conio.h>
void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
clrscr();
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0 ; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
getch();
}
Matrix Multiplication:
#include <stdio.h>
#include<conio.h>
void main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
clrscr();

printf("Enter the number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);

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


GE 6151 Unit – III 7
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the number of rows and columns of second matrix\n");


scanf("%d%d", &p, &q);

if (n != p)
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-\n");
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
printf("%d\t", multiply[c][d]);
}
printf("\n");
}
}
getch();
}

MULTI DIMENSIONAL ARRAY:


An Array with more than two subscripts are called Multi Dimensional Array.
GE 6151 Unit – III 8
Syntax:
data_type Array_name[size1][size2][size3]…….[sizen];
Example:
int a[3][3][4];
float b[4][5][6][8];
 Arrays with more than three subscripts are not used often
 Multi dimensional arrays are slower than single dimensional array.
Example:
void main()
{
int a[3][3][3],I,j,k;
clrscr();
printf(“Enter Array Elements:\n”);
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
scanf(“%d”, &a[i][j][k]);
}
}
}
printf(”Array Elements are\n”);
for (i=0;i<3;i++)
{
printf(“\n”);
for(j=0;j<3;j++)
{
printf(“\n”);
for(k=0;k<3;k++)
{
printf(“%d\t”, &a[i][j][k]);
}
}
}
getch();
}

GE 6151 Unit – III 9


SORTING

Bubble Sort:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j,n,a[20],temp;
clrscr( );
printf(“Sorting the elements using bubble sort\n”);
printf(“Enter the size of the array \n”);
scanf(“%d”,&n);
printf(“Enter the elements of the array:\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}

for(i=0;i<n;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf(“The elements sorted using bubble sort are:\n”);

for(i=0;i<n;i++)
{
printf(“%d\t”,a[i]);
}
getch( );
}

GE 6151 Unit – III 10


SEARCHING
Linear Search:
#include <stdio.h>
#include<conio.h>
void main()
{
int array[100], search, c, n;
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d",&n);

printf("Enter %d integer(s)\n", n);


for (c = 0; c < n; c++)
scanf("%d", &array[c]);

printf("Enter the number to search\n");


scanf("%d", &search);

for (c = 0; c < n; c++)


{
if (array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);
getch();
}
Binary Search:
#include <stdio.h>
#include<conio.h>
int main()
{
int i, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for ( i = 0 ; i < n ; i++ )
scanf("%d",&array[i]);
printf("Enter value to find\n");
GE 6151 Unit – III 11
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] >search )
{
last=middle+1;
}
else
printf("%d found at location %d.\n", search, middle+1);
}
if ( first > last )
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
STRING
 String is the collection of characters.
 In c language, the group of characters, digits and symbols enclosed with in “” is called
string
 A string is declared as a one dimensional array of characters.
 The string is terminated by a null(‘\0’ ) character
 It is not compulsory to add ‘\0’ in a string, compiler will automatically puts’\0’ in a
string
 The string are normally used to manipulate the text such as words and sentences.
 Header file used is string.h

String Declaration:
Syntax:
Datatype variable_name [size];
Ex:
char name[30];

String Initialization:
Syntax:
Datatype variable_name [size] = string;
Ex:
char name[]={‘r’,’a’,’j’,’a’,’\0’};
GE 6151 Unit – III 12
 where the \0 is specified at the end of string
 ‘C’ provides another method for initialing string
char name[]=”raja”;
 Here \0 is not necessary
Reading & writing String:
The %s control string can be used in scanf() function to read a string from the terminal. and
same may be used to write string to the terminal in printf() function.
Ex:
char a[10];
scanf(“%s”, a);
printf(“%s”, a);

Built-in String functions/ String Operations/ String Manipulation Functions:


There are several string functions to work with string variables and its values.
These functions are available C header file called string.h.
Consider the following example:
char string1[15]=”Hello”;
char string2[15]=”World”;

1) Copying String
Syntax: strcpy(destination,source);
 Here, source and destination are both the name of the string.
 This statement, copies the content of string source to the content of string
destination.
 This function will replace the existing value of destination with source.
 Example:
char string1[15]=”Hello”;
char string2[15]=”World”;
strcpy(string1,string2);
printf(“%s%s”,string1,string2);
 output:
World World

2) Comparing String:
Case Sensitive:
 This function compares the value from string2 with string1.
 If both the string1 and string2 are exactly the same then the function will return
zero or else it will return some positive or negative value.
 For the above example the function will return negative of positive value.
Here string1 and string2 will not change.
 Syntax:
GE 6151 Unit – III 13
strcmp(string1,string2);
 Example:
int n;
char string1[15]=”Hello”;
char string2[15]=”Hello”;
n=strcmp(string1,string2);
printf(“%n”,n);
 Output:
0

Non-Case Sensitive:
Syntax: stricmp(string1, string2);
Example:
int n;
char string1[15]=”Hello”;
char string2[15]=”hello”;
n=stricmp(string1,string2);
printf(“%n”,n);
Output:
0

3) Concatenation String
strcat(string1,string2);
 This function is used to join two strings.
 It concatenates source string at the end of destination string.
 Here String 2 is concatenate with String1.
Example:
char string1[15]=”Hello”;
char string2[15]=”World”;
n=strcat(string1,string2);
printf(“%s”,string1);
Output:
HelloWorld

strncat(string1,string2,No_of_characters);
 This function is used to join two strings.
 It concatenates portion of source string at the end of destination string.
 Here String 2 is concatenate with String1.
Example:
char string1[15]=”Hello”;
char string2[15]=”World”;

GE 6151 Unit – III 14


n=strcat(string1,string2,3);
printf(“%s”,string1);
Output:
HelloWor

4) Copying String
strcpy(string1,string2);
 This function copy’s the contents of one string2 into another string1.
Example:
char string1[15]=”Hello”;
char string2[15]=”World”;
n=strcpy(string1,string2);
printf(“%s”,str1);
Output:
World

strncpy(string1,string2,no_of_characters);
 This function copies portion of contents of one string2 into another string1.
Example:
char string1[15]=””;
char string2[15]=”Hello World”;
n=strcpy(string1,string2,5);
printf(“%s”,string1);
Output:
Hello

5) Find a value in string (strstr())


 This function will find the first occurance of string2 in string1.
 Assume string1 as “Apple” and string2 as “Ap”, now the function will return first
occurrence of “Ap”, since “Ap” is found in “Apple”.
 Syntax:
o strstr(string1, string2);
 Example:
char string1[20] = "Hello ";
char string2[10] = "World";
printf("The substring is: %s\n", strstr(string1,string2));
Output:
World

6) Find a value in string (strrstr())


 This function will find the last occurance of string2 in string1.

GE 6151 Unit – III 15


 Assume string1 as “Apple” and string2 as “Ap”, now the function will return
position of first occurrence of “Ap”, since “Ap” is found in “Apple”.
 Syntax:
o strrstr(string1, string2);
 Example:
 char string1[20] = "Hello world ";
 char string2[10] = "World";
 printf("The substring is: %s\n", strrstr(string1,string2));
o Output:
 World

7) Find a character in string (strchr())


 strchr( ) function returns pointer to the first occurrence of the character in a
given string
 Syntax:
strchr(String,chracter);
 Example:
char string1[15]=”Hello World”;
printf(strchr(string1,’l’));
 Output:
3

8) Duplicate String:
 strdup( ) function in C duplicates the given string
 Syntax:
string2=strdup(string1);
 Example:
char string1=”Hello”;
char string2;
string2=strdup(string1);
printf(“%s”,string2);
 Output:
Hello
9) Find a character in string (strrchr())
 strchr( ) function returns pointer to the last occurrence of the character in a
given string
 Syntax:
strrchr(String,chracter);
 Example:
char string1[15]=”Hello World”;
printf(strrchr(string1,’l’));
GE 6151 Unit – III 16
 Output:
10

10) Reversing a string


 strrev( ) function reverses a given string in C language
 Syntax:
strrev(string1);
 Example:
char name[30] = "Hello";
printf("String after strrev( ) : %s",strrev(name));
 Output: String after strrev( ) : olleH

11) Length of String


 This function will return length of the string.
 Syntax:
strlen(string1);
 Example:
int len;
char array[20]="Hello " ;
len = strlen(array) ;
printf ( "string length = %d " , len ) ;
 Output:
String Length = 5
12) Convert Lower case to Uppercase
 strupr( ) function converts a given string into uppercase
 Syntax:
strlwr(string1);
 Example:
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
 Output:
MODIFY THIS STRING TO UPPER
13) Convert Uppercase to Lower case
 strlwr( ) function converts a given string into lower case
 Syntax:
strupr(string1);
 Example:
char str[ ] = " MODIFY This String To LOwer";
printf("%s\n",strlwr(str));
 Output:
GE 6151 Unit – III 17
modify this string to lower
14) Set character:
 sets all character in a string to given character
 Syntax:
strset(string1,character);
 Example:
char str[ ] = " Hello";
printf("%s\n",strset(str,’#’));
 Output:
#####

15) Set character:


 sets portion of characters in a string to given character.
 Syntax:
strnset(string1,character,number);
 Example:
char str[ ] = " Hello";
printf("%s\n",strnset(str,’#’,4));
 Output:
####0w

Example: Palindrome of string data


#include <stdio.h>
#include <conio.h>
#include <string.h>
int r;
char s1[15], s2[15];
void main()
{
clrscr();
printf("Enter a string :");
scanf("%s", s1);
strcpy(s2,s1); //copy's s1 to another variable s2
strrev(s2); //reverse the value of s2
printf("%s\n", s1);
printf("%s\n", s2);
r= strcmp(s1,s2);
if (r==0)
printf("It is a Palindrome %s\n", s1);
else
printf("It is not a Palindrome %s\n", s1);

GE 6151 Unit – III 18


getch();
}

Simple Programs:
Binary Search
#include <stdio.h>
void main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last)


{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}

if (first > last)


printf("Not found! %d is not present in the list.\n", search);

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

GE 6151 Unit – III 19


int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
}

for (c = 1 ; c <= n - 1; c++)


{
d = c;
while ( d > 0 && array[d] < array[d-1])
{
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c <= n - 1; c++)


{
printf("%d\n", array[c]);
}
}

Selection Sort:
#include <stdio.h>
void main()
{
int array[100], n, c, d, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;

GE 6151 Unit – III 20


for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}

printf("Sorted list in ascending order:\n");

for ( c = 0 ; c < n ; c++ )


printf("%d\n", array[c]);
}

Quick Sort:

#include<stdio.h>
void quicksort(int [10],int,int);

void main()
{
int x[20],size,i;
printf("Enter size of the array: ");
scanf("%d",&size);
printf("Enter %d elements: ",size);
for(i=0;i<size;i++)
scanf("%d",&x[i]);
quicksort(x,0,size-1);
printf("Sorted elements: ");
for(i=0;i<size;i++)
printf(" %d",x[i]);
}

void quicksort(int x[10],int first,int last)


{
int pivot,j,temp,i;

GE 6151 Unit – III 21


if(first<last)
{
pivot=first;
i=first;
j=last;

while(i<j)
{
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j)
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}

temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);

}
}

GE 6151 Unit – III 22

You might also like