0% found this document useful (0 votes)
7 views50 pages

Slide 1

The document outlines a course on Computer Programming II, focusing on arrays and their operations in C++. It covers topics such as declaring, initializing, accessing, and modifying both one-dimensional and multidimensional arrays, along with searching and sorting algorithms. Additionally, it includes lab questions and code examples to reinforce learning.

Uploaded by

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

Slide 1

The document outlines a course on Computer Programming II, focusing on arrays and their operations in C++. It covers topics such as declaring, initializing, accessing, and modifying both one-dimensional and multidimensional arrays, along with searching and sorting algorithms. Additionally, it includes lab questions and code examples to reinforce learning.

Uploaded by

abudadee247
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

CSC 2302

COMPUTER PROGRAMMING
II
COURSE OUTLINE
• Introduction to Arrays
• Multidimensional Arrays
• Array Operations
• More Array Operations
• Dynamic Arrays (Pointers and Arrays)
• Array of Pointers and Pointers to Arrays
Day 1: Arrays and their Basics

– Introduction to arrays and their importance in


programming
– Declaring and initializing arrays
– Accessing array elements using index
– Array index and bounds
Introduction to arrays

• Arrays are a collection of elements of the


same data type, stored in contiguous memory
locations.
• They allow us to store and access multiple
values using a single variable name.
• They allow efficient access to elements using
index-based addressing, making them
essential for various applications.
Declaring Arrays
• In C++, you can declare an array using the
following syntax:
• data_type array_name[size];
• where data_type is the type of elements in
the array.
• array_name is the name of the array,
• and size is the number of elements the array
can hold.
Declaring Arrays

int numbers[5] ;

char vowels[10] ;

double balance[7];

String name[11];

Initializing arrays

You must assign values to array elements before using
them. Here are the two ways to initialize elements in an
array:
 Initialize the elements at declaration time
 Initialize the elements in the program

At Declaration


You can initialize an array at the time of declaration.

int numbers[5] = {1, 2, 3, 4, 5}; // Array of 5 integers initialized

char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; // Array of 5 characters
initialized

The number of values between braces { } cannot be larger than the
number of elements that we declare for the array between square
brackets [ ].

If you omit the size of the array, an array just big enough to hold
the initialization is created. Therefore, if you write:

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

Default Initialization

If fewer initializers are provided than the size of the array, the
remaining elements are initialized to zero.

int numbers[5] = {1, 2}; // Remaining elements initialized to 0:
{1, 2, 0, 0, 0}

Empty Initialization

Initializing an array with empty braces sets all elements to
zero.

int numbers[5] = {}; // All elements initialized to 0: {0, 0, 0, 0, 0}

 Initialize the elements in the program


The for loop is a perfect tool for looping through arrays
when you fill them with values.

Arrays can also be initialized using loops, which is useful
when you need to initialize elements based on some
condition or formula.

int numbers[5];

for (int i = 0; i < 5; i++) {

numbers[i] = i * 2;

}


string cars[5];

for (int i = 0; i < 5; i++) {

Cin >> cars[i];

}
Array Indexing in C++

Array indexing is the method used to access elements within an array using
their position within the array.

Understanding how to correctly index arrays is fundamental to working with
them effectively in C++.

Indexing Starts at 0: In C++, the first element of an array is at index 0, the
second element is at index 1, and so on.

Syntax: arrayName[index]

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

cout << numbers[0]; // Outputs 10

cout << numbers[4]; // Outputs 50

Accessing and Modifying Array Elements


Accessing Elements:

int numbers[3] = {10, 20, 30};

int first = numbers[0]; // first = 10

int second = numbers[1]; // second = 20

int third = numbers[2]; // third = 30

Modifying Elements:

numbers[1] = 25; // Changes the second element to 25

Iterating Through an Array


Using For Loop

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

for(int i = 0; i < 5; i++) {

cout << numbers[i] << " ";

}

// Outputs: 10 20 30 40 50

Lab Question


Question 1: Write a C++ program to perform the following
operations on an array:
 Declare and initialize an array of 5 integers.
 Access and print each element using a loop.
 Modify the third element of the array.
 Print the modified array.


Question 2: Write a C++ program to:
 Declare and initialize an array of 10 integers.
 Calculate and print the sum of all elements.
 Calculate and print the average of all elements.

Question 3: Write a C++ program to:
 Declare and initialize an array of 5 integers.
 Reverse the elements of the array.
 Print the reversed array.

Question: Write a C++ program to:

Declare and initialize an array of 6 integers.

Find and print the maximum element in the array.

Find and print the minimum element in the array.
Code Example 1: Array Sum and Average
• #include <iostream>
• using namespace std;

• int main() {
• const int size = 5;
• int numbers[size];
• int sum = 0;

• std::cout << "Enter " << size << " integers:\n";

• for (int i = 0; i < size; ++i) {
• cin >> numbers[i];
• sum += numbers[i];
• }

• double average = (sum) / size;

• std::cout << "Sum: " << sum << std::endl;
• std::cout << "Average: " << average << std::endl;

• return 0;
• }
Introduction to multidimensional arrays

• In C++, a multidimensional array is an array of


arrays.
• Unlike a one-dimensional array that consists of a
single row of elements.
• A multidimensional array contains multiple rows
and columns of elements, forming a grid-like
structure.
• They are particularly useful for representing tabular
data, matrices, and other structured data with
multiple dimensions.
Introduction to multidimensional arrays

• In C++, the most common type of multidimensional array


is the 2D array.
• but you can have arrays with more than two dimensions
as well.
• For example, a 3D array can be visualized as a cube with
multiple layers.
• Multidimensional arrays are powerful data structures that
allow efficient manipulation of structured data.
• They find applications in various fields, including image
processing, game development, and scientific
simulations.
Syntax for Declaring 2D Array
• data_type array_name[rows][columns];
• Here, data_type represents the type of
elements that the array will hold.
• array_name is the name of the array.
• rows specifies the number of rows, and
columns indicates the number of columns in
the 2D array.
Initializing a 2D Array
• A 2D array can be initialized during declaration
using nested braces.
• int matrix[3][3] = {
• {1, 2, 3},
• {4, 5, 6},
• {7, 8, 9}
• };
Accessing Elements in a 2D Array
• To access individual elements in a 2D array, you
use row and column indices enclosed in square
brackets.
• The indices are zero-based, meaning the first row
and column have an index of 0.
• For example, to access the element in the second
row and third column of the above matrix.
• int element = matrix[1][2]; // element will be 6
Iterating through a 2D Array
• To traverse all the elements of a 2D array, you can use nested loops.
• The outer loop iterates through the rows, and the inner loop iterates
through the columns.
• Example: Printing Elements of a 2D Array
• #include <iostream>

• int main() {
• int matrix[3][3] = {
• {1, 2, 3},
• {4, 5, 6},
• {7, 8, 9}
• };

• for (int i = 0; i < 3; ++i) {
• for (int j = 0; j < 3; ++j) {
• cout << matrix[i][j] << " ";
• }
• cout << endl;
• }

• return 0;
• }
Code Example 1: 2D Array Sum

• #include <iostream>
• using namespace std;

• const int rows = 3;


• const int columns = 3;

• int main() {
• int matrix[rows][columns];

• cout << "Enter " << rows * columns << " integers for the 2D array:\n";
• for (int i = 0; i < rows; ++i) {
• for (int j = 0; j < columns; ++j) {
• cin >> matrix[i][j];
• }
• }
• int sum = 0;
• for (int i = 0; i < rows; ++i) {
• for (int j = 0; j < columns; ++j) {
• sum += matrix[i][j];
• }
• }

• cout << "Sum of elements in the 2D array: " << sum << endl;

• return 0;
• }
Code Example 2: 2D Array Transpose
• #include <iostream>
• using namespace std;
• const int rows = 3;
• const int columns = 3;
• int main() {
• int matrix[rows][columns];
• cout << "Enter " << rows * columns << " integers for the 2D array:\n";
• for (int i = 0; i < rows; ++i) {
• for (int j = 0; j < columns; ++j) {
• cin >> matrix[i][j];
• }
• }
• int transpose[columns][rows];
• for (int i = 0; i < rows; ++i) {
• for (int j = 0; j < columns; ++j) {
• transpose[j][i] = matrix[i][j];
• }
• }
• cout << "Original 2D array:\n";
• for (int i = 0; i < rows; ++i) {
• for (int j = 0; j < columns; ++j) {
• cout << matrix[i][j] << " ";
• }
• cout << endl;
• }
• cout << "Transpose of the 2D array:\n";
• for (int i = 0; i < columns; ++i) {
• for (int j = 0; j < rows; ++j) {
• cout << transpose[i][j] << " ";
• }
• cout << endl;
• }
• return 0;
• }
Lab Questions

Question 1: Write a C++ program to:
 Declare and initialize two 3x3 matrices.
 Add the two matrices and store the result in a third matrix.
 Print the resulting matrix.

Question 2: Write a C++ program to:
 Declare and initialize two 2x2 matrices.
 Multiply the two matrices and store the result in a third
matrix.
 Print the resulting matrix.
Common Array Operations: Searching and Sorting

• Searching and sorting are fundamental


operations performed on arrays.
• Efficient algorithms for these operations are
crucial in various computer science
applications.
Searching Algorithms: Linear Search

• Linear search is a simple searching algorithm that sequentially


checks each element in the array until the target element is found.

• int linearSearch(int arr[], int size, int target) {


• for (int i = 0; i < size; ++i) {
• if (arr[i] == target) {
• return i; // Return the index of the target element if found
• }
• }
• return -1; // Return -1 if the target element is not found
• }
Binary Search
• Binary search is a faster searching algorithm
used on sorted arrays. It compares the target
element with the middle element and
eliminates half of the remaining elements at
each step.
• int binarySearch(int arr[], int size, int target) {
• int left = 0;
• int right = size - 1;
• while (left <= right) {
• int mid = left + (right - left) / 2;
• if (arr[mid] == target) {
• return mid; // Return the index of the target element if found
• } else if (arr[mid] < target) {
• left = mid + 1;
• } else {
• right = mid - 1;
• }
• }
• return -1; // Return -1 if the target element is not found
• }
Sorting Algorithms: Bubble Sort

• Bubble sort repeatedly swaps adjacent elements if they are in the wrong order
until the entire array is sorted
• void bubbleSort(int arr[], int size) {
• int temp; // Temporary variable to swap with
• for (int i = 0; i < size - 1; ++i) {
• for (int j = 0; j < size - i - 1; ++j) {
• if (arr[j] > arr[j + 1]) {
temp = ara[i]; // pair is not in order.
arr[i] = arr[j+1];
ara[j+1] = temp; // “Float” the lowest to the highest.

• }
• }
• }
• }
Selection Sort

• Selection sort repeatedly selects the minimum element from the


unsorted part of the array and swaps it with the first unsorted element.
• void selectionSort(int arr[], int size) {
• for (int i = 0; i < size - 1; ++i) {
• int minIndex = i;
• for (int j = i + 1; j < size; ++j) {
• if (arr[j] < arr[minIndex]) {
• minIndex = j;
• }
• }
• std::swap(arr[i], arr[minIndex]);
• }
• }
• These are some of the common searching and
sorting algorithms used on arrays.
• Depending on the size and nature of the data,
different algorithms may be more efficient.
• Understanding these algorithms can help
improve the performance of array-related
operations in your programs.

Introduction to Pointers

• In C++, a pointer is a data type that holds the


memory address of another variable. Pointers
provide a way to access and manipulate data
indirectly
• Pointers in C++ are similar to pointers in C, but
C++ introduces some additional features like
smart pointers, which help manage memory
more effectively.
Declaring and Initializing Pointers

• In C++, you declare a pointer using the *


symbol next to the data type.
• The general syntax for declaring a pointer is as
follows:
• data_type* pointer_name;
• To initialize a pointer, you can assign it the
memory address of another variable using the
& (address-of) operator:
Example
• Copy code
• int x = 10;
• int* p = &x; // p now points to the memory
location of x
• You can also declare and initialize pointers at
the same time:
• int* p = nullptr; // Initialize p as a null pointer
Dereferencing Pointers

• Dereferencing a pointer means accessing the


value stored in the memory address pointed
by the pointer.
• You use the * (dereference) operator for this:
• int y = *p; // y now holds the value of x (i.e.,
10)
Example: Working with Pointers

• #include <iostream>

• int main() {
• int x = 42;
• int* p = &x;

• std::cout << "Value of x: " << x << std::endl;
• std::cout << "Address of x: " << &x << std::endl;
• std::cout << "Value of p: " << p << std::endl;
• std::cout << "Value pointed by p: " << *p << std::endl;
• // Modifying x through the pointer p
• *p = 99;
• std::cout << "New value of x: " << x << std::endl;

• return 0;
• }
Dynamic Memory Allocation

• In C++, you can use the new operator to


allocate memory dynamically.
• This allows you to allocate memory at runtime
and deallocate it when it is no longer needed.
• The new operator returns a pointer to the
dynamically allocated memory.
Example: Dynamic Memory Allocation
• #include <iostream>
• int main() {
• int size;
• std::cout << "Enter the size of the array: ";
• std::cin >> size;
• int* arr = new int[size];
• std::cout << "Enter " << size << " elements:\n";
• for (int i = 0; i < size; i++) {
• std::cin >> arr[i];
• }
• std::cout << "Elements entered: ";
• for (int i = 0; i < size; i++) {
• std::cout << arr[i] << " ";}
• delete[] arr; // Deallocate the dynamically allocated memory
• return 0;
• }

Smart Pointers

• C++11 introduced smart pointers to automate


the process of memory management.
• Smart pointers are objects that act like pointers
but automatically manage the memory they
point to, ensuring that memory is deallocated
when it is no longer needed.
• The two most commonly used smart pointers in
C++ are std::unique_ptr and std::shared_ptr.

Example: Using Smart Pointers

• #include <iostream>
• #include <memory>

• int main() {
• std::unique_ptr<int> p = std::make_unique<int>(42);
• std::shared_ptr<int> q = std::make_shared<int>(10);

• std::cout << "Value of p: " << *p << std::endl;
• std::cout << "Value of q: " << *q << std::endl;

• return 0;
• }
Pointers and Functions

• Pointers are commonly used to pass variables


by reference to functions. This allows the
function to modify the original value passed to
it.
Passing Variables by Reference

• #include <iostream>

• void swap(int* a, int* b) {
• int temp = *a;
• *a = *b;
• *b = temp;
• }

• int main() {
• int x = 10, y = 20;

• std::cout << "Before swapping: x = " << x << ", y = " << y << std::endl;
• swap(&x, &y);
• std::cout << "After swapping: x = " << x << ", y = " << y << std::endl;

• return 0;
• }
Pointers and Arrays

• In C++, an array name is a pointer to the first


element of the array.
• This is because arrays are contiguous blocks of
memory, and the name of the array
represents the memory address of the first
element.
Array and Pointer Relationship
• #include <iostream>

• int main() {
• int arr[5] = {10, 20, 30, 40, 50};
• int* p = arr; // p points to the first element of the array

• std::cout << "Array elements: ";
• for (int i = 0; i < 5; i++) {
• std::cout << *(p + i) << " "; // Same as arr[i] or *(arr + i)
• }

• return 0;
• }

You might also like