
Arrays in C++
Prateek Narang
Topics
-
Introduction
-
Array Operations
-
Searching, Sorting
-
Passing Arrays to Functions
-
Dynamic Arrays


Motivation & Need for Arrays

Store marks of 1000 students, and create a ranklist

s1 - 86
s2 - 92
s3 - 100
s4 - 76
...

Arrays
- A C++ array is a collection of elements of the same type placed in contiguous memory locations
- Creation
- Input
- Output
- Update
int arr[1000];

Arrays Basic Operations
- Create
- Input
- Output
- Search
// Many ways to create the array
int a[100];
int a[100] = {0};
int a[100] = {1,2,3};
int a[] = {1,2,3};
string fruits[4] = {"apple","mango","guava"}

Passing Array to Functions
// Let's Practice
Example - Write a function to print the array.

More Operations
- Insert in an Array
- Delete in an Array
// Many ways to create the array
int a[100];
int a[100] = {0};
int a[100] = {1,2,3};
int a[] = {1,2,3};
string fruits[4] = {"apple","mango","guava"}
Searching means to find the index of element in a given array. The most common way of searching is Linear Search, in which we go through every element of the array and compare with the given element.

Searching in Arrays
int arr[] = {1,2,0,10,11,9,8,8,7};
int key = 9;
// Let's Build Linear Search Algorithm
Sorting means to arrange elements in a specific order, either increasing or decreasing based upon element's value.

Sorting in Arrays
//Unsorted Array
a = {10,12,5,4,1,3,2};
//Sorted Array in Increasing Order
a = {1,2,3,4,5,10,12}
//Sorted Array in Decreasing Order
a = {12,10,5,4,3,2,1}
Integer Arrays
Float Arrays
Character Arrays
Boolean Arrays

Arrays with other Datatypes
int x = 10, y=20;
// Declaring a Pointer
int * xPtr = &x; // a pointer to an integer value
// Setting to NULL
xPtr = 0;
int *p = 0;
int *q = NULL;
Reference Variables

A reference variable is an alias, that is, another name for an already existing variable.
Once a reference is initialised with a variable, either the variable name or the reference name may be used to refer to the variable.

Reference Variable
int x = 10;
int &y = x; // Here y is a reference variable
Problems!

1. Pass by Value
2. Pass by Reference
- using pointers
- using reference variables

Passing data to functions

[Topics 11] Arrays
By Prateek Narang
[Topics 11] Arrays
- 10