0% found this document useful (0 votes)
37 views34 pages

C UNIT 3 Notes

Uploaded by

ff17062007
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)
37 views34 pages

C UNIT 3 Notes

Uploaded by

ff17062007
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/ 34

PROGRAMMING IN C

UNIT III-ARRAYS AND STRINGS

Arrays – Initialization – Declaration – One dimensional and two

imensional arrays - String- String operations –Arrays of strings.

ARRAYS

Definition:
An array is a derived data type. It is a collection of data elements of similar
data types. The data elements are stored in contiguous memory location.

Syntax :
datatype arrayname[size]
int a[10];
where

int is the data type of the elements.


a is the array name.
[10] is the index which denotes the array contains 10 data elements.

ARRAY INITIALIZATION:
The array can be initialized with elements while declaring the array.
Example:
int a[5]={1,2,3,4,5}
Here, 5 data elements are stored in the array called “a”. The array elements
are stored sequentially in separate locations.
The array elements are called as below:
A[0] refers to 1st element 1
A[1] refers to 1st element 2
A[2] refers to 1st element 3
A[3] refers to 1st element 4
1
A[4] refers to 1st element
CHARACTERISTICS OF AN ARRAY:

1. All the data elements share the same name, and they are distinguished
from one another with the help of an element number.
2. Any particular element of an array can be modified separately without
disturbing other elements.
3. The element number in an array plays major role for calling each
element.

CLASSIFICATION OF ARRAY:

Arrays can be classified into major types.

1. One-dimensional Array.
2. Two dimensional Array.

3. Multi dimensional Array.

1. One-Dimensional Array:

The array elements are arranged in rows or columns. The data are stored
in continuous memory location.

Example:

int a[5]={1,2,3,4,5}

Address 2000 2004 2008 2012 2016


Element a[0] a[1] a[2] a[3] a[4]
Values 1 2 3 4 5

Example Program :

#include<stdio.h>
void main()
{
int a[10],n,i;
clrscr();
printf("\nEnter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements into the array one by one");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nThe array elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

OUTPUT:

Enter the size of the array5

Enter the elements into the array one by one


1
2
3
4
5

The array elements are


1 2 3 4 5

SUM OF ELEMENTS IN AN ARRAY:


#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,j,n,sum=0;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("\nThe sum of the elements in the array is %d",sum);
getch();}
OUTPUT:

Enter the no. of elements in the array4


Enter the elements in the array
4
3
2
1

The sum of the elements in the array is 10

LARGEST ELEMENT IN AN ARRAY

#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,n,max;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
printf("\nThe largest element is %d",max);
getch();
}

output:
Enter the no. of elements in the array4
Enter the elements in the array
6
7
5
45
The largest element is 45
SEARCHING AN ELEMENT IN AN ARRAY
Linear search

#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,j,n,x;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the element to be searched in the array");
scanf("%d",&x);
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("\nThe element is found");
break;
}
}
if(i==n)
{
printf("\nThe element is not found");
}
getch();
}
OUTPUT:
Enter the no. of elements in the array 4
Enter the elements in the array
2
1
4
5
Enter the element to be searched in the array 2
The element is found
SORTING OF AN ARRAY

#include <stdio.h>
#include <conio.h>
void main()
{
int a[25],i,j,n,temp;
clrscr();
printf("\nEnter the no. of elements in the array");
scanf("%d",&n);
printf("\nEnter the elements in the array\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nThe sorted array is \n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

OUTPUT:

Enter the no. of elements in the array6

Enter the elements in the array


4
1
7
4
7
2

The sorted array is


1 2 4 4 7 7
2.Two-Dimensional Array:

The array elements are thought to be stored in the form of rows and columns.

Syntax :
datatype arrayname[row
size][column size];
int a[3][3];

Diagrammatic representation:

Column 1 Column 2 Column 3


Row 1 a[0][0] a[0][1] a[0][2]
Row 2 a[1][0] a[1][1] a[1][2]
Row 3 a[2][0] a[2][1] a[2][2]

The above arrangement of array elements is only for understanding.


Physically array elements are stored in continuous memory locations. The
two dimensional array is a collection of one-dimensional array, which are
placed one after another.

Example Program:

#include<stdio.h>
void main()
{
int a[10][10],n,i,j;
clrscr();
printf("\nEnter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements into the array one by one");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nThe array elements are\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
getch();
}

OUTPUT:

Enter the size of the array2

Enter the elements into the array one by one


1
2
3
4

The array elements are


1 2
3 4

PROGRAMS IN TWO DIMENSIONAL


ARRAY

MATRIX ADDITION

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n;
clrscr();
printf("\nEnter the no. of rows in the matrix A");
scanf("%d",&m);
printf("\nEnter the no. of columns in the matrix A");
scanf("%d",&n);
printf("\nEnter the elements in the matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements in the matrix B");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nThe Resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

OUTPUT:

Enter the no. of rows in the matrix2

Enter the no. of columns in the matrix2

Enter the elements in the matrix A


1
1
1
1

Enter the elements in the matrix B


1
1
1
1

The Resultant matrix is


2 2
2 2
MATRIX MULTIPLICATION

#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,m,n,p;
clrscr();
printf("\nEnter the no. of rows in the matrix A");
scanf("%d",&m);
printf("\nEnter the no. of columns in the matrix A");
scanf("%d",&n);
printf("\nEnter the no. of columns in the matrix B");
scanf("%d",&p);
printf("\nEnter the elements in the matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the elements in the matrix B");
for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nThe Resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<p;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT:
Enter the no. of rows in the matrix A2

Enter the no. of columns in the matrix A2

Enter the no. of columns in the matrix B2

Enter the elements in the matrix A


1
1
1
1

Enter the elements in the matrix B


1
1
1
1

The Resultant matrix is


2 2
2 2

3.Multi Dimensional Array:


In C programming, you can create an array of arrays. These arrays are
known as multidimensional arrays.

int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}} };
Three-dimensional:

#include <stdio.h>
void main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

Advantages of Array in C:
Arrays have a great significance in the C language. They provide several
advantages to the programmers while programming. Some of them are:

⮚ Arrays make the code more optimized and clean since we can store
multiple elements in a single array at once, so we do not have to write or
initialize them multiple times.
⮚ Every element can be traversed in an array using a single loop.
⮚ Arrays make sorting much easier. Elements can be sorted by writing a few
lines of code.
⮚ Any array element can be accessed in any order either from the front or
rear in O(1) time.
⮚ Insertion or deletion of the elements can be done in linear complexity in
an array.
Disadvantages or Limitations of Arrays in C:
⮚ Array is Static Data Structure.
⮚ We cannot change the size of array in run-time.
⮚ We must know in advance that how many elements are to be stored in
array.
⮚ Only elements of same data types can be stored in an array. We cannot
store elements of multiple data types in a single array.
⮚ As Array elements are stored in consecutive memory locations. So,
insertions and deletions of an element is time consuming as we have to
shift other elements one position ahead or back respectively.
⮚ C doesn't perform any array index bound checking. In and array of size N,
you can write code to access N+5th element without getting error. When
we try to access elements from outside of array boundaries, we will get
garbage value.
⮚ As we cannot change the size of an array, developers generally declares large
arrays to handle any future data expansion. This ends up in creating large
arrays, where most of the space is unused.

STRING HANDLING:

In C language, the group of characters, digits and symbols


enclosed within quotation marks are called strings. The string is always
declared as character arrays. Every string is terminated with ‘\0’ (NULL)
character. The NULL character is a byte with all bits at logic zero.
DECLARATION & INITIALIZATION OF STRING

The string can be initialized as follows:

char name[]=”India”;

The C compiler inserts the NULL character automatically at the end of the
string. So, initialization of NULL character is not essential.
Display of strings with different formats:

Let the character array be

Char name[]=”computer”;

S.No Statement Output Meaning


1. printf(“%s”,name); Computer The whole string is
displayed
2. printf(“%.5s”,name); Compu Only 5 characters are
displayed
3. printf(“%-10.4s”,name); Comp 4 characters from the
left are displayed

Read & write Strings in C using Printf() and Scanf() functions


#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");


scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Read & Write Strings in C using gets() and puts() functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

/* Console display using puts */


puts("Enter your Nick name:");

/*Input using gets*/


gets(nickname);

puts(nickname);

return 0;
}

STRING STANDARD FUNCTIONS


Every C compiler supports a large number of string handling library
functions. Some of the standard string functions are given below:

S.No Function Description


1. strlen( ) Determines the length of the string

2. strcpy( ) Copies a string from source to destination

3. strcmp( ) Compares the characters of two strings.

4. strcat( ) Appends source string to destination string

5. strrev( ) Reverses the string

6. strupr( ) Converts s to all uppercase

7. strlwr( ) Converts string to all lowercase

6. strncpy( ) Copy the specified number of characters

7. strncmp( ) Compare two string upto given n character

8. stricmp( ) Compare two strings alphabetically


without case sensitivity

9. strncat( ) Appends a string to the end of another


string up to n

10. strtok( ) Breaks a string into tokens by delimiters

C String function – strlen


It returns the length of the string without including end character
(terminating char ‘\0’).

Syntax: strlen(string)

Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "Welcome";
printf("Length of string str1: %d", strlen(str1));
return 0;
}

Length of string str1: 7


OUTPUT:

C String function – strcpy


The strcpy() function copies the string pointed by
source (including the null character) to the destination.

Syntax:
strcpy(destination, source);

Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30];
char s2[30] = "Good Day!";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("%s", s1);
return 0;
}

OUTPUT: Good Day

C String function – strcmp


It compares the two strings and returns an integer value. If both
the strings are same (equal) then this function would return 0 otherwise
it may return a negative or positive value based on the comparison.
Syntax:
int strcmp (const char* str1, const char* str2);

Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "Goodday";
char s2[20] = "Welcome";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}

Output:
string 1 and 2 are different
C String function – strrev

strrev( ) function reverses a given string in Clanguage.


Syntax : strrev(string)

Example of strrev:
#include<stdio.h>
#include<string.h>

int main()
{
char name[30] = "Hello";

printf("String before strrev( ) : %s\n",name);


printf("String after strrev( ) : %s",strrev(name));

return 0;
}
Output:
String before strrev( ) :
Hello
String after strrev( ) :
olleH

C String function – strlwr

strlwr( ) function converts a given string into lowercase.

Syntax
strlwr(string)

Example of strlwr:

#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
Output:
modify this string to lower

C String function – strupr

strupr( ) function converts a given string into uppercase.

Syntax
strupr(string)

Example of stuprr:

#include<stdio.h>
#include<string.h>

int main()
{
char str[ ] = "Modify This String To Upper";

\ printf("%s\n",strupr(str));
return 0;
}
Output:
MODIFY THIS STRING TO UPPER
STRING OPERATIONS USING PREDEFINED FUNCTIONS
#include <stdio.h>
#include <conio.h>
#include <string.h>
void str_len();
void str_comp();
void str_con();
void str_cpy();
char a[25],b[25],c[50];
void main()
{
int choice;
clrscr();
printf("1. finding the length of the string");
printf("\n2. string comparison");
printf("\n3. string copy");
printf("\n4. String concatenate");
printf("\nEnter ur choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
str_len();
break;
case 2:
str_comp();
break;
case 3:
str_cpy();
break;
case 4:
str_con();
break;
default:
exit(1);
}
getch();
}

void str_len()
{
int n;
fflush(stdin);
printf("\n Enter the string");
gets(a);
n=strlen(a);
printf("\nThe length of the string is %d",n);
}

void str_comp()
{
fflush(stdin);
printf("\n Enter the I string");
gets(a);
printf("\nEnter the II String");
gets(b);
if(strcmp(a,b)==0)
printf("\n The two strings are identical");
else
printf("\nThe strings are different");
}

void str_cpy()
{
fflush(stdin);
printf("\n Enter the string");
gets(a);
strcpy(b,a);
printf("\nThe copied string :");
puts(b);
}

void str_con()
{
fflush(stdin);
printf("\n Enter the I string");
gets(a);
printf("\nEnter the II String");
gets(b);
strcat(a,b);
printf("\nThe concatenated string is : ");
puts(a);
}

OUTPUT:
1. finding the length of the string
2. string comparison
3. string copy
4. String concatenate

Enter ur choice 1

Enter the string computer

The length of the string is 9

STRING OPERATIONS WITHOUT USING PRE-DEFINED


FUNCTIONS

#include <stdio.h>
#include <conio.h>
#include <string.h>
void str_len();
void str_con();
void str_cpy();
char a[25],b[25],c[50];
void main()
{
int choice;
clrscr();
printf("1. finding the length of the string");
printf("\n2. string copy");
printf("\n3. String concatenate");
printf("\nEnter ur choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
str_len();
break;
case 2:
str_cpy();
break;
case 3:
str_con();
break;
default:
exit(1);
}
getch();
}
void str_len()
{
int n=0,i;
fflush(stdin);
printf("\n Enter the string");
gets(a);
for(i=0;a[i]!='\0';i++)
n++;
printf("\nThe length of the string is %d",n);
}

void str_cpy()
{
int i;
fflush(stdin);
printf("\n Enter the string");
gets(a);
for(i=0;a[i]!='\0';i++)
b[i]=a[i];
printf("\nThe copied string :");
puts(b);
}

void str_con()
{
int n=0,i;
fflush(stdin);
printf("\n Enter the I string");
gets(a);
printf("\nEnter the II String");
gets(b);
for(i=0;a[i]!='\0';i++)
{
n++;
}
for(i=0;b[i]!='\0';i++)
{
a[n++]=b[i];
}
printf("\nThe concatenated string is : ");
puts(a);
}
OUTPUT:

1. finding the length of the string


2. string copy
3. String concatenate
Enter ur choice 2

Enter the string computer

The copied string : computer

TWO DIMENSIONAL CHARACTER ARRAY

Like a two-dimensional integer array, a character array can be a two


dimensional array. A collection of strings can be stored in a two dimensional
array.

The syntax is:

Char a[2][10];

Here, The array accommodates 2 strings with 9 characters long. The last
location is allotted for storing the NULL character.

Example Program;

#include<stdio.h>
void main()
{
char a[4][10],i,j,n;
clrscr();
printf("\nEnter the number of names to be stored in the array");
scanf("%d",&n);
printf("\nEnter the names one by one\n");
for(i=0;i<n;i++)
{
fflush(stdin);
gets(a[i]);
}
printf("\nThe names are\n");
for(i=0;i<n;i++)
{
puts(a[i]);
printf("\n");
getch();
}

OUTPUT:

Enter the number of names to be stored in the array3

Enter the names one by one


arthi
archana
kanimozhi

The names are


arthi
archana
kanimozhi

SORTING OF NAMES IN A TWO DIMENSIONAL CHARACTER


ARRAY

#include <stdio.h>
#include <conio.h>
void main()
{
char a[25][25],i,j,n,temp[20];
clrscr();
printf("\nEnter the no. of strings in the array");
scanf("%d",&n);
printf("\nEnter the strings in the array\n");
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(a[i],a[j])>0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
printf("\nThe sorted strings in the array is \n");
for(i=0;i<n;i++)
{
printf("%s\n",a[i]);
}
getch();
}

OUTPUT:

Enter the no. of strings in the array3


Enter the strings in the array
cse
ece
it

The sorted strings in the array is


cse
ece
it

Search a String in the List of Strings


#include<stdio.h>
#include<string.h>
int main()
{
char str[20][50], s1[50];
int n, i, found=0;

printf("Enter how many string (names): ");


scanf("%d", &n);

printf("Enter %d strings:\n", n);


for(i=0; i<n; i++)
{
scanf("%s", str[i]);
}

printf("Enter a string to search: ");


scanf("%s", s1);
for(i=0; i<n; i++)
{
if(strcmp(s1, str[i]) == 0)
{
found=1;
printf("Found in row-%d\n", i+1);
}
}

if(found==0) printf("Not found");


return 0;
}

Output for the different


test-cases:-

Enter how many string


(names): 5
Enter 5
strings: Java
HTM
L
Pytho
n C++
Programmi
ng
Enter a string to search:
Python
Found in
row-3

Enter how many string


(names): 3
Enter 3
strings: C
C+
+
.NE
T
Enter string to search:
Java
Not
found

************

You might also like