0% found this document useful (0 votes)
10 views

PWC Unit-3 (Arrays and Strings)

Unit 3 of the Basics of Logic Development course covers Arrays and Strings, detailing the types of arrays (one-dimensional, two-dimensional, and multidimensional) and their declarations, initializations, and advantages/disadvantages. It also includes string handling, input/output operations, and built-in string functions in C. The unit provides solved programming examples to illustrate the practical application of arrays and strings.

Uploaded by

akbarikavya13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

PWC Unit-3 (Arrays and Strings)

Unit 3 of the Basics of Logic Development course covers Arrays and Strings, detailing the types of arrays (one-dimensional, two-dimensional, and multidimensional) and their declarations, initializations, and advantages/disadvantages. It also includes string handling, input/output operations, and built-in string functions in C. The unit provides solved programming examples to illustrate the practical application of arrays and strings.

Uploaded by

akbarikavya13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Chhotubhai Gopalbhai Patel Institute of


Technology, Bardoli

Subject
Basics of Logic Development
(IT3009)

Unit – 3
Arrays and Strings

Prepared by – Mr. Viral H. Panchal 1


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

CONTENTS
1. Basics of Array
2. One-dimensional Arrays
2.1. Declaration of One-dimensional Arrays
2.2. Initialization of One-dimensional Arrays
2.3. Solved Programs (One-dimensional Arrays)
3. Two-dimensional Arrays
3.1. Declaration of Two-dimensional Arrays
3.2. Initialization of Two-dimensional Arrays
3.3. Solved Programs (Two-dimensional Arrays)
4. Multidimensional Arrays
5. Basics of String
6. Declaration and Initializing String Variables
7. Reading Strings from Terminal
7.1. Using scanf() Function
7.2. Using getchar() and gets() Functions
8. Writing Strings to Screen
8.1. Using printf() Function
8.2. Using putchar() and puts() Functions
9. Arithmetic Operations on Characters
10. String Handling Functions (Built-in String Functions)
10.1. strcat() Function
10.2. strcmp() Function
10.3. strcpy() Function
10.4. strlen() Function
10.5. strrev() Function
10.6. Other String Functions
11. Solved Programs (Strings)

Prepared by – Mr. Viral H. Panchal 2


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

1. Basics of Array
An array is a collection of elements of similar data types referred by the same
variable name.
An array is a linear and homogeneous data structure. Linear data structure stores
its individual data elements in a sequential order in the memory. Homogeneous means
all individual data elements are of the same data type.
The individual elements of an array are referred by their index or sub-script value.
In C the index begins at zero and is always written inside square brackets.
For example, if marks of 10 students are stored in an array named mark, then
mark[0] refers to the marks of the first student, mark[1] refers to the marks of the
second student and mark[9] refers to the marks of the tenth student, that is, mark[n-1]
refers to the marks of nth student.

Advantages of Array:
• Unlike variable an array can store number of values under single name.
• The array elements are stored contiguously.
• Array index helps to access any random values from the array and perform
operations on it.
• An array is a flexible data structure, means we can perform addition or
removal of elements at any position.

Disadvantages of 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.
• If array size is big, that much amount of memory gets reserved.
• Big size of arrays and multi-dimensional arrays are complicated to access
and manipulate.
• If there is need to store more elements than array size, then it is not possible
and shortage of memory occurs.
• If less elements are stored than array size then it leads to memory wastage.

Prepared by – Mr. Viral H. Panchal 3


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Types of Arrays:
Arrays are categorized according to the dimensions used to define it. Here the
dimension indicates the number of rows and columns used to set size of an array.
There are following types of arrays:
• One-dimensional arrays
• Two-dimensional arrays
• Multidimensional arrays

2. One-dimensional Arrays
An array with single subscript is called as one-dimensional array.

2.1. Declaration of One-dimensional Arrays


The syntax of declaring one-dimensional array is:

data_type array_name[size];

where,
data_type = the type of data stored in the array
array_name = name of the array
size = maximum number of elements that an array can hold

For example,
float height[20];

declares the height to be an array containing 20 real elements. Any subscripts


0 to 19 are valid.
Similarly,
int marks[10];

declares the marks as an array to contain a maximum of 10 integer constants.


The C language treats character strings simply as arrays of characters.
The size in a character string represents the maximum number of characters that
the string can hold.
For example,
char name[10];

declares the name as a character array (string) variable that can hold a
maximum number of 10 characters.

Prepared by – Mr. Viral H. Panchal 4


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Suppose we read the following string constant into the string variable
name.
“WELL DONE”
Each character of the string is treated as an element of an array name
and is stored in the memory as follows:
‘W’ ‘E’ ‘L’ ‘L’ ‘’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’

When the compiler sees a character string, it terminates it with an


additional null character. Thus, the element name[10] holds the null character
‘\0’.
When declaring character arrays, we must allow an extra element space
for the null terminator.

2.2. Initialization of One-dimensional Arrays


After an array is declared, its elements must be initialized. Otherwise, they will
contain “garbage”.

You can initialize the array elements one by one.


Syntax:
array_name[index] = value;

For example,
marks[0] = 35;
marks[1] = 70;
.
.
.
marks[9] = 86;

You can also initialize the complete array directly.


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

For example,
int marks[10] = {35,70,40,55,26,43,56,82,78,86};

This array is stored in the memory as follows:

35 70 40 55 26 43 56 82 78 86
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]

Prepared by – Mr. Viral H. Panchal 5


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

The declaration and initialization of character array:


Example:
char a[8] = {‘L’,’E’’A’,’R’,’N’,’ ‘,’C’};

This array is stored in the memory as follows:


‘L’ ‘E’ ‘A’ ‘R’ ‘N’ ‘’ ‘C’ ‘\0’
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7]

The declaration and initialization of float array:


Example:
float price[4] = {1.25,0.75,3.5,10.2};

This array is stored in the memory as follows:


1.25 0.75 3.5 10.2
price[0] price[1] price[2] price[3]

The array size may be omitted during declaration.


Example:
int marks[] = {45,66,84};

is equivalent to
int marks[3] = {45,66,84};

In such cases, the subscript is assumed to equal to the number of elements in the
array (3 in this case).

The elements which are not explicitly initialized are automatically set to zero.
Example:
int x[5] = {2,5};

implies
x[0] = 2;

x[1] = 5;

x[2] = 0;

x[3] = 0;

x[4] = 0;

Prepared by – Mr. Viral H. Panchal 6


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

2.3. Solved Programs (One-dimensional Arrays)


Write a program to find out the Maximum and Minimum number from given
10 numbers.

#include<stdio.h>
int main()
{
int a[10],i,max,min;
for(i=0; i<10; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
}
max=a[0];
min=a[0];
for(i=1; i<10; i++) {
if(a[i]>max)
max=a[i];
if(a[i]<min)
min=a[i];
}
printf("\nArray elements are: ");
for(i=0; i<10; i++)
printf("%4d",a[i]);
printf("\nMaximum Number = %d \nMinimum Number = %d",max,min);
return 0;
}

Output –

Enter number 1: 10
Enter number 2: 12
Enter number 3: 14
Enter number 4: 16
Enter number 5: 18
Enter number 6: 19
Enter number 7: 11
Enter number 8: 13
Enter number 9: 15
Enter number 10: 17
Array elements are: 10 12 14 16 18 19 11 13 15 17

Prepared by – Mr. Viral H. Panchal 7


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Maximum Number = 19
Minimum Number = 10

Write a program to get n numbers and find sum and average of numbers.

#include<stdio.h>
int main()
{
int a[10],i,n;
float avg,sum=0;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
sum=sum+a[i];
}
avg=sum/n;
printf("\nArray elements are: ");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nSum = %0.2f \nAverage = %0.2f",sum,avg);
return 0;
}

Output –

Enter value of n: 5
Enter number 1: 12
Enter number 2: 6
Enter number 3: 78
Enter number 4: 32
Enter number 5: 16
Array elements are: 12 6 78 32 16
Sum = 144.00
Average = 28.80

Prepared by – Mr. Viral H. Panchal 8


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Write a program to find number of odd and even numbers from given n
numbers.

#include<stdio.h>
int main()
{
int a[10],i,n,odd=0,even=0;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
if(a[i]%2==0)
even++;
else
odd++;
}
printf("\nArray elements are: ");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nNumber of Odd = %d \nNumber of Even = %d",odd,even);
return 0;
}

Output –

Enter value of n: 6
Enter number 1: 4
Enter number 2: 9
Enter number 3: 1
Enter number 4: 3
Enter number 5: 6
Enter number 6: 8
Array elements are: 4 9 1 3 6 8
Number of Odd = 3
Number of Even = 3

Prepared by – Mr. Viral H. Panchal 9


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Write a program which finds maximum of n numbers and also finds how
many times maximum number is repeated.

#include<stdio.h>
int main()
{
int a[10],i,n,max,count;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
scanf("%d",&a[i]);
max=a[0];
}
for(i=1; i<n; i++) {
if(a[i]>max)
max=a[i];
}
count=0;
for(i=0; i<n; i++) {
if(max==a[i])
count++;
}
printf("\nArray elements are: ");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nMaximum number = %d and is repeated %d times", max,
count);
return 0;
}

Output –

Enter value of n: 7
Enter number 1: 12
Enter number 2: 34
Enter number 3: 23
Enter number 4: 34
Enter number 5: 32
Enter number 6: 4
Enter number 7: 34
Array elements are: 12 34 23 34 32 4 34
Maximum number = 34 and is repeated 3 times

Prepared by – Mr. Viral H. Panchal 10


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Write a program to sort given n numbers and display them in ascending and
descending order.

#include<stdio.h>
int main()
{
int a[10],i,j,n,temp;
printf("Enter value of n: ");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("Enter number %d: ",i+1);
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("\nNumbers in ascending order:\n");
for(i=0; i<n; i++)
printf("%4d",a[i]);
printf("\nNumbers in descending order:\n");
for(i=n-1; i>=0; i--)
printf("%4d",a[i]);
return 0;
}

Output –

Enter value of n: 7
Enter number 1: 8
Enter number 2: -2
Enter number 3: 12
Enter number 4: -6
Enter number 5: 34
Enter number 6: 26
Enter number 7: 15
Numbers in ascending order: -6 -2 8 12 15 26 34
Numbers in descending order: 34 26 15 12 8 -2 -6

Prepared by – Mr. Viral H. Panchal 11


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

3. Two-dimensional Arrays
• An array with two subscripts is called as two-dimensional array.
• 2D arrays are mostly used to perform matrix operations.
• A matrix has two subscripts – the first subscript denotes the number of rows and
the second subscript denotes the number of columns.

3.1. Declaration of Two-dimensional Arrays


The syntax of declaring two-dimensional array is:
data_type array_name[row_size][column_size];

where,
data_type = the type of data stored in the array
array_name = name of the array
row_size = maximum number of rows in the array
column_size = maximum number of columns in the array

For example,
int table[2][3]; //implies 2 rows and 3 columns

declares the table to be an array containing 2 rows and 3 columns, i.e., total 6
real elements.
A user can view this array as below.
Column 0 Column 1 Column 2
Row 0 [0][0] [0][1] [0][2]
Row 1 [1][0] [1][1] [1][2]

But in memory it will form different structure as below.

table[0][0] 4000
table[0][1] 4002
table[0][2] 4004 Memory
table[1][0] 4006 Address

table[1][1] 4008
table[1][2] 4010

Prepared by – Mr. Viral H. Panchal 12


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

3.2. Initialization of Two-dimensional Arrays


The two-dimensional array can be initialized at the time of declaration as in the
case of single dimensional array.
For example,
int table[2][3] = {0,0,0,1,1,1};

initialize first row data as {0,0,0} and second row data as {1,1,1}.
The above initialization is same as
int table[2][3] = {{0,0,0},{1,1,1}};

If the values are missing in an initializer, they are automatically set to 0. For
example, the statement
int table[2][3] = {{1,1},{2}};

will initialize the first two elements of the first row to 1, the first element of the
second row to 2, and all other elements to 0.

3.3. Solved Programs (Two-dimensional Arrays)


Write a program to find maximum number within 3x3 matrix.

#include <stdio.h>
int main()
{
int a[3][3],i,j,max;
printf("Enter the elements of matrix A:\n");
for(i=0; i<3; i++) { //Get matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
max=a[0][0];
for(i=0; i<3; i++) {

Prepared by – Mr. Viral H. Panchal 13


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

for(j=0; j<3; j++) {


if(a[i][j]>max)
max=a[i][j];
}
}
printf("\nThe Largest number in the matrix A is: %d",max);
return 0;
}

Output –

Enter the elements of matrix A:


a[0][0] = 6
a[0][1] = 12
a[0][2] = 23

a[1][0] = 45
a[1][1] = 67
a[1][2] = 9
a[2][0] = 78
a[2][1] = 23
a[2][2] = 4

Matrix A:
6 12 23
45 67 9
78 23 4

The Largest number in the matrix A is: 78

Write a program to perform addition of two 3x3 matrices.

#include <stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the elements of matrix A:\n");
for(i=0; i<3; i++) { //Get first matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}

Prepared by – Mr. Viral H. Panchal 14


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

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


for(i=0; i<3; i++) { //Get second matrix data
for(j=0; j<3; j++) {
printf("b[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display first matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0; i<3; i++) { //Display second matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",b[i][j]);
}
printf("\n");
}
printf("\nAddition of matrix A and B:\n");
for(i=0; i<3; i++) { //calculate sum and display result matrix
for(j=0; j<3; j++) {
c[i][j]=a[i][j]+b[i][j];
printf("%4d",c[i][j]);
}
printf("\n");
}
return 0;
}

Output –

Enter the elements of matrix A:


a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

a[1][0] = 4
a[1][1] = 5
a[1][2] = 6

Prepared by – Mr. Viral H. Panchal 15


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

a[2][0] = 7
a[2][1] = 8
a[2][2] = 9

Enter the elements of matrix B:


b[0][0] = 9
b[0][1] = 8
b[0][2] = 7

b[1][0] = 6
b[1][1] = 5
b[1][2] = 4

b[2][0] = 3
b[2][1] = 2
b[2][2] = 1

Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
9 8 7
6 5 4
3 2 1

Addition of matrix A and B:


10 10 10
10 10 10
10 10 10

Write a program to find transpose of any 3x3 matrix.

#include <stdio.h>
int main()
{
int a[3][3],i,j;
printf("Enter the elements of matrix:\n");
for(i=0; i<3; i++) { //Get matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
Prepared by – Mr. Viral H. Panchal 16
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of A:\n");
for(j=0; j<3; j++) { //Display transpose of matrix
for(i=0; i<3; i++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
return 0;
}

Output –

Enter the elements of matrix:


a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

a[1][0] = 4
a[1][1] = 5
a[1][2] = 6

a[2][0] = 7
a[2][1] = 8
a[2][2] = 9

Matrix A:
1 2 3
4 5 6
7 8 9

Transpose of A:
1 4 7
2 5 8
3 6 9

Prepared by – Mr. Viral H. Panchal 17


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Write a program to perform multiplication of two 3x3 matrices.

#include <stdio.h>
int main()
{
int a[3][3],b[3][3],c[3][3],i,j,k,sum;
printf("Enter the elements of matrix A:\n");
for(i=0; i<3; i++) { //Get first matrix data
for(j=0; j<3; j++) {
printf("a[%d][%d] = ",i,j);
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("Enter the elements of matrix B:\n");
for(i=0; i<3; i++) { //Get second matrix data
for(j=0; j<3; j++) {
printf("b[%d][%d] = ",i,j);
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("\nMatrix A:\n");
for(i=0; i<3; i++) { //Display first matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",a[i][j]);
}
printf("\n");
}
printf("\nMatrix B:\n");
for(i=0; i<3; i++) { //Display second matrix row row-wise
for(j=0; j<3; j++) {
printf("%4d",b[i][j]);
}
printf("\n");
}
for(i=0; i<3; i++) { //Finding multiplication of two matrices
for(j=0; j<3; j++) {
sum=0;
for(k=0; k<3; k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
Prepared by – Mr. Viral H. Panchal 18
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

printf("\nMultiplication of matrix A and B:\n");


for(i=0; i<3; i++) { //display result matrix
for(j=0; j<3; j++) {
printf("%4d",c[i][j]);
}
printf("\n");
}
return 0;
}

Output –

Enter the elements of matrix A:


a[0][0] = 1
a[0][1] = 2
a[0][2] = 3

a[1][0] = 4
a[1][1] = 5
a[1][2] = 6

a[2][0] = 7
a[2][1] = 8
a[2][2] = 9

Enter the elements of matrix B:


b[0][0] = 1
b[0][1] = 1
b[0][2] = 1

b[1][0] = 2
b[1][1] = 2
b[1][2] = 2

b[2][0] = 3
b[2][1] = 3
b[2][2] = 3

Matrix A:
1 2 3
4 5 6
7 8 9

Prepared by – Mr. Viral H. Panchal 19


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Matrix B:
1 1 1
2 2 2
3 3 3

Multiplication of matrix A and B:


14 14 14
32 32 32
50 50 50

4. Multidimensional Arrays
An array with more than two subscripts is called as multidimensional array.

For example, suppose we want to store 5 students marks information for 2 different
exams carried out in the term for 4 different subjects, this data can be stored by using
3-dimensional array like,
int marks[5][2][4];

where, 5 students, 2 exams, and 4 subjects. So, total entries in the array will
be 5*2*4 = 40.

The array will span from marks[0][0][0] to marks[4][1][3].

Prepared by – Mr. Viral H. Panchal 20


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

5. Basics of String
A string is a sequence of characters that is treated as a single data item. Any group
of characters (except double quote sign) defined between double quotation marks is
a string constant. Example:

“Programming in C is fun.”

If we want to include a double quote in the string to be printed, then we may use
it with a back slash as shown below.

"\"Programming in C is fun.\""

For example,

printf(“\”Welcome\””);

will output the string

“Welcome”

while the statement

printf(“Welcome”);

will output the string

Welcome

6. Declaration and Initializing String Variables


C does not support strings as a data type. However, it allows us to represent strings
as character arrays. In C, therefore, a string variable is any C valid variable name
and is always declared as an array of characters.
The general form of declaration of a string variable is:

char string_name[size];

The size determines the numbers of characters in the string_name. Some


examples are:
char university[30];
char college[50];

Prepared by – Mr. Viral H. Panchal 21


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

When the compiler assigns a character string to a character array, it automatically


supplies a null character (‘\0’) at the end of the string. Therefore, the size should be
equal to the maximum number of characters in the string plus one.
Like numeric arrays, character arrays may be initialized when they are declared.
C permits a character array to be initialized in either of the following two forms:

char university[13]=“UKA TARSADIA”;


char university[13]={‘U’,’K’,’A’,’ ‘,’T’,’A’,’R’,’S’,’A’,’D’,’I’,’A’,’\0’};

The reason that university had to be 13 elements long is that the string UKA
TARSADIA contains 12 characters and one element space is provided for the null
terminator. Note that when we initialize a character array by listing its elements, we
must supply explicitly the null terminator.
C also permits us to initialize a character array without specifying the number of
elements. In such cases, the size of the array will be determined automatically, based
on the number of elements initialized. For example, the statement

char string[] = {‘C’,’G’,’P’,’I’,’T’,’\0’};

defines the array string as a six element array.


We can also declare the size much larger than the string size in the initializer. That
is, the statement,

char string[10] = {‘C’,’G’,’P’,’I’,’T’,’\0’};

is permitted. In this case, the computer creates a character array of size 10, places the
value “CGPIT” in it, terminates with the null character, and initializes all other elements
to NULL. The storage will look like:

C G P I T \0 \0 \0 \0 \0

However, the following declaration is illegal.

char string[3] = “CGPIT”;

This will result in a compile time error. Also note that we can not separate the
initialization from declaration. That is,

Prepared by – Mr. Viral H. Panchal 22


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

char string[3];
string = “CGPIT”;

is not allowed. Similarly,

char s1[4] = “xyz”;


char s2[4];
s2 = s1; /* Error */

is not allowed. An array name cannot be used as the left operand of the assignment
operator.

7. Reading Strings from Terminal

7.1. Using scanf() Function


The input function scanf can be used with %s format specification to read in a string
of characters. Example:

char address[20];
scanf(“%s”, address);

The problem with scanf function is that it terminates its input on the first white space
it finds. A white space includes blanks, tabs, carriage returns, form feeds, and new
lines. Therefore, if the following line of text is typed in at the terminal,

UKA TARSADIA

then only the string “UKA” will be read into the array address, since the blank space
after the word “UKA” will terminate the reading of string.

The scanf function automatically terminates the string that is read with a null
character and therefore the character array should be large enough to hold the input
string plus the null character.
Note that in the case of character arrays, the ampersand (&) is not required before
the variable name.
The address array is created in the memory as shown below:

U K A \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9

Prepared by – Mr. Viral H. Panchal 23


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Note that the unused locations are filled with garbage.

If we want to read the entire line “UKA TARSADIA”, then we may use two character
arrays of appropriate sizes. That is,

char adr1[10], adr2[10];


scanf(“%s %s”, adr1, adr2);

with the line of text

UKA TARSADIA

will assign the string “UKA” to adr1 and “TARSADIA” to adr2.

We can also specify the field width using the form %ws in the scanf statement for
reading a specified number of characters from the input string. Example:

scanf(“%ws”, name);

Here, two things may happen:

1. The width w is equal to or greater than the number of characters typed in. The
entire string will be stored in the string variable.
2. The width w is less than the number of characters in the string. The excess
characters will be truncated and left unread.

Consider the following statements:

char name[10];
scanf(“%5s”, name);

The input string UKA will be stored as:

U K A \0 ? ? ? ? ? ?
0 1 2 3 4 5 6 7 8 9

The input string TARSADIA will be stored as:

T A R S A \0 ? ? ? ?
0 1 2 3 4 5 6 7 8 9

Prepared by – Mr. Viral H. Panchal 24


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Example –

/* Write a program to read a series of words from a terminal


using scanf function */

#include <stdio.h>
int main()
{
char word1[30], word2[30], word3[30], word4[30];
printf("Enter text:\n");
scanf("%s %s %s %s", word1, word2, word3, word4);
printf("\n");
printf("word1 = %s\nword2 = %s\n", word1, word2);
printf("word3 = %s\nword4 = %s\n", word3, word4);
return 0;
}

Output −

Enter text:
Uka Tarsadia University Bardoli

word1 = Uka
word2 = Tarsadia
word3 = University
word4 = Bardoli

Reading a Line of Text:


The scanf with %s and %ws can read only string without whitespaces. That is, they
cannot be used for reading a text containing more than one word. However, C supports
a format specification known as the edit set conversion code %s[..] that can be used to
read a line containing a variety of characters, including whitespaces.
For example, the program segment

char line[80];
scanf(“%[^\n]”, line);
printf(“%s”, line);

will read a line of input from the keyboard and displays the same on the screen.

Prepared by – Mr. Viral H. Panchal 25


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

7.2. Using getchar() and gets() Functions


We can use the getchar function repeatedly to read successive single characters
from the input and placed them into a character array. Thus, an entire line of text can
be read and stored in an array. The reading is terminated when the newline character
(‘\n’) is entered and the null character is then inserted at the end of the string.
The getchar function call takes the form:

char ch;
ch = getchar();

Note that the getchar function has no parameter.

Example –
/* Write a program to read a line of text containing a series of
words from a terminal using getchar function */

#include <stdio.h>
int main()
{
char line[50], ch;
int c=0;
printf("Enter text. Press <Enter> at end\n");
do {
ch = getchar();
line[c] = ch;
c++;
} while(ch != '\n');
c = c-1;
line[c] = '\0';
printf("\n%s\n", line);
return 0;
}

Output −

Enter text. Press <Enter> at end


Programming is C is Fun.
Programming is C is Fun.

The above program can read a line of text (up to maximum of 50 characters) into
the string line using getchar function. Every time a character is read, it is assigned to
Prepared by – Mr. Viral H. Panchal 26
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

its location in the string line and then tested for newline character. When the newline
character is read (signaling the end of line), the reading loop is terminated and the
newline character is replaced by the null character to indicate the end of character
string.

When the loop is exited, the value of the index c is one number higher than the last
character position in the string (since it has been incremented after assigning the new
character to the string). Therefore, the index value c-1 gives the position where the null
character is to be stored.

Another and more convenient method of reading a string of text containing


whitespaces is to use the library function gets available in the <stdio.h> header file.
This is a simple function with one string parameter and called as under:

gets(str);

str is a string variable declared properly. It reads characters into str from the
keyboard until a new-line character is encountered and then appends a null character
to the string. Unlike scanf, it does not skip whitespaces. For example, the code segment

char line[50];
gets(line);
printf(“%s”, line);

reads a line of text from the keyboard and displays it on the screen. The last two
statements may be combined as follows:

printf(“%s”, gets(line));

C does not provide operators that work on strings directly. For instance, we cannot
assign one string to another directly. For example, the assignment statements

string2 = “XYZ”;
string1 = string2;

are not valid. If we really want to copy the characters in string2 into string1, we may
do so on a character-by-character basis.

Prepared by – Mr. Viral H. Panchal 27


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Example –
/* Write a program to copy one string into another and count the
number of characters copied */

#include <stdio.h>
int main()
{
char string1[50], string2[50];
int i;
printf("Enter a string \n");
scanf("%s", string2);
for(i=0; string2[i]!='\0'; i++)
string1[i] = string2[i];
string1[i] = '\0';
printf("\n");
printf("%s", string1);
printf("\nNumber of characters = %d", i);
return 0;
}

Output −

Enter a string
CGPIT
CGPIT
Number of characters = 5

8. Writing Strings to Screen

8.1. Using printf() Function


The format %s can be used to display an array of characters that is terminated by
the null character. For example, the statement

printf(“%s”, name);

can be used to display the entire contents of the array name.

We can also specify the precision with which the array is displayed. For instance,
the specification %10.4 indicates that the first four characters are to be printed in a
field width of 10 columns. However, if we include the minus sign in the specification
(e.g., %-10.4s), the string will be printed left-justified.
Prepared by – Mr. Viral H. Panchal 28
Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

The below example illustrates the effect of various %s specifications.

Example –
/* Write a program to store the string “Uka Tarsadia University”
in the array uni and display the string under various format
specifications */

#include <stdio.h>
int main()
{
char uni[24] = "Uka Tarsadia University";
printf("------------------------\n");
printf("%24s\n", uni);
printf("%5s\n", uni);
printf("%16.3s\n", uni);
printf("%-16.3s\n", uni);
printf("%16.0s\n", uni);
printf("%.6s\n", uni);
printf("%s\n", uni);
printf("------------------------\n");
return 0;
}

Output −

------------------------
Uka Tarsadia University
Uka Tarsadia University
Uka
Uka

Uka Ta
Uka Tarsadia University
------------------------

The output illustrates the following features of the %s specifications.

1. When the field which is less than the length of the string, the entire string is
printed.
2. The integer value on the right side of the decimal point specifies the number
of characters to be printed.

Prepared by – Mr. Viral H. Panchal 29


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

3. When the number of characters to be printed is specified as zero, nothing is


printed.
4. The minus sign in the specification causes the string to be printed left-justified.
5. The specification %.ns prints the first n characters of the string.

8.2. Using putchar() and puts() Functions


Like getchar, C supports another character handling function putchar to output the
values of character variables. It takes the following form:

char ch = ‘A’;
putchar (ch);

The function putchar requires one parameter. This statement is equivalent to:

printf(“%c”, ch);

We can use this function repeatedly to output a string of characters stored in an


array using a loop. Example:
char name[6] = “CGPIT”;
for(i=0;i<5;i++)
putchar(name[i]);
putchar(“\n”);

Another and more convenient way of printing string values is to use the function
puts declared in the header file <stdio.h>. This is one parameter function and invoked
as under:
puts (str);

where str is a string variable containing a string value. This prints the value of the string
variable str and then moves the cursor to the beginning of the next line on the screen.
For example, the program segment

char line[50];
gets(line);
puts(line);

reads a line of text from the keyboard and displays it on the screen. Note that the
syntax is very imple compared to using the scanf and printf statements.

Prepared by – Mr. Viral H. Panchal 30


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

9. Arithmetic Operations on Characters


C allows us to manipulate characters the same way we do with numbers. Whenever
a character constant or character variable is used in an expression, it is automatically
converted into an integer value by the system. The integer value depends on the local
character set of the system.

To write a character in its integer representation, we may write it as an integer. For


example, if the machine uses the ASCII representation, then,
x = ‘a’;
printf(“%d\n”, x);

will display the number 97 on the screen.

It is also possible to perform arithmetic operations on the character constants and


variables. For example,
x = ‘z’ – 1;

is a valid statement. In ASCII, the value of ‘z’ is 122 and therefore, the statement will
assign the value 121 to the variable x.

We may also use character constants in relational expressions. For example, the
expression
ch >= ‘A’ && ch <= ‘z’

would test whether the character contained in the variable ch is an upper-case letter.

We can convert a character digit to its equivalent integer value using the following
relationship:
x = character – ‘0’;

where x is defined as an integer variable and character contains the character digit.
For example, let us assume that the character contains the digit ‘7’.

Then,
x = ASCII value of ‘7’ – ASCII value of ‘0’
= 55 – 48 = 7

Prepared by – Mr. Viral H. Panchal 31


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

The C library supports a function that converts a string of digits into their integer
values. The function takes the form
x = atoi(string);

x is an integer variable and string is a character array containing a string of digits.


Consider the following segment of program:

number = “2022”;
year = atoi(number);

number is a string variable which is assigned the string constant “2022”. The function
atoi converts the string “2022” (contained in number) to its numeric equivalent 2022
and assign it to the integer variable year. String conversion functions are stored in the
header file <stdlib.h>.

Example –
/* Write a program which would print the alphabet set a to z and
A to Z in decimal and character form */

#include <stdio.h>
int main()
{
char c;
for(c=65; c<=122; c++) {
if(c>90 && c<97)
continue;
printf("|%3d - %c ", c, c);
}
printf("|\n");
return 0;
}

Output –

| 65 - A | 66 - B | 67 - C | 68 - D | 69 - E | 70 - F | 71 - G
| 72 - H | 73 - I | 74 - J | 75 - K | 76 - L | 77 - M | 78 - N
| 79 - O | 80 - P | 81 - Q | 82 - R | 83 - S | 84 - T | 85 - U
| 86 - V | 87 - W | 88 - X | 89 - Y | 90 - Z | 97 - a | 98 - b
| 99 - c |100 - d |101 - e |102 - f |103 - g |104 - h |105 - i
|106 - j |107 - k |108 - l |109 - m |110 - n |111 - o |112 - p
|113 - q |114 - r |115 - s |116 - t |117 - u |118 - v |119 - w
|120 - x |121 - y |122 - z |

Prepared by – Mr. Viral H. Panchal 32


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

10. String Handling Functions (Built-in String Functions)


The C library supports a large number of string-handling functions that can be used
for string manipulation. Following are the most commonly used string-handling
functions.

• strcat() – concatenates two strings


• strcmp() – compares two strings
• strcpy() – copies one string over another
• strlen() – finds the length of a string
• strrev() – reverses the string

10.1. strcat() Function


The strcat() function joins two strings together. The process of joining two strings
together is called concatenation.

It takes two arguments, the first one is a string variable and the second can be a
string variable or a string constant.

The characters of the second string are appended at the end of the first one.

Syntax –
strcat(string1,string2);

Here, string1 and string2 are character arrays (string2 can be string constant also).

The NULL character is removed from the end of string1 and string2 is stored from
this position.

Example –
/* Program to use strcat() function */

#include<stdio.h>
#include<string.h>
int main()
{
char string1[50],string2[50];

Prepared by – Mr. Viral H. Panchal 33


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

printf("\nEnter the first string:\n");


gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
strcat(string1,string2);
printf("\nUsing strcat function the resultant string is:\n%s",
string1);
return 0;
}

Output –

Enter the first string:


Uka Tarsadia

Enter the second string:


University

Using strcat function the resultant string is:


Uka Tarsadia University

10.2. strcmp() Function


In C, the comparison of two strings is not allowed directly.

The comparison can be done either using the standard library function strcmp() or
the strings can be compared character by character.

Syntax –
strcmp(string1,string2);

Here, string1 and string2 are string variables or string constants.

It returns a 0 when strings are identical and returns the numeric difference between
the ASCII values of the first mismatch characters otherwise.

Prepared by – Mr. Viral H. Panchal 34


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Example –
/* Program to use strcmp() function */

#include<stdio.h>
#include<string.h>
int main()
{
char string1[50],string2[50];
int diff;
printf("\nEnter the first string:\n");
gets(string1);
printf("\nEnter the second string:\n");
gets(string2);
diff=strcmp(string1,string2);
if(diff==0)
printf("\nBoth strings are same");
else
printf("\nBoth strings are different");
return 0;
}

Output –

Enter the first string:


cgpit

Enter the second string:


cgpit

Both strings are same

Output –

Enter the first string:


cgpit

Enter the second string:


utu

Both strings are different

Prepared by – Mr. Viral H. Panchal 35


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

10.3. strcpy() Function


The process of copying one string into the other is called string copying. In C, the
function for copying of one string over the other is strcpy().

Syntax –
strcpy(string1,string2);

Here, string1 is the target string which stores the contents of the source string string2.
The string2 may be a character array variable or a string constant. The string1 must
have a size greater than or equal to that of string2. The string2 is copied into the
string1 character by character and the process terminates on getting NULL character
(‘\0’) in the source string.

Note that the contents of the target string will be lost and source string remains
unchanged.

Example –
/* Program to use strcpy() function */

#include<stdio.h>
#include<string.h>
int main()
{
char string1[50],string2[50];
printf("\nEnter a string:\n");
gets(string1);
strcpy(string2,string1);
printf("\nCopied string is:\n%s",string2);
return 0;
}

Output –

Enter a string:
UKA TARSADIA UNIVERSITY
Copied string is:
UKA TARSADIA UNIVERSITY

Prepared by – Mr. Viral H. Panchal 36


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

10.4. strlen() Function


The process of knowing the number of characters in a string is called finding length
of a string.

In C, the function for finding the length of a string is strlen(). This function finds and
returns the number of characters in a string.

Syntax –
n=strlen(string);

Here, n is an integer variable which stores the values of the length of the string. The
string can be both a string variable or a string constant. The process of counting is
terminated on first occurrence of NULL character (‘\0’).

Example –
/* Program to find the length of a given string using strlen()
function */

#include<stdio.h>
#include<string.h>
int main()
{
char string1[50];
int n;
printf("\nEnter a string:\n");
gets(string1);
n=strlen(string1);
printf("\nThe length of string is %d",n);
return 0;
}

Output –

Enter a string:
Uka Tarsadia University
The length of string is 23

Prepared by – Mr. Viral H. Panchal 37


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

10.5. strrev() Function


The strrev() function is used o print a string in reverse order.

Syntax –
strrev(string);

Here, the original string is overwritten with its reversed string.

Example –
/* Program to print a given string in reverse order using strrev()
function */

#include<stdio.h>
#include<string.h>
int main()
{
char string1[50];
printf("\nEnter a string:\n");
gets(string1);
strrev(string1);
printf("\nReversed string is:\n%s",string1);
return 0;
}

Output –

Enter a string:
cgpit

Reversed String is:


tipgc

Prepared by – Mr. Viral H. Panchal 38


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

10.6. Other String Functions


The header file <string.h> contains many more string manipulation functions. That
might be useful in certain situations.

• strncpy()

In addition to the function strcpy() that copies one string to another, we have
another function strncpy() that copies only the left-most n characters of the source
string to the target string variable.

This is a three-parameter function and is invoked as follows:

strncpy(s1,s2,5);

This statement copies the first 5 characters of the source string s2 into the target
string s1.

• strncmp()

A variation of the function strcmp() is the function strncmp(). This function has
three parameters as illustrated in the function call below:

strncmp(s1,s2,n);

This compared the lest-most n characters of s1 to s2 and returns.


a) 0 if they are equal;
b) negative numbers, if s1 substring is less than s2; and
c) positive number, otherwise

• strncat()

This is another concatenation function that takes three parameters as shown


below:

strncat(s1,s2,n);

This call will concatenate the left-most n characters of s2 to the end of s1.

Prepared by – Mr. Viral H. Panchal 39


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

• strstr()

It is a two-parameter function that can be used to locate a sub-string in a string.


This takes the forms:

strstr(s1,s2);
strstr(s1,”ABC”);

The function strstr() searches the string s1 to see whether the string s2 is contained
in s1. If yes, the function returns the position of the first occurrence of the sub-string.
Otherwise, it returns a NULL pointer. Example:

if(strstr(s1, s2) == NULL)


printf(“substring is not found”);
else
printf(“s2 is a substring of s1”);

• strchr() and strrchr()

We also have a function to determine the existence of a character in a string.


The function call

strchr(s1,’m’);

will locate the first occurrence of the character ‘m’ and the call

strrchr(s1,’m’);

will locate the last occurrence of the character ‘m’ in the string s1.
• strupr()

This function is used to convert the characters in string to upper case.


Syntax –
strupr(string);
• strlwr()

This function is used to convert the characters in string to lower case.


Syntax –
strlwr(string);

Prepared by – Mr. Viral H. Panchal 40


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

11. Solved Programs (Strings)


Write a program to accept a string and find the number of vowels in it.

#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, vowels = 0;
printf("Enter a string: \n");
gets(str);
for(i = 0; str[i]; i++) {
if(str[i]=='a'|| str[i]=='e'||str[i]=='i'||
str[i]=='o'|| str[i]=='u'||str[i]=='A'||
str[i]=='E'||str[i]=='I'||str[i]=='O' ||str[i]=='U') {
vowels++;
}
}
printf("Total number of vowels: = %d\n",vowels);
return 0;
}

Output –

Enter a string:
Uka Tarsadia University
Total number of vowels: = 10

Write a program to reverse a string without using strrev() function

#include<stdio.h>
#include<string.h>
int main()
{
int i,n;
char str[50];
printf("Enter the String to get reversed:\n");
gets(str);
n=strlen(str);
printf("\nReversed string is:\n");
for(i=n-1; i>=0; i--) {
printf("%c",str[i]);
}

Prepared by – Mr. Viral H. Panchal 41


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

return 0;
}

Output –

Enter the String to get reversed:


Uka Tarsadia University
Reversed string is:
ytisrevinU aidasraT akU

Write a program to find a character from given string.

#include<stdio.h>
#include<string.h>
int main()
{
char string[50];
char ch='p';
printf("\nEnter a string:\n");
gets(string);
if(strchr(string,ch))
printf("The character %c is at position: %d\n",
ch, strchr(string,ch)-string+1);
else
printf("\nThe character is not found");
return 0;
}

Output –

Enter a string:
cgpit
The character p is at position: 3

Write a program to replace a character in given string.

#include<stdio.h>
#include<string.h>
int main()
{
char string[50],chr,repl_chr;
int i=0;
printf("\nEnter a string: ");
gets(string);
printf("\nEnter a character to be replaced: ");

Prepared by – Mr. Viral H. Panchal 42


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

scanf("%s",&chr);
printf("\nEnter replacement character: ");
scanf("%s",&repl_chr);
while(string[i]!='\0') {
if(string[i]==chr) {
string[i]=repl_chr;
}
i++;
}
printf("\nModified string after replacement is: %s",
string);
return 0;
}

Output –

Enter a string: abcadefa


Enter a character to be replaced: a
Enter replacement character: z
Modified string after replacement is: zbczdefz

Write a program to delete a character in given string.

#include<stdio.h>
#include<string.h>
int main()
{
char str[50],ch;
int i,j;
printf("\nEnter a string: ");
gets(str);
printf("\nEnter a character to delete from string: ");
scanf("%c",&ch);
//Accessing each element of string to perform delete operation
for(i=0; i<strlen(str); i++) {
if(ch==str[i]) {
/*After deleting user provided element moving each element
one step forward to fill it's place */
for(j=i;j<strlen(str);j++)
str[j]=str[j+1];
}
}
printf("\nString after deleting character: %s",str);
return 0;

Prepared by – Mr. Viral H. Panchal 43


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Output –

Enter a string: cgpit


Enter a character to delete from string: p
String after deleting character: cgit

Write a program to convert string into upper case .

#include<stdio.h>
#include<string.h>
int main()
{
char str[50];
printf("\nEnter a string: ");
gets(str);
printf("\nThe string in upper case: %s",strupr(str));
return 0;
}

Output –

Enter a string: viral panchal


The string in upper case: VIRAL PANCHAL

Write a program to read a string and determine it is palindrome or not.

#include<stdio.h>
#include<string.h>
int main()
{
char str1[50],str2[50];
int diff;
printf("\nEnter a string: ");
gets(str1);
strcpy(str2,str1);
strrev(str2);
diff=strcmp(str1,str2);
if(diff==0)
printf("\nString is a palindrome");
else
printf("\nString is not a palindrome");
return 0;
}

Prepared by – Mr. Viral H. Panchal 44


Basics of Logic Development (IT3009) Unit - 3: Arrays and Strings

Output –

Enter a string: malayalam


String is a palindrome

Output –

Enter a string: viral


String is not a palindrome

Prepared by – Mr. Viral H. Panchal 45

You might also like