SlideShare a Scribd company logo
Prepared by Dawit T.
ITec 2042
Fundamentals of Programming II
Chapter one
Arrays and Strings
Prepared by Dawit T.
Arrays
Array
- Structures of related data items
- Static entity – same size throughout program
- Group of consecutive memory locations
- Same name and type
Referring to an element, specify
- Array name
- Position number
Format
type arrayName [integer value];
Prepared by Dawit T.
Name of array (Note that
all elements of this array
have the same name, c)
Position number of the
element within array c
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
c[0]
c[1]
c[2]
c[3]
c[11
]
c[10
]
c[9]
c[8]
c[7]
c[5]
c[4]
int c[11]={-45,6,0,72,1543,-89,0,62,-3,1,6453,78}
array c
- First element at position 0
- n element array named c:
o c[0], c[1],…c[n-1]
- Array elements are like
normal variables
c [8] = -3
Prepared by Dawit T.
DeclaringArrays
When declaring arrays, specify
- Types of array
- Name of array
- Number of elements
arrayType arrayName[ numberOfElements ];
- Examples:
- int c[ 10 ];
- float myArray[ 3284 ];
Declaring multiple arrays of same type
- Format similar to regular variables
- Example:
int b[ 100 ], x[ 27 ]
Prepared by Dawit T.
Array index out of Bounds
Index of an array is in bounds if the index is >=0 and <= ARRAY_SIZE-1
- Otherwise, the index is out of bounds
In C++, there is no guard against indices that are out of bounds
If the index is out of bounds
Sometimes it may crash
Sometimes it may display garbage values
It may even appear to work without any error
Prepared by Dawit T.
InitializingArrays
Elements in array may be initialized in two ways:
- Explicitly (using an assignment statement for each element)
- Using a list a list is denoted using braces, with element in the list
separated by a comma.
Initializing arrays explicitly Easily accomplished using a for loop.
- Example: Explicitly initialize all elements in an array to 5.0
const int Asize = 100;
int A[Asize];
for (int i = 0; i < Asize; i++)
A[i] = 5.0;
Prepared by Dawit T.
Initializing arrays using a list
Elements in array may be initialized using a list of values in braces.
- If not enough initializers, rightmost elements become 0.
int n[ 5 ] = { 0 } // All elements 0
- If array size omitted, array size is set to the number of elements in the list.
Example:
double X[4] = {1.1, 2.2, 3.3, 4.4}; // initialize array X with a list
Using the list above is equivalent to:
double X[4];
X[0] = 1.1;
X[1] = 2.2; initializing array X with explicitly
X[2] = 3.3;
X[3] = 4.4;
Prepared by Dawit T.
1. Initializing a Fixed-Size
Integer Array
You can initialize an integer
array at the time of declaration
by explicitly listing its elements:
int arr[5] = {10, 20, 30, 40, 50};
2. Partially Initializing Arrays
If you don’t provide enough
initial values, the remaining
elements will be automatically
initialized to 0 (for numeric
arrays).
int arr[5] = {10, 20};
3. Fully Initializing Arrays with Fewer
Elements Than Size
If you don’t specify the size of the array
but provide the elements, C++ will
automatically determine the size of the
array based on the number of elements
you provide.
int arr[] = {5, 10, 15, 20};
4. Initializing Multidimensional Arrays
For multidimensional arrays, each row
(or higher dimension) can also be
initialized explicitly.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Prepared by Dawit T.
Example: Initializing arrays using a list
int A[5] = {11,22}; // initializes array values to 11,22,0,0,0
double Sum[7] = {0.0};// initializes all 7 sums to 0.0
int B[ ] = {2,4,6,8}; // array B is assigned an array size of 4
char Vowels[8] = “aeiou”;// Vowels[0] = ‘a’, Vowels[1] = ‘e’, etc
Array
B
2
4
6
8
Prepared by Dawit T.
Some Restrictions on Array Processing
Aggregate operation: any operation that manipulates the entire array
as a single unit
- Not allowed on arrays in C++
Example:
Solution
Prepared by Dawit T.
Printing Arrays
Arrays are easily printed using
for loops.
Example 1:
int Grades[12] = {78,80,82,84,86,
88,90,92,94,96,98,100};
for (int j = 0; j < 12; j++)
cout << Grades[ j ] <<
endl;
Example 2:
for (int Row = 0; Row <= 2; Row+
+)
{
for (int Col = 0; Col <=3;
Col++)
cout <<
Grades[ 4*Row+Col ];
cout << endl;
}
Prepared by Dawit T.
Printing example 1
//For loop to fill & print a 10-int array
#include <iostream>
using namespace std;
int main ( ) {
int index, ar[10]; // array for 10 integers
// Read in 10 elements.
cout << "Enter 10 integers: ";
for(index = 0; index < 10; index ++)
cin >> ar[index];
cout << endl;
cout << "The integers are ";
for(index = 0; index < 10; index ++)
cout << ar[index] << " ";
cout << endl;
return 0;
}
Prepared by Dawit T.
A string is a sequence of characters used to represent text. C++ provides two main ways to work with strings:
C-style string
• These are arrays of characters
ending with a null character ('
0’).
• Declared using char arrays, like
char str[] = "Hello";.
• They have limited functionality
and require manual memory
management when dynamically
allocated.
C++ Standard library std::string
• Defined in the <string> library,
std::string is a more powerful
and flexible string type.
• It automatically manages
memory and provides many
built-in functions for easy string
manipulation,
like .length(), .substr(), .find(),
and .append().
String
Prepared by Dawit T.
Initializing a string
To initialize a string during declaration:
char my_message[20] = "Hi there.";
- The null character '0' is added
Another alternative:
char short_string[ ] = "abc";
but not this:
char short_string[ ] = {'a', 'b', 'c'};
This attempt to initialize a string does not cause the 0 to be inserted in
the array
• char short_string[]= {'a', 'b', 'c’,’0’};
Prepared by Dawit T.
Using Double Quotes (String Literal)
• This is the simplest and most common way to
initialize a string. The null terminator (0) is
automatically added at the end of the string.
char myString[] = "Hello, World!";
• Here, the array myString is automatically
sized to accommodate all characters of the
string, plus the null terminator. In this case,
the size would be 14 (including 0).
Initializing Character by Character
You can manually specify each character of the
string and explicitly include the null
terminator:
char myString[] = {'H', 'e', 'l', 'l', 'o', '0’};
This method requires you to remember to
include '0' at the end;
Specifying the Size of the Array
You can also specify the size of the
character array manually. The size must
be enough to hold the string, including
the null terminator.
char myString[14] = "Hello, World!";
• If the array size is larger than
needed, the remaining elements will
be set to zero:
char myString[20] = "Hello!";
In this case, the remaining elements
from index 6 to 19 will be initialized to
0.
Prepared by Dawit T.
Initializing string
• In C++, you can initialize strings in several ways using the std::string
class from the Standard Library.
• Here are some common methods with examples:
• Default Initialization
• A string is initialized as an empty string.
string str; // Default empty string
• Initialization with a C-style string (const char)
• A string can be initialized with a constant character array (C-string).
string str = "Hello, World!";
Prepared by Dawit T.
Initializing string
Using a String Literal:
std::string str = "Hello";
Using a Character
Array:
char arr[] = {'H', 'e', 'l',
'l', 'o', '0’};
std::string str(arr);
Using std::string Constructor
with std::initializer_list<char>
std::string str({'H', 'e', 'l', 'l', 'o'});
Using Direct Initialization
with Parentheses:
std::string str("Hello");
Prepared by Dawit T.
Initializing string
Using the std::string Constructor
with Size and Character
• You can create a std::string of a
specific size and initialize it with
a repeated character:
std::string str(10, ‘A');
Using the std::string Constructor
with Only Size
• You can also create an empty
string of a specified size:
std::string str(10, '0');
Using std::string::resize
• If you have an existing
std::string, you can use the resize
method to adjust its size:
std::string str;
str.resize(10);
Prepared by Dawit T.
Commonly Used String Functions in C++
Length and Size
length() and size(): Return the number
of characters in the string
std::string str = "Hello, World!";
str.length()
str.size()
Appending
append(): Adds another string or character(s)
to the end of the string.
operator +=: Concatenates a string or
character(s) to the current string.
std::string str = "Hello";
str.append (", World!"); // Appends a string
str += " Welcome!"; // Concatenation using
+=
Substring
substr(): Returns a substring starting at a specific
index with an optional length.
std::string str = "Hello, World!";
std::string sub = str.substr(7, 5); // Get substring
"World"
Finding
find(): Finds the first occurrence of a substring or
character. Returns std::string::npos if not found.
std::string str = "Hello, World!";
size_t pos = str.find("World");
if (pos != std::string::npos)
std::cout << "'World' found at position: " <<
pos << std::endl; else
std::cout << "'World' not found!" << std::endl;
Prepared by Dawit T.
Commonly Used String Functions in C++ Cont..
Inserting
insert(): Inserts a string or character(s) at a specified
position.
std::string str = "Hello World!";
str.insert(5, ","); // Insert a comma at position 5
Erasing
erase(): Removes characters from a string from a
specified position for a specified length.
std::string str = "Hello, World!";
str.erase(5, 7); // Erase ", World"
Replacing
replace(): Replaces a portion of the string with
another string.
std::string str = "Hello, World!";
str.replace(7, 5, "Universe"); // Replace
"World" with "Universe"
Comparison
compare(): Compares two strings lexicographically.
std::string str1 = "Hello";
std::string str2 = "World";
if (str1.compare(str2) == 0)
std::cout << "Strings are equal." << std::endl;
else
std::cout << "Strings are not equal." << std::endl;
Clearing
clear(): Removes all characters from the string,
making it empty.
std::string str = "Hello, World!";
str.clear(); // Clear the string
Prepared by Dawit T.
Commonly Used String Functions in C++ Cont..
Checking if Empty
empty(): Checks if the string is empty.
std::string str;
if (str.empty())
std::cout << "String is empty." << std::endl;
Accessing Characters
operator[] and at(): Access individual
characters in the string.
std::string str = "Hello“;
str[0];
str.at(1)
C-String Conversion
c_str(): Returns a pointer to a null-terminated
C-style string.
std::string str = "Hello, World!";
const char* cstr = str.c_str(); // Convert to C-
string
Capacity
capacity(): Returns the current capacity of the
string (the size of allocated memory).
reserve(): Requests a change in capacity.
std::string str = "Hello";
str.capacity()
str.reserve(50);
str.capacity()
Use strcmp() to compare C-style
const char* string1 = "Hello";
const char* string2 = "World";
const char* string3 = "Hello";
int result1 = strcmp(string1, string2);
Prepared by Dawit T.
Types Array
Prepared by Dawit T.
Types of Array
• In C++, arrays can be categorized based on their dimensions as:
One-Dimensional Array (1D Array)
Two-Dimensional Array (2D Array)
Multi-Dimensional Array (3D and higher)
• One-Dimensional Array (1D Array)
• A one-dimensional array is a list of elements stored in a single row. It
represents a simple sequence of elements of the same type.
• Syntax
data_type array_name[size];
Prepared by Dawit T.
Types of Array [Cont]
• Two-Dimensional Array (2D Array)
• A two-dimensional array is like a table or matrix where data is stored in rows and
columns. It’s essentially an array of arrays.
• Syntax
data_type array_name[rows][columns];
• Multi-Dimensional Array (3D and higher)
• A multi-dimensional array can have three or more dimensions. A common example
is a 3D array, which represents data in the form of a cube or a collection of matrices.
• Syntax
data_type array_name[x][y][z];
Prepared by Dawit T.
Two-dimensional array
- Tables with rows and columns (m by n array)
- A 2D array is typically represented as a matrix
Example:
int a[3][3]; // 2D array (matrix) with 3 rows and 3 columns
Row 0
Row 1
Row 2
Column 0 Column 1 Column 2 Column 3
a[ 0 ][ 0 ]
a[ 1 ][ 0 ]
a[ 2 ][ 0 ]
a[ 0 ][ 1 ]
a[ 1 ][ 1 ]
a[ 2 ][ 1 ]
a[ 0 ][ 2 ]
a[ 1 ][ 2 ]
a[ 2 ][ 2 ]
a[ 0 ][ 3 ]
a[ 1 ][ 3 ]
a[ 2 ][ 3 ]
Row subscript
(index)
Array name
Column subscript
(index)
Prepared by Dawit T.
Initialization
- int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
- Initializers grouped by row in braces
- If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
- Specify row, then column
cout << b[ 0 ][ 1 ];
1 2
3 4
1 0
3 4
Prepared by Dawit T.
Accessing components in a two-dimensional array:
- Where indexExp1 and indexExp2 are expressions with
positive integer values, and specify the row and column
position
Example:
sales[5][3] = 25.75;
Prepared by Dawit T.
Accessing array components (cont’d.)
Prepared by Dawit T.
Examples of array
Examples:
int A; // single variable
int B[6]; // 1D array
int C[3][4]; // 2D array (matrix)
int D[3][4][5]; // 3D array
int E[3][4][5][3]; // 4D array
//etc
Prepared by Dawit T.
1D – single row or column
2D – matrix
3D – cube of cells
4D – row or column of cubes
Example:
int A, B1[6], B2[6], C[3][4], D[3][4][5], E[3][4][5][3]; E
A B1
C D
B2
Visualizing multi-dimensional arrays
Prepared by Dawit T.
Reading and Writing String
String Input:
- cin>>name; stores the next input string in name
- String that contain blanks cannot be read using the extraction
operator >>
- Whitespace ends reading of data
- Example:
char a[80], b[80];
cout << "Enter input: " << endl;
cin >> a >> b;
cout << a << b << "End of Output";
Prepared by Dawit T.
Reading and Writing String
could produce:
Enter input:
- Hey welcome student!
- HeywelcomeEnd of Output
To read strings with blanks, use the predefined member getline
function, syntax cin.getline(str,m+1); 2 arguments
• The first variable str receives input
• 2nd
is an integer m , usually the size of the first argument
specifying the maximum # of elements
Prepared by Dawit T.
Reading and Writing String
The following code is used to read an entire line including spaces into
a single variable
char a[80];
cout<<"Enter input:n";
cin.getline(a, 80);
cout << a << “End Of Outputn";
and could produce:
Enter some input:
Do be do to you!
Do be do to you!End of Output
Prepared by Dawit T.
Reading and Writing String (continued)
String Output:
- cout<<name; outputs the content of name on the screen
- The insertion operate << continues to write the contents of name
until it finds the null character
• If name does not contain the null character, then we will see
strange output:
• << continues to output data from memory adjacent to name
until ‘0’ is found
Prepared by Dawit T.
Summary
• An array is a variable that can store multiple values of the same type.
• The array indices start with 0. Meaning x[0] is the first element stored
at index 0.
• If the size of an array is n, the last element is stored at index (n-1).
When passing an array as an actual parameter, use only its
name
- Passed by reference only
A function cannot return an array type value
Strings are null terminated and are stored in character arrays
Prepared by Dawit T.
Thank You !!!
Any Questions
??

More Related Content

Similar to Chapter 1 Introduction to Arrays and Strings (20)

CHAPTER-5.ppt
CHAPTER-5.pptCHAPTER-5.ppt
CHAPTER-5.ppt
Tekle12
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
lecture5.ppt
lecture5.pptlecture5.ppt
lecture5.ppt
KarthiKeyan462713
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
donnajames55
 
lecture 5 string in c++ explaination and example.ppt
lecture 5 string in c++ explaination and example.pptlecture 5 string in c++ explaination and example.ppt
lecture 5 string in c++ explaination and example.ppt
MUhammadMiladAwan
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Venkateswarlu Vuggam
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
SajalFayyaz
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Structured Data Type Arrays
Structured Data Type ArraysStructured Data Type Arrays
Structured Data Type Arrays
Praveen M Jigajinni
 
Programming in c plus plus4
Programming in c plus plus4Programming in c plus plus4
Programming in c plus plus4
AA Coaching Academy
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
KirubelWondwoson1
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
Data Structures asdasdasdasdasdasdasdasdasdasd
Data Structures asdasdasdasdasdasdasdasdasdasdData Structures asdasdasdasdasdasdasdasdasdasd
Data Structures asdasdasdasdasdasdasdasdasdasd
abdulrahman39ab
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
Vikash Dhal
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
Mohammed Khan
 
Arrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptxArrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptx
samreenghauri786
 
Chapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdfChapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdf
mylinhbangus
 
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
 
CHAPTER-5.ppt
CHAPTER-5.pptCHAPTER-5.ppt
CHAPTER-5.ppt
Tekle12
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
donnajames55
 
lecture 5 string in c++ explaination and example.ppt
lecture 5 string in c++ explaination and example.pptlecture 5 string in c++ explaination and example.ppt
lecture 5 string in c++ explaination and example.ppt
MUhammadMiladAwan
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
SajalFayyaz
 
Array,string structures. Best presentation pptx
Array,string structures. Best presentation pptxArray,string structures. Best presentation pptx
Array,string structures. Best presentation pptx
Kalkaye
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
KirubelWondwoson1
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
Data Structures asdasdasdasdasdasdasdasdasdasd
Data Structures asdasdasdasdasdasdasdasdasdasdData Structures asdasdasdasdasdasdasdasdasdasd
Data Structures asdasdasdasdasdasdasdasdasdasd
abdulrahman39ab
 
Strinng Classes in c++
Strinng Classes in c++Strinng Classes in c++
Strinng Classes in c++
Vikash Dhal
 
Arrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptxArrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptx
samreenghauri786
 
Chapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdfChapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdf
mylinhbangus
 
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
 

Recently uploaded (20)

Introduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdfIntroduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdf
CME4Life
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based EducatorDiana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910
PankajRodey1
 
Critical Thinking and Bias with Jibi Moses
Critical Thinking and Bias with Jibi MosesCritical Thinking and Bias with Jibi Moses
Critical Thinking and Bias with Jibi Moses
Excellence Foundation for South Sudan
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
Swachata Quiz - Prelims - 01.10.24 - Quiz Club IIT Patna
Swachata Quiz - Prelims - 01.10.24 - Quiz Club IIT PatnaSwachata Quiz - Prelims - 01.10.24 - Quiz Club IIT Patna
Swachata Quiz - Prelims - 01.10.24 - Quiz Club IIT Patna
Quiz Club, Indian Institute of Technology, Patna
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
wygalkelceqg
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSELET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
OlgaLeonorTorresSnch
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
0b - THE ROMANTIC ERA: FEELINGS AND IDENTITY.pptx
0b - THE ROMANTIC ERA: FEELINGS AND IDENTITY.pptx0b - THE ROMANTIC ERA: FEELINGS AND IDENTITY.pptx
0b - THE ROMANTIC ERA: FEELINGS AND IDENTITY.pptx
Julián Jesús Pérez Fernández
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Introduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdfIntroduction to Online CME for Nurse Practitioners.pdf
Introduction to Online CME for Nurse Practitioners.pdf
CME4Life
 
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based EducatorDiana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda - A Wauconda-Based Educator
Diana Enriquez Wauconda
 
Multicultural approach in education - B.Ed
Multicultural approach in education - B.EdMulticultural approach in education - B.Ed
Multicultural approach in education - B.Ed
prathimagowda443
 
K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910K-Circle-Weekly-Quiz-May2025_12345678910
K-Circle-Weekly-Quiz-May2025_12345678910
PankajRodey1
 
Exploring Identity Through Colombian Companies
Exploring Identity Through Colombian CompaniesExploring Identity Through Colombian Companies
Exploring Identity Through Colombian Companies
OlgaLeonorTorresSnch
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesHow to Manage Orders in Odoo 18 Lunch - Odoo Slides
How to Manage Orders in Odoo 18 Lunch - Odoo Slides
Celine George
 
A Brief Introduction About Jack Lutkus
A Brief Introduction About  Jack  LutkusA Brief Introduction About  Jack  Lutkus
A Brief Introduction About Jack Lutkus
Jack Lutkus
 
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
Active Surveillance For Localized Prostate Cancer A New Paradigm For Clinical...
wygalkelceqg
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSELET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
LET´S PRACTICE GRAMMAR USING SIMPLE PAST TENSE
OlgaLeonorTorresSnch
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
Order Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptxOrder Lepidoptera: Butterflies and Moths.pptx
Order Lepidoptera: Butterflies and Moths.pptx
Arshad Shaikh
 
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptxQUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
QUIZ-O-FORCE FINAL SET BY SUDIPTA & SUBHAM.pptx
Sourav Kr Podder
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Ad

Chapter 1 Introduction to Arrays and Strings

  • 1. Prepared by Dawit T. ITec 2042 Fundamentals of Programming II Chapter one Arrays and Strings
  • 2. Prepared by Dawit T. Arrays Array - Structures of related data items - Static entity – same size throughout program - Group of consecutive memory locations - Same name and type Referring to an element, specify - Array name - Position number Format type arrayName [integer value];
  • 3. Prepared by Dawit T. Name of array (Note that all elements of this array have the same name, c) Position number of the element within array c c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 c[0] c[1] c[2] c[3] c[11 ] c[10 ] c[9] c[8] c[7] c[5] c[4] int c[11]={-45,6,0,72,1543,-89,0,62,-3,1,6453,78} array c - First element at position 0 - n element array named c: o c[0], c[1],…c[n-1] - Array elements are like normal variables c [8] = -3
  • 4. Prepared by Dawit T. DeclaringArrays When declaring arrays, specify - Types of array - Name of array - Number of elements arrayType arrayName[ numberOfElements ]; - Examples: - int c[ 10 ]; - float myArray[ 3284 ]; Declaring multiple arrays of same type - Format similar to regular variables - Example: int b[ 100 ], x[ 27 ]
  • 5. Prepared by Dawit T. Array index out of Bounds Index of an array is in bounds if the index is >=0 and <= ARRAY_SIZE-1 - Otherwise, the index is out of bounds In C++, there is no guard against indices that are out of bounds If the index is out of bounds Sometimes it may crash Sometimes it may display garbage values It may even appear to work without any error
  • 6. Prepared by Dawit T. InitializingArrays Elements in array may be initialized in two ways: - Explicitly (using an assignment statement for each element) - Using a list a list is denoted using braces, with element in the list separated by a comma. Initializing arrays explicitly Easily accomplished using a for loop. - Example: Explicitly initialize all elements in an array to 5.0 const int Asize = 100; int A[Asize]; for (int i = 0; i < Asize; i++) A[i] = 5.0;
  • 7. Prepared by Dawit T. Initializing arrays using a list Elements in array may be initialized using a list of values in braces. - If not enough initializers, rightmost elements become 0. int n[ 5 ] = { 0 } // All elements 0 - If array size omitted, array size is set to the number of elements in the list. Example: double X[4] = {1.1, 2.2, 3.3, 4.4}; // initialize array X with a list Using the list above is equivalent to: double X[4]; X[0] = 1.1; X[1] = 2.2; initializing array X with explicitly X[2] = 3.3; X[3] = 4.4;
  • 8. Prepared by Dawit T. 1. Initializing a Fixed-Size Integer Array You can initialize an integer array at the time of declaration by explicitly listing its elements: int arr[5] = {10, 20, 30, 40, 50}; 2. Partially Initializing Arrays If you don’t provide enough initial values, the remaining elements will be automatically initialized to 0 (for numeric arrays). int arr[5] = {10, 20}; 3. Fully Initializing Arrays with Fewer Elements Than Size If you don’t specify the size of the array but provide the elements, C++ will automatically determine the size of the array based on the number of elements you provide. int arr[] = {5, 10, 15, 20}; 4. Initializing Multidimensional Arrays For multidimensional arrays, each row (or higher dimension) can also be initialized explicitly. int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
  • 9. Prepared by Dawit T. Example: Initializing arrays using a list int A[5] = {11,22}; // initializes array values to 11,22,0,0,0 double Sum[7] = {0.0};// initializes all 7 sums to 0.0 int B[ ] = {2,4,6,8}; // array B is assigned an array size of 4 char Vowels[8] = “aeiou”;// Vowels[0] = ‘a’, Vowels[1] = ‘e’, etc Array B 2 4 6 8
  • 10. Prepared by Dawit T. Some Restrictions on Array Processing Aggregate operation: any operation that manipulates the entire array as a single unit - Not allowed on arrays in C++ Example: Solution
  • 11. Prepared by Dawit T. Printing Arrays Arrays are easily printed using for loops. Example 1: int Grades[12] = {78,80,82,84,86, 88,90,92,94,96,98,100}; for (int j = 0; j < 12; j++) cout << Grades[ j ] << endl; Example 2: for (int Row = 0; Row <= 2; Row+ +) { for (int Col = 0; Col <=3; Col++) cout << Grades[ 4*Row+Col ]; cout << endl; }
  • 12. Prepared by Dawit T. Printing example 1 //For loop to fill & print a 10-int array #include <iostream> using namespace std; int main ( ) { int index, ar[10]; // array for 10 integers // Read in 10 elements. cout << "Enter 10 integers: "; for(index = 0; index < 10; index ++) cin >> ar[index]; cout << endl; cout << "The integers are "; for(index = 0; index < 10; index ++) cout << ar[index] << " "; cout << endl; return 0; }
  • 13. Prepared by Dawit T. A string is a sequence of characters used to represent text. C++ provides two main ways to work with strings: C-style string • These are arrays of characters ending with a null character (' 0’). • Declared using char arrays, like char str[] = "Hello";. • They have limited functionality and require manual memory management when dynamically allocated. C++ Standard library std::string • Defined in the <string> library, std::string is a more powerful and flexible string type. • It automatically manages memory and provides many built-in functions for easy string manipulation, like .length(), .substr(), .find(), and .append(). String
  • 14. Prepared by Dawit T. Initializing a string To initialize a string during declaration: char my_message[20] = "Hi there."; - The null character '0' is added Another alternative: char short_string[ ] = "abc"; but not this: char short_string[ ] = {'a', 'b', 'c'}; This attempt to initialize a string does not cause the 0 to be inserted in the array • char short_string[]= {'a', 'b', 'c’,’0’};
  • 15. Prepared by Dawit T. Using Double Quotes (String Literal) • This is the simplest and most common way to initialize a string. The null terminator (0) is automatically added at the end of the string. char myString[] = "Hello, World!"; • Here, the array myString is automatically sized to accommodate all characters of the string, plus the null terminator. In this case, the size would be 14 (including 0). Initializing Character by Character You can manually specify each character of the string and explicitly include the null terminator: char myString[] = {'H', 'e', 'l', 'l', 'o', '0’}; This method requires you to remember to include '0' at the end; Specifying the Size of the Array You can also specify the size of the character array manually. The size must be enough to hold the string, including the null terminator. char myString[14] = "Hello, World!"; • If the array size is larger than needed, the remaining elements will be set to zero: char myString[20] = "Hello!"; In this case, the remaining elements from index 6 to 19 will be initialized to 0.
  • 16. Prepared by Dawit T. Initializing string • In C++, you can initialize strings in several ways using the std::string class from the Standard Library. • Here are some common methods with examples: • Default Initialization • A string is initialized as an empty string. string str; // Default empty string • Initialization with a C-style string (const char) • A string can be initialized with a constant character array (C-string). string str = "Hello, World!";
  • 17. Prepared by Dawit T. Initializing string Using a String Literal: std::string str = "Hello"; Using a Character Array: char arr[] = {'H', 'e', 'l', 'l', 'o', '0’}; std::string str(arr); Using std::string Constructor with std::initializer_list<char> std::string str({'H', 'e', 'l', 'l', 'o'}); Using Direct Initialization with Parentheses: std::string str("Hello");
  • 18. Prepared by Dawit T. Initializing string Using the std::string Constructor with Size and Character • You can create a std::string of a specific size and initialize it with a repeated character: std::string str(10, ‘A'); Using the std::string Constructor with Only Size • You can also create an empty string of a specified size: std::string str(10, '0'); Using std::string::resize • If you have an existing std::string, you can use the resize method to adjust its size: std::string str; str.resize(10);
  • 19. Prepared by Dawit T. Commonly Used String Functions in C++ Length and Size length() and size(): Return the number of characters in the string std::string str = "Hello, World!"; str.length() str.size() Appending append(): Adds another string or character(s) to the end of the string. operator +=: Concatenates a string or character(s) to the current string. std::string str = "Hello"; str.append (", World!"); // Appends a string str += " Welcome!"; // Concatenation using += Substring substr(): Returns a substring starting at a specific index with an optional length. std::string str = "Hello, World!"; std::string sub = str.substr(7, 5); // Get substring "World" Finding find(): Finds the first occurrence of a substring or character. Returns std::string::npos if not found. std::string str = "Hello, World!"; size_t pos = str.find("World"); if (pos != std::string::npos) std::cout << "'World' found at position: " << pos << std::endl; else std::cout << "'World' not found!" << std::endl;
  • 20. Prepared by Dawit T. Commonly Used String Functions in C++ Cont.. Inserting insert(): Inserts a string or character(s) at a specified position. std::string str = "Hello World!"; str.insert(5, ","); // Insert a comma at position 5 Erasing erase(): Removes characters from a string from a specified position for a specified length. std::string str = "Hello, World!"; str.erase(5, 7); // Erase ", World" Replacing replace(): Replaces a portion of the string with another string. std::string str = "Hello, World!"; str.replace(7, 5, "Universe"); // Replace "World" with "Universe" Comparison compare(): Compares two strings lexicographically. std::string str1 = "Hello"; std::string str2 = "World"; if (str1.compare(str2) == 0) std::cout << "Strings are equal." << std::endl; else std::cout << "Strings are not equal." << std::endl; Clearing clear(): Removes all characters from the string, making it empty. std::string str = "Hello, World!"; str.clear(); // Clear the string
  • 21. Prepared by Dawit T. Commonly Used String Functions in C++ Cont.. Checking if Empty empty(): Checks if the string is empty. std::string str; if (str.empty()) std::cout << "String is empty." << std::endl; Accessing Characters operator[] and at(): Access individual characters in the string. std::string str = "Hello“; str[0]; str.at(1) C-String Conversion c_str(): Returns a pointer to a null-terminated C-style string. std::string str = "Hello, World!"; const char* cstr = str.c_str(); // Convert to C- string Capacity capacity(): Returns the current capacity of the string (the size of allocated memory). reserve(): Requests a change in capacity. std::string str = "Hello"; str.capacity() str.reserve(50); str.capacity() Use strcmp() to compare C-style const char* string1 = "Hello"; const char* string2 = "World"; const char* string3 = "Hello"; int result1 = strcmp(string1, string2);
  • 22. Prepared by Dawit T. Types Array
  • 23. Prepared by Dawit T. Types of Array • In C++, arrays can be categorized based on their dimensions as: One-Dimensional Array (1D Array) Two-Dimensional Array (2D Array) Multi-Dimensional Array (3D and higher) • One-Dimensional Array (1D Array) • A one-dimensional array is a list of elements stored in a single row. It represents a simple sequence of elements of the same type. • Syntax data_type array_name[size];
  • 24. Prepared by Dawit T. Types of Array [Cont] • Two-Dimensional Array (2D Array) • A two-dimensional array is like a table or matrix where data is stored in rows and columns. It’s essentially an array of arrays. • Syntax data_type array_name[rows][columns]; • Multi-Dimensional Array (3D and higher) • A multi-dimensional array can have three or more dimensions. A common example is a 3D array, which represents data in the form of a cube or a collection of matrices. • Syntax data_type array_name[x][y][z];
  • 25. Prepared by Dawit T. Two-dimensional array - Tables with rows and columns (m by n array) - A 2D array is typically represented as a matrix Example: int a[3][3]; // 2D array (matrix) with 3 rows and 3 columns Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript (index) Array name Column subscript (index)
  • 26. Prepared by Dawit T. Initialization - int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; - Initializers grouped by row in braces - If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements - Specify row, then column cout << b[ 0 ][ 1 ]; 1 2 3 4 1 0 3 4
  • 27. Prepared by Dawit T. Accessing components in a two-dimensional array: - Where indexExp1 and indexExp2 are expressions with positive integer values, and specify the row and column position Example: sales[5][3] = 25.75;
  • 28. Prepared by Dawit T. Accessing array components (cont’d.)
  • 29. Prepared by Dawit T. Examples of array Examples: int A; // single variable int B[6]; // 1D array int C[3][4]; // 2D array (matrix) int D[3][4][5]; // 3D array int E[3][4][5][3]; // 4D array //etc
  • 30. Prepared by Dawit T. 1D – single row or column 2D – matrix 3D – cube of cells 4D – row or column of cubes Example: int A, B1[6], B2[6], C[3][4], D[3][4][5], E[3][4][5][3]; E A B1 C D B2 Visualizing multi-dimensional arrays
  • 31. Prepared by Dawit T. Reading and Writing String String Input: - cin>>name; stores the next input string in name - String that contain blanks cannot be read using the extraction operator >> - Whitespace ends reading of data - Example: char a[80], b[80]; cout << "Enter input: " << endl; cin >> a >> b; cout << a << b << "End of Output";
  • 32. Prepared by Dawit T. Reading and Writing String could produce: Enter input: - Hey welcome student! - HeywelcomeEnd of Output To read strings with blanks, use the predefined member getline function, syntax cin.getline(str,m+1); 2 arguments • The first variable str receives input • 2nd is an integer m , usually the size of the first argument specifying the maximum # of elements
  • 33. Prepared by Dawit T. Reading and Writing String The following code is used to read an entire line including spaces into a single variable char a[80]; cout<<"Enter input:n"; cin.getline(a, 80); cout << a << “End Of Outputn"; and could produce: Enter some input: Do be do to you! Do be do to you!End of Output
  • 34. Prepared by Dawit T. Reading and Writing String (continued) String Output: - cout<<name; outputs the content of name on the screen - The insertion operate << continues to write the contents of name until it finds the null character • If name does not contain the null character, then we will see strange output: • << continues to output data from memory adjacent to name until ‘0’ is found
  • 35. Prepared by Dawit T. Summary • An array is a variable that can store multiple values of the same type. • The array indices start with 0. Meaning x[0] is the first element stored at index 0. • If the size of an array is n, the last element is stored at index (n-1). When passing an array as an actual parameter, use only its name - Passed by reference only A function cannot return an array type value Strings are null terminated and are stored in character arrays
  • 36. Prepared by Dawit T. Thank You !!! Any Questions ??