Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

C++ Chapter 4 Array, String and Pointer

Introduction to computer programing C++ chapter 4 Array,String and pointer

Uploaded by

surafelfisseha27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C++ Chapter 4 Array, String and Pointer

Introduction to computer programing C++ chapter 4 Array,String and pointer

Uploaded by

surafelfisseha27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter - 4

Array and String

1
Introduction to Array
➢Variables in a program have values associated with them.

➢During program execution these values are accessed by using the


identifier associated with the variable in expressions.

➢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.

➢An array in C++ is a collection of items stored at contiguous memory


locations and elements can be accessed randomly using indices of an array.

➢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.

➢An array is a series of elements of the same type placed in contiguous


memory locations that can be individually referenced by adding an index
to a unique identifier.

➢Represented as a group of consecutive memory locations .

➢To refer to a particular location or element in the array, we specify the


name of the array and the position number of the particular element in
the array.

➢Each element of an array is accessed its index. 4


Introduction to Array
➢ For example 1 , an array to contain 5 integer values of type int called foo could be represented like this

➢ 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;

➢ In C++, the index of the first array element is always zero.

➢ For example : Suppose a class has 27 students, and we need to store the grades of all of them.

➢ Instead of creating 27 separate variables, we can simply create an array.

➢ Like a regular variable, an array must be declared before it is used.

➢ A typical declaration for an array in C++ is: Type array_Name [ size ];


➢ typical declaration for the above examples:
✓ example 1 => int foo[5];
✓ example 2 => double grade[27]; 5
Types of Array

➢One Dimensional Array


➢Multidimensional arrays

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.

➢Below is illustration of array.

7
One Dimensional Array
➢It is a collection of same data types. 1-D array is declared as:

Syntax: data_type variable_name[size]

data_type is the type of array, like int, float, char, etc.

variable_name is the name of the array.

size is the length of the array which is fixed.

The Size must be an integer constant greater than zero.

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

arrays of same type

10
Array Initialization:

➢ We can explicitly initialize arrays at the time of declaration.

➢Syntax: data_type array_name[size]={value1, value2,……..valueN};

➢Value1, value2, valueN are the constant values known as initializers,


which are assigned to the array elements one after another.
▪ Example: Define an array temperature of 5 elements contains float numbers ,

and Initialize it with these numbers : 12.3 , 7.5 , 65 , 72.1, 87.5 .

11
Array Initialization:
➢ double temperature [5] = {12.3 , 7.5 , 65 , 72.1, 87.5 };

temperature [0] 12.3

temperature [1] 7.5

temperature [2] 65.0 Elements

temperature [3] 72.1

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 .

➢ int C[4] = {2, 4, 8, 16, 32};

• Error — compiler detects too many initial values .


13
Accessing Array Element:
❖An individual element within array is accessed by use of a subscript (index) that

describes the position of an element in the array , it must be an integer or integer

expression .

➢We can’t copy the elements of one array to another array by simply assigning it.

Example: int a[5]={9,8,7,6,5}; and int b[5]; b=a; //not valid


➢ we have to copy all the elements by using for loop.
➢Sizeof operator used to show memory allocation of the given
Array element using Sizeof(array name);

14
Accessing Array Element Example:

The symbol table for the program


Variable Name Address Value a
Out put
a 0x7ffe58e7cc4 7
15
Array Initialization:
Const int SIZE=10
➢x = y ; // Error - Illegal
int x [SIZE] ;
int y [SIZE] ;
➢Only individual elements can be assigned to using the index operator,
➢e.g., x[1] = y[2];
➢To make all elements in 'x' the same as those in 'y' (equivalent to assignment), a
loop has to be used.
for (int i = 0 ; i < SIZE; i++) // Loop to do copying, one element at a time
x[i] = y[i];
➢This code will copy the elements of array y into x, overwriting the original
contents of x.
16
Array Initialization:
1. Write a c++ program that display the elements of the following array
➢ Double marks[20]={50,90,30,100,78,68};

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.

➢We can calculate the total number of elements in an array by multiplying


the size of each dimension of a multidimensional array.

➢Here size1, size2 up to sizeN describe the number of dimensions.

➢type array_Name [ x ][ y ];

• Int array[3][2] // two dimensional array

• int array [5][2][3] // three dimensional array


20
Multidimensional arrays
➢In this type of array two indexes describe each elements the first index
represent a row and the second index represent a column.
(0,0) (0,1) (0,2)

(1,0) (1,1) (1,2)

(2,0) (2,1) (2,2)

➢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
• .

The first element


col 0 col 1 col 2 col 3 col 4

row 0 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4]

row 1 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4]

row 2 a[2][0] a[2][1] a[2][2] a[2][3] a[2][4]

row 3 a[3][0] a[3][1] a[3][2] a[3][3] a[3][4]

The last element

23
Initializing Two-dimensional array
➢ 2D arrays can be initialized in a way similar to 1D arrays.

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


The values are assigned as:
➢The initialization of group of elements as follows:
a[0][0] =11 a[0][1] =0 a[0][2] =0
int m[4][3]={{11},{12,13},{14,15,16},{17}}; a[1][0] =12 a[1][1] =13 a[1][2] =0

➢ 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

➢ For processing of 2D arrays we need two nested for loops.

➢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};

2. Write a c++ program to display the sum of two dimensional array.

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.

➢The syntax for passing array to function is

➢Return type function name(datatype array name[array size])

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.

For example it is declared as: char str[ ] = “Hello"

A string variable contains a collection of characters surrounded by double


quotes: // Include the string library
#include <string>
// Create a string variable
string greeting = "Hello";
33
String

The string data_type in C++ provides various functionality of string


manipulation. They are:

strcpy(): It is used to copy characters from one string to another string.

strcat(): It is used to add the two given strings.

strlen(): It is used to find the length of the given string.

strcmp(): It is used to compare the two given string.

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:

string firstName = “Abel";


string lastName = “Abraham";
string fullName = firstName + " " + lastName;
cout << fullName;

36
C++ Numbers and Strings

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

37
C++ String Length

To get the length of a string, use the length() function:

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is:
" << txt.length();

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is:
" << txt.size();

38
Access Strings

You can access the characters in a string by referring to its index


number inside square brackets [ ].

This example prints the first character in myString:

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.";

The sequence \" inserts a double quote in a string:


Example
string txt = "We are the so-called \"Vikings\" from the north.";
string txt = "It\'s alright."; 40
C++ User Input Strings
It is possible to use the extraction operator >> on cin to store a string
entered by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from
the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John


// Your name is: John

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

You might also like