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

C++ Note Array and String

The document discusses arrays in C++. Some key points: 1) Arrays allow storing multiple values of the same type using a single name. Elements are accessed via an index. 2) Arrays are declared with the syntax "type arrayName[size]". For example, "int numbers[100]". 3) Values can be initialized in the declaration like "int arr[5] = {1, 2, 3, 4, 5}". 4) Multidimensional arrays represent matrices and are declared like "type arrayName[rowSize][columnSize]".

Uploaded by

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

C++ Note Array and String

The document discusses arrays in C++. Some key points: 1) Arrays allow storing multiple values of the same type using a single name. Elements are accessed via an index. 2) Arrays are declared with the syntax "type arrayName[size]". For example, "int numbers[100]". 3) Values can be initialized in the declaration like "int arr[5] = {1, 2, 3, 4, 5}". 4) Multidimensional arrays represent matrices and are declared like "type arrayName[rowSize][columnSize]".

Uploaded by

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

CHAPTER 4

▪ The elements of an array are related by the fact that


they have the same array name and type.
▪ The number used to refer to a particular element of
an array is called its index or subscript.
▪ Arrays are blocks of static memory of a given size. A
typical declaration for an array in C++ syntax is:
type arrayName[size];

▪ For example, to declare an array A as shown above:


int A[5];

Computer Programming 3/20/2021 2


▪ The array size used to declare an array must be a
constant expression in standard C++.
▪ For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong

▪ But it is all right if SIZE is a constant as follows:


const int SIZE = 4;
double myList[SIZE]; // Correct

▪ If arrays have the same element type, they can be declared


together that are separated by commas.
For example,
double listA[10], listB[25];

Computer Programming 3/20/2021 3


We can assign values to members of an array at the
point of declaration using the following syntax:
type arrayName[arraySize] = {value0, value1, ..., valuek};

▪ For example, int A[5] = {11, 3, 5, 7, 9};


▪ This is called the array initializer, declares and initializes
the array A with 5 elements in a single statement, making
it equivalent to the statements shown below:
int A[5];
A[0] = 11;
A[1] = 3;
A[2] = 5;
A[3] = 7;
A[4] = 9;
Computer Programming 3/20/2021 4
▪ When declaring an array of local scope (within a function),
if we do not specify otherwise, it will not be initialized, so its
content is undetermined until we store some values on it.
▪ If we declare a global array (outside any function) its
content will be initialized with all its elements filled with
zeros. Thus, if in the global scope we declared:

int billy [5];


▪ When we declare an Array, we have the possibility to assign
initial values to each one of its elements.

int billy [5] = { 16, 2, 77, 40, 12071 };


This looks like:

Computer Programming 3/20/2021 5


Example: Finding the Maximum of 100 randomly assigned integers.
#include <iostream.h>
int main()
{
int i, max = 0;
int list[100];
// initialize the array with random values
for(i=0; i<100; i++) list[i] = rand();
// find maximum value
for(i=0; i<100; i++)
if(max < list[i]) max = list[i];
cout << “Maximum value: “ << max;

return(0);
}
Computer Programming 3/20/2021 6
▪ Using an array initializer, Splitting the declaration
and initialization parts would cause a syntax error.
▪ Thus, the next statement is wrong:
double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
▪ C++ allows you to omit the array size when declaring
and creating an array using an initializer.
▪ For example, the following declaration is fine because
the compiler automatically figures out how many elements
are in the array:

double myList[] = {1.9, 2.9, 3.4, 3.5};

Computer Programming 3/20/2021 7


▪ No Array-to-Array Assignments
You cannot assign one array to another in C++.
The following is wrong:
int a[10], b[10];
// Now, assign all elements of
// array b to array a
a = b; // error – illegal
Instead, you have to do the assignments for each
element:
int i;
// Now, assign all elements of
// array b to array a
for(i=0; i<10; i++) a[i] = b[i];
Computer Programming 3/20/2021 8
▪ Each element in the array is represented using the
following syntax:
arrayName[index];

▪ For example, storing 75 in the third element of array A:

A[2] = 75;
▪ And passing the third element of A value to the variable a,
we could write:

a = A[2];
▪ We can use loop to manipulate/process an array.

Computer Programming 3/20/2021 9


▪ The most common multidimensional array is an array
of dimension 2. It is called matrix. The syntax is:
type arrayName[rowSize][columnSize];

▪ For example, declaring an array B as shown above:


int B[3][5];
▪ B represents a 3 by 5 bidimensional array of type integer

Computer Programming 3/20/2021 10


Example - 2D vs. 1D arrays.
// 1. multidimensional array // 2. pseudo-multidimensional array
#include <iostream.h> #include <iostream.h>
#define WIDTH 5 #define WIDTH 5
#define HEIGHT 3 #define HEIGHT 3
int jimmy [HEIGHT][WIDTH]; int jimmy [HEIGHT * WIDTH];
int n, m; int n, m;
int main ( ) { int main ( ) {
for (n=0; n<HEIGHT; n++) for (n=0; n<HEIGHT; n++)
for (m=0; m<WIDTH; m++) { for (m=0; m<WIDTH; m++) {
jimmy[n][m]=(n+1)*(m+1); jimmy[n * WIDTH + m]=(n+1)*(m+1);
} }
return 0; return 0;
} }
Computer Programming 3/20/2021 11
▪ Multidimensional arrays are just an abstraction, since we
can simply obtain such results with a simple array with a
factor between its indices:
int jimmy [3][5]; is equivalent to
int jimmy [15]; (3 * 5 = 15)
▪ with the only difference that the compiler remembers for us
the depth of each imaginary dimension.
▪ In both cases, you can assign values to the memory block
called jimmy in the following way:

Computer Programming 3/20/2021 12


▪ C++ allows arrays with more than two dimensions.
The syntax for an N-dimensional array declaration is:
type array_name [size_1] [size_2] … [size_N];
▪ For example, the following declaration creates a
4 x 10 x 20 character array, or a matrix of strings:
char string_matrix[4][10][20];
▪ Memory Allocation: Storage for all array elements is
determined at compile time. A char allocates 1 byte.
▪ This requires 4 * 10 * 20 = 800 bytes.

Computer Programming 3/20/2021 13


Computer Programming 3/20/2021 14
▪ strings of characters allow to represent sequences of
characters, like: words, sentences, texts, et cetera.
▪ The most common use for one-dimensional arrays is to store
strings of characters.

▪ In C++, a string is defined as a character array terminated by


a null symbol ( ‘\0’ ).

▪ For example, to declare an array str that could hold a


5-character string as shown above:
char str[6];
▪ The size is 6 making room for the null at the end of the string

Computer Programming 3/20/2021 15


▪ Some examples of string constants in C++ are:

Example: strings Output


"hello there" hello there
"I like C++." I like C++.
"#$%§@@+*" #$%§@@+*
"\"" "
"\"\"" ""
"\\" \
"" null

▪ The null string, "", only contains the null terminator


and represents the empty string.

Computer Programming 3/20/2021 16


▪ Make an array, that will receive the string, the target of
a cin stream. The following program reads (part of) a
string entered by the user:
#include <stdio.h>
int main()
{
char str[80];
cout << “Enter a string: ”;
cin >> str; // read string from keyboard
cout << “Here is your string: ”;
cout << str;

return(0);
}

Computer Programming 3/20/2021 17


▪ Problem: Entering the string “This is a test”, the above
program only returns “This”, not the entire sentence.
▪ Reason: The C++ input/output system stops reading a
string when the first whitespace character is encountered.
▪ Solution: Use another C++ library function, gets().
#include <iostream.h>
#include <cstdio.h>
int main()
{
char str[80]; // long enough for user input?
cout << “Enter a string: ”;
gets(str); // read a string from the keyboard
cout << “Here is your string: ”;
cout << str << endl;
return(0);
}
Computer Programming 3/20/2021 18
▪ C++ supports a range of string-manipulation functions.

▪ The most common are:

• strcpy() : copy characters from one string to another


• strcat() : concatenation of strings
• strlen() : length of a string
• strcmp() : comparison of strings
▪ First of all, include <cstring.h> or include <string> in the
very first lines of the code.

Computer Programming 3/20/2021 19


▪ strcpy(to_string, from_string) — String Copy :
#include <iostream.h>
#include <cstring.h>
int main()
{
char a[10];
strcpy(a, “hello”);
cout << a;
return(0);
}

Computer Programming 3/20/2021 20


▪ strlen(string) — String Length :

#include <iostream.h> strlen(str) returns the length of


#include <cstdio.h> the string pointed to by str, i.e.,
#include <cstring.h> the number of characters
int main() excluding the null terminator.
{
char str[80];
cout << “Enter a string: “;
gets(str); // let the input is: hello
// Length is: 5
cout << “Length is: “ << strlen(str);
return(0);
}
Computer Programming 3/20/2021 21
▪ strcat(string_1, string_2) — Concatenation of Strings :

#include <iostream.h>
The strcat(s1,s2) function
#include <cstdio.h>
appends s2 to the end of s1.
#include <cstring.h>
String s2 is unchanged.
int main(){
char s1[21], s2[11];
strcpy(s1, “Hello”);
strcpy(s2, “ there”); Displays:
strcat(s1, s2);
Hello there
cout << s1 << endl;
there
cout << s2 << endl;
return(0);
}
Computer Programming 3/20/2021 22
The first string array has to be large enough to hold both strings:
▪ To be on the safe side:
strlen(s1concats2) >= strlen(s1) + strlen(s2)

Computer Programming 3/20/2021 23


▪ strcmp(string_1, string_2) — Comparison of Strings :

The strcmp(str_1, str_2) function compares two


strings and returns the following result:
• str_1 == str_2 :0
• str_1 > str_2 : positive number
• str_1 < str_2 : negative number
The strings are compared lexicographically
(i.e., according to dictionary order), for example:
a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd

Computer Programming 3/20/2021 24


// Comparing strings
#include <iostream.h>
#include <cstring.h>
#include <cstdio.h>
int main(){
char str[80];
cout << “Enter password: “;
gets(str);
if(strcmp(str, “password”)) // strings differ
cout << “Invalid password.\n”;
else cout << “Logged on.\n”;
return(0);
}

Computer Programming 3/20/2021 25

You might also like