C++ Chapter 4 Array, String and Pointer
C++ Chapter 4 Array, String and Pointer
1
Introduction to Array
➢Variables in a program have values associated with them.
➢If there were 1,000,000 values imagine the tedium of typing the
program and making up variable names and remembering which is which.
➢To get round this difficulty all high-level programming languages use
the concept of a data structure called an Array.
2
Introduction to Array
➢Array is a kind of data structure that can store fixed size(finite) sequential
collection of homogeneous element.
➢They are used to store similar types of elements as in the data type must
be the same for all elements.
➢ They can be used to store the collection of primitive data types such as
int, float, double, char, etc. of any particular type.
3
Introduction to Array
➢An array is a variable that can store multiple values of the same type.
➢ where each blank panel represents an element of the array. These elements are numbered from 0 to 4, with
0 being the first while 4 being the last;
➢ For example : Suppose a class has 27 students, and we need to store the grades of all of them.
6
One Dimensional Array
➢ It stores elements in a single dimension. And, in this array a single
specification is required to describe elements of the array.
➢ The diagram below shows that it arranged all the elements in row wise
in a single dimension, one after other.
7
One Dimensional Array
➢It is a collection of same data types. 1-D array is declared as:
Note: The location of the array elements depends upon the data
type we use. 8
One Dimensional Array Example:
Output
9
Example
❖int A[10];
• An array of ten
integers
❖Char str[20];
▪ An array of twenty
characters .
❖ int a[ 100 ], b[ 27 ] ;
▪ Defining multiple
10
Array Initialization:
11
Array Initialization:
➢ double temperature [5] = {12.3 , 7.5 , 65 , 72.1, 87.5 };
temperature [ 4 ] 87.5
Index 12
Array Initialization:
➢ int N[ ] = { 1, 2, 3, 4, 5 };
In 1-D arrays it is optional to specify the size of the array. If size is omitted
during initialization then the compiler assumes the size of array equal to the
number of initializers.
➢ int N[5] = { 0 } ; // the first element of the array is being initialized to 0.
➢ int B[20] = {2, 4, 8, 16, 32};
• Unspecified elements are guaranteed to be zero .
• If not enough initializers, rightmost elements become 0 .
expression .
➢We can’t copy the elements of one array to another array by simply assigning it.
14
Accessing Array Element Example:
2. Write a c++ program that initialize elements for the following array from the user, and display the
values/elements. double scores[5];
3. Write a c++ Program to Increment every Element of the Array by one & Print Incremented Array for the
following array. int array[4] = {100, 200, 300, 400};
4.Write a c++ Program that display the sum of the following array elements
➢ int array[4] = {100, 200, 300, 400};
5. Write a c++ Program to search the element is found in the given array element
6. Write a c++ Program to revers the given array element
7. Write a c++ program to sort the given array element either in ascending or descending order
17
Array Initialization:
Q? Write a c++ program that display the maximum value from the array
elements.
Q? At what index is
the maximum located
18
Multidimensional arrays
➢A multidimensional array is an array with more than one dimension.
➢ It is the homogeneous collection of items where each element is accessed
using multiple indices.
➢A 2D array also falls under the category of a multidimensional array.
• MD array can have any number of dimensions.
• Data type array_name [size 1][size2]….[size n]
where,
Data_type: Type of data to be stored in the array.
Array_Name: Name of the array.
size1, size2,…, sizeN: Size of each dimension.
19
Multidimensional arrays
➢ The size of an array is equal to the size of the data type multiplied by the
total number of elements that can be stored in an array.
➢type array_Name [ x ][ y ];
➢The above figure is a two dimensional array, the elements are arranged in
row-wise and column-wise, in a two dimensional array there are N number
of rows and columns. The above figure is a representation of a 3X3 matrix,
which means there are three rows and three columns in the array.
21
Multidimensional arrays
➢Declaration:
➢ The syntax is same as for 1-D array but here 2 subscripts are used.
Syntax: data_type array_name[rowsize][columnsize];
✓ Rowsize specifies the number of rows and
✓Columnsize specifies the number of columns.
Example: int a[4][5];
➢ This is a 2D array of 4 rows and 5 columns. Here the first element of the array
is a[0][0] and last element of the array is a[3][4] and total number of elements is
4*5=20.
22
Multidimensional arrays
• .
23
Initializing Two-dimensional array
➢ 2D arrays can be initialized in a way similar to 1D arrays.
➢ In 2D arrays it is optional to specify the first dimension a[2][0] =14 a[2][1] =15 a[2][2] =16
but the second dimension should always be present. a[3][0] =17 a[3][1] =0 a[3][2] =0
➢The outer loop indicates the rows and the inner loop indicates the columns.
24
Two-dimensional array
Example: int a[4][5];
➢ Reading values in a
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
cin>>a[i][j];
➢Displaying values of a
for(int i=0;i<4;i++)
for(int j=0;j<5;j++)
cout<<a[i][j];
25
Two-dimensional array
1. Write a c++ program that display the maximum value from the
following array elements.
int arr[3][4]={12,10,23,56,27,18,10,23,45,60,23};
int arr[3][4]={12,10,23,56,27,18,10,23,45,60,23};
3. Write a c++ program that display the sum of two 2X2 matrices.
int arr1[2][2]
int arr2[2][2]
26
27
Arrays as parameters
➢Just like a Variable an array may also be a parameter of a function.
28
Arrays as parameters
➢In C++ it is not possible to pass by value a complete block of memory
as a parameter, even if it is ordered as an array, to a function, but it is
allowed to pass its address.
➢To pass arrays as parameters the only thing that we must do when
declaring the function is to specify in the argument the base type for the
array that it contains, an identifier and a pair of void brackets [].
29
Arrays as parameters
Here you have a complete example: Output
#include <iostream>
Using namespace std; 5 10 15
void printarray (int arg[], int length) 2 4 6 8 10
{
for (int n=0; n<length; n++)
cout << arg[n] << " "; cout << "\n";}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;}
30
Arrays as parameters
Write a c++ program to display 5 student marks using pass array to function concept?
#include <iostream>
using namespace std;
void display(int m[5]){
Example 1: Passing
cout << "Displaying marks: " << endl;
One-dimensional for (int i = 0; i < 5; ++i)
Array to a Function {
cout << "Student " << i + 1 << ": " << m[i] << endl;
}}
int main() {
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
Exercise: Passing Two-dimensional Array to a Function? 31
Arrays as parameters
#include <iostream>
using namespace std;
int printarray (int arg[2][3])
{
Example 1: Passing
for (int n=0; n<2; n++){
Two-dimensional
for (int j=0; j<3; j++){
Array to a Function cout << arg[n][j] << " ";}
cout<<endl;}}
int main ()
{
int firstarray[2] [3]= {5, 10,2,7,5,4};
printarray (firstarray);
return 0;
}
32
String
Strings are used for storing text.
C++ string class internally uses character array to store character but all
memory management, allocation, and null termination are handled by
string class itself.
34
35
C++ String Concatenation
The + operator can be used between strings to add them
together to make a new string, this is called concatenation:
Examples:
36
C++ Numbers and Strings
Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)
37
C++ String Length
38
Access Strings
Example
string myString = "Hello";
cout << myString[0];
// Outputs H
39
C++ Special Characters
Because strings must be written within quotes, C++ will
misunderstand this string, and generate an error:
string txt = "We are the so-called "Vikings" from the north.";
41
C++ String Namespace
You might see some C++ programs that runs without the standard
namespace library. The using namespace std line can be omitted and
replaced with the std keyword, followed by the :: operator for string
(and cout) objects:
Example
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
} 42