0% found this document useful (0 votes)
13 views47 pages

Chapter 4

The document discusses arrays and strings in C/C++ programming. It covers one-dimensional and two-dimensional arrays, including declaration, initialization, and examples of using arrays. It also covers basics of strings such as memory storage and input/output operations.

Uploaded by

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

Chapter 4

The document discusses arrays and strings in C/C++ programming. It covers one-dimensional and two-dimensional arrays, including declaration, initialization, and examples of using arrays. It also covers basics of strings such as memory storage and input/output operations.

Uploaded by

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

Programming With C/C++

Arrays and Strings

Dr. Ubaidullah Rajput


Associate Professor
CSE Department, QUEST, Nawabshah
Email: [email protected]
About Me
• QUALIFICATION:
– Ph.D. (Computer Science & Engineering)
• HANYANG UNIVERSITY, ANSAN, SOUTH KOREA
– M.E (Computer Engineering)
• NATIONAL UNIVERSITY OF SCIENCE AND TECHNOLOGY (NUST), ISLAMABAD
PAKISTAN
– B.E (Computer System)
• QUAID-E-AWAM UNIVERSITY OF ENGINEERING SCIENCE & TECHNOLOGY
(QUEST), NAWABSHAH, PAKISTAN
• RESEARCH INTERESTS
– Security and Privacy issues in:
• Vehicle ad hoc networks (VANETs)
• Mobile Social Networks
• Cryptocurrency (Bitcoin)
• VANET based Cloud
Contents
• Arrays
– One dimensional Array
– Array Initialization
– Program Examples:1D Arrays
– 2D Array
– Program Examples: 2D Arrays
• Strings
– Memory Storage for Strings
– Arrays of Strings
– I/O Strings
– Left Right Justifications
– Program Examples
– String Libraries and Functions
– String and Character Comparisons
– Conversions
ARRAYS
• An array is a collection of similar data elements
• Compared to the basic data type (int, float & char) it is an aggregate or
derived data type.
• All the elements of an array occupy a set of contiguous memory locations.
• Why need to use array type?
• Consider the following issue:

"We have a list of 1000 students' marks of an


integer type. If using the basic data type (int),
we will declare something like the following…"

int  studMark0, studMark1, studMark2, ..., studMark999;


ARRAYS

• Can you imagine how long we have to write


the declaration part by using normal variable
declaration?

void main()
{
int studMark1, studMark2, studMark3, studMark4,
…, …, studMark998, stuMark999, studMark1000;


}
ARRAYS
 By using an array, we just declare like this,

int  studMark[1000];

 This will reserve 1000 contiguous memory locations for storing the
students’ marks.
 Graphically, this can be depicted as in the following figure.
ARRAYS

• This absolutely has simplified our declaration of the variables.


• We can use index or subscript to identify each element or location
in the memory.
• Hence, if we have an index of jIndex, studMark[jIndex]
would refer to the jIndexth element in the array of studMark.
• For example, studMark[0] will refer to the first element of the
array.
• Thus by changing the value of jIndex, we could refer to any
element in the array.
• So, array has simplified our declaration and of course, manipulation
of the data.
One Dimensional Array: Declaration

 Dimension refers to the array's size, which is how big the


array is.
 A single or one dimensional array declaration has the
following form,
array_element_data_type array_name[array_size];

 Here, array_element_data_type define the base type of the


array, which is the type of each element in the array.
 array_name is any valid C / C++ identifier name that obeys
the same rule for the identifier naming.
 array_size defines how many elements the array will hold.

www.tenouk.com, ©
One Dimensional Array: Declaration
• For example, to declare an array of 30 integers, that
construct the marks of 30 students of a class, we could
declare,
• int   marks[30]; 80 marks[0]
• Which can be depicted as follows, 77 marks[1]
79 marks[2]

• 66 marks[3]
In this statement, the array can store up to 30
integers with the first integer value occupying … …
location marks[0] and the last value occupying … …
marks[29].  80 marks[29]
• Note that the index runs from 0 to 29.  In C, an
index always starts from 0 and ends with array's
(size-1).
• So, take note the difference between the array
size and subscript/index terms.
One Dimensional Array: Declaration
 Examples of the one-dimensional array declarations,

int      xNum[20], yNum[50];
float    fPrice[10], fYield;
char     chLetter[70];
 The first example declares two arrays named xNum and yNum of type
int.  Array xNum can store up to 20 integer numbers while yNum can
store up to 50 numbers. 
 The second line declares the array fPrice of type float.  It can
store up to 10 floating-point values.
 fYield is basic variable which shows array type can be declared
together with basic type provided the type is similar.
 The third line declares the array chLetter of type char.  It can store a
string up to 69 characters.
 Why 69 instead of 70? Remember, a string has a null terminating
character (\0) at the end, so we must reserve for it.
Array Initialization
 An array may be initialized at the time of declaration.
 Giving initial values to an array.
 Initialization of an array may take the following form,
type   array_name[size] = {a_list_of_value};
 For example:
int    idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float  fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char   chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
 The first line declares an integer array idNum and it immediately
assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1],
idNum[2],..., idNum[6] respectively.
 The second line assigns the values 5.6 to fFloatNum[0], 5.7  to 
fFloatNum[1], and so on.
 Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to
chVowel[1], and so on.  Note again, for characters we must use the
single apostrophe/quote (') to enclose them.
 Also, the last character in chVowel is NULL character ('\0').
Array Initialization
• Initialization of an array of type char for holding strings may take the following
form,

• char    array_name[size] = "string_lateral_constant";

• For example, the array chVowel in the previous example could have been
written more compactly as follows,

• char    chVowel[6] = "aeiou";

• When the value assigned to a character array is a string (which must be


enclosed in double quotes), the compiler automatically supplies the NULL
character but we still have to reserve one extra place for the NULL.
• For unsized array (variable sized), we can declare as follow,

• char chName[ ] = "Mr. Dracula";

• C compiler automatically creates an array which is big enough to hold all the
initializer.
Program Examples
 Arrays allow programmers to group related items of the same
data type in one variable.
 However, when referring to an array, one has to specify not only
the array or variable name but also the index number of interest.
 Program example 1: Sum of array’s element.
 Notice the array's element which is not initialized is set to 0
automatically.
Program Examples
• Program example 2: Searching the smallest value.
• Finding the smallest element in the array named fSmallest. 
• First, it assumes that the smallest value is in fSmallest[0] and
assigns it to the variable nSmall.
• Then it compares nSmall with the rest of the values in fSmallest,
one at a time.
• When an element is smaller than the current value contained in
nSmall, it is assigned to nSmall.  The process finally places the
smallest array element in nSmall.
Program Examples
• Program example 3: Searching the biggest valu
e
. By modifying the previous example we can
search the biggest value.
Program Examples
• Program example 4: Searching the location for th
e given value in an array
Program Examples
• Program example 5: Storing and reading a string
Program Examples
• Program example 6: Storing and reading array
content and its index
Two Dimensional/2D Arrays
• A two dimensional array has two subscripts/indexes. 
• The first subscript refers to the row, and the second, to the column.
• Its declaration has the following form,
• data_type    array_name[1st dimension size][2nd dimension
size];

• For examples,
• int      xInteger[3][4];
• float    matrixNum[20][25];

• The first line declares xInteger as an integer array with 3 rows and
4 columns.
• Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.
Two Dimensional/2D Arrays
• If we assign initial string values for the 2D array it will look
something like the following,

• char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole",


"Kidman", "Arnold", "Jodie"};

• Here, we can initialize the array with 6 strings, each with


maximum 9 characters long.
• If depicted in rows and columns it will look something like the
following and can be considered as contiguous arrangement in
the memory.
Two Dimensional/2D Arrays
• Take note that for strings the null character (\0) still needed.
• From the shaded square area of the figure we can determine the size of the
array.
• For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square. In general, for

• array_name[x][y];

• The array size is = First index x second index = xy.


• This also true for other array dimension, for example three dimensional
array,

• array_name[x][y][z]; => First index x second index x third index = xyz


• For example,

• ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
• And if you want to illustrate the 3D array, it could be a cube with wide, long
and height dimensions.
Program Example: 2D Array
• Program example 7: Storing and reading
array content and its index
Program Example: 2D Array
• Program example 8: Swapping iIndex (
iRow) with jIndex (iColumn
) in the previous program example
Program Example: 2D Array
1. Program example 9: Strings are read in by the rows.
2. Each row will have one string. Enter the following data:
“you”, “are”, “cat” for the following example.
3. Remember that after each string, a null character is
added.
4. We are reading in strings but printing out only characters.
ARRAYS
• The contents of the array in memory after the three
strings are read in the array.

• Re-run the program, enter the following data:


“you”, “my”. Illustrates the content as done
previously.
ARRAYS
1. Does your output agree?
2. How is the null character, '\0' printed?
3. Is there a garbage character in a[1][3]? If so,
why?

a) The output matched, except the garbage.


b) Just an empty space.
c) Yes. This slot has been reserved but not
filled so whatever the previous data that
has been stored here would be displayed
(if possible).
End-of-C-arrays
Strings
• C implements the string data structure
using arrays of type char.
• You have already used the string
extensively.
– printf(“This program is terminated!\n”);
– #define ERR_Message “Error!!”
• Since string is an array, the declaration of a
string is the same as declaring a char
array.
– char string_var[30];
– char string_var[20] = “Initial value”;
Memory Storage for a String
• The string is always ended with a null character ‘\0’.
• The characters after the null character are ignored.
• e.g., char str[20] = “Initial value”;

[0] [13]

I n i t i a l v a l u e \0 ? ? …
Arrays of Strings
• An array of strings is a two-dimensional array of
characters in which each row is one string.
– char names[People][Length];
– char month[5][10] = {“January”, “February”,
“March”, “April”, “May”};
Input/Output of a String
• The placeholder %s is used to represent
string arguments in printf and scanf.
– printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a
positive number in the placeholder.
– printf(“%8s”, str);
• The string can be left-justified by placing a
negative number in the placeholder.
– Printf(“%-8s”, str);
Right and Left Justification of Strings

The “%8s” placeholder displays a string which is right-justified and in 8-


columns width.
If the actual string is longer than the width, the displayed field is expanded
with no padding.
An Example of Manipulating String with scanf
and printf

The dept is the initial memory address of the


string argument. Thus we don’t apply the &
operator on it.

9-33
Execution of scanf ("%s", dept);
• Whenever encountering a white space, the scanning stops and scanf
places the null character at the end of the string.
• e.g., if the user types “MATH 1234 TR 1800,” the string “MATH” along
with ‘0’ is stored into dept.

9-34
String Library Functions
• The string can not be copied by the assignment operator
‘=’.
– e..g, “str = “Test String”” is not valid.
• C provides string manipulating functions in the “string.h”
library.
– The complete list of these functions can be found in Appendix B
of the textbook.
Some String Functions from String.h
Function Purpose Example
strcpy Makes a copy of a strcpy(s1, “Hi”);
string
strcat Appends a string to the strcat(s1, “more”);
end of another string
strcmp Compare two strings strcmp(s1, “Hu”);
alphabetically
strlen Returns the number of strlen(“Hi”)
characters in a string returns 2.
strtok Breaks a string into strtok(“Hi, Chao”,
tokens by delimiters. “ ,”);
Functions strcpy and strncpy
• Function strcpy copies the string in the second
argument into the first argument.
– e.g., strcpy(dest, “test string”);
– The null character is appended at the end
automatically.
– If source string is longer than the destination string, the
overflow characters may occupy the memory space
used by other variables.
• Function strncpy copies the string by specifying
the number of characters to copy.
– You have to place the null character manually.
– e.g., strncpy(dest, “test string”, 6); dest[6] = ‘\0’;
– If source string is longer than the destination string, the
overflow characters are discarded automatically.
9-37
Extracting Substring of a String (1/2)
• We can use strncpy to extract substring of one string.
– e.g., strncpy(result, s1, 9);

9-38
Extracting Substring of a String (2/2)
• e.g., strncpy(result, &s1[5], 2);

9-39
Functions strcat and strlen
• Functions strcat and strncat
concatenate the fist string argument with the
second string argument.
– strcat(dest, “more..”);
– strncat(dest, “more..”, 3);
• Function strlen is often used to check the
length of a string (i.e., the number of
characters before the fist null character).
– e.g., dest[6] = “Hello”;
strncat(dest, “more”, 5-strlen(dest));
dest[5] = ‘\0’;
Distinction Between Characters and Strings

• The representation of a char (e.g., ‘Q’) and


a string (e.g., “Q”) is essentially different.
– A string is an array of characters ended with the
null character.

Q Q \0

Character ‘Q’ String “Q”


String Comparison (1/2)
• Suppose there are two strings, str1 and str2.
– The condition str1 < str2 compare the initial
memory address of str1 and of str2.
• The comparison between two strings is done by
comparing each corresponding character in them.
– The characters are comapared against the ASCII table.
– “thrill” < “throw” since ‘i’ < ‘o’;
– “joy” < joyous“;
• The standard string comparison uses the strcmp
and strncmp functions.
String Comparison (2/2)
Relationship Returned Value Example
str1 < str2 Negative “Hello”< “Hi”
str1 = str2 0 “Hi” = “Hi”
str1 > str2 Positive “Hi” > “Hello”

• e.g., we can check if two strings are the same by


if(strcmp(str1, str2) != 0)
printf(“The two strings are different!”);
Input/Output of Characters and Strings
• The stdio library provides getchar
function which gets the next character from
the standard input.
– “ch = getchar();” is the same as
“scanf(“%c”, &ch);”
– Similar functions are putchar, gets, puts.
• For IO from/to the file, the stdio library
also provides corresponding functions.
– getc: reads a character from a file.
– Similar functions are putc, fgets, fputs.
Character Analysis and Conversion
• The <ctype.h> library defines facilities for
character analysis and conversion.

Functions Description
isalpha Check if the argument is a letter

isdigit Check if the argument is one of the ten digits

isspace Check if argument is a space, newline or tab.

tolower Converts the lowercase letters in the


argument to upper case letters.
Conversions Between Strings Numbers
• The <stdlib.h> defines some basic functions
for conversion from strings to numbers:
– atoi(“123”) converts a string to an integer.
– atol(“123”) converts a string to a long integer.
– atof(“12.3”) converts a string to a float.
• However, there is no functions such as itoa,
itof, …etc,
– because there is a function called sprintf which
can converts many formats to a string.
The sprintf and sscanf Functions
• The sprintf function substitutes values for
placeholders just as printf does except that
it stores the result into a character array
– sprintf(s, “%d%d%d”, mon, day,
year);
• The sscanf function works exactly like
scanf except that it takes data from the
string as its input argument.
– sscanf(“ 11 22.2 Hello”, “%d%lf%s”,
&num, &val, word);

You might also like