Arrays & Strings
© Oxford University Press 2013. All rights reserved.
Objective
Understand what an array is
Learn about one-dimensional array, their declaration, initialization,
ways to access individual array elements, representation of array
elements in memory, and other possible operations
Learn about one-dimensional strings and the way they are declared,
initialized, manipulated, inputted, and displayed
Learn about two-dimensional arrays, initialization of sized and
unsized two-dimensional
Arrays, accessing elements in such arrays, and how this kind of an
array can be used
Know about array of strings, its declaration, initialization, other
operations, manipulations, and uses
Get a brief idea of three-dimensional arrays or even larger ones
© Oxford University Press 2013. All rights reserved.
Introduction
A scalar variable is a single variable whose stored value is an
atomic type.
For example, each of the variables ch, n, and price declared in the
statements
char ch;
int n;
float price;
Are of different data types and each variable can only store one value of
the declared data type. These types of variables are called scalar
variables.
This means that the value cannot be further subdivided or separated
into a legitimate data type.
An aggregate type, which is referred to as both a structured type and a
data structure, is any type whose values can be decomposed and are
related by some defined structure.
© Oxford University Press 2013. All rights reserved.
Key Words
Aggregate data type: It is an agglomeration of data, of any data type,
that is identified with a single name and can be decomposed and related
by some defined structure.
Array identifier: A name assigned to an array.
Array initialization: The procedure of assigning numerical value or
character to each element of an array.
Array of strings: An array that contains strings as its elements.
Array: It is a collection of individual data elements that is ordered, fixed
in size and homogeneous.
Concatenation of strings: A kind of string manipulation where one
string is appended to another string.
© Oxford University Press 2013. All rights reserved.
Key words
Homogeneous data: Data of same kind or same data type.
Index of an array: It is an integer constant or variable ranging
from 0 to (size – 1).
Library functions: Pre-written functions, provided with the C
compiler, which can be attached to user written programs to carry
out some task.
Multidimensional array: An array that is represented by a name
and more than one index or subscript.
One-dimensional array: An array that is represented by a name
and single index or subscript.
Scalar variable: It is a single variable whose stored value is an
atomic data type.
Scanset: It is a conversion specifier that allows the programmer
to specify the set of characters that are (or are not) acceptable as
part of the string.
© Oxford University Press 2013. All rights reserved.
Key Words
Size of array: The number of elements in an array.
Stderr: The side stream of output characters for errors is called standard-
error.
Stdin: Standard input stream that is used to receive and hold input data
from standard input device.
Stdout: Standard output stream that is used to hold and transfer output
data to standard output device.
String compare: A kind of string manipulation where two strings are
compared to primarily find out whether they are similar or not.
String copy: A kind of string manipulation where one string is copied into
another.
String manipulation: Carrying out various operations like comparing,
appending, copying, etc. among strings.
String : One-dimensional array of characters that contain a NUL at the
end.
© Oxford University Press 2013. All rights reserved.
Why Array?
Consider a brand-new problem: a program that
can print its input in reverse order. If there are
two or three values, this is easy but what if there
are ten or twenty or one hundred values? Then it
is not so easy. To avoid above problem we use
array .
A scalar variable is a single variable whose stored value
is an atomic data type.
An array is a collection of individual data elements that is
ordered, fixed in size, and homogeneous.
An array is considered to be a derived data type.
Array enables the storing and manipulation of potentially
huge quantities of data.
© Oxford University Press 2013. All rights reserved.
One-Dimensional Array
There are several forms of an array used in C:
One dimensional or single-dimensional and multidimensional
array.
Since the array is one dimensional, there will be a single
subscript or index whose value refers to the individual array
element which ranges from 0 to (n–1), where n is the total
number of elements in the array.
When defining an array in a program three things need to
be specified.
The type of data it can hold, i.e., int, char, double, float, etc.
The number of values it can hold, i.e., the maximum number of
elements it can hold
A name
© Oxford University Press 2013. All rights reserved.
One-Dimensional Array
The array size must be a positive integer number
or an expression that evaluates to a positive
integer number that must be specified at the
time of declaration with the exception that it may
be unspecified while initializing the array.
In C, the array index starts at 0 and ends at
(size–1) and provides the means of accessing and
modifying the specific values in the array.
C never checks whether the array index is valid—
either at compile time or when the program is
running.
© Oxford University Press 2013. All rights reserved.
Syntax: Array
The syntax for declaration of a one-dimensional array is data_type
array_name [SIZE];
All the array elements hold values of type <data type>
The size of the array is indicated by <SIZE>, the number of
elements in the array. <SIZE> must be an int constant or a
constant expression.
int a[size]; /* memory space for a[0],a[1],…, a[size –1] allocated */
lower bound = 0
upper bound = size –1
size = upper bound + 1
number[0] & number[4] refers to the first & fifth number stored
in the ‘number’ array respectively .
© Oxford University Press 2013. All rights reserved.
Initializing Integer Arrays
Variables can be assigned values during declaration like the
following example.
int x = 7;
Array initialization statements as shown.
(a) int A[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
9 8 7 6 5 4 3 2 1 0 ¨ values stored in array elements
0 1 2 3 4 5 6 7 8 9 ¨index values of array elements
(b) double a[5] = {3.67, 1.21, 5.87, 7.45, 9.12}
Automatic sizing While initializing, the size of a one
dimensional array can be omitted as shown.
int arr[] = {3,1,5,7,9};
Here, the C compiler will deduce the size of the array from the
initialization statement.
© Oxford University Press 2013. All rights reserved.
Array declaration,
initialization and Example
accessing
Integer array example:
int age [5];
int age[5]={0, 1, 2, 3, 4};
Array declaration age[0]; /*0 is accessed*/
syntax: age[1]; /*1 is accessed*/
data_type arr_name age[2]; /*2 is accessed*/
[arr_size];
Array initialization
syntax: Character array example:
data_type arr_name char str[10];
[arr_size]=(value1, char str[10]={‘H’,‘a’,‘i’};
value2, value3,….); (or)
Array accessing char str[0] = ‘H’;
syntax: char str[1] = ‘a’;
arr_name[index]; char str[2] = ‘i;
str[0]; /*H is accessed*/
str[1]; /*a is accessed*/
str[2]; /*i is accessed*/
© Oxford University Press 2013. All rights reserved.
example
#include<stdio.h>
int main()
{
int i; value of arr[0] is 10
int arr[5] = {10,20,30,40,50}; value of arr[1] is 20
for (i=0;i<5;i++) value of arr[2] is 30
{ value of arr[3] is 40
// Accessing each variable value of arr[4] is 50
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}
example
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
balance[4] = 50.0;
0 1 2 3 4
1000.0 2.0 3.4 7.0 50.0
pictorial representation of the array we discussed above
© Oxford University Press 2013. All rights reserved.
#include <stdio.h>
int main () Output
{ int n[ 10 ];
/* n is an array of 10 integers */ Element[0] = 100
Element[1] = 101
int i,j;
Element[2] = 102
/* initialize elements of array n to 0 */ Element[3] = 103
for ( i = 0; i < 10; i++ ) Element[4] = 104
{ Element[5] = 105
n[ i ] = i + 100; Element[6] = 106
/* set element at location i to i + 100 Element[7] = 107
*/ Element[8] = 108
} Element[9] = 109
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Accessing Array Elements
x and y are similar arrays (i.e., of the same data type,
dimensionality, and size), then assignment operations,
comparison operations, etc., involving these two arrays
must be carried out on an element-by-element basis.
Determine total of all elements in a number array
Examples using the elements of an array named ‘numbers’
are shown here:
numbers [0] = 98;
numbers [1] = numbers [0] – 11
numbers [2] = 2 * (numbers [0] – 6);
numbers [3] = 79;
numbers [4] = (numbers [2] + numbers [3] – 3)/2;
total = numbers[0] + numbers[1] + numbers[2] + numbers[3]
+ numbers[4];
© Oxford University Press 2013. All rights reserved.
Accessing Array Elements
This makes statements such as:
Total = numbers[0] + numbers[1] + numbers[2] + numbers[3] +
numbers [4];
One extremely important advantage of using integer
expressions as subscripts is that it allows sequencing
through an array using a for loop.
Example, using the for loop statements,
total = 0; /*initialize total to zero */
for(i = 0; i <5; ++i)
total = total + numbers[i]; /* add in a number */
© Oxford University Press 2013. All rights reserved.
Array : Other Allowed Operations
These operations include the following, for an array named ‘ar’.
◦ (a) To increment the ith element, the given statements
can be used.
ar[i]++;
ar[i] += 1;
ar[i] = ar[i] + 1;
◦ (b) To add n to the ith element, the following statements
may be used,
ar[i] += n;
ar[i] = ar[i] + n;
© Oxford University Press 2013. All rights reserved.
Array : Other Allowed Operations
These operations include the following, for an array named ‘ar’.
◦ (c) To copy the contents of the ith element to the kth
element, the following statement may be written.
ar[k] = ar[i];
(d) To copy the contents of one array ‘ar’ to another array ‘br’, it
must again be done one by one.
int ar[10],br[10];
ar[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
for(i = 0; i < 10; i = i + 1)
{
br[i] = ar[i];
}
© Oxford University Press 2013. All rights reserved.
Array : Other Allowed Operations
These operations include the following, for an array named ‘ar’.
◦ (e) To exchange the values in ar[i] and ar[k], a
‘temporary’ variable must be declared to hold one
value, and it should be the same data type as the array
elements being swapped.
int temp;
temp = ar[i];
/* save a copy of value in ar[i] */
ar[i] = ar[j];
/* copy value from ar[j] to ar[i] */
ar[j] = temp;
/* copy saved value of ar[i] to ar[j] */
© Oxford University Press 2013. All rights reserved.
Storing values given by the user in an
array
Reading the input into an array is done as
shown. int a[10]; /* an array with 10 “int”
elements */
int i;
for(i=0 ; i< 10; i++)
scanf(“%d”, &a[i]);
The idea is that first a value must be read and
copied into a[0], then another value read and
copied into a[1], and so on, until all the input
values have been read.
© Oxford University Press 2013. All rights reserved.
#include <stdio.h> Enter the 10 numbers:
int main(void) 1> 2
{ 2> 3
int numbers[10]; 3> 1
int count = 10; 4> 2
5> 1
int sum = 0;
6> 1
float average = 0.0f; 7> 1
printf("\nEnter the 10 numbers:\n"); 8> 2
9> 1
int i; 10> 1
for(i = 0; i < count; i ++) Average of the ten
{ numbers entered is:
printf("%d> ",i+1); 1.500000
scanf("%d", &numbers[i]);
sum += numbers[i];
}
printf("\nsum of the ten numbers entered is: %d\n", sum);
average = (float)sum/count;
printf("\nAverage of the ten numbers entered is: %f\n", average);
return 0;
© Oxford } Press 2013. All rights reserved.
University
Printing an Array
The following code segment prints the elements of an
array, a[10].
for(i=0 ; i< 10; i++)
printf(“%d”, a[i]);
For printing of numbers entered by the user in the reverse
order, the program will be as follows
© Oxford University Press 2013.
All rights reserved.
Print odd numbers
#include <stdio.h>
int main() in an array
{
int a[5],i;
printf("Enter 5 Numbers:\n");
/*For accepting 5-integer numbers from user*/
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printf("Odd Numbers in Array are:\n");
for(i=0;i<5;i++)
{
if(a[i]%2!=0) //Check number is odd
{
printf("%d ",a[i]);
}
}
return 0;
}
Write a program to find largest element
stored in an array.
#include <stdio.h>
int main()
{
int a[50],i,n, large;
printf(“\nEnter how many numbers :”);
scanf(“%d”,&n);
printf(“\nEnter values for the array: ”);
for(i=0; i<n; i++) /* Stores number entered by user. */
scanf("%d",&a[i]);
/*code to find largest element in an array*/
large=a[0];
for(i=1; i<n; i++)
{
if(a[i]>large)
large=a[i];
}
printf(“\nThe largest element stored in array a is %d”, large);
return 0;
}
Now , you find out the min of an array
How to find second largest element in an
array
Second largest array element in
C
Max 1 = a[0]
Max 2 =0
if a[i] > Max1
{Max2= Max1
Max 1=a[i]}
Internal Representation of Arrays in C
References to elements outside of the array bounds It is
important to realize that there is no array bound checking in C.
A bit of memory allocation It has been seen how arrays can
be defined and manipulated. It is important to learn how to do this
because in more advanced C programs it is necessary to deal with
something known as dynamic memory management.
◦ It is given a small area of the computer’s memory to use. This memory,
which is known as the stack, is used by variables in the program
int a = 10;
fl oat values[100];
© Oxford University Press 2013. All rights reserved.
for(loop = 2; loop < 10; loop++) {
#include <stdio.h>
if( largest < array[loop] ) {
second = largest;
int main() {
largest = array[loop];
int array[10] = {101, 11,
}
3, 4, 50, 69, 7, 8, 9, 0};
else if( second < array[loop] )
int loop, largest, second;
{
second = array[loop];
if(array[0] > array[1])
}
{
}
largest = array[0];
second = array[1];
printf("Largest - %d \nSecond -
}
%d \n", largest, second);
else
{
return 0;
largest = array[1];
}
second = array[0];
}
Variable Length Arrays and the
C99 changes
With the earlier version of C(C89) compilers, an array’s size
must be a constant integral expression so that it can be
calculated at compile-time.
This has already been mentioned in earlier sections.
But in the C99 compilers, an array size can be an integral
expression and not necessarily a constant one.
This allows the programmer to declare a variable-length array
or an array whose size is determined at runtime.
In next slide ,the following program illustrates the concept:
Some changes in initializing an array has been made in C99.
In C99, initial values can be set only for certain elements, with
uninitialized elements being initialized as 0.
© Oxford University Press 2013. All rights reserved.
size is determined at runtime.
© Oxford University Press 2013. All rights reserved.
© Oxford University Press 2013. All rights reserved.
APPLICATION :
One-Dimensional Array
Printing binary equivalent of a decimal number
using array
Here the remainders of the integer division of a
decimal number by 2 are stored as consecutive array
elements.
The division procedure is repeated until the number
becomes 0.
© Oxford University Press 2013. All rights reserved.
© Oxford University Press 2013. All rights reserved.
Fibonacci Series Using Array
© Oxford University Press 2013. All rights reserved.
Searching an
element within an
array
For loop
Sorting an array
© Oxford University Press 2013. All rights reserved.
Bubble sort
A bubble sort compares adjacent array elements and
exchanges their values if they are out of order.
Bubble sort is a simple sorting algorithm. This sorting
algorithm is comparison-based algorithm in which
each pair of adjacent elements is compared and the
elements are swapped if they are not in order.
In this way, the smaller values ‘bubble’ to the top of the
array (towards element 0), while the larger values sink to
the bottom of the array.
This sort continues until no exchanges are performed in a
pass.
This algorithm is not suitable for large data sets
© Oxford University Press 2013. All rights reserved.
After second iteration
After one iteration
© Oxford University Press 2013. All rights reserved.
algorithm
for all elements of list (outer for)
for each element in the list (inner for)
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
End for
return list
Also , keep a swapped flag so that you know that
there is no more swapping in the process. Array
is sorted.
/*if no number
was swapped
that means
array is sorted
now (sorted =1,
break the
loop.*/
© Oxford University Press 2013. All rights reserved.
Bubble sort
Binary Search
This search algorithm works on the principle of divide
and conquer. For this algorithm to work properly, the
data collection should be in the sorted form.
Binary search looks for a particular item by comparing
the middle most item of the collection. If a match
occurs, then the index of item is returned.
If the middle item is greater than the item, then the
item is searched in the sub-array to the left of the
middle item.
Otherwise, the item is searched for in the sub-array to
the right of the middle item. This process continues
on the sub-array as well until the size of the subarray
reduces to zero.
Binary search example
search the
location of
value 31
mid = low + (high - low) / 2
We find that
the value at
location 4 is
27. our
number 31 is
greater than
27.
Now we
consider the
right half of
the array
only.
© Oxford University Press 2013. All rights reserved.
Binary search example contd.
Set new low
and new mid
As mid low = mid + 1
number 35 is mid = low + (high - low) / 2
greater than
31, then the
value must be
in the lower
Hence, we
part.
calculate
the mid
again. This
time it is 5.
Match is
found We conclude that the target value 31 is stored at
© Oxford University Press 2013. All rights reserved.
Pseudocode
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists.
set midPoint = lowerBound + ( upperBound -
lowerBound ) / 2 if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint – 1
if A[midPoint] = x
EXIT: x found at location midPoint
end while
#include <stdio.h> while (first <= last)
int main() {
{ int c, first, last, middle, n, key, if (array[middle] < key)
array[100]; first = middle + 1;
printf("Enter number of elements\ else if(array[middle] == key)
n"); {
scanf("%d",&n); printf("%d found at
location %d.\n", key,
printf("Enter %d integers\n", n); middle+1);
for (c = 0; c < n; c++) break;
scanf("%d",&array[c]); }
else
printf("Enter value to find\n"); last = middle - 1;
scanf("%d", &key);
middle = (first + last)/2;
first = 0; }
last = n - 1; if (first > last)
middle = (first+last)/2; printf("Not found! %d is not
present in the list.\n", key);
return 0;
}
Note
Single operations, which involve entire arrays, are not
permitted in C.
Neither can all elements of an array be set at once nor
can one array be assigned to another.
For an array of length L and data type X, the compiler
allocates L* sizeof (X) bytes of contiguous space in
memory.
char = 1 byte; int = 2 bytes ; float = 4 bytes;
Note the arrays
char array_nr1[40]; 40*sizeof(char) = 40 bytes
int array_nr1[10]; 10*sizeof(int) = 20 bytes
int array_nr2[10]; 10*sizeof(int) = 20 bytes
STRINGS: ONE-DIMENSIONAL
CHARACTER ARRAYS
Strings in C are represented by arrays of characters. The
end of the string is marked with a special character.
In the ASCII character set, the null character value is 0.
The null or string-terminating character is represented by
another character escape sequence, \0.
Strings are actually one-dimensional array of
characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that
comprise the string followed by a null.
© Oxford University Press 2013. All rights reserved.
Declaration of A String
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
The C compiler automatically places the '\0' at the end of
the string when it initializes the array
•char test[100] = "Null terminator will follow me";
•sprintf(test,"Null terminator will follow me");
Declaration of A String
Strings can be declared like one-dimensional arrays.
For example,
char str[30];
char text[80];
An array formed by characters is a string in C.
The end of the string is marked with a the null
character.
When the character array size is explicitly specified
and the number of initializers completely fills the array
size, the null character is not automatically appended to
the array.
© Oxford University Press 2013. All rights reserved.
Initiation of a string
char s[]=“Hello, World”;
Printing Strings
The conversion type ‘s’ may be used for output
of strings using printf().
The following points should be noted.
When the field width is less than the length of the string,
the entire string is printed.
The integer value on the right side of the decimal point
specifies the number of characters to be printed.
When the number of characters to be printed is specified
as zero, nothing is printed.
The minus sign in the specification causes the string to
be printed as left justified.
© Oxford University Press 2013. All rights reserved.
Example
#include <stdio.h>
output
int main()
{
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s); >>Hello, World<<
printf(“>>%20s<<\n”,s); >> Hello, World<<
printf(“>>%-20s<<\n”,s); >>Hello, World <<
printf(“>>%.4s<<\n”,s); >>Hell<<
printf(“>>%-20.4s<<\n”,s); >>Hell<<
printf(“>>%20.4s<<\n”,s);
>> Hell<<
return 0;
}
© Oxford University Press 2013. All rights reserved.
String INPUT/OUTPUT
One special case, where the null character is not
automatically appended to the array, is when the
array size is explicitly specified and the number
of initializers completely fills the array size.
char nonterminated[5] = "12345“;
printf() with the width and precision modifiers in the
%s conversion specifier may be used to display a
string.
The %s format does not require the ampersand before
the string name in scanf().
© Oxford University Press 2013. All rights reserved.
String INPUT/OUTPUT
If fewer input characters are provided, scanf() hangs until it
gets enough input characters.
scanf() only recognizes a sequence of characters delimited
by white space characters as an external string.
The library function sprintf() is similar to printf().
The C library function sprintf () is used to store formatted
data as a string.
You can also say the sprintf () function is used to create
strings as output using formatted data.
The only difference is that the formatted output is written to
a memory area rather than directly to a standard output.
© Oxford University Press 2013. All rights reserved.
Enter your Name and Print
#include <stdio.h>
int main()
{
char str[50];
printf("Enter a string : ");
//Option 1 to read and print string
scanf("%[^\n]s",str);
printf("You entered: %s", str);
//option 2 to read and print string
//gets(str);
//puts(str);
return(0);
}
Character Manipulation in the String
isupper()
#include <stdio.h>
#include <ctype.h>
int main()
{ int var1 = 'M';
int var2 = 'm';
if( isupper(var1) )
{
printf("var1 = |%c| is uppercase character\n", var1 );
}
else
{
printf("var1 = |%c| is not uppercase character\n", var1 );
}
return 0;
}
toupper()
#include <stdio.h>
#include <ctype.h>
int main()
{ char c; c = 'm';
printf("%c -> %c", c, toupper(c));
/*Displays the same argument passed if other characters
than lowercase character is passed to toupper()*/.
c = 'D';
printf("\n%c -> %c", c, toupper(c));
c = '9'; m -> M
D -> D
printf("\n%c -> %c", c, toupper(c)); 9 -> 9
return 0;
}
fscanf & fprintf
fprintf(FILE *stream, const char *format, ...) sends
formatted output to a stream.
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);
fclose(fp); return(0); }
fscanf(FILE *stream, const char *format, ...)
reads formatted input from a stream.
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
© Oxford University Press 2013. All rights reserved.
String input and output using
fscanf() and fprintf()
stdin, stdout, and stderr: Each C program has three I/O
streams.
◦ The input stream is called standard-input (stdin); the
output stream is called standard-output (stdout); and the
side stream of output characters for errors is called
standard error (stderr).
◦ Now one might think that calls to fprinf() and fscanf()
differ significantly from calls to printf() and scanf().
◦ fprintf() sends formatted output to a stream and fscanf()
scans and formats input from a stream.
© Oxford University Press 2013. All rights reserved.
Standard input and output
Standard File File Pointer What is happening
Standard input stdin Standard input is stream data
(often text) going into a
program (data transfers by use
of the read operation)
Standard output stdout Standard output is the stream
where a program writes its
output data(data transfer with
the write operation)
Standard error stderr Another output stream typically
used by programs to
output error messages. It is a
stream independent of standard
output and can be redirected
separately
© Oxford University Press 2013. All rights reserved.
See the following example
#include <stdio.h>
int main()
{
int first, second;
fprintf(stdout,“Enter two inputs in this line: ”);
fscanf(stdin,“%d %d”, &first, &second);
fprintf(stdout,“Their sum is: %d.\n”, first + second);
return 0;
}
© Oxford University Press 2013. All rights reserved.
String Manipulation
C has the weakest character string capability of
any general-purpose programming language.
Strictly speaking, there are no character strings in
C, just arrays of single characters that are really
small integers.
If s1 and s2 are such ‘strings’ a program cannot
Assign one to the other: s1 = s2;
Compare them for collating sequence: s1 < s2;
Concatenate them to form a single longer string: s1 + s2;
Return a string as the result of a function.
© Oxford University Press 2013. All rights reserved.
String Manipulation
© Oxford University Press 2013. All rights reserved.
Copying a String into another
Since C never lets entire arrays to be assigned, the strcpy()
function can be used to copy one string to another.
◦ strcpy() copies the string pointed to by the second
parameter into the space pointed to by the first
parameter.
◦ The entire string, including the terminating NUL, is copied
and there is no check that the space indicated by the first
parameter is big enough.
◦ The given code shows the use of the strcpy(str1, str2)
function.
#include <string.h>
char s1[] =“Hello, world!”;
char s2[20];
strcpy(s2, s1);
puts (s2);
strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
char str1[15];
char str2[15];
strcpy(str1, “Finally");
Finally
strcpy(str2, “Mid-sem is over !");
Mid-sem is over!
puts(str1);
puts(str2);
return(0);
}
© Oxford University Press 2013. All rights reserved.
puts() and gets()
The C library function #include <stdio.h>
puts(str) writes a string to
int main()
stdout up to but not including
{
the null character.
A newline character is char str[50];
appended to the output. printf("Enter a string : ");
gets(str);
The C library function printf("You entered: %s",
gets (str) reads a line from str);
stdin and stores it into the return(0);
string. }
It stops when either the
newline character is read or
when the end-of-file is reached,
whichever comes first.
© Oxford University Press 2013. All rights reserved.
Comparing strings
strcmp() takes the start addresses of two strings as
parameters and returns the value zero if the strings are
equal.
declaration
int strcmp(char *str1, char *str2)
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2.
Each character is compared in turn an a decision is made
as to whether the first or second string is greater, based on
that character (ASCII value).
Only if the characters are identical do you move to the next
character and, if all the characters were identical, zero is
returned.
#include <stdio.h>
#include <string.h> strcmp()
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strcmp(str1, str2);
if(ret < 0)
{
printf("str1 is less than str2"); str2 is less than str1
}
else if(ret > 0) //strcmp will give a
{ positive number if the
printf("str2 is less than str1");
first string is greater
}
else
{
printf("str1 is equal to str2");
}
return(0);
}
The following program illustrates
the comparison of two strings:
© Oxford University Press 2013. All rights reserved.
Comparing strings
Since C never lets entire arrays to be assigned,
the strcpy() function can be used to copy one
string to another.
Strings can be compared by the help of strcmp()
function.
The arithmetic addition cannot be applied for
joining two or more strings; this can be done by
using the standard library function, strcat().
© Oxford University Press 2013. All rights reserved.
Putting strings together strcat()
char strcat(dest, src)
Parameters
dest -- This is (pointer to) the destination array, which should
contain a C string, and should be large enough to contain
the concatenated resulting string.
src -- This is the string to be appended. This should not
overlap the destination.
This function returns (a pointer to the) resulting string
dest.
© Oxford University Press 2013. All rights reserved.
#include <stdio.h> String concatenation
int main()
{
char string1[20];
char string2[20];
strcpy(string1, “Welcome");
strcpy(string2, “ToPCclass");
printf("Returned String : %s\n", strcat( string1, string2 ));
printf("Concatenated String : %s\n", string1 );
return 0;
}
Returned String : WelcomeToPCclass
Concatenated String : WelcomeToPCclass
© Oxford University Press 2013. All rights reserved.
Putting strings together strcat()
The arithmetic addition cannot be applied
for joining of two or more strings in the
manner
string1 = string2 + string3; or
string1 = string2 +”RAJA”;
For this, the standard library function,
strcat(), that concatenates strings is
needed. It does not concatenate two
strings together and give a third, new
string.
In this example, the first call to printf
prints “Hello,”, and the second one
prints “Hello, world!”, indicating that
the contents of str have been appended
to the end of s.
© Oxford University Press 2013. All rights reserved.
Programs on strings
WAP to find the reverse of a string by using
library function for reverse operation.
WAP to replace all occurrences of a character in a
given string with a new character.
© Oxford University Press 2013. All rights reserved.
PROGRAM CODE
#include<stdio.h> Reverse a string
#include<string.h>
int main()
{
char s[100]; revs[100]
printf("\nEnter a string : ");
gets(s);
revs = strrev(s);
printf("\nThe reverse of the string is %s ", revs)
return 0 ;
} RUN-1
Enter a String : I am good.
The reverse of the string is .doog
ma I
RUN-1
Enter a String : How are you?
The reverse of the string is
© Oxford University Press 2013. All rights reserved. ?uoy era woH
PROGRAM CODE Reverse a string –
#include<stdio.h> without library
function
#include<string.h>
int main()
INPUT/ OUTPUT
{
RUN-1
char s[100];
Enter a String : I am good.
int l, i; The reverse of the string is .doog
ma I
printf("\nEnter a string : "); RUN-1
gets(s); Enter a String : How are you?
l=strlen(s); The reverse of the string is
?uoy era woH
printf("\nThe reverse of the string is ");
for(i=l-1; i>=0; i--)
printf(“%c”, s[i]);
return 0;
}
© Oxford University Press 2013. All rights reserved.
PROGRAM CODE INPUT/OUTPUT
#include<stdio.h> Replace a char
RUN-1
#include<string.h> Enter a string: Bachelor of
int main() Engineering
{
char s[100], och, nch; Enter a character: e
int i, flag=0;
printf(“\nEnter a string :”); Enter a new character: A
gets(s);
printf(“\nEnter a character :”); After the replacement by
scanf(“%c”, &och); new character, the string is
printf(“\nEnter the new character :”); BachAlor of EnginAAring
scanf(“ %c”, &nch)//add a space
for(i=0; s[i]!=’\0’; i++) if(flag==1)
{ printf("\nAfter the replacement by new
if(s[i]==och) character, the string is %s”, s;);
{ else
s[i]=nch; printf("\nThe given string does not
flag=1; contain the character %c”, och);
} return 0;
}//for loop
© Oxford ends
University Press here }
2013. All rights reserved.
Multidimensional Arrays
Arrays with more than one dimension are called
multidimensional arrays.
An array of two dimensions can be declared as
follows:
• data_type array_name[size1][size2];
• Here, data_type is the name of some type of data, such
as int. Also, size1 and size2 are the sizes of the array’s
first and second dimensions, respectively.
A three-dimensional array, such as a cube, can
be declared as follows:
◦ data_type array_name[size1][size2][size3]
© Oxford University Press 2013. All rights reserved.
Two dimensional Array
Computer memory is
Row 0 1 2 3
essentially one dimensional
with memory location Row 1 4 5 6
running straight from 0 to
highest. Row 2 7 8 9
A multidimensional array
cannot be stored in memory
as grid.
In computer, this array will
be stored 1as below
2 3 4 5 6 7 8 9
Row 0 Row 1 Row 2
© Oxford University Press 2013. All rights reserved.
Two dimensional array
A two-dimensional array can be considered as a table
which will have x number of rows and y number of
columns.
Thus, every element in the array a is identified by an
element name of the form a[ i ][ j ], where 'a' is the name
of the array, and 'i' and 'j' are the subscripts that uniquely
identify each element in 'a'.
© Oxford University Press 2013. All rights reserved.
© Oxford University Press 2013. All rights reserved.
#include <stdio.h> Accessing Two-Dimensional Array
int main () Elements
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ ) // for rows
{
for ( j = 0; j < 2; j++ ) //for columns
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
} a[0][0]: 0
} a[0][1]: 0
return 0; 0 0 a[1][0]: 1
a[1][1]: 2
}} 1 2 a[2][0]: 2
2 4 a[2][1]: 4
a[3][0]: 3
3 6 a[3][1]: 6
4 8 a[4][0]: 4
a[4][1]: 8
Matrix form printing
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ ) // for rows
{
for ( j = 0; j < 2; j++ ) //for columns
{
printf("%d", a[i][j] );
printf("\t");
}
printf("\n");
}
return 0;
}
Matrix - Addition
sum of two matrices of
#include <stdio.h>
int main() order 2*2
{
// adding corresponding
float a[2][2], b[2][2], c[2][2];
elements of two arrays
int i, j;
for(i=0; i<2; ++i)
// Taking input using nested for loop
for(j=0; j<2; ++j)
printf("Enter elements of 1st matrix\n");
{
for(i=0; i<2; ++i)
c[i][j] = a[i][j] + b[i][j];
for(j=0; j<2; ++j)
}
{
printf("Enter a%d%d: ", i+1, j+1);
// Displaying the sum printf("\
scanf("%f", &a[i][j]);
nSum Of Matrix:"); for(i=0; i<2; +
}
+i)
for(j=0; j<2; ++j)
// Taking input using nested for loop
{
printf("Enter elements of 2nd matrix\n");
printf("%.1f\t", c[i][j]);
for(i=0; i<2; ++i)
if(j==1)
for(j=0; j<2; ++j)
printf("\n"); }
{
return 0;
printf("Enter b%d%d: ", i+1, j+1);
© Oxford University Press 2013. All rights reserved. }
scanf("%f", &b[i][j]);
© Oxford University Press 2013. All rights reserved.
3 D Arrays
© Oxford University Press 2013. All rights reserved.
© Oxford University Press 2013. All rights reserved.
Multidimensional Arrays
Unsized Array Initializations
◦ C compiler automatically creates an array big enough to
hold all the initializers. This is called an unsized array.
◦ The following are examples of declarations with
initialization.
char e1[] =“read error\n”;
char e2[] =“write error\n”;
© Oxford University Press 2013. All rights reserved.
Multidimensional Arrays
Multi-dimensional arrays are kept in computer
memory as a linear sequence of variables.
The elements of a multi-dimensional array are
stored contiguously in a block of computer memory.
The number of subscripts determines the
dimensionality of an array.
The separation of initial values into rows in the
declaration statement is not necessary.
If unsized arrays are declared, the C compiler
automatically creates an array big enough to hold
all the initializers.
© Oxford University Press 2013. All rights reserved.
Transpose of a matrix
#include <stdio.h>
void main() printf("Transpose of matrix is \n");
{ for (j = 0; j < n; ++j)
static int array[10][10]; {
int i, j, m, n; for (i = 0; i < m; ++i)
printf("Enter the order of the matrix \n"); {
scanf("%d %d", &m, &n); printf(" %d", array[i][j]);
printf("Enter the coefficients of the matrix\ }
n"); printf("\n");
for (i = 0; i < m; ++i) }
{ }
for (j = 0; j < n; ++j) Enter the order of the matrix 3 3
{ Enter the coefficients of the matrix
scanf("%d", &array[i][j]); 3 7 9
} 275
} 634
printf("The given matrix is \n"); The given matrix is
for (i = 0; i < m; ++i) 379
{ 275
for (j = 0; j < n; ++j) 634
{ Transpose of matrix is
printf(" %d", array[i][j]); 326
} 773
printf("\n");} 954
© Oxford University Press 2013. All rights reserved.
Multiplication matrix
© Oxford University Press 2013. All rights reserved.
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
PROGRAM CODE
Multiplication of two
#include<stdio.h>
int main() matrix
{
int a[10][10],b[10][10],c[10][10];
int i,j,k,m,n,p,q;
clrscr();
printf("\nThe row & column of Matrix A :");
scanf("%d%d",&m,&n); read
fflush(stdin);
printf("\nThe row & column of Matrix B :");
scanf("%d%d",&p,&q);
if (n==p)
{
printf("\nFor Matrix A:-\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Read
{
First
printf("\nEnter values for A[%d][%d]=> ",i,j);
scanf("%d",&a[i][j]); matrix
}
} © Oxford University Press 2013. All rights reserved.
printf("\nFor Matrix B:-\n");
for(i=0;i<p;i++) Read
{ Second
for(j=0;j<q;j++) matrix
{
printf("\nEnter values for B[%d][%d]=> ",i,j);
scanf("%d",&b[i][j]);
}
}
//Matrix Multiplication Logic
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{ Multiplication
c[i][j]=0; logic
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
is\n");
© Oxford University Press 2013. All rights reserved.
printf("\nMatrix A is\n");
for(i=0;i<m;i++)
Print 1st Matrix
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n");
printf("\nMatrix B is\n");
for(i=0;i<p;i++) Print 2nd matrix
{
for(j=0;j<q;j++)
printf("%d\t",b[i][j]);
printf("\n");
}
printf("\n"); Print result
printf("\nMultiplication Matrix C is\n"); matrix
for(i=0;i<m;i++)
{
for(j=0;j<q;j++) else
printf("%d\t",c[i][j]); printf("\nMultiplication is not
printf("\n”); possible.\n");
}});© Oxford University Press 2013. All rights reserved. return 0;
} }
Arrays of Strings: Two-dimensional
Character Array
A two-dimensional array of strings can be
declared as follows:
◦ <data_type> <string_array_name>[<row_size>]
[<columns_size>];
Consider the following example on declaration of
a two-dimensional array of strings.
char s[5][30];
© Oxford University Press 2013. All rights reserved.
2 D char array
char name[5][10]={ The areas marked in green shows
"tree", the memory locations that are
"bowl", reserved for the array but are not
"hat", used by the string. Each
"mice", character occupies 1 byte of
"toon" storage from the memory.
};
Initialization
Two-dimensional string arrays can be initialized as shown
char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”};
which is equivalent to
s[0] C o w \0
S[1] G o a t \0
S[2] R a m \0
S[3] D o g \0
S[4] C a t \0
Here every row is a string. That is, s[i] is a string. Note that
the following declarations are invalid.
char s[5][] ={“Cow”,“Goat”,“Ram”,”Dog”,“Cat”};
char s[][] ={“Cow”,“Goat”,“Ram”,“Dog”,“Cat”};