Introduction to C++
Session #2
1 One-dimensional arrays
OUTLINE
2 Two-dimensional arrays
3 Addresses and Pointers
4 Pointer Arithmetic
1. One-dimensional arrays
● Arrays are a fundamental data structure in C++ and are
used to store and manipulate collections of data.
● Arrays are linear data structure that contains same data
type
…ctd
1. Declaring an Array #include <iostream>
using namespace std;
int main() {
data_type array_name[size]; // Example 1: Initialization in the
declaration
int temp1[5];
temp1[5] = {98, 87, 92, 79, 85};
// Example 3: Omitting the size when
initializing in the declaration
int temp3[] = {5, 10, 15, 20, 25};
return 0;
}
…ctd
#include <iostream>
using namespace std;
•char array will contain an
extra null character at the int main() {
// Example: Initialization of a char
end of the string array with a string literal
•Example: char codes[] = "sample";
return 0;
}
•Allof the elements of an array can be processed by
using a loop #include <iostream>
using namespace std;
int main()
{
int temp[5] = {10, 12, 5, 8, 4};
int sum = 0;
for (int i=0; i<5; i++){
sum = sum + temp[i];
}
cout<<"The sum is: "<<sum<<endl;
return 0;
}
Input and Output of Array Values
}
…ctd
#include <iostream> // Output values of the array
cout << "Outputting array values:" <<
using namespace std; endl;
for (int i = 0; i < size; i++) {
int main() { cout << "Element " << i << ": " <<
const int size = 5; // You can change the size of the myArray[i] << endl;
array as needed }
int myArray[size];
return 0;
// Input values into the array }
cout << "Enter " << size << " integers:" << endl;
for (int i = 0; i < size; i++) {
cout << "Enter value for element " << i << ": ";
cin >> myArray[i];
}
…ctd
Enter 5 integers:
Enter value for element 0: 4
OUTPUT Enter value for element 1: 5
Enter value for element 2: 6
Enter value for element 3: 5
Enter value for element 4: 2
Outputting array values:
Element 0: 4
Element 1: 5
Element 2: 6
Element 3: 5
Element 4: 2
Example: find maximum value in array
#include <iostream>
using namespace std;
int main() {
const int size = 5;
Result:
int myArray[size] = {42, 17, 89, 56, 23};
int maxVal = myArray[0];
for (int i = 1; i < size; ++i) {
if (myArray[i] > maxVal) {
maxVal = myArray[i];
}
}
cout << "Result " << maxVal << endl;
return 0;
}
2. Two-dimensional arrays
● A two-dimensional array in C++ is essentially an array of arrays.
● It is a data structure that organizes elements in a table or matrix,
where each element is identified by two indices instead of one.
Think of it as a grid with rows and columns.
#include <iostream>
● Declaration using namespace std;
int main() {
// Declaration and Initialization of a 2D array
const int rows = 3;
const int columns = 4;
data_type array_name[row][column]; int myArray[rows][columns] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
return 0;
● Initialization }
You can initialize a 2D array either during declaration or later, similar to a 1D
array. When initializing, you can use nested curly braces to represent the
rows and columns
#include <iostream>
● Accessing Elements: using namespace std;
int main() {
// Declaration and Initialization of a 2D array
To access an element in a 2D array, const int rows = 3;
you can use two for loops: one for const int columns = 4;
int myArray[rows][columns] = {
the row and one for the column. {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing and outputting elements of the 2D array
cout << "2D Array Elements:" << endl;
•Example: for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
cout << myArray[i][j] << " ";
myArray[1][3]; }
cout << endl;
}
return 0;
}
…ctd
2D Array Elements:
1 2 3 4
OUTPUT 5 6 7 8
9 10 11 12
#include <iostream>
❖ Arrays as Arguments using namespace std;
int findMax(int arr[], int size) {
int maxVal = arr[0];
for (int i = 1; i < size; i++) {
● An individual array if (arr[i] > maxVal) {
maxVal = arr[i]; }
element can be }
return maxVal;
passed as an }
argument just like any int main() {
individual variable const int size = 5;
int myArray[size] = {42, 17, 89, 56, 23};
int maxValue = findMax(myArray, size);
cout << "The maximum value in the array is: " <<
maxValue << endl;
return 0;
}
3. Addresses and Pointers
● Address of a Variable: Every variable in C++ is stored in a specific memory
location, and you can obtain the address of a variable using the address-of
operator (&).
&num means the address of num
int x = 10;
cout<<"Address of x: " << &x << endl;
…cont
● Declaration of Pointers: Pointers are variables that store memory
addresses. You declare a pointer by specifying the type it points to,
followed by an asterisk (*).
● To use a stored address, C++ provides the indirection operator, *
● *numAddr means the variable whose address is stored in numAddr
int *ptr;
// Declaration of an integer pointer
cont…
● Initialization of Pointers: Pointers can be initialized with the address
of a variable.
int y = 20;
// Initializing the pointer with the address of
variable y
int *ptr = &y;
cont…
● Dereferencing Pointers: To access the value stored at the memory
location pointed to by a pointer, you use the dereference operator (*).
// Getting the value at the memory location
pointed to by ptr
int z = *ptr;
Example: combining addresses and pointers
#include <iostream>
using namespace std;
int main() {
int number = 42; Output
// Address of the variable
cout << "Address of number: " << &number << endl;
// Pointer declaration and initialization
int *ptr = &number;
// Value through dereferencing
cout << "Value at the memory location pointed to by ptr:
" << *ptr << endl;
return 0;
}
…ctd
Address of number: 0x7ffe10c779dc
OUTPUT Value at the memory location pointed to by
ptr: 42
…ctd
…ctd
OUTPUT
❖ Array Names as Pointers
Example:
#include <iostream>
using namespace std;
int main() { Output
int myArray[] = {10, 20, 30, 40, 50};
// Using array name as a pointer
int *ptr = myArray;
// Accessing array elements using the pointer
for (int i = 0; i < 5; ++i) {
cout << "Element " << i << ": " << *(ptr + i) << endl;
}
return 0;
}
…ctd
Element 0: 10
OUTPUT Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
4. Pointer Arithmetic
● Pointer variables, like all variables, contain values
● The value stored in a pointer is a memory address
● By adding or subtracting numbers to pointers you can obtain different
addresses
● Pointer values can be compared using relational operators (==, <, >,
etc.)
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
// Incrementing the pointer to the next element
ptr++;
// Now, ptr points to the second element in the array (20)
Example:
#include <iostream>
using namespace std;
int main() {
const int size = 5;
int myArray[size] = {10, 20, 30, 40, 50}; Output
// Using a pointer to iterate through the array and calculate the sum
int *ptr = myArray;
0
15
int sum = 0;
:
ts
for (int i = 0; i < size; ++i) {
en
em
sum += *ptr; // Add the value at the current memory location to the
el
sum
y
ra
ptr++; // Move to the next element in the array
ar
}
of
m
// Output the sum
Su
cout << "Sum of array elements: " << sum << endl;
return 0;
}
…cont
● Increment and decrement operators can be applied as both
prefix and postfix operators
❖ Passing Addresses: Example
#include <iostream>
using namespace std;
// Function to double the value at a specific memory location
void doubleValue(int *ptr) {
*ptr = *ptr * 2; Output
}
int main() {
int num = 5; Original value: 5
// Output the original value Modified value: 10
cout << "Original value: " << num << endl;
// Pass the address of 'num' to the function
doubleValue(&num);
// Output the modified value
cout << "Modified value: " << num << endl;
return 0;
}
❖ Passing Arrays
● When an array is passed to a function, its address is the only item
actually passed
“Address” means the address of the first location used to store
the array
First location is always element zero of the array
❖ Passing Arrays: Example
#include <iostream>
using namespace std;
void modifyArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
arr[i] *= 2; // Doubling each element Output
}
}
int main() {
const int size = 5;
2 4 6 8 10
int myArray[size] = {1, 2, 3, 4, 5};
// Passing the array to the function
modifyArray(myArray, size);
// Outputting the modified array
for (int i = 0; i < size; ++i) {
cout << myArray[i] << " ";
}
return 0;
}
OUTLINE
1. Files
2. Structures
FILES
Introduction
Embarking on File Operations in C++
File operations in C++ enable us to interact with
external files, read and write data, and manage
information persistently. Let's dive into the basics of
reading and writing files, exploring the fundamental
concepts and operations.
File Reading Basics
Read data from a text file in C++
File Reading - Processing
Content
● Utilize a `while` loop with
`getline()` for reading the file line
by line.
● Adapt the loop body to process
each line as needed.
File Writing - Appending
Content
Open the file in append mode to
add content without overwriting
existing data.
Modes of File Operations
Modes
Best Practices for File
Operations
● Always check if the file is successfully
opened.
● Ensure proper error handling to manage
unexpected situations.
● Close the file after finishing operations
to free up resources.
Common Mistakes in File
Operations
Mistake: Forgetting to check if the file is
open.
Solution: Prioritize error checking for
robust file handling.
Structures
Introduction
Structuring Data in C++
Structures provide a powerful way to organize and
encapsulate related data under a single name. Let's
explore the fundamentals of defining, creating
instances, and working with structures in C++.
Defining a Structure
● A structure is a user-defined
data type.
● Declared using the struct
keyword.
Creating Structure
Instances
Instances of structures hold specific
data.
Access structure members using the
dot (.) operator.
Displaying Structure Data
Print structure data to the console
for verification.
Nested Structures
Structures can be nested for more
complex data structures.
Displaying Nested
Structure Data
Print nested structure data to the
console for verification.
Passing Structures to
Functions
Send structures on missions to
functions.
Best Practices for
Structures
● Meaningful member names
enhance code readability.
● Structures group related
data; use them accordingly.
Common Mistakes in
Structure Usage
● Mistake: Accessing
uninitialized members.
● Solution: Always initialize
structure members.