Array and String
Array and String
During program execution these values are accessed by using the identifier
associated with the variable in expressions.
If there were 10000 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.
Arrays
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;
In C++, the index of the first array element is always zero.
For example 2: Suppose a class has 27 students, and we need to store the grades of all of them.
• The diagram above shows that it arranged all the elements in row wise
in a single dimension, one after other
Declaration:
Before using the array in the program it must be declared
Size represents the number of elements that can be stored in the array.
The Size must be an integer constant greater than zero.
Examples-
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 .
8
Initialization:
We can explicitly initialize arrays at the time of declaration.
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
temperature [ 4 ] 87.5
Index 10
Initializing Arrays
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 } ;
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};
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. A loop like
Write a c++ program that display the elements of the following array
Double marks[20]={50,90,30,100,78,68};
Write a c++ program that initialize elements for the following array from the user, and display the
values/elements.
double scores[5];
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};
Write a c++ Program that display the sum of the following array elements
int array[4] = {100, 200, 300, 400};
Multidimensional arrays
A two dimensional array also falls under the category of a
multidimensional array.
• 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.
Declaration:
The syntax is same as for 1-D array but here 2 subscripts are used.
Rowsize specifies the number of rows and Columnsize specifies the number of
columns.
This is a 2-D 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.
• .
The first element
col 0 col 1 col 2 col 3 col 4
In 2-D arrays it is optional to specify the first dimension a[2][0] =14 a[2][1] =15 a[2][2] =16
For processing of 2-D arrays we need two nested for loops. The outer loop
indicates the rows and the inner loop indicates the columns.
• 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];
Write a c++ program that display the maximum value from the
following array elements. And show the position(index) where the
maximum value is located.
int arr[3][4]={12,10,23,56,27,18,10,23,45,60,23};
Write a c++ program that display the sum of two 2X2 matrices
int arr1[2][2]
int arr2[2][2]
3D
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.
#include <iostream> 5 10 15
Using namespace std; 2 4 6 8 10
void printarray (int arg[], int length)
{
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;
}
Example 1: Passing One-dimensional Array to a Function
// C++ Program to display marks of 5 students
#include <iostream>
using namespace std;
void display(int m[5])
{
cout << "Displaying marks: " << endl;
for (int i = 0; i < 5; ++i)
{
cout << "Student " << i + 1 << ": " << m[i] << endl;
}}
int main()
{
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}
C-strings
For example:
To read the text containing blank space, cin.get() function can be
used. This function takes two arguments.
First argument is the name of the string and second argument is the
maximum size of the array.
Example
string Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can
be extended as per your requirement.
• Example : C++ string using string data type
• In this program, a string str is declared. Then the string is asked from
the user.
• Instead of using cin>> or cin.get() function, you can get the entered
line of text by using getline().
• Getline() function takes the input stream as the first parameter which is
cin and str as the location of the line to be stored.
Counting the number of characters in a string.
The length method returns the number of characters in a string, including
spaces and punctuation.
The string that is the receiver is to the left of the dot, the member function
we are invoking is to the right, (e.g. str.length() ).
In such an expression, we are requesting the length from the variable str.
String Functions & Purpose
strcpy(destination, source);
Strcpy copies character's from the location specified by sources to the location specified by destination. It
stops copying character's after it copies the terminating null character.
strcat(destination, source);
The first character of the source string is copied to the location of the terminating null character of the
destination string.
Returns 0 string 1 is equal to string 2, 1 if string 1 is greater than string 2, -1 if string 1 is less than string
2
strncmp(str1, str2, int n);