0% found this document useful (0 votes)
84 views23 pages

ARRAYS PPT-oct2024

The document provides an overview of arrays and strings in C++, detailing their types, declarations, initializations, and access methods. It explains one-dimensional and two-dimensional arrays, along with multidimensional arrays, and introduces C-style character strings and the string class type. Additionally, it covers common string manipulation functions such as strcpy, strcat, strcmp, and strlen.

Uploaded by

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

ARRAYS PPT-oct2024

The document provides an overview of arrays and strings in C++, detailing their types, declarations, initializations, and access methods. It explains one-dimensional and two-dimensional arrays, along with multidimensional arrays, and introduces C-style character strings and the string class type. Additionally, it covers common string manipulation functions such as strcpy, strcat, strcmp, and strlen.

Uploaded by

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

ARRAYS

Arrays
-Types
-Declaration
Strings
-Types
-Use
ARRAYS
• An array is a collection of variables of the same type that are referred to
by a common name.
• Arrays offer a convenient means of creating lists of related variables.
• For instance, instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable such as
numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
• A specific element in an array is accessed by an index.
• All arrays consist of contiguous memory locations.
• The lowest address corresponds to the first element and the highest
address to the last element.
Array Declaration
• To declare an array in C++, the programmer specifies the type of the
elements and the number of elements required by an array as follows −
type arrayName [ arraySize ];
• This is called a single-dimension array.
• The arraySize must be an integer constant greater than zero and type can
be any valid C++ data type.
• For example, to declare a 10-element array called balance of type double,
use this statement
• double balance[10]
Initializing Arrays
• You can initialize C++ array elements either one by one or using a single statement as
follows :
• double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
• 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};
• You will create exactly the same array as you did in the previous example. Example:
balance[4] = 50.0;
• The above statement assigns element number 5th in the array a value of 50.0.
• Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index
of their first element which is also called base index.
• Pictorial representation of the same array we discussed above
Accessing Array Elements
• An element is accessed by indexing the array name. This is done by
placing the index of the element within square brackets after the name
of the array. For example
• double salary = balance[9];
• The above statement will take 10th element from the array and assign
the value to salary variable. Following is an example, which will use all
the above-mentioned three concepts viz. declaration, assignment and
accessing arrays .
Array example program
• #include <iostream>
using namespace std; 3
#include <iomanip>
using std::setw;
int main () {
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0; }
One-dimensional arrays
• Is a list of related variables.
• Such lists are common in programming.
• For example, you might use a one-dimensional array to store the
account numbers of the active users on a network. When computing the
average of a list of values, you will often use an array to hold the values.
Arrays are fundamental to modern programming.
• The general form of a one-dimensional array declaration is
type name[size];
One-dimensional array Example program
Array example
The following program creates an array of ten elements and assigns each
element a value. It then computes the average of those values and finds
the minimum and the maximum value
Two-Dimensional Arrays
• A list of one-dimensional arrays.
• To declare a two- dimensional integer array twoD of size 10,20, you
would write
int twoD[10][20];
• Unlike some other computer languages, which use commas to separate
the array dimensions, C++ places each dimension in its own set of
brackets.
• Similarly, to access an element, specify the indices within their own set of
brackets.
• For example, for point 3,5 of array twoD, you would use twoD[3][5].
• In the next example, a two-dimensional array is loaded with the numbers
1 through 12.
2-D Array example
• In this example, nums[0][0] will have the value 1, nums[0][1] the value 2,
nums[0][2] the value 3, and so on. The value of nums[2][3] will be 12.
2-d continued
• Two-dimensional arrays are stored in a row-column matrix, where the
first index indicates the row and the second indicates the column.
• This means that when array elements are accessed in the order in
which they are actually stored in memory, the right index changes
faster than the left.
• You should remember that storage for all array elements is determined
at compile time. Also, the memory used to hold an array is required the
entire time that the array is in existence. In the case of a two-
dimensional array, you can use this formula to determine the number
of bytes of memory that are needed:
• bytes = number of rows × number of columns × number of bytes in
type
• Therefore, assuming four-byte integers, an integer array with
dimensions 10,5 would have 10×5×4 (or 200) bytes allocated.
Multidimensional Arrays
• C++ allows arrays with more than two dimensions. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
• For example, the following declaration creates a 4×10×3–integer array:
int multidim[4][10][3];
• Arrays of more than three dimensions are not often used, due to the amount of
memory required to hold them. Remember, storage for all array elements is
allocated during the entire lifetime of an array.
• When multidimensional arrays are used, large amounts of memory can be
consumed. For example, a four-dimensional character array with dimensions
10,6,9,4 would require 10×6×9×4 (or 2,160) bytes.
• If each array dimension is increased by a factor of 10 each (that is,
100×60×90×40), then the memory required for the array increases to 21,600,000
bytes! As you can see, large multidimensional arrays may cause a shortage of
memory for other parts of your program. Thus, a program with arrays of more
than two or three dimensions may find itself quickly out of memory
STRING
• C++ provides following two types of string representations −
• 1. The C-style character string.
• 2. The string class type introduced with Standard C++.
• 1. The C-Style Character String
• Originated within the C language and continues to be supported within C++. This string
is actually a one-dimensional array of characters which is terminated by a null
character '\0'.
• The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character
array containing the string is one more than the number of characters in the word
"Hello."
• It is not necessary to manually add the null terminator onto the end of string
constants; the C++ compiler does this for you automatically. Therefore, the string
“Mars” will appear in memory like this
String Example
• The following program reads a string entered by the user:
• Although
• Although this program is technically correct, it will not always work the way
that you expect. To see why, run the program and try entering the string “This
is a test”. Here is what you will see:
• Enter a string: This is a test
• Output: This
• When the program redisplays your string, it shows only the word “This”, not
the entire sentence. The reason for this is that the C++ I/O system stops
reading a string when the first whitespace character is encountered.
Whitespace characters include spaces, tabs, and newlines.
• One way to solve the whitespace problem is to use another of C++’s library
functions, gets( ). The general form of a call to gets( ) is gets(array-name);
• To read a string, call gets( ) with the name of the array, without any index, as
its argument. Upon return from gets( ), the array will hold the string input
from the keyboard. The gets( ) function will continue to read characters,
including whitespace, until you enter a carriage return. The header used by
gets() is <cstdio>.
Example
• This version of the program uses gets( ) to allow the entry of strings
containing spaces:
Some String Library Functions
• C++ supports a wide range of string manipulation functions. The most
common are strcpy( ) , strcat( ) strcmp( ) and strlen( )
• The string functions all use the same header, <cstring>.
strcpy
• A call to strcpy( ) takes this general form:
• strcpy(to, from);
• The strcpy( ) function copies the contents of the string from into to.
Remember, the array that forms to must be large enough to hold the string
contained in from. If it isn’t, the to array will be overrun, which will probably
crash your program.
strcat
• A call to strcat( ) takes this form: strcat(s1, s2); The strcat( ) function appends
s2 to the end of s1; s2 is unchanged. You must ensure that s1 is large enough
to hold its original contents and those of s2.
strcmp
• A call to strcmp( ) takes this general form:
strcmp(s1, s2);
• The strcmp( ) function compares two strings and returns 0 if they are equal. If s1 is
greater than s2 lexicographically (that is, according to dictionary order), then a
positive number is returned; if it is less than s2, a negative number is returned.
• The key to using strcmp( ) is to remember that it returns false when the strings
match.
• Therefore, you will need to use the ! operator if you want something to occur when
the strings are equal. For example, the condition controlling the following if
statement is true when str is equal to “C++”:
• if(!strcmp(str, "C++") cout << "str is C++";
• strlen
• The general form of a call to strlen( ) is strlen(s);
• where s is a string. The strlen( ) function returns the length of the string pointed to
by s.
A String Function Example
• The following program illustrates the use of all four string functions:
// Demonstrate the string functions.
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char s1[80], s2[80];
strcpy(s1, "C++"); 13
strcpy(s2, " is power programming.");
cout << "lengths: " << strlen(s1);
cout << ' ' << strlen(s2) << '\n';
if(!strcmp(s1, s2))
cout << "The strings are equal\n";
else
cout << "not equal\n"; strcat(s1, s2);
cout << s1 << '\n'; strcpy(s2, s1);
cout << s1 << " and " << s2 << "\n"; if(!strcmp(s1, s2))
cout << "s1 and s2 are now the same.\n";

You might also like