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

Module - 3 C Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 37

MODULE-3

Arrays & Strings


NOTE:

THIS PDF CONSISTS OF A SEPARATE NOTES FOR ARRAY AND


STRINGS
3

Arrays & Strings


Chapter Checklist
ARRAYS

 Introduction
 Classification of arrays
 One Dimensional Array
 Declaration of One Dimensional Array
 Initialization of One Dimensional Array
 Processing an One Dimensional Array
 Accessing Elements of an Array
 Two Dimensional Arrays
 Declaration of Two dimensional Arrays
 Initialization of Two dimensional Arrays
 Processing a Two Dimensional Array
 Multi-Dimensional arrays
 Advantages of Arrays
INTRODUCTION:
An array is a group of related data items that share a common name
and each individual data items in an array is referenced by a subscript or
index enclosed in a pair of square brackets. This subscript indicates the
position of an individual data item in an array and the subscript must be
either an unsigned integer constant or integer variable or integer expression.
All these elements are stored in consecutive memory locations.

For example, we can define an array name “student” to represent a set


of marks of a group of students.

CLASSIFICATION OF ARRAYS:

Arrays are classified into two types. They are


1. One dimensional array
2. Multi-dimensional array

Multi-dimensional arrays are further classified into two dimensional, three


dimensional and so on an N-dimensional arrays.

The dimensionality of an array is determined by the number of subscripts


present in the given array.

ONE DIMENSIONAL ARRAY:

Arrays which have elements with single subscript are known as one
dimensional array or single subscripted variable.

DECLARATION OF A ONE DIMENSIONAL ARRAY:


An array must be declared before it is used. It is declared by giving the
type of its elements, name and size. The general form of one dimensional array
declaration is as follows

data_type array_name[ size ];


where,

data_type ⭢ specifies the data type of elements to be stored in the array such
as int, float, char or double
array_name ⭢ name of the array which follows the rules of forming an
identifier.
size ⭢ The maximum number of elements that can be in the array.
Examples

int marks[50];
flaot height[20];
char name[30];
Here, the first declaration creates an array name “marks” 50 integers
elements. The second declaration creates “height” as an array of 20 real
elements and third declaration creates “name” as an array of 30 characters
long.

Note
1) The subscript of an array can be positive integer constant or integer
variable or integer expression.
2) In C, the subscript value ranges from 0 to maximum size-1
3) C does not perform bound checking. Therefore, the maximum subscript
appearing in a program for an array should not exceed the declared one.

INITIALIZATION OF ONE DIMENSIONAL ARRAY:

The elements of an array can be initialized in the declaration itself. The


general form of initialization of one dimensional array is as follows

data_type array_name [ size ] = { list of values };


where,

data_type ⭢ specifies the data type of elements to be stored in the array such
as int, float, char or double
array_name ⭢ name of the array which follows the rules of forming an
identifier.
size ⭢ The maximum number of elements that can be in the array.
list of values ⭢ The values of the array elements separated by commas.
All these initial values must be constants.

Examples
int marks[5]={56,35,49,70,88};
In this declaration, marks [0] in initialized to 56, marks [1] is initialized to 35
and so on.

Note
1) There must be at least one initial value between the braces.
2) If you specify too few values, the remaining array elements are initialized
to zero.
3) If you specify too many values, an error message will be displayed.
4) There is no convenient way to initialize only selected array elements.
5) There is no short cut method for initializing a large number of array
elements.

PROCESSING ONE DIMENSIONAL ARRAY:

C does not support any operation that is to be performed on the entire


array. That is the whole array cannot be processed as a single unit (element).
But, it allows us to perform certain operations on an element by element basis.

ACCESSING ELEMENTS OF AN ARRAY:


To access an individual element, we write the array name followed by
subscript enclosed in square brackets. The subscript specifies which element
to access.
Ex: a[5], where a is array name and 5 within square brackets represents
position of the element to be accessed

Ex: C program to read and print the one dimensional array

#include<stdio.h>
main( )
{
int a[100], i, n;
printf(“\nEnter total number of elements in array :”);
scanf(“%d”,&n);
printf(“\nEnter the array elements :\n”);
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]);
}
Ex: C program to find maximum, minimum and average weight of all the newly
born babies in a hospital

#include<stdio.h>
main( )
{
int i, n;
flaot w[20], max, min, average, sum;
clrscr( );
printf(“\nEnter number of babies :”);
scanf(“%d”,&n);
printf(“\nEnter weight of babies in kgs\n”);
for(i=0; i<n; i++)
scanf(“%f”,&w[i]);
max = w[0];
min = w[0];
sum = w[0];
for(i=1; i<n; i++)
{
if(w[i] > max)
max = w[i];
else if(w[i] < min)
min = w[i];
sum = sum + w[i];
}
average = sum/n;
printf(“\nMaximum weight = %f kgs”,max);
printf(“\nMinimum weight = %f kgs”,min);
printf(“\nAverage weight = %f kgs”,average);
getch( );
}
Ex: Write a C program to generate N Fibonacci series using one dimensional
array.

#include<stdio.h>
main()
{
int a[50],n,i ;
clrscr();
printf(“Enter the value of N\n”);
scanf(“%d”, &n);
a[0]=0;
a[1]=1;
for(i=0; i<n; i++)
{
a[i]=a[i-2]+a[i-1];
}
printf(“Fibonacci series is:\n”);
for(i=0; i<n; i++)
{
printf(“%d\t”, a[i]);
}
getch();
}
Output:
Enter the value of N 6
Fibonacci series is 11235
TWO-DIMENSIONAL ARRAYS:

Arrays which have elements with two subscripts are known as two
dimensional array or two subscripted variable. or

It is an ordered table of homogenous elements. Each element is


accessed by two subscripts. The first refers to the row in which the elements
lie and the second to the column number in that row.

DECLARATION OF TWO DIMENSIONAL ARRAY:

The syntax for declaring a two dimensional array in C is as follows: -

type array_name [rowsize][colsize];

where,
type ⭢ Specifies the data type of elements to be stored in the
array such as int, float etc
array_name ⭢ Name of the array, which follows the rules of the identifiers.
rowsize ⭢ Maximum number of rows
colsize ⭢ Maximum number of columns

Examples: -

int marks [5][5];


float matrix[3][3];
Here, the first declaration creates an array name ‘marks’ with five rows and
four columns of twenty integer elements. Rows may represent students and
columns the marks of student. The second declaration creates an array named
‘matrix’ with three rows and columns of nine real elements.
Note: -The elements of two dimensional array are stored in row major
form i,e., row by row.

INITIALIZATION OF TWO DIMENSIONAL ARRAY:

The syntax for initializing a two dimensional array in declaration is as follows:

type array_name[rowsize][colsize] = {list of values};

Where,

type ⭢ Specifies the data type of elements to be stored in the


array.
array_name ⭢ Name of the array, which follows the rules of identifiers.
rowsize & colsize ⭢ Maximum number of rows and columns
respectively.
list of values ⭢ The initial values of the array elements separated by
comma

Example: - int matrix[2][3] = {10,20,30,40,50,60};

Here, the elements of the matrix are initialized as

follows:

matrix[0][0] = 10 matrix[0][1] = 20 matrix[0][2] = 30

matrix[1][0] = 40 matrix[1][1] = 50 matrix[1][2] = 60

The above initialization statement can be equivalently written as

in matrix[2][3] = {{10,20,30},{40,50,60}};
Note: -

1) The number of sets of initial values must be equal to the number of rows
in the array.
2) If the values are minimum in initializing set, they are automatically set to
zero.
3) If the number of initial values in each initializing set is more than the
number of the corresponding row elements then there will be a
compilation error.

PROCESSING A TWO DIMENSIONAL ARRAY:

In general, to process each and every elements of a two dimensional


array is done by using two loops [nested]. The first loop is used to change the
row values [row indices] and the second loop is used to change the column
values [column indices].

Two dimensional arrays are usually called as matrix. Certain kind of


operations can be performed on matrices by using two dimensional arrays
such as: -

1) Reading and printing elements of matrix


2) Addition and Subtraction of two matrix
3) Multiplication of two matrix
4) Transpose of a matrix
5) Comparing corresponding elements of two matrices.
Ex: Write a C program to read and display the elements of a given matrix.

#include<stdio.h>
main()
{
int a[10][10],m,n,i,j;
clrscr();
printf(“Enter matrix order\n”);
scanf(“%d%d”, &m, &n);
printf(“Enter matrix elements\n”);
for(i=0; i<m; i++)
{
For(j=0; j<m; j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“The matrix elements are :\n”);
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
printf(“%d\t”, a[i][j]);
printf(“\n’);
}
}
getch();
}
Output:
Enter matrix order 22
Enter matrix elements 05
07
The matrix elements are
:
15
27

Ex: Write a C program to find sum of given two matrices.

#include<stdio.h>
main()
{
int a[10][10], b[10][10], c[10][10] m,n,i,j;
clrscr();
printf(“Enter matrix orders\n”); scanf(“%d
%d”, &m, &n);
printf(“Enter first matrix elements\n”);
for(i=0; i<m; i++)
{
For(j=0; j<m; j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“Enter second matrix elements\n”);
for(i=0; i<m; i++)
{
For(j=0; j<m; j++)
{
scanf(“%d”, &b[i][j]);
}
}

printf(“The Resultant matrix is :\n”);


for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
C[i][j]=a[i][j]+b[i][j];
printf(“%d\t”, c[i][j]);

}
printf(“\n”);
}
getch();

}
Output:
Enter matrix orders 22
Enter first matrix elements 24
35
Enter second matrix elements
05
11
The Resultant matrix is 29
86

Ex: Write a C program to find the difference between two matrices.

#include<stdio.h>
main()
{
int a[10][10], b[10][10], c[10][10] m,n,i,j;
clrscr();
printf(“Enter matrix orders\n”); scanf(“%d
%d”, &m, &n);
printf(“Enter first matrix elements\n”);
for(i=0; i<m; i++)
{
For(j=0; j<m; j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“Enter second matrix elements\n”);
for(i=0; i<m; i++)
{
For(j=0; j<m; j++)
{
scanf(“%d”, &b[i][j]);
}
}
printf(“The Resultant matrix is :\n”);
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
C[i][j]=a[i][j]-b[i][j];
printf(“%d\t”, c[i][j]);

}
printf(“\n”);
}
getch();

}
Output:
Enter matrix orders 22
Enter first matrix elements 64
45
Enter second matrix elements 33
11
The Resultant matrix is 31
34

MULTI-DIMENSIONAL ARRAYS:

Multi-dimensional arrays are defined like one-dimensional arrays


except that a separate of square bracket is required for each subscript. Thus
two dimensional array will require two pairs of square brackets. Three
dimensional arrays will require three pairs of brackets and so on.
or
In an array if subscripts are more than two is called multidimensional array.
The syntax is:

data_type array_name[s1][s2][s3]..........[sn] ;

where sn is the size of nth dimension.

ADVANTAGES OF ARRAYS:
1. Arrays are use d to store similar data elements.
2. Arrays are used to represent matrices in memory.
Chapter Checklist

HANDLING OF CHARACTER STRINGS

 String Manipulation
 String Declaration
 String Initialization
 Reading and Writing Strings
 Reading Strings
 Writing Strings
 Putting Strings Together
 Comparison of Two strings
 String Handling Functions (String Operations)
 String Length (Strlen)
 String Copy (Strcpy)
 String Reverse (Strrev)
 String Lower (Strlwr)
 String Upper (Strupr)

INTRODUCTION:
A string is an array of characters. Any group of characters defined
between pair of double quotation marks is a string constant.
Ex: “My Name is Raju”

Character strings are often used to build meaningful readable program.

Definition:
Sequence of characters enclosed between two quote marks is
called string or string constant.

STRING MANIPULATION:

Character string in C are stored as one-dimensional character arrays;


i.e. successive characters are stored in contiguous memory locations. A string
is defined as a character array that is terminated by a null character ‘\0’.

Ex: char name[12];

When the string “PROGRAMMING” is assigned to a string variable name, the


characters are stored in the memory as follows.

P R O G R A M M I N G \0

STRING DECLARATION:
Like integer and float variables, we can also declare string variables for
storing string values. The syntax for string declaration is:

char str_var[size];

Where char is a key word for character data type.


str_var is a string variable name.
size is the number of characters in the string.

Ex: char name[20] ;

Will reserve a block of 20 20 bytes to store the elements of name. Each


element can hold a character and its contents can be accessed by its subscript
number.

STRING INITIALIZATION:

Once you declare an array, you can also assign the array initial values
when you declare it.

Ex: Consider the following three cases of string initialization.

Case – I:

char name[9]=”COMPUTER” ;
Will create nine elements with the following

values. C O M P U T E R \0

Case –II:
char name[ ]=”COMPUTER” ;

Case –III:
char name[9]={‘C’ , ’O’ , ’M’ , ‘P’ , ‘U’ ,’T’ , ‘E’ , ‘R’ , ‘\0’ } ;

READING AND WRITING STRINGS:


READING STRINGS:

A string or group of strings can be read from input device using the
following functions.
1. scanf() with %s format .
2. gets() function.
3. getchar() function.

WRITING STRINGS:

A string or group of strings can be written to the monitor using the


following output functions.

1. printf( ) with %s format.


2. puts( ) function.
3. putchar( ) function.

Ex: Write a C program to read and print a given string.


#include<stdio.h>
main()
{
char name[20];
clrscr();
printf(“Enter given string\n”);
gets(name);
printf(“The entered string is :\n”, name);
getch();
}
Output:
Enter given string Dinesh Singanamala The entered string is Dinesh Singanamala

PUTTING STRINGS TOGETHER (STRING CONCATNATION):

Combining two strings together is called putting strings together or


string concatenation. The strcat( ) function joins two strings together.
The general form is:

strcat(string1, string2) ;

Where string1 and string2 are character arrays. When strcat() is


executed string2 is appended to string1. The information of string2 is
unchanged.

Ex: strcpy(string1,”Dinesh”);
strcpy(string2,” Singanamala”);
printf(“%s”, strcat(string1,string2));

Here the value of string1 becomes Dinesh Singanamala , but the value of
string2 Sinaganamala remains same.
There for the output of the above program segment

is: Dinesh Singanamala


Ex: Write a C program to combine two strings using the function strcat() .

#include<stdio.h>
#include<string.h>
main()
{
char str1[20]=”Data” ;
char str2[20]=”Base”
; char str3[20] ;
clrscr();
str3=strcat(str1,str2);
printf(“After string concatenation : %s”, str3);
getch();
}

Output:
After string concatenation : DataBase

COMPARISON OF TWO STRINGS:

In C we cannot directly compare the value of two strings. Like if


(string1==string2) is invalid. And also if (string1==”Dinesh”) invalid.
Strcmp() function is used to compare two strings whether they are equal or
not. Strcmp() returns the value 0 if two strings are equal otherwise a non-zero
value is returned.

The syntax is :
strcmp (string1,string2)
Where string1 and string2 may be string variables or string constants.
Note:
Some compliers returns a negative value if string1 is less than string2
alphabetically and a positive value if string1 is greater than string2
alphabetically.

Ex:
1. strcmp(“ BALLARI” , “BALLARI”)
will return 0 because two strings are equal.
2. strcmp(“Their” , “There”)
will return -9 which is the numeric difference between Ascii i
and Ascii r
3. strcmp(“There” , “Their”)
will return 9 which is the numeric difference between Ascii r
and Ascii i
4. strcmp(“The” , “the”)
will return -32 which is the numeric difference between Ascii T
and Ascii t .

Ex: Write a C program to compare two string variable values using library
function strcmp().

#include<stdio.h>
#include<string.h>
main(()
{
char str1[20], str2[20];
clrscr();
printf(“Enter string1 \n”);
gets(str1);
printf(“Enter string2 \n”);
gets(str2);
if (strcmp(str1,str2)==0)
{
printf (“ Given two strings are equal\n”);
}
else
{
printf (“ Given two strings are not equal\n”);
}

getch();
}

Output 1:
Enter string1 Ballari
Enter string2 Ballari
Given two strings are equal

Output 2:
Enter string1 Ballari
Enter string2 Gadag
Given two strings are not equal

The strcmpi() function :


This is same as strcmp() , which compare two strings , but not case
sensitive.
Ex : strcmpi(“THE” , ‘the”) will return zero.

i.e It will consider both are same and hence it returns 0.

STRING HANDLING FUNCTIONS (STRING OPERATIONS):

In C the followings are some important string functions.


1. String Length ( strlen )
2. String Copy (strcpy)
3. String Reverse (strrev)
4. String Lower (strlwr)
5. String Upper (strupr)

STRING LENGTH (STRLEN):

This function counts and returns the total number of characters in a


string. The length does not include the NULL character.
The syntax is:
variable=strlen (string) ;

Where variable is any integer variable which receives the value of the length of
the string.

Ex: n=strlen(“Dinesh”);
Here the value of n is 6.
Ex: write a C program to find length of a given string using strlen() function.

#include<stdio.h>
#include<string.h>
main()
{
char name[20];
int length;
clrscr();
printf(“Enter given string\n”);
gets(name);
length=strlen(name);
printf(“Length of string=%d\n”, length);
getch();
}

Output:
Enter given string Computer
Length of string=8

STRING COPY (STRCPY):

The strcpy function works almost like string assignment operator.

The syntax is:


strcpy(string1, string2);

here it assigns the contents of string2 to string1. String2 may be a character


array variable or a string constant.

Ex : char name[30];
strcpy(name, “ballari”);

In the above example, the characters “ballari”are assigned to the string called
name.

Ex: Write a C program to copy the content of one string to another string using
strcpy function.

#include<stdio.h>
#include<string.h>
main()
{
char orgnl[20],dupli[20];
clrscr();
printf(“ Enter a string\n”);
gets (orgnl);
srtcpy (dupli , orgnl);
printf(“ Given string =%s\n”, orgnl);
printf(“ Copied string=%s\n”, dupli);
getch();
}

Output:
Enter a string Ballari
134
Given string = Ballari
Copied string= Ballari
STRING REVERSE (STRREV):

This function reverses the characters in a string. The syntax is:

strrev(string);

where string is variable or string constant.

Ex: strrev(“ballari”);

wll returns irallab


strrev (“ gadag”); returns gadag

Ex:Write a C program to check whether the given word is palindrome or not.


(If the given word is equal to its reverse then such word is called palindrome
word. For example MADAM , GADAG, LIRIL , MALAYALAM etc. )

#include<stdio.h>
#include<string.h>
main()
{
char str1[20], str2[20];
printf(“Enter Given word\n”);
gets(str1);

13
5
strcpy(str2,str1);
strrev(str2);
if(strcmp(str1,str2)==0)
printf(“ The given word is polindrom\n”);
else
printf(“The given word is not polindrom\n”);
getch();
}

Output 1:
Enter Given word malayalam
The given word is polindrom

Output 2:
Enter Given word ballari
The given word is not polindrom

STRING LOWER (STRLWR):

This function converts all characters in a string from upper case to


lowercase. The syntax is:
strlwr(string);

Ex: strlwr(“DINESH ”);


will returns dinesh

STRING UPPER (STRUPR):

13
6
This function converts all characters in a string from lowercase to
uppercase. The syntax is:

strupr(string);

Ex : strupr(“ballari”);

will returns BALLARI.

13
7
Exam Practice

I. Short Answer Type Questions [2 Marks]


1) What is an array?
2) What are the different types of arrays?
3) What is the difference between one & two dimensional arrays?
4) Write the syntax of one dimensional array declaration.
5) Write the syntax of one dimensional array initialization.
6) Write the syntax of two dimensional array declaration.
7) Write the syntax of two dimensional array initialization.
8) Write the advantages of arrays.
9) What is string?
10) Write the syntax of strcat) function.
11) What are the possible results of strcmp() function.

II. Short Answer Type Questions [5 Marks]


1) What is array? Write the different types of arrays.
2) With example explain one dimensional array initialization.
3) With example explain initialization of two dimensional arrays.
4) Write a C program to read and display the elements of a given matrix.
5) With example explain string initialization.
6) With example explain the working of strcmp() function.
7) With example explain the working of strcat() function.
8) Write a C program to check the given word is polindrom or not.

13
8
III. Essay Answer Type Questions [15 Marks]

1) With example explain the working of one and two dimensional


arrays declaration and initialization.
2) Write a C program to find sum of given two matrices.
3) Write a C program to find difference of given two matrices.
4) Explain string functions with suitable examples.
5) Write a C program to copy the content of one string to another string
using strcpy() function.

13
9
14
0

You might also like