Chapter 4
Arrays and Strings
FE – C Programming
Prof. Namrata Jiten Patel
Assistant Professor
Dept. of Computer Engineering,
SIES Graduate School of Technology
Objectives :To provide exposure to problem-solving by developing an
algorithm, flowchart and implement the logic using C programming
language
Outcomes: Learner will be able to…
1. Demonstrate the use of arrays, strings and structures in C
language.
Namrata Jiten Patel 2
Namrata Jiten Patel 3
Learning Outcomes
• Define an Array
• Declaration of 1-dim array,ways of access individual array
element,representation of array element in memory and other
possible operations.
• Declaration of 2-dim array,ways of access individual array
element,representation of array element in memory and other
possible operations
• Explain array of Strings ,their declarations ,initialization and
other operations.
Namrata Jiten Patel 4
Introduction
• The variables used so far have all had a common characteristic:
each variable can only be used to store a single value at a time. For
example, each of the variables ch, n, and price declared in the
statements.
These kind of variable holds different data types, and each variable
can only store one value of the declared data type.
These types of variables are called scalar variables.
A scalar variable is a single variable whose stored value is an atomic
type. This means that the value cannot be further subdivided or
separated into a legitimate data type.
Namrata Jiten Patel 5
continue
• In contrast to atomic type like integer , float, double there are
aggregate types.
• An aggregate type, which is referred to Structured type and Data
structured type whose value can be decomposed and are related to
some defined structure.
• Operation must be available for retrieving and updating individual
values in the data structure.
• Such a derived data type is an array
Namrata Jiten Patel 6
Define Array
• An array is a fundamental data structure that enables the storing and
manipulation of potentially huge quantities of data.
• An array stores an ordered sequence of homogeneous values.
Homogeneous means that all the values are of the same data type.
• The order of the values are also preserved, i.e., the integer array {1,
2, 3, 4} is different from {1, 4, 3, 2}
Namrata Jiten Patel 7
• An array is a collection of individual data elements that is
Ordered—one can count off the elements 0, 1, 2, 3, ...
Fixed in size
Homogeneous—all elements must be of the same type, e.g., int, float, char,
etc.
• In C, each array has two fundamental properties: the data type and
the size.
• Individual array elements are identified by an integer index. In C, the
index begins at zero and is always written inside square brackets.
Namrata Jiten Patel 8
Basic form of Array
When defining an array in a program, three things need to be specified .
Name of an
array
• data_type name_of_array[size]
Maximum
type_data it number of
can hold elements it can
hold
Namrata Jiten Patel 9
One-Dimensional array
• A one-dimensional array declaration is a data type followed by an
identifier with a bracketed constant integral expression
• The value of the expression, which must be positive, is the size of the
array.
• It specifies the number of elements in the array.
• The array subscripts can range from 0 to (size –1).
• The lower bound of the array subscripts is 0 and the upper bound is
(size –1). Thus, the following relationships hold.
Namrata Jiten Patel 10
Illustrating the organization of number array in memory
with the correct designation for each array element.
Namrata Jiten Patel 11
• Advantages of an Array in C:
1.Random access of elements using array index.
2.Use of less line 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 less line of code.
• Disadvantages of an Array in C:
1.Allows a fixed number of elements to be entered which
is decided 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 elements are needed to be managed in accordance
with the new memory allocation.
Namrata Jiten Patel 12
Array Declarations
Namrata Jiten Patel 13
Initializing the array
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. From the above initialization statement, the size of the array is
deduced to be 5.
Namrata Jiten Patel 14
Accessing the array
• The subscript value in each of the subscripted variables in this
statement can be replaced by the counter in a for loop to access each
element in the array sequentially.
• For example, the C statements
Namrata Jiten Patel 15
Basic example
• #include
• #define ARRAY_SIZE 10
• int main()
• { int index, a[ARRAY_SIZE];
• for(index = 0; index < ARRAY_SIZE;
index++)
• {
• a[index] = 0;
• printf(“a[%d] = %d\n”, index, a[index]);
• }
• printf(“\n”);
• return 0;
• }
Namrata Jiten Patel 16
Internal representation of Array
“In C, an array is implemented as a single block of memory, with element 0 occupying the
first ‘slot’ in that block.
That is, arrays are allocated contiguous space in memory and so they are closely related to
the notion of pointer which will be discussed later.”
• For a simple variable (e.g., int, double, etc.) of data type X, the
compiler allocates sizeof(X) bytes to hold it.
• For an array of length L and data type X, the compiler allocates
• L* sizeof (X) bytes.
• For example
• Given an array like int scores[100],
• The compiler allocates 200 bytes starting at some location, say 64789.
• Given an expression like scores[5], the compiler accesses the value
stored at the memory location starting with byte
• 64789+(5*2).
• In general, a[i] is located at byte: base address of a + i * sizeof (type
of array).
Namrata Jiten Patel 17
References to elements outside of
the array bounds
• If an array x is declared to have 100 elements, the compiler will
reserve 100 contiguous, appropriately sized slots in computer
memory on its behalf
• The contents of these slots can be accessed via expressions of the
form x[i], where the integer i should lie in the range 0 to 99.
• If it goes beyond the range it is not going to produce some sort of
error.
• Exactly what sort of error is very difficult to say—the program may
crash, it may produce an absurdly incorrect output, it may produce
plausible but incorrect output, it may even produce correct output—
it all depends on exactly what information is being stored in the
memory locations surrounding the block of memory reserved for x.
Namrata Jiten Patel 18
References to elements outside of
the array bounds
• Therefore, the programmer’s responsibility to ensure that all
references to array elements lie within the declared bounds of the
associated arrays
Namrata Jiten Patel 19
Glimpse of memory allocation
• It is important to see how memory is allocated to arrays.
• 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
• Example:
Namrata Jiten Patel 20
Points to be remembered
• Size of memory allocated from the stack must be fixed at compile
time.
• For example, it is impossible to declare an array using a variable for
the size because at compile time the compiler does not know how
big the array will be.
• For this reason, the following code will not work
• int size;
• printf(“How big do you want the array?\n”);
• scanf(“%d”, &size);
• int array[size];
Namrata Jiten Patel 21
• Therefore, dynamically allocating memory is real problem because
stack is not very big.
• It is typically only 64k in size, even on a machine with tens of
megabytes of memory.
• . The rest of this memory is left alone by the compiler, but the user
can access it explicitly; it is called the heap
Namrata Jiten Patel 22
Few points to be noted
• In C99, initial values can be set only for specific members, with
uninitialized members being initialized as 0.
• This is useful when the elements requiring initialization are limited,
or when arrays have large element counts.
• Example:
int arr[6] = { [2] =3, [5] = 7 };
Here array element arr[2] and arr[5] is assigned the value 3
and 7 respectively, while all other element in arr are assigned the
value 0.
Namrata Jiten Patel 23
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, the null
character, which is a character all of whose bits are zero, i.e., a NUL
(not a NULL).
• The null or string-terminating character is represented by another
character escape sequence, \0.
• Although C does not have a string data type, it allows string
constants. For example,” hello students” is a string constant
Namrata Jiten Patel 24
Declaration of a String
• Strings can be declared like one-dimensional arrays. For example,
char str[30];
char text[80];
• String Initialization
• Character arrays or strings allow a shorthand initialization,
• for example,
char str[9] = “I like C”;
which is the same as:
char str[9] = {‘I’,‘ ’,‘l’,‘i’,‘k’,‘e’,‘ ’,‘C’,‘\0’};
Namrata Jiten Patel 25
String Initialization
• C language allows the alternative notation
char msg[] = “Hello”;
• The size of the aggregate ‘msg’ is six bytes, five for the letters and
one for the terminating NULL
• There is one special case where the null character is not
automatically appended to the array.
• This is when the array size is explicitly specified and the number of
initializers completely fills the array size.
For example,
char c[4] = “abcd”;
• Here, the array c holds only the four specified characters, a, b, c, and
d. No null character terminates the array
Namrata Jiten Patel 26
Points to note
1.An array formed by characters is a string in C.
2. The end of the string is marked with a the null character.
3. 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.
Namrata Jiten Patel 27
Printing Strings
• The conversion type ‘s’ may be used for output of strings using
printf().
• Width and precision specifications may be used with the %s
conversion specifier.
• The width specifies the minimum output field width; if the string is
shorter, then space padding is generated.
• The precision specifies the number of characters to display.
• If the string is too long, it is truncated.
• A negative width implies left justification of short strings rather than
the default right justification.
• For example,
printf(“%7.3s”,name)
• This specifies that only the first three characters have to be printed in
a total field width of seven characters and right justified in the
allocated width by default.
• We can include a minus sign to make it left justified (%-7.3).
Namrata Jiten Patel 28
Points to note
• 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.
Namrata Jiten Patel 29
Program illustrating the use of the
%sconversion specifier
#include <stdio.h>
int main()
{ • Producing the output
char s[]=“Hello, World”;
printf(“>>%s<<\n”,s);
printf(“>>%20s<<\n”,s);
printf(“>>%-20s<<\n”,s);
printf(“>>%.4s<<\n”,s);
printf(“>>%-20.4s<<\n”,s);
printf(“>>%20.4s<<\n”,s);
return 0;
}
Namrata Jiten Patel 30
• The >> and << symbols are included in this program so that
the limits of the output fi elds are clearly visible in the
output.
• There is another way to print a string. The library function
puts() writes a line of output to the standard output.
• It terminates the line with a new line, ‘\n’.
• It returns an EOF if an error occurs. It will return a positive
number upon success. The use of puts() is given as follows:
Namrata Jiten Patel 31
Use of puts()
#include <stdio.h>
int main()
{
char s[]=“Hello, World”;
puts(s);
return 0;
}
Namrata Jiten Patel 32
• 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.
• It is particularly useful when it is necessary to construct formatted
strings in memory for subsequent transmission over a
communications channel or to a special device.
• Its relationship with printf() is similar to the relationship between
sscanf() and scanf().
• The library function puts() may be used to copy a string to the
standard output, its single parameter is the start address of the
string.
• puts() writes a new-line character to standard output after it has
written the string.
Namrata Jiten Patel 33
Example of the use of sprintf() and puts()
Value of Pi=3.141593
Namrata Jiten Patel 34
• If ‘\n’ had been incorporated in the format string of the sprintf(), the
output would have been double-spaced because the function would
have put a new-line character in the generated string and puts()
would then generate a further new line.
Namrata Jiten Patel 35
String Input
Using %s control string with scanf()
• Strings may be read by using the %s conversion with the function
scanf() but with some restrictions
• The first is that scanf() only recognizes a sequence of characters
delimited by white space characters as an external string.
• The second is that it is the programmer’s responsibility to ensure that
there is enough space to receive and store the incoming string along
with the terminating null which is automatically generated and stored
by scanf() as part of the %s conversion.
• The associated parameter in the value list must be the address of the
first location in an area of memory set aside to store the incoming
string.
• A field width may be specified and this is the maximum number of
characters that are read in, but remember that any extra characters
are left unconsumed in the input buffer
Namrata Jiten Patel 36
Example scanf with %s
int main() • Dissimilar to the integer,
{ float, and characters, the
char str[50]; %s format does not
printf(“Enter a string”);
require the ampersand
before the variable str.
scanf(“%s”,str);
printf(“The string was :%s\n”,str);
return 0;
}
Output of sample runs:
(a) Enter a string manas
The string was :manas
(b) Enter a string manas ghosh
The string was :manas
(c) Enter a string “manas and
ghosh”
The string was : “manas”
Namrata Jiten Patel 37
e.g.,
printf(“%*.*s”,w,d,str);
prints the first d characters of the string in the field width
of w. For example,
int main()
{
char str[50];
printf(“\n Enter a string:”);
scanf(“%s”,str);
printf(“\n %*.*s\n”,2,3,str);
return 0;
}
Arrays and Strings sample run:
Enter a string:Manas
Man (Man First three characters of entered string
“Manas” is displayed on the screen.)
Namrata Jiten Patel 38
Using Scanset
• The scanset conversion facility provided by scanf() is a useful string
input method.
• This conversion facility allows the programmer to specify the set of
characters that are (or are not) acceptable as part of the string.
• A scanset conversion consists of a list of acceptable characters
enclosed within square brackets.
• A range of characters may be specified using notations such as‘a-z’,
meaning all characters within this range.
• The actual interpretation of a range in this context is
implementation-specific, i.e., it depends on the particular character
set being used on the host computer.
• If an actual ‘-’ is required in the scanset, it must be the fi rst or last
character in the set.
• If the first character after the ‘[’ is a ‘^’ character, then the rest of the
scanset specifies unacceptable characters rather than acceptable
characters.
Namrata Jiten Patel 39
Example of scanset
int main()
{
char str[50];
printf(“Enter a string in lower case:”);
scanf(“%[a-z]”,str); In the second case, the
printf(“The string was : %s\n”,str); character, ‘,’ (comma) is
not in
return 0;
the specifi ed range.
} Note that in all cases,
Three sample runs are given below. conversion is
terminated by the input
(a) Enter a string in lower case: hello world
of something other than
The string was: hello world a space or
(b) Enter a string in lower case: hello, world lowercase letter.
The string was: hello
(c) Enter a string in lower case: abcd1234
The string was : abcd
Namrata Jiten Patel 40
String input using scanf() with conversion
specifier %c
• An alternative method for the input of strings is to use scanf() with
the %c conversion which may have a count associated with it. This
conversion does not recognize the new-line character as special. The
count specifies the number of characters to be read in.
• Unlike the %s and %[] (scanset) conversions, the %c conversion does
not automatically generate the string terminating NUL and strange
effects will be noted if the wrong number of characters is supplied.
Namrata Jiten Patel 41
• The output of the sample runs is
int main() given below.
{ (a) Enter a string of 9
char str[10]; characters: 123456789
int i; String was : 123456789
while(1) (b) Enter a string of 9
{ characters: abcdefghi
printf(“Enter a string of String was : abcdefghi
9 characters:”); (c) Enter a string of 9
scanf(“%10c”,str); characters:
abcdefghijklmnopqr
str[9]=‘\0’; /* Make it a
string */ String was :abcdefghi
printf(“String was :%s\ (d) Enter a string of 9
n”,str); characters: 123456789
if(str[0] == ‘Z’) break; String was :klmnopqr
} (e) Enter a string of 9
characters: ttttttttt
return 0;
String was :23456789
}
Namrata Jiten Patel 42
Points to note
• The first point to note is that, contrary to the prompt, 10 characters
are being converted.
• This is done so that the new-line character at the end of the input
line is also read in; otherwise it would be left in the input buffer to be
read in as one of the input characters the next time round.
• The effect of providing too many input characters is that
‘unconsumed’ input characters (including newline characters) are left
in the input buffer.
• These will be ‘consumed’ by the next call to scanf().
• If too few input characters are provided, scanf() hangs (or blocks)
until it gets enough input characters.
• Both types of behavior can be seen in the above example.
Namrata Jiten Patel 43
Using gets()
• The best approach to string input is to use a library function called gets(). This takes
the start address of an area of memory suitable to hold the input as a single
parameter.
• The complete input line is read in and stored in the memory area as a null-terminated
string
int main()
{
char str[150];
printf(“Enter a string”);
gets(str);
printf(“The string was :%s\n”,str);
return 0;
}
Sample run:
(a) Enter a string manas
The string was :manas
(b) Enter a string manas ghosh
The string was :manas ghosh
Namrata Jiten Patel 44
Multi-dimensional Array
• Arrays with more than one dimension are called multidimensional
arrays.
• Although humans cannot easily visualize objects with more than
three dimensions, representing multidimensional arrays presents no
problem to computers
Namrata Jiten Patel 45
Declaration of 2-d Array
• 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 fi rst and second
dimensions, respectively.
• Example of an 8*8 chessboard
• int chess[8][8].
Namrata Jiten Patel 46
Declaration of a Three-dimensional
Array
• A three-dimensional array, such as a cube, can be declared as follows:
data_type array_name[size1][size2][size3]
• Arrays do not have to be shaped like squares and cubes; each
dimension of the array can be given a different size, as follows: int
• Example:non_cube[2][6][8]
Namrata Jiten Patel 47
Initialization of 2-d array
• Multidimensional arrays are initialized in the same way as are single-
dimension arrays.
• For example,
• (a) int a[6][2] = { 1,1, 2,4, 3,9, 4,16, 5,25, 6,36 };
• (b) int b[3][5] = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} };
• The same effect is achieved by int b[3]
[5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
• Although the commas in the initialization braces are always required,
the inner braces can be omitted.
• Thus, the initialization for an array val may be written as
Namrata Jiten Patel 48
Consider the following example
In this example, 1 and 2 initialize the first row of the array x, and the following
two lines initialize the second and third rows, respectively. The initialization
ends before the fourth row is initialized, so the members of the fourth row
default to0 or garbage depending on the compiler. Here is the result.
Namrata Jiten Patel 49
Unsized Array
Namrata Jiten Patel 50
Accessing
multidimension
al Array
• The elements of the two-
dimensional array x[2][2] are
stored in the order:
• x[0][0], x[0][1], x[1][0], x[1][1].
[0][0] [0][1]
[1][0] [1][1]
• Take a look at the following code.
Namrata Jiten Patel 51
String Functions
Namrata Jiten Patel 52
Character manipulation
<c.type>
Namrata Jiten Patel 53
Counting number of characters of a string
• Its single parameter is the address of the start of the string and its
value is the number of characters in the string excluding the
terminating NUL
Namrata Jiten Patel 54
Copying a string into another
#include <string.h>
int main()
{
char s1[] =“Hello, world!”;
char s2[20];
strcpy(s2, s1);
• The destination string is
puts (s2); strcpy’s first argument, so
return 0; that a call to strcpy mimics
} an assignment expression,
with the destination on the
left-hand side.
• Note that string s2 must
be allocated suffi cient
memory so that it can hold
the string that would be
copied to it.
• Also, at the top of any source
fi le, the following line must
Namrata Jiten Patel be included 55
#include <string.h>
Comparing strings
• Another function, strcmp(), takes the start addresses of two strings as
parameters and returns the value zero if the strings are equal. If the
strings are unequal, it returns a negative or positive value.
• The returned value is positive if the first string is greater than the
second string and negative if the first string is lesser than the second
string
Namrata Jiten Patel 56
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2 O/P
strcmp(str1, str2) = 1
result = strcmp(str1, str2); strcmp(str1, str3) = 0
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
} Namrata Jiten Patel 57
Putting strings together
• 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 appends one string at the end of another
Namrata Jiten Patel 58
#include <stdio.h>
#include <string.h>
int main()
Note:
{ • The first call to printf
char s[30] =“Hello,”; prints “Hello,”, and
char str[] =“world!”; the second one prints
“Hello,world!”,
printf(“%s\n”, s); indicating that the
strcat(s, str); contents of str have
been appended to the
printf(“%s\n”, s); end of s.
return 0; • Notice that s was
} declared with extra
space, to make room
for the appended
characters.
Namrata Jiten Patel 59
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>];
• e.g. two-dimensional array of strings.
char s[5][30];
• Initialization
• Two-dimensional string arrays can be initialized as shown
• char s[5][10] ={“Cow”,”Goat”,”Ram”,”Dog”,”Cat”}; which
is equivalent to:
Namrata Jiten Patel 60
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”};
Namrata Jiten Patel 61
Manipulating String Arrays
• The following program demonstrates how an individual string of
an array of strings can be used to take input from the user
#include <stdio.h>
int main()
{
int i;
char s[10][30], t[30];
for(i=0;i<10;i++)
scanf(“%s”,s[i]);
for(i=0;i<10;i++)
printf(“\n%s”,s[i]);
return 0;
}
Namrata Jiten Patel 62
• The following codes show how arrays of strings may be
manipulated. This program checks whether a number is odd or
even without using any control statement.
#include <stdio.h>
int main()
{
char s[2][5]={“EVEN”,“ODD”};
int n;
printf(“\n enter the number:”);
scanf(“%d”,&n);
printf(“\n The number is %s”,s[n%2]);
return 0;
}
Namrata Jiten Patel 63
The following program accepts one line of text and prints the
words in reverse order. For example, if input is ‘Today is Tuesday’,
then output will be ‘Tuesday is
Today’.
• #include <stdio.h>
w[j++]=s[i++];
#include <string.h>
int main()
}
{ w[j]=‘\0’;
char st[25][30],s[80],w[20],d[20]; strcpy(st[k],w);
int i,j, k=0;
printf(“\n Enter the Sentence :”);
k++;
gets(s); if(s[i]!=‘\0’)
i=0; i++;
while(s[i]!=‘\0’)
}
{
j=0; for(k--;k>=0;k--)
while(1) printf(“%s”,st[k]);
{
return 0;
if(s[i]==‘ ’||s[i]==‘\0’)
break; }
Namrata Jiten Patel 64
The following program sorts an array of strings using bubble sort.
Note here that strcmp() is used to compare the string. strcpy()
is used for interchanging the strings.
#include <stdio.h> if(strcmp(s[i],s[j])
#include <string.h> >0)
int main()
{
{
char s[10][30], t[30]; strcpy(t,s[i]);
int i,j,n; strcpy(s[i],s[j]);
printf(“\n how many strcpy(s[j],t);
strings:”);
scanf(“%d”,&n); }
printf(“\n enter the printf(“\n **sorted
strings:\n”);
array**\n”);
for(i=0;i<n;i++)
scanf(“%s”,s[i]); for(i=0;i<n;i++)
printf(“\n **starting printf(“\n%s”,s[i]);
comparing and sorting**”);
return 0;
for(i=0;i<n-1;i++)
for(j=i+1; j<n; ++j) }
Namrata Jiten Patel 65
Thank You!!
[email protected] Namrata Jiten Patel 66