SlideShare a Scribd company logo
Fundamentals of
Computer Programming
Chapter 4
Array and Strings
Chere L. (M.Tech)
Lecturer, SWEG, AASTU
Outline
 Basic concepts of Array
 Types of Array
One Dimensional Arrays
Multi-dimensional Arrays
 Array declaration and initialization
 Accessing and processing Array Elements
 Basics of String
 String declaration and initialization
 String manipulation and operation
Input/output, Copying, Comparing, concatenation, etc.
 String library functions and operators
Chapter 4
2
Part II
Array of Character
(Strings)
Chapter 4
3
4) Basic of String
What is string?
 A string is a collection of characters .
 It is usually a meaningful sequence representing the name of
an entity.
 Generally it is combination of two or more characters
enclosed in double quotes.
 Example:
“Good Morning” // string with 2 words
“Mehak” // string with one word
”B.P.” // string with letters and symbols
“” // an empty string
 The above examples are also known as string literals
Chapter 4
4
4) Basic of String (cont’d)
String in C++
 C++ does not provide with a special data type to store strings.
• Thus we use arrays of the type char to store strings
 Strings in C++ are always terminated using a null character
(‘0’)
 Strings can be one dimensional or multi- dimensional
character arrays terminated by a null character (‘0’)
 String literals are the values stored in the character array
 Example: "Hi there!“
===> would be stored in memory as shown:
Chapter 4
5
H i t h e r e ! 0
4.1) String Declaration (C Style)
 To declare a character array (string) the syntax is
char stringName[size]; //One dimensional string
char stringName[rSize] [cSize]; //Two dimensional string
 Example: char name[20];
char stud_Name [30][20];
Note:
 Here name and stud_name is a character array or string capable of
storing maximum of 19 characters and 570 characters respectively.
 Since one character is reserved for storing ‘0’, the number of elements
that can be stored in a 1D string is always size-1
 Incase of 2D string each row should ends with ‘0’ and the maximum
number of characters that will stored is total_size – row_Size
Chapter 4
6
rsize: no of strings
cSize: size of each string
4.1) String Declaration (C++ Style)
 In C++ a string can be declared with string object in addition to that
of C-style declaration.
 Example:
string myString;
string city, country; string address[10];
 C-strings vs. string objects
Chapter 4
7
C-strings string objects
Implemented as arrays of type char Instance of string class
Terminated with the null character Not terminated with null character
Compile-time allocation and
determination of size
run-time allocation and undetermined
size
Fixed size, but do not track their own
size
Dynamic size and also track their own
size
4.1) String Declaration (C++ Style)
 Unlike C-style string, the string class library used to declared a
string as regular variables (not as arrays), and they support:
 The assignment operator =
 Comparison operators ==, !=, etc
 The + operator for concatenation
 Type conversions from c-strings to string objects
 A variety of other member functions
Chapter 4
8
4.2) String initialization
(a) 1D String Initialization
 Example 1:
char name[20] = “John Eyob”;
- The above string will have 9 characters and 1 space for the null.
Thus size of name will be 10.
 Example 2: string name = “John Eyob”;
Chapter 4
9
string
name[0] name[1]
name[7] name[9]
null
character
J o h n E y . .
. . . . . . . . . . . . . . .
o b ‘0
4.2) String initialization (cont’d)
 Example 2: omitting string size
- Like as we do in array string size can be omitted also
char myAddress[] = “Addis Ababa, Ethiopia”;
 In this case the string is initialized to the mentioned string literal and it’s
size is the number of characters in the string literal plus null character.
Here it is 20.
 The null character is automatically inserted at the end of the string.
 Example 3: initializing string character by character
char city [10] = {‘A’, ‘d’, ‘a’, ‘m’, ‘a’, ‘0’};
char myCity [ ] = {‘D’, ‘i’, ‘r’, ‘e’, ‘d’, ‘e’, ‘w’, ‘a’, ‘0’};
Note: The ‘0’ has to be inserted by the programmer.
Chapter 4
10
4.2) String initialization (cont’d)
 Some more examples of string initialization
Chapter 4
11
Initialization Memory representation
char animal[7]=“Lion”;
char location[]=“Aksum City”;
char serial_no[]=“A011”;
char name [5] = “Gamechis”; //invalid, out of bound
char company[10] =
“Ethiotel”;
char country [] = ‘Ethioipia’; //invalid, string must enclosed within
double quote
A k s u m C i t y ‘0’
A 0 1 1 ‘0’
L i o n ‘0’
E t h i o t e l ‘0’
4.2) String initialization (cont’d)
(b) Initializing 2 D Strings - 2D string can be initialize as follows
 Example 1:
char word[4][5]={“Cat”, “Boat”, “Mat”,”Rate”};
12
4.2) String initialization (cont’d)
 Example 2: Omitting string rowSize (number of strings)
char name[][12] = {"Mr. Biniam", "Mr. Abush",
“Miss Nardos", “Mrs. Kidest",
“Dr. Andualem", “Eng. Yodit"};
- #strings (rowSize) = 6
13
M r . B i n i a m 0
M r . A b u s h 0
M i s s N a r d o s 0
M r s . K i d e s t 0
D r . A n d u a l e m 0
E n g . Y o d i t 0
Columns
0 1 2 3 4 5 6 7 8 9 10 11 12
5
4
3
2
1
0
rows
name[2][2]
2nd index 1st
index
name[5][7] name[4][8]
4.2) String initialization (cont’d)
 Example 3: initializing string objects
string address = “Addis Ababa”;
string name[12] = {"Mr. Biniam", "Mr. Abush",
“Miss Nardos", “Mrs. Kidest",
“Dr. Andualem", “Eng. Yodit"};
 Example 4: initializing 2D strings character by character
char myName[][6] = { {‘C’, ‘H’, ‘A’, ‘L’, ‘A’, ‘0’},
{‘B’, ‘O’, ‘N’, ‘S’, ‘A’, ‘0’}
{‘H’, ‘A’, ‘G’, ‘O’, ‘S’, ‘0’ };
14
4.2) String initialization (cont’d)
 Example 6: initializing string after declaration
char mystring [6];
mystring[0] = 'H'; mystring[1] = 'e';
mystring[2] = 'l'; mystring[3] = 'l';
mystring[4] = 'o'; mystring[5] = '0';
Note: Like wise 2D strings can be initialized after declaration.
 Example 7: Invalid string initialization/assignment
char mystring[6];
mystring="Hello"; // not allowed
mystring[] = "Hello"; //illegal
mystring = { 'H', 'e', 'l', 'l', 'o', '0' }; //neither would be valid
Chapter 4
15
4.3) String input/output
 A string is displayed using a simple cout<< stream statement
 However, input a string or character array can be performed through
any one of the following
Chapter 4
16
No Input method Descriptions
1 cin>> stream
• Inputs a string without spaces
• The >> operator stops input when it encounters a
space
• Syntax: cin>>str;
2 get() function
• Used to input either single character or a line of text
with spaces
• Syntax 1: cin.get(ch);
where ch is a character
• Syntax 2: cin.get(str, n);
where str is string and n specify the size of
string to be read.
4.3) String input/output (cont’d)
Chapter 4
17
No Input method Descriptions
3 gets() function
• Can be used to input a single line of text including
spaces.
• As soon as the enter is pressed it stops input
• Syntax: gets( str );
where str is a string
4 getline() function
• Can be used to input multiple lines of text.
• Syntax: cin.getline(string, MAX, Delimiter)
were - String is the character array
- Max is the maximum number of characters
allowed input
- Delimeter is the character which when
encountered in the input stream
stops the input
Note: it is no needed to use loop to input or display a string unless the character
array (string) is 2D and we need to read/print multiple strings.
4.3) String input/output (cont’d)
Chapter 4
18
4.3) String input/output (cont’d)
Note:
 The getline function continues to input the string until either the maximum
number of characters are input or it encounters the delimiter character
whichever comes first.
Chapter 4
19
4.4) String Operation/manipulations
 Assignment/copy and comparison operation
 In C-style, strings cannot be copied or compared using the
simple assignment or comparison operator as follow.
char str1[20], str2[20];
str2=str1; // Not allowed
if(str1==str2) //Not allowed
{ ….. }
 However, using the C++ string objects the above two string
operations are valid
str2=str1; if(str1==str2) //both are valid
Chapter 4
20
4.4) String Operation/manipulations (cont’d)
 Assignment/copy and comparison operation
 In C-style, strings cannot be copied or compared using the
simple assignment or comparison operator as follow.
char str1[20], str2[20];
str2=str1; // Not allowed
if(str1==str2) //Not allowed
{ ….. }
 However, using the C++ string objects the above two string
operations are valid
str2=str1; if(str1==str2) //both are valid
Chapter 4
21
4.4) String Operation/manipulations (cont’d)
 Other string operations
 Find the string length
 Search string or substring
 Characters case conversion
 Reverse or swap string
 Concatenating strings
 String tokenization etc.
 Modifying (replace) string
 The above mentioned string manipulations can be performed
either through hard coding or using library functions
Chapter 4
22
4.4) String Manipulations and Library Functions
 Here below list of string manipulation library functions
Chapter 4
23
Description
Function
String
operations
Copies string str2 (source string) into
the character array str1 (destination
string). The value of str1 is returned.
strcpy(str1, str2);
String copying
Copies at most n characters of string
s2 into the array s1. The value of s1
is returned.
strncpy(str1, str2, size_t n);
Appends string s2 to string s1. The
value of s1 is returned.
strcat (str1, str2);
String
concatenation Appends at most n characters of
string s2 to string s1. The value of s1
is returned.
strncat (str1, str2, size_t n);
4.4) String Library Functions (cont’d)
 Here below list of string manipulation library functions
Chapter 4
24
Description
Function
String
operations
Compares string str1 with string str2. The
function returns a value of
• zero, if str1 is equal to str2
• less than zero, if str1 is less than str2
• greater than zero, if str1 greater than
str2
strcmp(str1, str2);
String
comparison
Compares up to n characters of string str1
with string str2. It works in the fashion as
strcmp().
strncmp(str1, str2, size n);
Compares string str1 with string str2 in
regardless of their cases (upper case or
lower case.
int stricmp(str1, str2);
Compares up to n characters of string str1
with string str2 in regardless of their cases
strnicmp(str1, str2, size n);
4.4) String Library Functions (cont’d)
 Here below list of string manipulation library functions
Chapter 4
25
Description
Function
String operations
Determines the length of string str. The
number of characters preceding the
terminating null character is returned.
strlen(str);
String length
Returns a the first left occurrence of
character ch in string str1.
strch(str1, ch);
Looking for string /
character
Occurrence
Returns a the first right occurrence of
character ch in string str1 .
strrch(str1, ch);
Returns a the first occurrence of string str2
in string str1.
strstr(str1, str2);
Converts lowercase characters in strings to
uppercase
strupr(str1)
String case
conversion Converts uppercase characters in strings to
lowercase
strlwr(str1)
4.4) String Library Functions (cont’d)
 Here below list of string manipulation library functions
Chapter 4
26
Description
Function
String
operations
finds up at what length two strings are identical
strspn(str1, str2)
Others
Reversing all characters of a string
strrev( str )
A sequence of calls to strtok breaks string str1
into “tokens”—logical pieces such as words in a
line of text—delimited by characters contained
in string s2.
The first call contains str1 as the first argument,
and subsequent calls to continue tokenizing the
same string contain NULL as the first argument
strtok( str1, s2 );
Repalcae character(s) of string to a given
character
strset(str, ch),
strnset(str, ch, 5)
Note: These are some of the library functions and Many More are available
4.4) String Library Functions (cont’d)
Relational Operators and library functions
supported by C++ String objects
Chapter 4
27
functions Descriptions
append() appends a part of a string to another string
assign() assigns a partial string
at() obtains character stored at a specified
location
begin() returns a reference to the start of the string
capacity() gives the total element that can be stored
compare() compares a string against the invoking string
empty() returns true if the string is empty
end() returns a reference to the end of the string
erase() removes character as specified
find() searches for the occurrence of a specified
substring
swap() swaps the given string with the invoking on
4.4) String Library Functions (cont’d)
Correspondence between
the C-library and the C++ string class/object
Chapter 4
28
4.4) String Library Functions (cont’d)
Character handling library functions of ctype.h
Chapter 4
29
Prototype Description
isdigit(c ) Returns true if c is a digit and false otherwise
isalpha( c ) Returns true if c is a letter and false otherwise
isalnum( c ) Returns true if c is a digit/letter and false otherwise
isxdigit( c ) Returns true if c is a hexadecimal digit and false otherwise
islower( c) Returns true if c is a lowercase letter and false otherwise
isupper( c) Returns true if c is an uppercase letter; false otherwise
tolower( c ),
toupper( c )
If c is an uppercase letter, it returns c as a lowercase letter. Otherwise,
leave the character/string unchanged and vice versa
isgraph( c ) Returns true if c is a printing character other than space (' ')
isspace(c )
Returns true if c is a white-space, newline ('n'), space (' '), form feed ('f'),
carriage return ('r'), horizontal tab ('t'), or vertical tab ('v') and false
otherwise
iscntrl( c ) Returns true if c is a control character and false otherwise
ispunct( c )
Returns true if c is a printing character other than a space, a digit, or a
letter and false otherwise
isprint( c ) Returns true value if c is a printing character including space (' ')
4.4) String manipulation (cont’d)
 Example 1: string length
Chapter 4
30
(a) Hard coding
(b) Using strlen() library function
4.4) String manipulation (cont’d)
 Example 2: copying and compare (Hard coding )
Chapter 4
31
(a) Copying string
(b) String comparison
4.4) String manipulation (cont’d)
 Example 3: copying, concatenate and compare using library functions
Chapter 4
32
(b) String comparison
copying and concatenating
the 1st nth string
Comparing the 1st nth
characters of strings
4.4) String manipulation (cont’d)
 Example 4: more on string manipulations
Chapter 4
33
String case conversion
Reverse string
4.4) String manipulation (cont’d)
 Example 5: string tokenization
Chapter 4
34
4.4) String manipulation (cont’d)
 Example 6: Program to display the words which start with a capital ‘A’
Chapter 4
35
Practical Exercises 2 - Strings
1. Write a program to count total number of vowels and consonants
present in a string.
2. Design a program to find the frequency of characters within string and
display character with largest and smallest frequency respectively.
3. Write a program that find the frequency of vowel, consonant, digit and
special character
4. Design a program to check either the word is palindrome or not using
loop.
5. Write a program to remove non-alphabet character from string
6. Write a program to store and print the names of your two favorite
television programs. Store these programs in two character arrays.
Initialize one of the strings (assign it the first program’s name) at the
time you declare the array. Initialize the second value in the body of
the program with the strcpy() function.
7. Write an application that inputs a line of text and outputs the text
twice, once in all uppercase and once in all lowercase letters.
Chapter 2
36
Reading Resources/Materials
Chapter 13:
 Diane Zak; An Introduction to Programming with C++ (8th Edition),
2016 Cengage Learning
Chapter 8:
Walter Savitch; Problem Solving With C++ [10th edition,
University of California, San Diego, 2018
Link:
 https://www.w3schools.in/category/cplusplus-tutorial/
37
Thank You
For Your Attention!!
38
Ad

More Related Content

Similar to Chapter 4 (Part II) - Array and Strings.pdf (20)

ARRAY's in C Programming Language PPTX.
ARRAY's in C  Programming Language PPTX.ARRAY's in C  Programming Language PPTX.
ARRAY's in C Programming Language PPTX.
MSridhar18
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
Strings In C and its syntax and uses .ppt
Strings In C and its syntax and uses .pptStrings In C and its syntax and uses .ppt
Strings In C and its syntax and uses .ppt
fallengaming1606
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
International Islamic University
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
M C6java7
M C6java7M C6java7
M C6java7
mbruggen
 
Java Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptxJava Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptx
OmarBinkasimSefat
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
Python data handling
Python data handlingPython data handling
Python data handling
Prof. Dr. K. Adisesha
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
mathesh0303
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
Strings
StringsStrings
Strings
Saranya saran
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...
jr2710
 
CP-STRING (1).ppt
CP-STRING (1).pptCP-STRING (1).ppt
CP-STRING (1).ppt
mounikanarra3
 
CP-STRING.ppt
CP-STRING.pptCP-STRING.ppt
CP-STRING.ppt
TAPANDDRAW
 
CP-STRING.ppt
CP-STRING.pptCP-STRING.ppt
CP-STRING.ppt
arunatluri
 
ARRAY's in C Programming Language PPTX.
ARRAY's in C  Programming Language PPTX.ARRAY's in C  Programming Language PPTX.
ARRAY's in C Programming Language PPTX.
MSridhar18
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
Strings In C and its syntax and uses .ppt
Strings In C and its syntax and uses .pptStrings In C and its syntax and uses .ppt
Strings In C and its syntax and uses .ppt
fallengaming1606
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
mikeymanjiro2090
 
Java Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptxJava Object Orientend Programming 1.pptx
Java Object Orientend Programming 1.pptx
OmarBinkasimSefat
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...Computer Programming Utilities the subject of BE first year students, and thi...
Computer Programming Utilities the subject of BE first year students, and thi...
jr2710
 

More from KirubelWondwoson1 (6)

00 C++ For Engineers and Scientists.pdf
00 C++ For Engineers and Scientists.pdf00 C++ For Engineers and Scientists.pdf
00 C++ For Engineers and Scientists.pdf
KirubelWondwoson1
 
Chapter 4 (Part I) - Array and Strings.pdf
Chapter 4 (Part I) - Array and Strings.pdfChapter 4 (Part I) - Array and Strings.pdf
Chapter 4 (Part I) - Array and Strings.pdf
KirubelWondwoson1
 
Chapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdfChapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdf
KirubelWondwoson1
 
Chapter 5 - Modular Programming.pdf
Chapter 5 - Modular Programming.pdfChapter 5 - Modular Programming.pdf
Chapter 5 - Modular Programming.pdf
KirubelWondwoson1
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
KirubelWondwoson1
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdf
KirubelWondwoson1
 
00 C++ For Engineers and Scientists.pdf
00 C++ For Engineers and Scientists.pdf00 C++ For Engineers and Scientists.pdf
00 C++ For Engineers and Scientists.pdf
KirubelWondwoson1
 
Chapter 4 (Part I) - Array and Strings.pdf
Chapter 4 (Part I) - Array and Strings.pdfChapter 4 (Part I) - Array and Strings.pdf
Chapter 4 (Part I) - Array and Strings.pdf
KirubelWondwoson1
 
Chapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdfChapter 1 - Basic concepts of programming.pdf
Chapter 1 - Basic concepts of programming.pdf
KirubelWondwoson1
 
Chapter 5 - Modular Programming.pdf
Chapter 5 - Modular Programming.pdfChapter 5 - Modular Programming.pdf
Chapter 5 - Modular Programming.pdf
KirubelWondwoson1
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
KirubelWondwoson1
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdf
KirubelWondwoson1
 
Ad

Recently uploaded (20)

Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Ad

Chapter 4 (Part II) - Array and Strings.pdf

  • 1. Fundamentals of Computer Programming Chapter 4 Array and Strings Chere L. (M.Tech) Lecturer, SWEG, AASTU
  • 2. Outline  Basic concepts of Array  Types of Array One Dimensional Arrays Multi-dimensional Arrays  Array declaration and initialization  Accessing and processing Array Elements  Basics of String  String declaration and initialization  String manipulation and operation Input/output, Copying, Comparing, concatenation, etc.  String library functions and operators Chapter 4 2
  • 3. Part II Array of Character (Strings) Chapter 4 3
  • 4. 4) Basic of String What is string?  A string is a collection of characters .  It is usually a meaningful sequence representing the name of an entity.  Generally it is combination of two or more characters enclosed in double quotes.  Example: “Good Morning” // string with 2 words “Mehak” // string with one word ”B.P.” // string with letters and symbols “” // an empty string  The above examples are also known as string literals Chapter 4 4
  • 5. 4) Basic of String (cont’d) String in C++  C++ does not provide with a special data type to store strings. • Thus we use arrays of the type char to store strings  Strings in C++ are always terminated using a null character (‘0’)  Strings can be one dimensional or multi- dimensional character arrays terminated by a null character (‘0’)  String literals are the values stored in the character array  Example: "Hi there!“ ===> would be stored in memory as shown: Chapter 4 5 H i t h e r e ! 0
  • 6. 4.1) String Declaration (C Style)  To declare a character array (string) the syntax is char stringName[size]; //One dimensional string char stringName[rSize] [cSize]; //Two dimensional string  Example: char name[20]; char stud_Name [30][20]; Note:  Here name and stud_name is a character array or string capable of storing maximum of 19 characters and 570 characters respectively.  Since one character is reserved for storing ‘0’, the number of elements that can be stored in a 1D string is always size-1  Incase of 2D string each row should ends with ‘0’ and the maximum number of characters that will stored is total_size – row_Size Chapter 4 6 rsize: no of strings cSize: size of each string
  • 7. 4.1) String Declaration (C++ Style)  In C++ a string can be declared with string object in addition to that of C-style declaration.  Example: string myString; string city, country; string address[10];  C-strings vs. string objects Chapter 4 7 C-strings string objects Implemented as arrays of type char Instance of string class Terminated with the null character Not terminated with null character Compile-time allocation and determination of size run-time allocation and undetermined size Fixed size, but do not track their own size Dynamic size and also track their own size
  • 8. 4.1) String Declaration (C++ Style)  Unlike C-style string, the string class library used to declared a string as regular variables (not as arrays), and they support:  The assignment operator =  Comparison operators ==, !=, etc  The + operator for concatenation  Type conversions from c-strings to string objects  A variety of other member functions Chapter 4 8
  • 9. 4.2) String initialization (a) 1D String Initialization  Example 1: char name[20] = “John Eyob”; - The above string will have 9 characters and 1 space for the null. Thus size of name will be 10.  Example 2: string name = “John Eyob”; Chapter 4 9 string name[0] name[1] name[7] name[9] null character J o h n E y . . . . . . . . . . . . . . . . . o b ‘0
  • 10. 4.2) String initialization (cont’d)  Example 2: omitting string size - Like as we do in array string size can be omitted also char myAddress[] = “Addis Ababa, Ethiopia”;  In this case the string is initialized to the mentioned string literal and it’s size is the number of characters in the string literal plus null character. Here it is 20.  The null character is automatically inserted at the end of the string.  Example 3: initializing string character by character char city [10] = {‘A’, ‘d’, ‘a’, ‘m’, ‘a’, ‘0’}; char myCity [ ] = {‘D’, ‘i’, ‘r’, ‘e’, ‘d’, ‘e’, ‘w’, ‘a’, ‘0’}; Note: The ‘0’ has to be inserted by the programmer. Chapter 4 10
  • 11. 4.2) String initialization (cont’d)  Some more examples of string initialization Chapter 4 11 Initialization Memory representation char animal[7]=“Lion”; char location[]=“Aksum City”; char serial_no[]=“A011”; char name [5] = “Gamechis”; //invalid, out of bound char company[10] = “Ethiotel”; char country [] = ‘Ethioipia’; //invalid, string must enclosed within double quote A k s u m C i t y ‘0’ A 0 1 1 ‘0’ L i o n ‘0’ E t h i o t e l ‘0’
  • 12. 4.2) String initialization (cont’d) (b) Initializing 2 D Strings - 2D string can be initialize as follows  Example 1: char word[4][5]={“Cat”, “Boat”, “Mat”,”Rate”}; 12
  • 13. 4.2) String initialization (cont’d)  Example 2: Omitting string rowSize (number of strings) char name[][12] = {"Mr. Biniam", "Mr. Abush", “Miss Nardos", “Mrs. Kidest", “Dr. Andualem", “Eng. Yodit"}; - #strings (rowSize) = 6 13 M r . B i n i a m 0 M r . A b u s h 0 M i s s N a r d o s 0 M r s . K i d e s t 0 D r . A n d u a l e m 0 E n g . Y o d i t 0 Columns 0 1 2 3 4 5 6 7 8 9 10 11 12 5 4 3 2 1 0 rows name[2][2] 2nd index 1st index name[5][7] name[4][8]
  • 14. 4.2) String initialization (cont’d)  Example 3: initializing string objects string address = “Addis Ababa”; string name[12] = {"Mr. Biniam", "Mr. Abush", “Miss Nardos", “Mrs. Kidest", “Dr. Andualem", “Eng. Yodit"};  Example 4: initializing 2D strings character by character char myName[][6] = { {‘C’, ‘H’, ‘A’, ‘L’, ‘A’, ‘0’}, {‘B’, ‘O’, ‘N’, ‘S’, ‘A’, ‘0’} {‘H’, ‘A’, ‘G’, ‘O’, ‘S’, ‘0’ }; 14
  • 15. 4.2) String initialization (cont’d)  Example 6: initializing string after declaration char mystring [6]; mystring[0] = 'H'; mystring[1] = 'e'; mystring[2] = 'l'; mystring[3] = 'l'; mystring[4] = 'o'; mystring[5] = '0'; Note: Like wise 2D strings can be initialized after declaration.  Example 7: Invalid string initialization/assignment char mystring[6]; mystring="Hello"; // not allowed mystring[] = "Hello"; //illegal mystring = { 'H', 'e', 'l', 'l', 'o', '0' }; //neither would be valid Chapter 4 15
  • 16. 4.3) String input/output  A string is displayed using a simple cout<< stream statement  However, input a string or character array can be performed through any one of the following Chapter 4 16 No Input method Descriptions 1 cin>> stream • Inputs a string without spaces • The >> operator stops input when it encounters a space • Syntax: cin>>str; 2 get() function • Used to input either single character or a line of text with spaces • Syntax 1: cin.get(ch); where ch is a character • Syntax 2: cin.get(str, n); where str is string and n specify the size of string to be read.
  • 17. 4.3) String input/output (cont’d) Chapter 4 17 No Input method Descriptions 3 gets() function • Can be used to input a single line of text including spaces. • As soon as the enter is pressed it stops input • Syntax: gets( str ); where str is a string 4 getline() function • Can be used to input multiple lines of text. • Syntax: cin.getline(string, MAX, Delimiter) were - String is the character array - Max is the maximum number of characters allowed input - Delimeter is the character which when encountered in the input stream stops the input Note: it is no needed to use loop to input or display a string unless the character array (string) is 2D and we need to read/print multiple strings.
  • 18. 4.3) String input/output (cont’d) Chapter 4 18
  • 19. 4.3) String input/output (cont’d) Note:  The getline function continues to input the string until either the maximum number of characters are input or it encounters the delimiter character whichever comes first. Chapter 4 19
  • 20. 4.4) String Operation/manipulations  Assignment/copy and comparison operation  In C-style, strings cannot be copied or compared using the simple assignment or comparison operator as follow. char str1[20], str2[20]; str2=str1; // Not allowed if(str1==str2) //Not allowed { ….. }  However, using the C++ string objects the above two string operations are valid str2=str1; if(str1==str2) //both are valid Chapter 4 20
  • 21. 4.4) String Operation/manipulations (cont’d)  Assignment/copy and comparison operation  In C-style, strings cannot be copied or compared using the simple assignment or comparison operator as follow. char str1[20], str2[20]; str2=str1; // Not allowed if(str1==str2) //Not allowed { ….. }  However, using the C++ string objects the above two string operations are valid str2=str1; if(str1==str2) //both are valid Chapter 4 21
  • 22. 4.4) String Operation/manipulations (cont’d)  Other string operations  Find the string length  Search string or substring  Characters case conversion  Reverse or swap string  Concatenating strings  String tokenization etc.  Modifying (replace) string  The above mentioned string manipulations can be performed either through hard coding or using library functions Chapter 4 22
  • 23. 4.4) String Manipulations and Library Functions  Here below list of string manipulation library functions Chapter 4 23 Description Function String operations Copies string str2 (source string) into the character array str1 (destination string). The value of str1 is returned. strcpy(str1, str2); String copying Copies at most n characters of string s2 into the array s1. The value of s1 is returned. strncpy(str1, str2, size_t n); Appends string s2 to string s1. The value of s1 is returned. strcat (str1, str2); String concatenation Appends at most n characters of string s2 to string s1. The value of s1 is returned. strncat (str1, str2, size_t n);
  • 24. 4.4) String Library Functions (cont’d)  Here below list of string manipulation library functions Chapter 4 24 Description Function String operations Compares string str1 with string str2. The function returns a value of • zero, if str1 is equal to str2 • less than zero, if str1 is less than str2 • greater than zero, if str1 greater than str2 strcmp(str1, str2); String comparison Compares up to n characters of string str1 with string str2. It works in the fashion as strcmp(). strncmp(str1, str2, size n); Compares string str1 with string str2 in regardless of their cases (upper case or lower case. int stricmp(str1, str2); Compares up to n characters of string str1 with string str2 in regardless of their cases strnicmp(str1, str2, size n);
  • 25. 4.4) String Library Functions (cont’d)  Here below list of string manipulation library functions Chapter 4 25 Description Function String operations Determines the length of string str. The number of characters preceding the terminating null character is returned. strlen(str); String length Returns a the first left occurrence of character ch in string str1. strch(str1, ch); Looking for string / character Occurrence Returns a the first right occurrence of character ch in string str1 . strrch(str1, ch); Returns a the first occurrence of string str2 in string str1. strstr(str1, str2); Converts lowercase characters in strings to uppercase strupr(str1) String case conversion Converts uppercase characters in strings to lowercase strlwr(str1)
  • 26. 4.4) String Library Functions (cont’d)  Here below list of string manipulation library functions Chapter 4 26 Description Function String operations finds up at what length two strings are identical strspn(str1, str2) Others Reversing all characters of a string strrev( str ) A sequence of calls to strtok breaks string str1 into “tokens”—logical pieces such as words in a line of text—delimited by characters contained in string s2. The first call contains str1 as the first argument, and subsequent calls to continue tokenizing the same string contain NULL as the first argument strtok( str1, s2 ); Repalcae character(s) of string to a given character strset(str, ch), strnset(str, ch, 5) Note: These are some of the library functions and Many More are available
  • 27. 4.4) String Library Functions (cont’d) Relational Operators and library functions supported by C++ String objects Chapter 4 27 functions Descriptions append() appends a part of a string to another string assign() assigns a partial string at() obtains character stored at a specified location begin() returns a reference to the start of the string capacity() gives the total element that can be stored compare() compares a string against the invoking string empty() returns true if the string is empty end() returns a reference to the end of the string erase() removes character as specified find() searches for the occurrence of a specified substring swap() swaps the given string with the invoking on
  • 28. 4.4) String Library Functions (cont’d) Correspondence between the C-library and the C++ string class/object Chapter 4 28
  • 29. 4.4) String Library Functions (cont’d) Character handling library functions of ctype.h Chapter 4 29 Prototype Description isdigit(c ) Returns true if c is a digit and false otherwise isalpha( c ) Returns true if c is a letter and false otherwise isalnum( c ) Returns true if c is a digit/letter and false otherwise isxdigit( c ) Returns true if c is a hexadecimal digit and false otherwise islower( c) Returns true if c is a lowercase letter and false otherwise isupper( c) Returns true if c is an uppercase letter; false otherwise tolower( c ), toupper( c ) If c is an uppercase letter, it returns c as a lowercase letter. Otherwise, leave the character/string unchanged and vice versa isgraph( c ) Returns true if c is a printing character other than space (' ') isspace(c ) Returns true if c is a white-space, newline ('n'), space (' '), form feed ('f'), carriage return ('r'), horizontal tab ('t'), or vertical tab ('v') and false otherwise iscntrl( c ) Returns true if c is a control character and false otherwise ispunct( c ) Returns true if c is a printing character other than a space, a digit, or a letter and false otherwise isprint( c ) Returns true value if c is a printing character including space (' ')
  • 30. 4.4) String manipulation (cont’d)  Example 1: string length Chapter 4 30 (a) Hard coding (b) Using strlen() library function
  • 31. 4.4) String manipulation (cont’d)  Example 2: copying and compare (Hard coding ) Chapter 4 31 (a) Copying string (b) String comparison
  • 32. 4.4) String manipulation (cont’d)  Example 3: copying, concatenate and compare using library functions Chapter 4 32 (b) String comparison copying and concatenating the 1st nth string Comparing the 1st nth characters of strings
  • 33. 4.4) String manipulation (cont’d)  Example 4: more on string manipulations Chapter 4 33 String case conversion Reverse string
  • 34. 4.4) String manipulation (cont’d)  Example 5: string tokenization Chapter 4 34
  • 35. 4.4) String manipulation (cont’d)  Example 6: Program to display the words which start with a capital ‘A’ Chapter 4 35
  • 36. Practical Exercises 2 - Strings 1. Write a program to count total number of vowels and consonants present in a string. 2. Design a program to find the frequency of characters within string and display character with largest and smallest frequency respectively. 3. Write a program that find the frequency of vowel, consonant, digit and special character 4. Design a program to check either the word is palindrome or not using loop. 5. Write a program to remove non-alphabet character from string 6. Write a program to store and print the names of your two favorite television programs. Store these programs in two character arrays. Initialize one of the strings (assign it the first program’s name) at the time you declare the array. Initialize the second value in the body of the program with the strcpy() function. 7. Write an application that inputs a line of text and outputs the text twice, once in all uppercase and once in all lowercase letters. Chapter 2 36
  • 37. Reading Resources/Materials Chapter 13:  Diane Zak; An Introduction to Programming with C++ (8th Edition), 2016 Cengage Learning Chapter 8: Walter Savitch; Problem Solving With C++ [10th edition, University of California, San Diego, 2018 Link:  https://www.w3schools.in/category/cplusplus-tutorial/ 37
  • 38. Thank You For Your Attention!! 38
  翻译: