0% found this document useful (0 votes)
15 views28 pages

Aut - Unit 2

Uploaded by

it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views28 pages

Aut - Unit 2

Uploaded by

it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT II ARRAYS AND STRINGS

Arrays: Introduction – Declaration of Arrays – Storing Values in Array – Accessing elements of


the Array– Operations on Array – one dimensional arrays – Two dimensional Arrays –String:
Declaring, Initializing, Printing and reading strings, String input and output functions, String
handling functions, Arrays of strings.

INTRODUCTION TO ARRAYS:
An array is a collection of similar data items that are stored under a common name.
Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.
It is a derived data type in C.
What is the use of array?
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Example where arrays are used,
 to store roll numbers of the students in a class
 to store marks of a students
 to store list of names of employees etc..

Array can store integer, float and double values which is said to be integer array.
Array that is used to store characters are said to be Character array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
Array index starts with 0 and ends with n-1.
Element of an array is accessed using index or subscript.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t
assign any values to array.
Advantage of array:
 Code Optimization: Less code is required, one variable can store numbers of
value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily sort the data using swapping technique.
 Random Access: With the help of array index you can randomly access any
elements from array.
Types of an array:
1. Single dimensional array
2. Multi dimensional array
Single(one)dimensional array:
 Array having only one subscript [ ] variable is called One-Dimensional array.
 It is also called as Single Dimensional Array or Linear Array or list.
 The elements of one dimensional array is also called as linear array
Declaring Array:
data_type array_name[size];
Example:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
 After an array is declared it must be initialized.
 An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization
(i) Compile time Array initialization:
- Compile time initialization of array elements is same as ordinary variable
initialization.
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
double balance[10]={1000.0,20.0,3.4,7.2,50.0}
char str[10]={‘H’,‘a’,‘i’}; // character array
Accessing Array Elements:
We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}
here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to
initialize array by getting the input from the user.
Syntax:

for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Reading and Printing array of elements( Run Time Output:
initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1D array:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);
2. Assigning an array to another array
A variable can be assigned to another variable but array can’t be assigned to
another array directly.
Output:
#include<stdio.h> //compilation error
int main()
{
int a[3], b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}

Example Programs: (using One Dimensional Array)


C program to find sum of array of elements: Output:
#include<stdio.h> Enter the size of
int main() array:
{ 4
int i, arr[20], n, sum=0; Enter the values:
printf("Enter the size of array:\n"); 2
scanf("%d",&n); 5
printf("Enter the values:\n"); 1
for(i=0;i<n;i++) 12
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("the sum of the array is %d",sum);
return(0);
}
C Program to find the largest element in an array: Output:
#include<stdio.h> enter the size of an
int main() array :3
{ enter the elements of
int arr[10]; an array
int large,i,n; 23
printf("enter the size of an array :"); 2
scanf("%d",&n); 15
printf("enter the elements of an array\n"); largest element is: 23
for(i=0;i<=n-1;i++)
{
scanf("%d",&arr[i]); Note:
} Can also try the size
large=arr[0]; of array and
for(i=1;i<=n-1;i++) elements of array by
{ getting input from
if(arr[i]>large) user.
large=arr[i];
}
printf("largest element is: %d\n",large);
return(0);
}
Note:
(Same can be done to find the smallest element also. use < to
find smallest element)
Program to insert an element in an array at specific position Output:
#include<stdio.h> enter the position
int main() where the new
{ element to be inserted
int arr[50]={10,20,30,40,50},i,pos,element; 2
printf("enter the position where the new element to be enter the new element
inserted\n"); to be inserted
scanf("%d",&pos); 25
printf("enter the new element to be inserted\n"); after
scanf("%d",&element); insertion ,elements
for(i=4;i>=pos;i--) are
{ 10
arr[i+1]=arr[i]; //moving the elements 20
} 25
arr[pos]=element; 30
printf("after insertion ,elements are\n"); 40
for(i=0;i<=5;i++) 50
{
printf("%d\n",arr[i]);
}
return(0);
}
C program to delete an element in an array: Output:
#include<stdio.h> Enter the size of an
int main() array
{ 4
int n, a[10],i,pos; Enter the array
printf("Enter the size of an array\n"); elements
scanf("%d",&n); 23
printf("Enter the array elements\n"); 12
for(i=0;i<n;i++) 5
{ 47
scanf("%d",&a[i]); Enter the position to
} be deleted
printf("Enter the position to be deleted\n"); 1
{ After deletion:
scanf("%d",&pos); 23
} 5
if(pos>=n) 47
{
printf("deletion is not possible");
}
else
{
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
}
printf("After deletion:\n");
for(i=0;i<n-1;i++)
{
printf("%d\n",a[i]);
}
return(0);
}
C program to display elements in Descending order: Output:
#include <stdio.h> Enter the size of
int main() array: 5
{ Enter the elements of
int arr[50],n,i,j; array:
int temp; 2
printf("Enter the size of array: "); 6
scanf("%d",&n); 8
printf("Enter the elements of array:\n"); 9
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); Array elements after
sorting:
for(i=0;i<=n-1;i++) 9
{ 8
for(j=i+1;j<=n-1;j++) 6
{ 2
if(arr[i]<arr[j]) //sort array 1
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}

Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.
Types:
1. Linear search
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues till
the end of the list.
Concept of linear Search:
i. To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:
 The linear search is simple - It is very easy to understand and implement;
 It does not require the data in the array to be stored in any particular order.
Disadvantages:
The linear search is inefficient(takes more time) if the list has more number of elements.
C program to perform Linear Search:
#include<stdio.h> Output:
int main() Enter the number of
{ elements in array
int array[100], item, i, n, found=0; 4
printf("Enter the number of elements in array\n"); Enter the elements
scanf("%d",&n); 6
printf("Enter the elements \n", n); 12
for (i = 0; i < n; i++) 5
scanf("%d", &array[i]); 8
Enter the element to
printf("Enter the element to search\n"); search
scanf("%d", &item); 5
5 is present in array and
for (i = 0; i <=n-1; i++) position is 2
{
if (array[i] == item) // if required element found
{
found=1;
break;
}
}
if (found==1)
printf("%d is present in array and position is %d\n", item,i);
else
printf("%d is not present in array.\n", item);
return 0;
}
Binary Search:
 Binary search is an algorithm used to find an element in an sorted array by using the
divide and conquer concept.
 This method can be applied only if list is in sorted order.
 List is divided into two halves separated by middle element.
Left half Middle Right half
Concept of Binary search:
i. Find the middle element
ii. Check the middle element with the element to be found
iii. If the middle element is equal to that element, then it will provide the output.
iv. If the value is not same, then it will check whether the middle element value is less
than or greater than the element to be found.
v. If the value is less than that element, then the search will start with the elements next
to the middle element.
vi. If the value is high than that element, then the search will start with the elements
before to the middle element.
vii. This process continues, until that particular element has been found.
Example: Consider the following set of elements in array where 31 is the element to be
searched.

Middle =(First+Last)/2 =>(0+9)/2 =4.5=>4

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

We change our low to mid + 1 and find the new mid value again.
Like this searching continues until we find the desired element.

Advantages:
 Faster than linear search.
Disadvantages :
 Binary search algorithm can work only with the sorted array (either ascending or
descending order).
 It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of the first one.
Program for Binary search: Output:
#include <stdio.h>
int main() enter size of array
{ 6
int i, first, last, middle, n, item, arr[50]; enter the elements
printf("enter size of array"); 5
scanf("%d",&n); 12
printf("enter the elements\n"); 4
for (i = 0; i <=n-1; i++) 7
{ 18
scanf("%d",&arr[i]); 240
} Enter element to find
printf("Enter element to find\n"); 18
scanf("%d", &item); 18 found at location 4
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (arr[middle] < item)
{
first = middle + 1;
}
else if (arr[middle] == item)
{
printf("%d found at location %d.\n", item, middle);
break;
}
else
{
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", item);
return (0);
}
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Consider the following example:

Program to perform selection sorting (ascending order) Output:


#include <stdio.h> Enter the size of array: 5
int main() Enter the elements of array:
{ 1
int arr[50],n,i,j; 6
int temp; 4
printf("Enter the size of array: "); 6
scanf("%d",&n); 1
printf("Enter the elements of array:\n"); Array elements after sorting:
for(i=0;i<=n-1;i++) 1
scanf("%d",&arr[i]); 1
4
for(i=0;i<=n-1;i++) 6
{ 6
for(j=i+1;j<=n-1;j++)
{
if(arr[i]>arr[j]) //sort array
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return (0);
}
Computing Mean, Median
Mean: The average of a set of numbers.
The mean is the usual average, so I'll add and then divide:
(13 + 18 + 13 + 14 + 13 + 16 + 14 + 21 + 13) ÷ 9 = 15
Median: The middlemost number in a set of number arranged in order.
The median is the middle value, so first I'll have to rewrite the list in numerical order:
13, 13, 13, 13, 14, 14, 16, 18, 21
There are nine numbers in the list, so the middle one will be the (9 + 1) ÷ 2 = 10 ÷ 2 = 5th
number:
13, 13, 13, 13, 14, 14, 16, 18, 21
So the median is 14.
Mode: Mode is the number that is repeated more often than any other, so 13 is the mode.

C program to create mean and median of array of Output:


elements enter size of array
#include <stdio.h> 5
int main() enter the elements
{ 6
int i,j,a[20], sum=0,n,temp,b[20]; 4
float mean=0.0, median=0.0; 3
printf("enter size of array\n"); 2
scanf("%d",&n); 4
printf("enter the elements\n"); mean value is
for (i = 0; i <=n-1; i++) 3.800000median is 4.000000
{
scanf("%d",&a[i]);
sum=sum+a[i]; //Calculating mean
}
mean=(float)sum/(float)n;
printf("mean value is %f",mean);
for(i=0;i<=n-1;i++)
{
for(j=i+1;j<=n-1;j++) //calculating median
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
median=(float)(a[n/2]+a[(n-1)/2])/2;
else
median=a[(n-1)/2];
printf("median is %f",median);
}
Two dimensional Arrays:( Multidimensional Arrays
- In 2-dimentional array, elements are arranged in row and column format.
- An array with two subscripts[ ][ ] is termed as two dimensional arrays.
- A two dimensional array enables us to store multiple rows of elements, in form of
matrix.
Array Declaration Syntax:
data_type arr_name [num_of_rows][num_of_column];

Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
Array Initialization:
(i) Compile time Initialization
Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };
int arr[2][3] = { 0,0,0, 1,1,1 };
Array accessing syntax:
arr_name[index];
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;
Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.
ii) Run Time initialization:
Syntax:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,a[i][j]);
}
}
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];

Matrix multiplication: Output:


#include<stdio.h> enter the size
int main() 2
{ 2
int i, j, k,m,n; Enter A matrix
int a[10][10], b[10][10]; 2
int c[10][10]={0}; 2
printf("enter the size"); 2
scanf("%d%d",&m,&n); 2
printf("Enter A matrix\n"); Enter B matrix
for (i = 0; i <=m-1; i++) 2
{ 2
for (j = 0; j <=n-1; j++) 2
{ 2
scanf("%d", &a[i][j]); The product of matrix is
} 8 8
} 8 8
printf("Enter B matrix\n");
for (i = 0; i <= m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The product of matrix is\n");
for (i = 0; i <=m-1; i++)
{
for (j = 0; j <=n-1; j++)
{
for (k = 0; k <=m-1; k++)
{
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
C Program to perform scalar multiplication: Enter Rows and Columns of
#include <stdio.h> Matrix
int main() 2
{ 2
int a[50][50]; enter the elements of matrix
int m, n, i, j, scalar; 2
printf("Enter Rows and Columns of Matrix\n"); 1
scanf("%d %d", &m, &n); 3
5
printf("enter the elements of matrix\n"); Enter a scalar number to
for(i = 0; i <=m-1; i++) multiply with matrix
for(j = 0; j <=n-1; j++) 5
scanf("%d", &a[i][j]); Product Matrix is
10 5
printf("Enter a scalar number to multiply with matrix \n"); 15 25
scanf("%d", &scalar);
/* Multiply each element of matrix with scalar*/
for(i = 0; i <= m-1; i++)
{
for(j = 0; j <=n-1; j++)
{
a[i][j] = a[i][j]*scalar;
}
}

printf("Product Matrix is\n");


for(i= 0; i <=m-1; i++)
{
for(j = 0; j<=n-1; j++)
printf("%d ", a[i][j]);
}
printf("\n");
return(0);
}
C Program to TRANSPOSE a matrix: Output:
#include <stdio.h> Enter the SIZE of the matrix
int main() 2
{ 3
int a[10][10], i, j, m, n; Enter the ELEMENTS of the
printf("Enter the SIZE of the matrix \n"); matrix
scanf("%d %d", &m, &n); 2
printf("Enter the ELEMENTS of the matrix\n"); 1
for (i = 0; i <= m-1; i++) 5
{ 3
for (j = 0; j<= n-1; j++) 7
{ 8
scanf("%d", &a[i][j]); The given matrix is
} 215
} 378
printf("The given matrix is \n"); Transpose of matrix is
for (i = 0; i <=m-1; ++i) 23
{ 17
for (j = 0; j <= n-1; ++j) 58
{
printf(" %d", a[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is \n");
for (j = 0; j <=n-1; j++) //interchanging rows and
columns
{
for (i = 0; i <=m-1; i++)
{
printf(" %d", a[i][j]);
}
printf("\n");
} return(0);
}
C program to find determinant of 2*2 Matrix :
#include<stdio.h>
int main()
{ Example:
int a[2][2],i,j; Output:
long determinant;
printf("Enter the elements of matrix:\n "); Enter the elements of matrix:
for(i=0;i<2;i++) 8
for(j=0;j<2;j++) 3
scanf("%d",&a[i][j]); 2
1
printf("\nThe matrix is\n"); The matrix is
for(i=0;i<2;i++) 8 3
{ 2 1
printf("\n"); Determinant is :2
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];
printf("\nDeterminant is :%ld",determinant);
return(0);
}
Determinant of 3*3 matrix Enter the elements of
#include<stdio.h> matrix: 1
int main() 5
{ 4
int a[3][3],i,j; 2
int determinant=0; 1
printf("Enter the elements of matrix: "); 2
for(i=0;i<3;i++) 1
for(j=0;j<3;j++) 2
scanf("%d",&a[i][j]); 1
printf("\nThe First matrix is\n");
for(i=0;i<3;i++) The First matrix is
{
printf("\n"); 1 5 4
for(j=0;j<3;j++) 2 1 2
printf("%d\t",a[i][j]); 1 2 1
} Determinant of matrix is: 9
for(i=0;i<3;i++)
determinant = determinant + (a[0][i]*(a[1]
[(i+1)%3]*a[2][(i+2)%3] - a[1][(i+2)%3]*a[2][(i+1)%3]));
printf("\nDeterminant of matrix is: %d",determinant);
return(0);
}
Three Dimensional array:
Total number of elements that can be stored in a multidimensional array can be calculated
by multiplying the size of all the dimensions.
Example:
int arr[5][10][20] can store total (5*10*20) = 1000 elements totally.

Disadvantages of an array:
 The elements in an array must be same data type.
 The size of an array is fixed. we can’t expand the size in run time.
 The insertion and deletion operations in an array require shifting of
elements which takes more time.

INTRODUCTION TO STRINGS
Nowadays, computers are widely used for word processing applications such as creating,
inserting, updating, and modifying textual data. Besides this we need to search for a
particular pattern within a text, delete it, or replace it with another pattern. So there is
actually a lot we as users do to manipulate the textual data.
Programming Tip: Character constants are enclosed in single quotes. String constants are
enclosed in double quotes.

In C language, a string is a null-terminated character array. This means that after the last
character, a null character ('\0') is stored to signify the end of the character array. For
example, if we write

char str[] = "HELLO";

We are declaring a character array that has five usable characters namely, H, E, L, L, and O.
Apart from these characters, a null character ('\0') is stored at the end of the string. So, the
internal representation of the string becomes HELLO'\0'. To store a string of length 5, we
need 5 + 1 locations (1 extra for the null character). The name of the character array (or
the string) is a pointer to the beginning of the string. Figure 6.1 shows the difference
between character storage and string storage.

If we declare str as,

char str[5] = "HELLO";

Then the null character will not be appended automatically to the character array. This is
because str can hold only 5 characters and the characters in HELLO have already filled the
locations allocated to it.

Note

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


appends a null character to the end of the string. Therefore, the size of the string should
be equal to maximum number of characters in the string plus one.
Programming Tip: When allocating memory space for a character array, reserve space to
hold the null character also.

Like we use subscripts (also known as index) to access the elements of an array, similarly
subscripts are also used to access the elements of the character array. The subscript starts
with a zero (0). All the characters of a string array are stored in successive memory
locations. Figure 6.2 shows how str[] is stored in ed in memory.

Thus we see that a string is a sequence of characters. In Figure 6.2, 1000, 1001, 1002, and
so on are the memory addresses of individual characters. From the figure, we see that H is
stored at memory location 1000 but in reality the ASCII codes of characters are stored in
memory and not the character itself, i.e., at address 1000, 72 will be stored since the ASCII
code for H is 72.

char str[] = "HELLO";

The above statement declares a constant string as we have assigned value to it while
declaring the string. However, the general form of declaring a string is

char str[size];

When we declare the string in this way, we can store size -1 characters in the array
because the last character would be the null character. For example, char mesg [100]; can
store a maximum of 99 usable characters.

Till now we have seen one way of initializing strings. The other way to initialize a string is
to initialize it as an array of characters, like

char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};

In this example, we have explicitly added the null character. Also observe that we have not
mentioned the size of the string (or the character array). Here, the compiler will
automatically calculate the size based on the number of elements initialized. So, in this
example 6 memory slots will be reserved to store the string variable, str.
We can also declare a string with size much larger than the number of elements that are
initialized. For example, consider the statement below:

char str [10] = "HELLO";

In such cases, the compiler creates a character array of size 10; stores the value "HELLO" in
it and finally terminates the value with a null character. Rest of the elements in the array
are automatically initialized to NULL. Figure 6.3 shows the memory representation of such
a string.

Consider the following declaration:

char str[3];

str = "HELLO";

The above declaration is illegal in C and would generate a compile time error because of
two reasons. First, the array is initialized with more elements than it can store. Second,
initialization cannot be separated from declaration.

Note

An array name cannot be used as the left operand of an assignment operator. Therefore,
the following statement is illegal in C.

char str2, str1[]="HI";

str2 = strl;

Reading Strings
If we declare a string by writing

char str[100];

Then str can be read by using three ways:


1. using scanf function

2. using gets () function

3. using getchar(), getch() or getche () function repeatedly

Strings can be read using scanf() by writing

scanf("%s", str);

Programming Tip: Using & operand with a string variable in the scanf statement is
optional as string variable is a character array and denotes the address where the array
begins.

Although the syntax of scanf() function is well known and easy to use, the main pitfall with
this function is that the function terminates as soon as it finds a blank space. For example,
if the user enters Hello World, then str will contain only Hello. This is because the moment
a blank space is encountered, the string is terminated by the scanf() function. You may
also specify a field width to indicate the maximum number of characters that can be read
in. Remember that extra characters are left unconsumed in the input buffer.

Unlike int (%d), float (f), and char (c), %s format does not require ampersand before the
variable name.

Note

When scanf() encounters a white space character, it ter- minates reading further and
appends a null character to the string that has been read. The white space character is
left in the input stream and might be mistakenly read by the next scanf() statement. So
in order to delete the white space character from the input stream, either use a space in
the format string before the next conversion code or FLUSH the input stream by using the
fflush function by writing fflush(stdin).

The next method of reading a string is by using gets () function. The string can be read by
writing

gets (str);

gets () is a simple function that overcomes the drawbacks of the scanf() function. The gets
() function takes the starting address of the string which will hold the input. The string
inputted using gets () is automatically terminated with a null character.

Last but not the least, strings can also be read by calling the getchar() function repeatedly
to read a sequence of single characters (unless a terminating character is entered) and
simultaneously storing it in a character array as shown below.
i=0;

ch = getchar(); // Get a character

while (ch != '*')

str[i] = ch;

// Store the read character in str

i++;

ch= getchar(); // Get another character

str[i] = '\0'; // terminate str with null character

Programming Tip: A compile time error will be generated if a string is assigned to a


character variable.

Note that in this method, you have to deliberately append the charac- ters with a null
character. The other two functions automatically do this.

Writing Strings
Strings can be displayed on screen using three ways:

1. using printf() function

2. using puts() function

3. using putchar () function repeatedly

A string can be displayed using printf () by writing

printf("%s", str);

We use the conversion character 's' to output a string. We may also use width and
precision specifications along with %s (as discussed in Chapter 2). The width specifies the
minimum output field width. If the string is short, extra space is either left padded or right
padded. A negative width left pads short string rather than the default right justification.
The precision specifies the maximum number of characters to be displayed. If the string is
long, the extra characters are truncated. For example,
printf("%5.3s", str);

The above statement would print only the first three characters in a total field of five
characters. Also these three characters are right justified in the allocated width. To make
the string left justified, we must use a minus sign. For example,

printf("%-5.3s", str);

Note

When the field width is less than the length of the string, the entire string will be printed.
Also if the number of characters to be printed is specified as zero, then nothing is printed
on the screen.

The next method of writing a string is by using puts () function. The string can be displayed
by writing

puts (str);

puts () is a simple function that overcomes the drawbacks of the printf() function. The puts
() function writes a line of output on the screen. It terminates the line with a newline
character ('\n'). It returns an EOF (-1) if an error occurs and returns a positive number on
success. Last but not the least, strings can also be written by calling the putchar() function
repeatedly to print a sequence of single characters.

i=0;

while (str[i] != '\0')

putchar (str[i]);

// Print the character on the screen

i++;

Note

Note one interesting point from the given fragment.

char str = "Hello";


printf("\n %s", str); // prints Hello

printf("\n %s", &str); // prints Hello

printf("\n %s", &str[2]); // prints llo

This is possible because a string is an array of characters.

Summary of Functions Used to Read and Write Characters


Table 6.1 contains a list of functions that are used to read characters from the keyboard
and write characters to the screen.

1. Write a program to display a string using printf().


#include <stdio.h>

#include <conio.h>

int main()

char str[] = "Introduction to C";

clrscr();

printf("\n |%\s", str);

printf("\n |%20s|", str);

printf("\n |%-20s", str);

printf("\n %.4s", str);

printf("\n |%20.4s", str);

printf("\n %-20.4s", str);

getch();

return 0;

Output
| Introduction to C |

| Introduction to C |

| Introduction to C |

| Intr |

| Intr |

| Intr |

The printf() function in UNIX supports specification of variable field width or precision, i.e.,
if we write,

printf("\n %*.s*, w, p, str);

Then the printf() statement will print first p characters of str in the field width of w.

2. Write a program to print the following pattern.

HE

HEL
HELL

HELLO

HELLO

HELL

HEL

HE

H
#include <stdio.h>

#include <conio.h>

int main()

int i, w, p;

char str[] = "HELLO";

printf("\n");

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

p = i+1;

printf("\n %-5.*s", p, str);

printf("\n");

for (i=4;i>=0; i--)

{
p = i+1;

printf("\n %-5.*s", p, str);

getch();

return 0;

sprintf() Function
The library function sprintf() is similar to printf (). The only difference is that the formatted
output is written to a memory area rather than directly to a standard output
(screen). sprintf() is useful in situations when formatted strings in memory have to be
transmitted over a communication channel or to a special device. The syntax
of sprintf() can be given as

int sprintf( char * buffer, const char * format [ , argument, ..] );

Here, buffer is the place where string needs to be stored. The arguments command is an
ellipsis so you can put as many types of arguments as you want. Finally, format is the
string that contains the text to be printed. The string may contain format tags.

#include <stdio.h>

main()

char buf[100];

int num = 10;

sprintf(buf, "num = %3d", num);

You might also like