Loop, Array, String
Loops
In C++, there are two ways to write loops in a program.
Firstly, we can use for
to create a loop for certain times
1 2 3 4 5 6 7 |
|
Secondly, we can use while
, when we don't know exactly how many times to loop.
1 2 3 4 5 6 7 8 9 10 |
|
We can nest up the loops when we want the program to execute for multiple times:
1 2 3 4 5 6 7 8 |
|
Array
When we want to store multiple elements together, we can use an array
1 2 3 4 5 6 7 8 |
|
Also, we can create 2d array
the first dimension is row, the second dimension is column
For example, if the array is
1 2 3
11 12 13
21 22 23
then, the number 3 is at row 0 column 2 (the index of an array starts from 0)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
String
String is sort of like a array of characters.
Similar to how we access an element in an array, we can access a char of the string using [].
1 2 3 4 5 6 7 |
|
In C++, string also have some functions built in.
str.length()
: returns the length of a string.
str.substring(index, len)
: returns a substring from the starting index with given length.
str.substring(index)
: returns a substring from the starting index to the end of the string.
str.find(str2)
: find out the first occurance of str2 in str. (returns string::npos, which is -1)
Practice Problems:
to be completed.