0% found this document useful (0 votes)
8 views84 pages

Unit 3

The document is a lecture note on programming in C, focusing on arrays and strings. It covers the definition, declaration, initialization, and operations of one-dimensional and multi-dimensional arrays, along with illustrative code examples. Additionally, it discusses string operations and provides examples of string functions.
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)
8 views84 pages

Unit 3

The document is a lecture note on programming in C, focusing on arrays and strings. It covers the definition, declaration, initialization, and operations of one-dimensional and multi-dimensional arrays, along with illustrative code examples. Additionally, it discusses string operations and provides examples of string functions.
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/ 84

Dr. K.

Venkateshwalru 1/19

Programming in C
Unit-3
Topic: Arrays and Strings

by
Dr. K. Venkateshwalru,
Assistant Professor,
Anurag University.
Dr. K. Venkateshwalru 2/19

Unit-III : Arrays and Strings

Arrays:
Introduction to Arrays, One-Dimensional Arrays and Multi-Dimensiona
Arrays with suitable illustrative programs.
Strings:
Introduction to Strings, Unformatted I/O ,String Operations
with and without builtin functions. (strlen( ), strcmp( ), strcat(
),strcpy( ), and strrev( )) with suitable illustrative programs.
Dr. K. Venkateshwalru 3/19

What is an Array?

An array is a collection of items of same data type stored at


contiguous memory locations.
Dr. K. Venkateshwalru 3/19

What is an Array?

An array is a collection of items of same data type stored at


contiguous memory locations.
Array elements are stored in a contiguous memory location.
Array elements are always indexed (counted) from zero (0) on-
wards.
Array elements can be accessed using the position of the ele-
ment in the array.
The array can have one or more dimensions.
Dr. K. Venkateshwalru 4/19

Array

Instead of declaring individual variables, such as number0, number1,


..., and number99
one array variable can be declared as numbers[100] and use
numbers[0],
numbers[1],
and
...,
numbers[99]
to represent individual variables.
A specific element in an array is accessed by an index.
Dr. K. Venkateshwalru 5/19
Dr. K. Venkateshwalru 6/19

Declaration of Array:

1 To declare an array in C, the type of the elements and the


number of elements required to be stored in an array are to be
specified as follows.
2 data type Array name[Array size];
This is called a single dimensional array.
3 The Array size must be an integer constant greater than zero
and type can be any valid C data type.
4 For example, declaration of a 10-elements array called marks
of type double
double marks [10];
5 Here marks is a variable array which is sufficient to hold up to
10 double numbers
Dr. K. Venkateshwalru 7/19

Declaration and initialization of Array:

There are various ways in which we can declare an array. It can be


done by specifying its type and size, initializing it or both.
1 Array declaration by specifying the size
data type Array name[Array size];
Example: int arr1[10];
2 Array declaration by initializing elements
Example: int arr[] = {10, 20, 30, 40};
3 Array declaration by specifying the size and initializing ele-
ments.
Example: int arr[6] = {10, 20, 30, 40};
Dr. K. Venkateshwalru 8/19

Example: int scores[10] = {23, 45, 12, 67, 95, 45, 56, 34, 83, 16};
Dr. K. Venkateshwalru 9/19

Initialization of array

Note: One array cannot be copied to another using assignment


operator.
Dr. K. Venkateshwalru 9/19

One array cannot be copied to another using assignment oper

#include<stdio.h>
int main()
{
int a[4]={1,2,3,4};
int b[4];
b=a;// copying not allowed
for(int i=0; i<4; i++)
printf("%d\t",a[i]);
}
Dr. K. Venkateshwalru 9/19

// Copying one array elements into another array using for

#include<stdio.h>
int main()
{
int i,a[4]={1,2,3,4};
int b[4];
// Copying array
for(i=0; i<4; i++)
b[i]=a[i];
// displaying
printf("\n b=[ ");
for( i=0; i<4; i++)
printf("%d\t",b[i]);
printf("]");
}
Dr. K. Venkateshwalru 9/19

Out put:
b=[ 1 2 3 4 ]
Dr. K. Venkateshwalru 10/19

Accessing Array Elements

Accessing Array Elements


1 Array elements are accessed by using an integer index. Array
index starts with 0 and goes till the size of the array minus 1
2 The name of the array is also a pointer to the first element of
the array.
3 Index Out of bound Checking:
There is no index out of bounds checking in C.
Dr. K. Venkateshwalru 10/19

1-D array

// Program to implement array declaration and initializatio


#include <stdio.h>

int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];
printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]);
return 0;
}

Out put:

5 2 -10 5
Dr. K. Venkateshwalru 10/19

1-D array

// Index Out of bound Checking

#include <stdio.h>
int main()
{
int arr[2]={10, 20};
printf("%d ", arr[1]);
printf("%d ", arr[2]);
printf("%d ", arr[3]);
printf("%d ", arr[-1]);
return 0;
}

Out put

20 1 0 0
Dr. K. Venkateshwalru 10/19

1-D array

// declaration and initialization of array elements

#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20, 30, 40, 50, 60};
for (i=0;i<5;i++)
printf("%d\n", marks[i]);
return 0;
}
Dr. K. Venkateshwalru 10/19

1-D array

//Program to accept and display 1D array elements


#include<stdio.h>
int main()
{
int i,a[10],n,sum=0, min=0, max=0;
float avg;
printf("enter array size : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{printf("\n Enter a[%d]=",i);
scanf("%d",&a[i]);
}
printf("The array elements are [ ");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
Dr. K. Venkateshwalru 10/19

1-D array

printf("]");
for(i=0;i<n;i++) // calculating sum
sum=sum+a[i];
avg=(float)sum/n;
printf("\n sum=%d \n Average=%f",sum, avg);
min=a[0];
max=a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
min=a[i];
if(a[i]>max)
max=a[i];
}
printf("\n minimum=%d\n Maximum=%d",min, max);
return 0;
}
Dr. K. Venkateshwalru 10/19

1-D array

Output:

enter array size : 5

Enter a[0]=8
Enter a[1]=6
Enter a[2]=5
Enter a[3]=4
Enter a[4]=2
The array elements are [ 8 6 5 4 2 ]
sum=25
Average=5.000000
minimum=2
Maximum=8
Dr. K. Venkateshwalru 10/19

1-D array

//Program to search an element in an array

#include<stdio.h>
int main()
{
int a[30],i,flag=0,n,key;
printf("Enter no.of elements\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
printf("\n Enter a[%d]=",i);
scanf("%d",&a[i]);
}
printf("Enter key element\n");
scanf("%d",&key);
for(i=0;i<n;i++)
Dr. K. Venkateshwalru 10/19

1-D array

{
if(key==a[i])
{
flag=1;
break;
}
}
if(flag==1)
{
printf("\n The Element is found at position %d\n ",i+1);
printf("\n Search is Successful\n");
}
else
printf("The Element is not found \nSearch is Unsuccessful\
return 0;
}
Dr. K. Venkateshwalru 10/19

1-D array

Out put:
Enter no.of elements 5
Enter 5 elements

Enter a[0]=7
Enter a[1]=8
Enter a[2]=5
Enter a[3]=4
Enter a[4]=3

Enter key element 4

The Element is found at position 4


Search is Successful
Dr. K. Venkateshwalru 10/19

1-D array

//Multiply each element in an array by 2


#include<stdio.h>
int main()
{
int i,n;
printf("\n Enter the size of an arry:");
scanf("%d",&n);
int a[n];
printf("\n enter %d element of array:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
a[i]=a[i]*2;
printf("\n Array elements=\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
Dr. K. Venkateshwalru 10/19

1-D array

Out put:
Enter the size of an arry:5

enter 5 element of array:1 2 3 4 5

Array elements=
2 4 6 8 10
Dr. K. Venkateshwalru 11/19
Multi-Dimensional Arrays

A multi-dimensional array can be termed as an array of arrays that


stores homogeneous data in tabular form. Data in multidimensional
arrays are stored in row-major order.
The general form of declaring N-dimensional arrays is: data type
array name[size1][size2]....[sizeN];
Examples:
Two dimensional array: int two d[10][10];
Three dimensional array: int three d[10][20][30];
Size of Multidimensional Arrays:The total number of elements
that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000
elements.
Dr. K. Venkateshwalru 12/19
Multi-Dimensional Arrays
Two-dimensional array

Two-Dimensional Array is the simplest form of a multidimensional


array.
Syntax:
data type array name[x][y];
Example
int x[10][20];
Elements in two-dimensional arrays are commonly referred to by
x[i][j] where i is the row number and ‘j’is the column number.
Initializing Two – Dimensional Arrays: There are various ways
in which a Two-Dimensional array can be initialized.
First Method: int x[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
Second Method: int x[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

The declarations
int arr[2][3]={10, 20, 30, 40, 50, 60};
int arr[ ][3]={10, 20, 30, 40, 50, 60};
are prefectly acceptable.

Where as,
int arr[2][ ]={10, 20, 30, 40, 50, 60};
int arr[ ][ ]={10, 20, 30, 40, 50, 60}
would never work.
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

// Reading 2D array elements and display

#include<stdio.h>
int main()
{ int r, c, i, j, a[10][10];
printf("\n Enter no. of rows");
scanf("%d",&r);
printf("\n Enter no. of columns");
scanf("%d",&c);
// Reading 2D array elements

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("a[%d][%d]=",i+1,j+1);
scanf("%d",&a[i][j]);
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

}
}
// display 2D array elements
printf("\n A=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d\t",a[i][j]);
printf("\n");
}

}
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Output:
Enter no. of rows 3
Enter no. of columns 3
a[1][1]=1
a[1][2]=2
a[1][3]=3
a[2][1]=4
a[2][2]=5
a[2][3]=6
a[3][1]=7
a[3][2]=8
a[3][3]=9

A=
1 2 3
4 5 6
7 8 9
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

// Addition of two matrices (2D array)


#include<stdio.h>
int main()
{
int r1, c1,r2, c2, i, j, a[10][10],b[10][10],c[10][10];
printf("Input rows and columns of A Matrix:");
scanf("%d%d",&r1,&c1);
printf("Input rows and columns of B Matrix:");
scanf("%d%d",&r2,&c2);
if (r1==r2 && c1==c2)// condition of Addition
{ // Reading elements of matrix A
printf("Enter %d elements of matrix A:\n", r1*c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d",&a[i][j]);
// Reading elements of matrix B
printf("Enter %d elements of matrix B:\n", r2*c2);
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
printf("\n =====Matrix Addition=====\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
} printf("\n");
}
}//end of if
else
printf("\n Addition of matrices is not possible");
}// end of main
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Out put: 1
----------------------
Input rows and columns of A Matrix: 2 2
Input rows and columns of B Matrix: 2 2
Enter 4 elements of matrix A:
1 2
3 4
Enter 4 elements of matrix B:
2 2
3 4
=====Matrix Addition=====
3 4
6 8
--------------------------------
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Out put: 2

Input rows and columns of A Matrix:2 3


Input rows and columns of B Matrix:3 3

Addition of matrices is not possible


Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

//Write a C program to check whether the given matrix is


// an upper triangular matrix or not
#include<stdio.h>
int main()
{
int r, c, i, j, a[5][5], flag=0;
printf("\n Enter no. of rows");
scanf("%d",&r);
printf("\n Enter no. of columns");
scanf("%d",&c);
// Reading 2D array elements
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("a[%d][%d]=",i+1,j+1);
scanf("%d",&a[i][j]);
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

}
}
// display 2D array elements
printf("\n A=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
if (i>j)
{
if(a[i][j]!=0)
flag=1;
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

}
}
if (flag==0)
printf("\n Matrix A is an Upper Triangle Matrix");
else
printf("\n Matrix A is not an Upper Triangle Matrix");

}// end of main


Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

// Write a C Program to find the product of two matrices.


#include<stdio.h>
int main()
{
int r1, c1,r2, c2, i, j,k;
printf("Input rows and columns of A Matrix:");
scanf("%d%d",&r1,&c1);
int a[r1][c1];
printf("Input rows and columns of B Matrix:");
scanf("%d%d",&r2,&c2);
int b[r2][c2];
if (c1==r2)
{ int c[r1][c2];
// Reading elements of matrix A
printf("Enter %d elements of matrix A:\n", r1*c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

scanf("%d",&a[i][j]);
// Reading elements of matrix B
printf("Enter %d elements of matrix B:\n", r2*c2);
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d",&b[i][j]);
printf("\n =====Matrix Multiplication Result==\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<r2;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
} // end of i-loop
// displaying result matrix
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
printf("%d\t", c[i][j]);
printf("\n");
}
} // end of if
else
printf("\n Matrix multiplication is not possible");
}
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Out Put: 1
---------------------------------
Input rows and columns of A Matrix:2 2
Input rows and columns of B Matrix:2 2
Enter 4 elements of matrix A:
1 2
3 4
Enter 4 elements of matrix B:
2 2
1 1

=====Matrix Multiplication=====
4 4
10 10
-----------------------------------------------
Out Put: 2
Input rows and columns of A Matrix:2 3
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Input rows and columns of B Matrix:4 3

Matrix multiplication is not possible


---------------------------------
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

/*Write a program to find the second smallest


and second largest elements in an array. */
#include <stdio.h>

int main()
{
int n, i, j, temp;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the %d elements of array :",n);
int a[n]; //Array Declaration
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++) //Sorting Array in descending orde
for(j=i+1; j<n ;j++)
{
if(a[i]<a[j])
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

printf("\n Sorted array");


for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n The second smallest element is %d",a[n-2]);
printf("\n");
printf("\n The second largest element is %d",a[1]);
return 0;
}
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Out put:

Enter the number of elements:5

Enter the 5 elements of array :12 10 25 4 5

Sorted array
25 12 10 5 4
The second smallest element is 5

The second largest element is 12


Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

/*Write a program to sort an array in descending


order and find the median. */
#include <stdio.h>

int main()
{
int n, i, j, temp;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter the %d elements of array :",n);
float a[n]; //Array Declaration
for(i=0;i<n;i++)
scanf("%f",&a[i]);
for(i=0;i<n;i++) //Sorting Array in descending order
for(j=i+1; j<n ;j++)
{
if(a[i]<a[j])
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

printf("\n Array elements in Descending order\n");


for(i=0;i<n;i++)
printf(" %.1f\t",a[i]);
if (n%2!=0)
printf("\n Median=%.1f",a[n/2]);
else
printf("\n Median=%.1f",(a[n/2]+a[n/2-1])/2.0);
}
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Out put:
Enter the number of elements:5
Enter the 5 elements of array :1 2 3 4 5

Array elements in Descending order


5.0 4.0 3.0 2.0 1.0
Median=3.0
--------------------------------
Out put:
Enter the number of elements:6
Enter the 6 elements of array :
1 2 3 4 5 6

Array elements in Descending order


6.0 5.0 4.0 3.0 2.0 1.0
Median=3.5
--------------------------------
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

/*Write a program to find the product of digits


of a number.*/
#include<stdio.h>
int main()
{
int n,r, p=1,i;
printf("\n Enter a number:");
scanf("%d",&n);
for(i=n;i>0;i=i/10)
{
r=i%10;
p=p*r;
}
printf("\n Product of digits of %d =%d", n, p);
}
--------------------------------
Output:
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Enter a number:123

Product of digits of 123 =6


--------------------------------
Output:
Enter a number:120

Product of digits of 120 =0


Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

/*Write a program to take a 4 digit number N from the user


and print the largest digit in it. Also,
calculate the sum of the digits. */
#include<stdio.h>
int main()
{
int n,r, sum, ld,i,no_of_digits;
printf("\n Enter a 4-digit no:");
scanf("%d",&n);
for(i=n;i>0;i=i/10)// if(n>999 && n<=9999)
no_of_digits++;
if(no_of_digits==4)
{
ld=0;
for(i=n;i>0;i=i/10)
{
r=i%10;
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

sum=sum+r;
if(ld<r)
ld=r;
}
printf("\n Largest digit=%d",ld);
printf("\n sum of digits of %d =%d", n, sum);
}
else
printf("\n your not entered 4-digit no");
}
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

out put:

Enter a 4-digit no:4571

Largest digit=7
sum of digits of 4571 =17
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

/* Write a C program to input elements


in a one-dimensional array and find
frequency of each element in array*/
#include<stdio.h>
int main()
{
int size;
printf("\n Enter the size of array");
scanf("%d",&size);
int arr[size], freq[size],i,j,count;
printf("\n Enter the %d elements of array:",size);
for(i=0; i<size;i++)
{
scanf("%d",&arr[i]);
freq[i]=-1;
}
for(i=0;i<size;i++)
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

{
count=1;
for(j=i+1;j<size;j++)
if(arr[i]==arr[j])
{
count++;
freq[j]=0;
}
if(freq[i]!=0)
freq[i]=count;
}
printf("\n Frequency of all elements of array : \n");
for(i=0; i<size; i++)
if(freq[i]!=0)
printf("%d occurs %d times\n", arr[i], freq[i]);

}
Dr. K. Venkateshwalru 13/19
Multi-Dimensional Arrays
Two-dimensional array

Enter the size of array10

Enter the 10 elements of array:5 10 25 50 5 10 1 2 2 2

Frequency of all elements of array :


5 occurs 2 times
10 occurs 2 times
25 occurs 1 times
50 occurs 1 times
1 occurs 1 times
2 occurs 3 times
Dr. K. Venkateshwalru 14/19
Multi-Dimensional Arrays
Advantages and Disadvantages of Arrays

Advantages of an Array in C:
1 Random access of elements using the array index.
2 Use of fewer lines of code as it creates a single array of multiple
elements.
3 Easy access to all the elements.
4 Traversal through the array becomes easy using a single loop.
5 Sorting becomes easy as it can be accomplished by writing fewer
lines of code.
Disadvantages of an Array in C:
1 Allows a fixed number of elements to be entered which is de-
cided at the time of declaration. Unlike a linked list, an array
in C is not dynamic.
2 Insertion and deletion of elements can be costly since the ele-
ments are needed to be managed in accordance with the new
memory allocation
Dr. K. Venkateshwalru 15/19
Strings in C

Strings

1 Strings are used for storing text/characters. String in C pro-


gramming is a sequence of characters terminated with a null
character ‘\0 ’.
2 Strings are defined as an array of characters.
3 The difference between a character array and a string is the
string is terminated with a unique character ‘\0 ’.
Dr. K. Venkateshwalru 16/19
Strings in C

Declaration of Strings

Declaring a string is as simple as declaring a one-dimensional array.


Below is the basic syntax for declaring a string.
char str name[size];
In the above syntax str name is any name given to the string
variable and
size is used to define the length of the string, i.e the number of
characters strings will store.
Note:
1. There is an extra terminating character which is the Null char-
acter used to indicate the termination of a string.
2. When a sequence of characters enclosed in the double quotation
marks in encountered by the compiler, a null character ‘\0 ’is ap-
pended at the end of the string by default.
Dr. K. Venkateshwalru 17/19
Strings in C

Initializing a String

A string can be initialized in 4 different ways in C.


1 Assigning a string literal without size: String literals can be
assigned without size. Here, the name of the string str acts as
a pointer because it is an array.
Example: char str [ ] =“ Hello world”;
2 Assigning a string literal with a predefined size: String
literals can be assigned with a predefined size.
To store a string of size n, always declare a string with a size
equal to or greater than n+1 as one extra space will be assigned
to the null character.
Example: char str[12]=“Hello world”;
Dr. K. Venkateshwalru 18/19
Strings in C

3 Assigning character by character with size: A sing can be


assigned character by character and a null character should be
assigned at the end.

Example: char str[14]= {‘H ′ , ‘e′ , ‘l′ , ‘l′ , ‘o′ , ‘\0′ };


4 Assigning character by character without size:
A string can be assigned character by character without size
with the NULL character at the end .
The size of the string is determined by the compiler
automatically.

Example: char str[]= {‘H ′ , ‘e′ , ‘l′ , ‘l′ , ‘o′ , ‘\0′ };


Dr. K. Venkateshwalru 18/19
Strings in C

//Program to initialize and print the string

#include <stdio.h>
int main()
{
char data[]={’H’,’E’,’L’,’L’,’O’,’\0’};

printf("string is :%s\n",data);

printf("%c",data[0]);

return 0;
}

// OUT PUT
string is : HELLO
H
Dr. K. Venkateshwalru 18/19
Strings in C

//Program to demonstrate different ways of


//string declaration

#include <stdio.h>
int main()
{
char data1[20]={’H’,’E’,’L’,’L’,’O’,’\0’};
char data2[]={’H’,’E’,’L’,’L’,’O’,’\0’};
char data3[20]="HELLO";
char data4[]="HELLO";
printf("data1 is:%s\n",data1);
printf("data2 is:%s\n",data2);
printf("data3 is:%s\n",data3);
printf("data4 is:%s\n",data4);
return 0;
}
Dr. K. Venkateshwalru 18/19
Strings in C

// out put

data1 is:HELLO
data2 is:HELLO
data3 is:HELLO
data4 is:HELLO
Dr. K. Venkateshwalru 18/19
Strings in C

//Reading string without predefined functions

#include <stdio.h>
int main()
{
char data[10];
printf(" Enter String:");
for(int i=0;i<10;i++)
scanf("%c", &data[i]);
printf(" Entered String is:");
printf("%s",data);
return 0;
}
// Out put
Enter String:Anurag University
Entered String is:Anurag Uni
Dr. K. Venkateshwalru 18/19
Strings in C

//Strings in C can be printed using printf()

#include <stdio.h>
int main()
{
char data[]="Hello World";
for(int i=0;data[i]!=’\0’;i++)
printf("%c",data[i]); // printing string as characters
printf("\n%s",data); // printing string as string
return 0;
}
// Out Put

Hello World
Hello World
Dr. K. Venkateshwalru 18/19
Strings in C

/// C program to show the use of


//gets and puts functions
#include <stdio.h>
int main()
{
char str[10];
printf("\n Enter a String\n ");
gets(str); // Reads string from user
printf("\n The string you entered is :\n");
puts(str);// display string
return 0;
}

// out put
Enter a String
Anurag University
The string you entered is :
Dr. K. Venkateshwalru 18/19
Strings in C

Anurag University
Dr. K. Venkateshwalru 19/19
Strings in C

Implimentation of built in functions: Strings

S.no Function Description


1 strlen(s1) Returns the length of string s1
2 strcpy(s1, s2); Copies string s2 into string s1
3 strcat(s1, s2); Concatenates string s2 onto the end
of string s1
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same;
less than 0 if s1 < s2; greater than 0
if s1 > s2
5 strrev(s1) Reverse all characters of a string
Dr. K. Venkateshwalru 19/19
Strings in C

/* C-Program to impliment built in functions:


strlen(), strcpy(), strcat(), strcmp(),and strrev()*/

#include <stdio.h>
#include<string.h>
int main()
{
char str1[]="Anurag";
char str2[]="Anurag";
char str3[]="University";
printf("\n str1=%s\n",str1);//printing each string
printf("\n str2=%s\n",str2);
printf("\n str3=%s\n",str3);
int c;
c=strcmp(str2, str1);
printf("\n Strcmp(str2, str1)=%d\n",c);
int length;
Dr. K. Venkateshwalru 19/19
Strings in C

length=strlen(str1);
printf("\n The length of the str1 is:%d\n",length);
strcpy(str2, str3);
printf("\n After strcpy(str2, str3), str2=\n");
puts(str2);
strcat(str1, str3);
printf("\n After strcat(str1, str3), str1=\n");
puts(str1);
printf("\n");
printf("\n str3=%s\n",str3);
strrev(str3);// reverse of a string
printf("\n After strrev(str3), str3=%s\n",str3);
return 0;
}
Dr. K. Venkateshwalru 19/19
Strings in C

Out put:

str1=Anurag

str2=Anurag

str3=University

Strcmp(str2, str1)=0

The length of the str1 is:6

After strcpy(str2, str3), str2=


University

After strcat(str1, str3), str1=


AnuragUniversity
Dr. K. Venkateshwalru 19/19
Strings in C

str3=University

After strrev(str3), str3=ytisrevinU


Dr. K. Venkateshwalru 19/19
without Built-in functions

/* calculating string length with and without


built-in function */

#include<stdio.h>
#include<string.h>
int main()
{
char name[10];
int i, length=0;
printf("\n Enter your name: ");
gets(name);
printf("\n name =");
puts(name);
// length of string with strlen
length=strlen(name);
printf("\n length of string=%d",length);
// length of string without strlen
Dr. K. Venkateshwalru 19/19
without Built-in functions

length=0;
for(i=0;name[i]!=’\0’;i++)
length++;
printf("\n length of string=%d",length);
}

Out put:

Enter your name: Anurag

name =Anurag

length of string=6
length of string=6
Dr. K. Venkateshwalru 19/19
without Built-in functions

/*reverse of a string without using


inbuilt functions*/

#include <stdio.h>
#include<string.h>
int main()
{ int c=0;
char s1[20],s2[20];
printf("\n Enter a string: ");
gets(s1);
for(int i=0;s1[i]!=’\0’;i++)
c++;
printf("\n Length of string s1=%d\n",c);
int j=0;
printf("\n string s1=%s\n",s1);
for(int i=c-1; s1[i]!=’\0’; i--)
s2[j++]=s1[i];
Dr. K. Venkateshwalru 19/19
without Built-in functions

printf("\n Reverse of a String is=\n");


puts(s2);

Out put:

Enter a string: Hello hi

Length of string s1=8

string s1=Hello hi

Reverse of a String is=


ih olleH
Dr. K. Venkateshwalru 19/19
without Built-in functions

/* Program to check whether a given string is palindrome


or not without using built-in functions */

#include<stdio.h>
int main()
{
char s1[100], s2[100];
printf("\n Enter a string to check palindrome or not ");
gets(s1);
printf("\n String1= ");
puts(s1);
int length=0,i,c;
for(i=0; s1[i]!=’\0’;i++)
length++;
c=length;
printf("\n length of string1=%d", length);
for(i=0; s1[i]!=’\0’; i++)
Dr. K. Venkateshwalru 19/19
without Built-in functions

s2[i]=s1[--length];
printf("\n reverse of string1=");
puts(s2);
int flag=0;
for(i=0; i<c;i++)
{
if(s1[i]!=s2[i])
{
flag=1;
break;
}
}
if(flag==0)
printf("\n Given string %s is palindrome", s1);
else
printf("\n Given word %s is not a palindrome",s1);
}
Dr. K. Venkateshwalru 19/19
without Built-in functions

Out put:1

Enter a string to check palindrome or not madam


String1= madam

length of string1=5
reverse of string1=madam

Given string madam is palindrome

Out put 2:

Enter a string to check palindrome or not ABCDE


Dr. K. Venkateshwalru 19/19
without Built-in functions

String1= ABCDE

length of string1=5
reverse of string1=EDCBA

Given word ABCDE is not a palindrome


Dr. K. Venkateshwalru 19/19
without Built-in functions

/*This C program is used to concatenate strings


without using strcat() function */
#include<stdio.h>
int main()
{
char s1[20],s2[10];
int length=0,i,j;
printf("\n Enter a string1:");
gets(s1);
printf("\n Enter a string2:");
gets(s2);
for(i=0;s1[i]!=’\0’;i++)
length++;
printf("\n length of s1=%d\n",length);
printf("string1=%s\n string2=%s",s1,s2);
j=0;
for(i=length; s2[j]!=’\0’;i++)
Dr. K. Venkateshwalru 19/19
without Built-in functions

s1[i]=s2[j++];
printf("\n After concatenation s1=%s",s1);
}

Out put:

Enter a string1:Hello

Enter a string2:Hi

length of s1=5

string1=Hello

string2=Hi

After concatenation s1=HelloHi

You might also like