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

2nd Chapter 5 Array

The document provides an overview of arrays and strings in C++, detailing their definitions, memory representation, advantages, and disadvantages. It covers one-dimensional and two-dimensional arrays, initialization, traversal, and the use of the sizeof operator. Additionally, it explains C-style strings and the C++ std::string class, including string concatenation and copying methods.

Uploaded by

mrqareeb8
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 views11 pages

2nd Chapter 5 Array

The document provides an overview of arrays and strings in C++, detailing their definitions, memory representation, advantages, and disadvantages. It covers one-dimensional and two-dimensional arrays, initialization, traversal, and the use of the sizeof operator. Additionally, it explains C-style strings and the C++ std::string class, including string concatenation and copying methods.

Uploaded by

mrqareeb8
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

Unit 5 Array and strings

In C++, an array is a collection of elements that are of the same data type, stored in contiguous
memory locations. It allows you to group multiple values together under a single variable name,
which simplifies the management of related data.

Array Definition in C++

The syntax for defining an array in C++ is:

data_type array_name[array_size];

Where:

 data_type: The type of data that the array will store (e.g., int, float, char).
 array_name: The name of the array.
 array_size: The number of elements that the array will hold.

Int arr[6];

Memory Representation:

In memory, this array is stored as a contiguous block of memory where each element is stored
at a consecutive address.

Index Memory Address Value


0 1000 10
1 1004 20
2 1008 30
3 1012 40
4 1016 50

 Memory Address: The address where each element of the array is stored. The starting
address of the array is 1000, and each subsequent element is stored 4 bytes apart
(assuming an int takes 4 bytes).
 Index: The position of the element in the array. The index starts at 0 and goes up to n-1,
where n is the size of the array.
 Value: The actual value stored at that index.

Visual Representation of an array.

Array: [10] [20] [30] [40] [50]


Index: 0 1 2 3 4
Address: 1000 1004 1008 1012 1016
Terminologies used in an array

ame of the Array

 The name of an array refers to the identifier given to the array variable.
 The array name represents a reference to the first element of the array and can be used to
access elements of the array.
 In most contexts, the name of the array is treated as a pointer to the first element of
the array.

Example:

int arr[5] = {10, 20, 30, 40, 50};

 The name of the array is arr. When used, it refers to the base address of the array (i.e.,
the address of arr[0]).

2. Size of an Array

 The size of an array refers to the total number of elements that the array can hold.
 You can specify the size when declaring an array. Once the size is defined, it cannot be
changed.
 In C++, the size of an array is not automatically tracked, so you need to use a method
to determine it if the size is unknown.

3. Index of an Array

 The index of an array refers to the position of an element within the array. Array indices
in C++ are zero-based, meaning the first element is at index 0, the second element is at
index 1, and so on.
 The valid index range for an array of size n is from 0 to n-1.

Advantages of Arrays

1. Efficient Memory Management:


Arrays store elements in contiguous memory locations, which optimizes memory usage
and enables fast access to elements.
2. Random Access:
Arrays allow constant-time access to any element using its index, making retrieval
extremely fast (O(1)).
3. Ease of Use:
They are simple to implement and understand, making them ideal for beginners and
straightforward tasks.
4. Fixed Size:
The size of an array is determined at the time of declaration, providing predictability in
memory allocation.
5. Suitability for Iteration:
Arrays are well-suited for operations like sorting, searching, and iteration using loops.

Disadvantages of Arrays

1. Fixed Size Limitation:


The size of an array must be declared in advance and cannot be dynamically changed.
This can lead to memory wastage if the array is too large or insufficient space if it's too
small.
2. Insertion and Deletion Complexity:
Adding or removing elements requires shifting elements, leading to O(n) time complexity
for these operations in most cases.
3. Wasted Space:
If the array size is overestimated, unused spaces can lead to inefficient memory usage.
4. Homogeneous Data:
Arrays usually store elements of the same data type, limiting flexibility for heterogeneous
data storage.

intializing one dimensional array

In programming, a one-dimensional array is a linear data structure used to store a collection of


elements of the same data type. Here are examples of initializing one-dimensional arrays in
different programming languages:

int arr[5] = {1, 2, 3, 4, 5}; // Initialize with values


int arr2[5] = {}; // All elements initialized to 0
int arr3[] = {10, 20, 30}; // Compiler determines size

Example of initializing using initializer list method

#include<iostream>

Using namespace std;

Int main()

Int A[5]= [3,2,7,5,8];

Cout<<A[0]<<endl;
Cout<<A[1]<<endl;

Cout<<A[2]<<endl;

Cout<<A[3]<<endl;

Cout<<A[4]<<endl;

Output

Definition: Traversing an Array in C++

Traversing an array in C++ refers to the process of accessing each element in the array, one at a
time, usually using a loop. This allows you to perform operations like displaying, modifying, or
processing the elements of the array.

C++ program that demonstrates array traversal using a for loop to display only the odd values
from the array:

#include <iostream>
using namespace std;

int main() {
int arr[] = {12, 7, 5, 20, 15, 8}; // Define an array
int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size
of the array

cout << "Odd values in the array are: ";


for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) { // Check if the element is odd
cout << arr[i] << " "; // Print odd elements
}
}

return 0;
}

Output:

If the array is {12, 7, 5, 20, 15, 8}, the output will be:

Odd values in the array are: 7 5 15

sizeof operator :

The sizeof operator in C++ is used to determine the size (in bytes) of a data type or variable,
including arrays. When applied to arrays, sizeof can help calculate the total size of the array in
memory as well as the size of individual elements. This information is often used to determine
the number of elements in an array.

Two-dimensional (2D) array

A two-dimensional (2D) array in C++ is essentially an array of arrays. It can be visualized as a


table or a matrix with rows and columns. Each element is accessed using two indices: one for the
row and one for the column.

Declaration of a 2D Array

data_type array_name[rows][columns];

Example Declaration:

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

Initialization of a 2D Array

You can initialize a 2D array during declaration:

int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

Definition of Two-Dimensional Arrays in C++

A two-dimensional array in C++ is an array of arrays, where elements are stored in a tabular
form (rows and columns). Each element is accessed using two indices: one for the row and one
for the column. It allows the storage and manipulation of data in a grid-like structure.
Syntax for Declaration:

data_type array_name[rows][columns];

Access the Elements of a Multi-Dimensional Array

To access an element of a multi-dimensional array, specify an index number


in each of the array's dimensions.

This statement accesses the value of the element in the first row
(0) and third column (2) of the letters array.

Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

cout << letters[0][2]; // Outputs "C"

String:

string is used for storing text or characters. It is a variable contains a collection of characters
surrounded by double quotes.

Char str[4] = “C++”;

Char str[]= {“C”,”+”,”+”);

In C++, a string is a sequence of characters used to store and manipulate textual data. There are
two main ways to define a string in C++:
1. C-style string (character array)
2. C++ std::string (a class provided by the C++ Standard Library)

1. C-style String (Character Array)

A C-style string is defined as an array of characters terminated by a null character ('\0'). It is a


low-level way to handle strings in C++ and requires manual memory management and
manipulation.

Definition:

char str[] = "Hello, World!"; // C-style string, automatically


null-terminated

 str is a character array, and the string "Hello, World!" is stored in memory with a
null terminator ('\0') at the end.
 You can access individual characters in the string using an index, e.g., str[0] for 'H'.

2. C++ std::string

The std::string is a class in the C++ Standard Library that provides a more convenient and
safer way to work with strings. It handles memory management automatically and provides
many built-in functions for string manipulation.

Definition:

#include <iostream>
#include <string> // Required for std::string

string str = "Hello, World!"; // C++ string

In C++, concatenation refers to joining two or more strings together to form a new string. There
are different ways to concatenate strings in C++, depending on whether you're using C-style
strings or C++ std::string.

String Concatenation

In C++, string provides an easy way to concatenate strings using the + operator or the
append() method.

Using the + Operator

You can use the + operator to concatenate two or more std::string objects.

Example:
#include <iostream>
#include <string>
using namespace std;

int main() {
string str1 = "Hello, ";
string str2 = "World!";

// Concatenate strings using the + operator


string result = str1 + str2;

cout << result << endl; // Output: Hello, World!

return 0;
}

The swap() is a built-in function in the C++ STL which swaps the value of two
variables. This function supports almost every data type available in C++, whether it is
a primitive type such as int, char, etc. or STL containers such as vector, maps, etc.
b)

Q 1: Declare an array to hold the high temperature to the nearest tenth of a degree for each
day of a year. assign value of 0 to each day.

#include <bits/stdc++.h>
using namespace std;

int main() {
int a = 10;
int b = 20;

// Swap values of a and b


swap(a, b);

cout << "a = " << a << "\t" << "b = " << b;
return 0;
}
Output is
Output
a = 20 b = 10

#include <iostream>
int main() {
const int daysInYear = 365; // Number of days in a non-leap year
double temperatures[daysInYear] = {}; // Declare and initialize an array with 0 for each day

// Printing the values to verify


for (int i = 0; i < daysInYear; ++i) {
std::cout << "Day " << (i + 1) << " temperature: " << temperatures[i] << "°C" << std::endl;
}

return 0;
}
Output

Day 1 temperature: 0°C

Day 2 temperature: 0°C

...

Day 365 temperature: 0°C

Q2: Write down a C++ program to find the number of elements in array using sizeof() operator.

#include <iostream>

int main() {
int arr[] = {10, 20, 30, 40, 50}; // Array with 5 elements

// Using sizeof() to calculate the number of elements


int numElements = sizeof(arr) / sizeof(arr[0]);

std::cout << "The number of elements in the array is: " << numElements << std::endl;

return 0;
}

Output

The number of elements in the array is: 5

Q3: Write down a C++ program to find out the multiplication of two matrices A[3][2] and
B[2][3].

#include <iostream>
using namespace std;

int main() {
// Declare and initialize matrices A (3x2) and B (2x3)
int A[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int B[2][3] = {{7, 8, 9}, {10, 11, 12}};

// Declare a matrix C (3x3) to store the result of A * B


int C[3][3] = {0};

// Perform matrix multiplication: C = A * B


for (int i = 0; i < 3; i++) { // Rows of A
for (int j = 0; j < 3; j++) { // Columns of B
for (int k = 0; k < 2; k++) { // Columns of A or Rows of B
C[i][j] += A[i][k] * B[k][j];
}
}
}

// Display the result (Matrix C)


cout << "Result of Matrix A * Matrix B (Matrix C):" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}

return 0;
}

Output
Result of Matrix A * Matrix B (Matrix C):
27 30 33
61 68 75
95 106 117

Q 4: Wite a c++ program to copying string using strcpy() function.


#include <iostream>
#include <cstring> // For strcpy() function

using namespace std;

int main() {
// Declare and initialize the source string
char source[] = "Hello, C++ World!";

// Declare a destination string with enough space


char destination[50]; // Make sure the destination array is large enough to hold the source
string

// Use strcpy() to copy the string from source to destination


strcpy(destination, source);

// Display both the source and destination strings


cout << "Source String: " << source << endl;
cout << "Destination String: " << destination << endl;

return 0;
}

Output
Source String: Hello, C++ World!
Destination String: Hello, C++ World!

You might also like