0% found this document useful (0 votes)
2 views36 pages

Understanding Arrays and Strings in C++

Uploaded by

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

Understanding Arrays and Strings in C++

Uploaded by

sinmonatolasa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter One

Array, String and Structure


Array
An array is a series of elements of the same type placed in
contiguous memory locations

It allows you to store and access multiple values using a single
variable name with an index

Each element of an array is accessed by its index

Index of the first array element is always zero


Array can be:
 One Dimensional Array
 Multidimensional arrays
One Dimensional Array

 This type of array stores elements in a single dimension

 It is the simplest form of an array and is used to manage a


list of data items, such as numbers, strings, or characters.

0 1 2 3 4

All the elements arranged in row wise in a single


dimension, one after other
Declaring Arrays
 Declaring an array involves specifying its type, name, and
size

Syntax: data_type array_name[size];

data_type: The type of elements the array will hold


(e.g., int, float, char).

array_name: The name of the array

size: The number of elements in the array

This must be a positive integer or a constant expression


Cont.
 For example ,
int age [3];
 This tells the compiler to associate 3 memory cells with
name age
 These cells will be adjacent to each other in memory
 Each element of array age contains a value of integer
type
 More than one array can be declared on a line
int age [10] , height [10] , names [20] ;
 Mix declaration of variables with declaration of arrays
int i , j , age [10] ;
Initialization of Array

Array initialization refers to assigning initial values to the

elements of an array when it is declared

Syntax: data_type array_name[size]={value1, value2,……..valueN};

The number of values between braces { } cannot be larger

than the number of elements that we declare for the array

between square brackets [ ]


Cont.
If fewer values are provided than the size of the array, the
remaining elements are initialized to 0.

int numbers[5] = {1, 2}; // Initialized to {1, 2, 0, 0, 0}

If too many initializers, a syntax error is generated

If size omitted, the initializers determine it

int numbers[] = { 1, 2, 3, 4, 5 }; // Size is automatically set to 5


Cont.

You can initialize C++ array elements either one by one


or using a single statement as follows:

double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

Following is an example to assign a single element of


the array:
balance[0]=1000.0
balance[1]=2.0
balance[2]=3.4
Accessing Arrays
An element of the array is accessed by indexing the array name

placing the index of the element within square brackets after


the name of the array

An index describes the position of an element within an array

 It must be an integer or integer expression

The index of the first element in an array is 0, the second is 1,


and so on.
The index of the last element is size – 1
Syntax:
array_name[index];
Cont.

double marks [5] = {85.5, 76.5 , 69, 72.5, 87.5 };

Index

marks[0] 85.5

marks[1] 76.5

marks[2] 69 Elements

marks[3] 72.5

marks[4] 87.5

10
Cont…
#include <iostream>

using namespace std;

int main() {

double marks [5] = {85.5, 76.5 , 69, 72.5, 87.5 };

cout << marks[0]; // Outputs: 85.5

cout << marks[2]; // Outputs: 69

return 0;

}
11
Iterating through an Array
Loops can be used to iterate through an array to access or process all
elements
Using a For Loop
#include <iostream>
using namespace std;
int main() {

double marks [5] = {85.5, 76.5 , 69, 72.5, 87.5 };


for (int i = 0; i < 5; i++)
{
cout << marks[i] << " ";
}
return 0;
} 12
Multidimensional arrays
Multidimensional array can have any number of
dimensions
Data_type array_name [size 1][size2]….[size n];

 Here size 1, size 2 up to size n describe the number of


dimensions
int array[3][3]; // two dimensional array
int array [5][2][3]; // three dimensional array

A two dimensional array also falls under the category of


a multidimensional array
Two-Dimensional Arrays
A two-dimensional (2D) array is a collection of elements
arranged in rows and columns
N number of rows and columns

Each element is accessed using two indices: one for the row and
one for the column

Representation of a 3X3 matrix, which means there are three


rows and three columns in the array

(0,0) (0,1) (0,2)

(1,0) (1,1) (1,2)

(2,0) (2,1) (2,2)


Cont.

It is often used to represent tabular data, such as matrices or


grids

The syntax for declaring a 2D array is:

data_type array_name[rows][columns];

Example

int matrix[3][3]; // A 2D array with 3 rows and 3 columns

15
Initializing a 2D Array
A 2D array can be initialized during declaration
int matrix[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
Or int matrix[2][3] = {1, 2, 3, 4, 5, 6};

Uninitialized elements are set to 0


int matrix[2][3] = {
{1, 2}, // Only first two elements of Row 0 are initialized
{4} // Only the first element of Row 1 is initialized
}; 16
Accessing Elements in a 2D Array
Elements in a 2D array are accessed using their row and column
indices:
array_name[row_index][column_index];

#include <iostream>
using namespace std;
int main() {
int numbers[2][3] = {
{1, 2, 3},
{4, 5, 6}};
cout << numbers[0][1] << endl; // Outputs: 2
cout << numbers[1][2] << endl; // Outputs: 6
return 0;
} 17
Iterating Through a 2D Array
#include <iostream>
using namespace std;
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) { // Loop through rows
for (int j = 0; j < 3; j++) { // Loop through columns
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
} 18
Cont.
#include <iostream>
using namespace std;
int main() {
int students = 3;
int subjects = 4;
int marks[students][subjects] = { Output
{85, 90, 78, 88}, // Marks of Student 1
{76, 81, 72, 85}, // Marks of Student 2
{90, 92, 89, 95} // Marks of Student 3
};
for (int i = 0; i < students; i++) {
cout << "Student " << i + 1 << ": ";
for (int j = 0; j < subjects; j++) {
cout << marks[i][j] << " ";
}
cout<<"\n";
}
} 19
String
A string is a sequence of characters used to represent textual
data, such as words, sentences, or other text
C++ supports two primary types of strings:
C-style strings
Array with base type char
 End of string marked with null, ‘\0’
 Older method inherited from C
C++ strings
 Objects of string class

20
C-style strings
A C-style string is a sequence of characters stored in a

character array and terminated by a null character ('\0')

This null terminator signifies the end of the string

C-style strings are inherited from the C language and are

used for compatibility with C-based APIs and libraries

Requires manual memory management

21
Declaration and Initialization
C-style strings are declared as character arrays
char string_name[size];
char str1[6] = “Mizan"; // Size includes '\0‘
char str1[6] = {‘M', ‘i', ‘z', ‘a', ‘n', '\0'};
char str2[] = “Tepi"; // Compiler determines the size (5 including '\0')

Individual characters can be accessed or modified using their index


cout << str1[2]; // Outputs: z
str1[0] = ‘S'; // Modifies the first character
cout <<str1; //Mizan
22
Cont.
Common String Functions (from <cstring> liberary)
strlen() : Returns the length of a string (excluding the null terminator)
strlen(str)
strcat() : Concatenates two strings
strcat(str1, str2): Concatenates string str2 onto the end of string str1
strcmp() : Compares two strings lexicographically
 Returns 0 if they are equal, a positive value if the first string
is greater, and a negative value if it is smaller
strcmp(str1, str2)
strcpy() : Copies one string to another
strcpy(str1, str2): Copies string str2 into string str1
23
Cont.
#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str1[10] = "Mizan";
char str2[10] = "Tepi";
char str3[10];

cout <<"Length: " << strlen(str1) << endl;


strcpy(str3, str1);
cout <<"Copy: " << str3 << endl;
strcat(str1, str2);
cout <<"Concatenation : " << str1 << endl;
cout<<"Compare: "<<strcmp(str1, str2)<<endl;
return 0;
}
24
Input functions for C-Style Strings
cin: Stops reading at the first whitespace character
Considers a space (whitespace, tabs, etc.) as a terminating
character
Only store a single word (even if you type many words)
char str[20];
cin >> str; // Input: Mizan Tepi
cout << str << endl; // Mizan
getline() : Reads an entire line (recommended for strings with
spaces)
It takes cin as the first parameter, and the string variable as
second:
[Link](str, 20); 25
C++ String
Provided by <string>, is a modern alternative to C-style
strings

It is safer, more flexible, and easier to use

string str = “Mystring”;

string str1 = “Mizan Tepi”;

Characteristics:

• Mutable: Strings can be modified

• Automatically manages memory

• Provides rich functionality via member functions 26


String Manipulation
[Link]() or [Link]() : Returns length of string variable

[Link]()

compare() : Compares two strings

str1 > str2 or [Link](str2)

substr() : Extracts a substring

[Link](start, length)

insert() : inserts a string at a specific position

[Link](position, str2) 27
Cont.
replace() : Replaces a portion of the string with another
string

[Link](start, length, new_string)

append() : Appends another string or character to the end

[Link](str2)
find() : Returns the position of the first occurrence of a
substring

[Link](substring)
28
Cont…
 To read entire lines use getline(cin, string):
string str;
cout << "Enter lines of string: ";
getline(cin, str);
 Be careful mixing cin and getline
int number;
string str;
cin >> number;
getline(cin, str);
 cin >> n skips whitespace and leaves ‘\n’ for getline()
• If there is a leftover \n from a previous cin >> n, getline() reads it
immediately, giving you an empty string 29
Cont.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1= "Mizan";
string str2 = "Tepi";
string str3;
cout <<"Length: " <<[Link]() << endl;
str3=str1;
cout <<"Copy: " << str3 << endl;
cout <<"Concatenation: " << str1 + str2 << endl;
cout <<"Append: " << [Link](str2)<< endl;
cout<<"Compare: "<<[Link](str2)<<endl;
cout<<"Substring: "<<[Link](5,4)<<endl;
cout<<"Replace: "<<[Link](5,4,"Aman")<<endl;
cout<<"Insert: "<<[Link](5," ")<<endl;
cout<<"Find: "<<[Link]("man")<<endl; 30

}
Structure
A structure is a user-defined data type that allows grouping multiple
variables of different types under a single name
Defining a Structure
A structure is defined using the keyword struct, followed by the
structure name and its members enclosed in curly braces {}
Syntax:
struct StructureName {
data_type member1;
data_type member2;
// Additional members...
}; 31
Declaring and Initializing Structure Variables
Student structure:

struct Student {
string name;
string dept;
float gpa;
};
Once a structure is defined, you can declare variables of that
structure type and initialize them
Declaration:
Student student1, student2; // Declares two variables of type Student
Initialization:
Student student1 = {“Tesfa", “SE”, 3.58}; // Initializes all members
32
Accessing Members
dot operator (.) is used to access or modify structure members
#include <iostream>
using namespace std;
struct Student {
string name;
string dept;
float gpa;
};
int main() {
Student student1 = {“Tesfa", “SE”, 3.58};
cout << "Name: " << [Link] << endl;
cout << “Department: " << [Link] << endl;
cout << “GPA: " << [Link] << endl;
[Link] = 3.75; // Modifying members
cout << "Updated GPA: " << [Link] << endl;
33
}
Array of Structures
An array of structures can be declared to manage multiple entities of the same
type

Allows to store multiple records, where each record is represented as a structure

Defining an Array of Structures:


StructureName array_name[array_size];
Student students[3]; // Array of 3 Student structures

Initializing an Array of Structures:


Student students[3] = { Student students[3];
{“Tesfa", “SE”, 3.75}, students[0] = {“Tesfa", “SE”, 3.75};
{“Hiwot", “IT”, 3.7}, students[1] = {“Hiwot", “IT”, 3.7},

{“Selam", “CS”, 3.65} students[2] = {“Selam", “CS”, 3.65};

}; 34
#include <iostream>
using namespace std;
struct Student {
string name;
string dept;
float gpa;
};
int main() {
Student students[3] = { {“Tesfa", “SE”, 3.75}, {“Hiwot", “IT”, 3.7},
{“Selam”,“CS”, 3.65}};
for (int i = 0; i < 3; i++) {
cout << "Student " << i + 1 << ":" << endl;
cout << "Name: " << students[i].name << endl;
cout << “Department: " << students[i].dept<< endl;
cout << “GPA: " << students[i].gpa<< endl;
35
}}
Arrays vs. Structures
Arrays:
- Store elements of the same type
- Use indices to access elements
- Fixed size and contiguous memory allocation

Structures:
- Can store elements of different types
- Accessed using member names
- Size depends on types of its members and members
may not be contiguous

You might also like