Lecture 4 - Arrays, Numbers and Strings
Lecture 4 - Arrays, Numbers and Strings
● Multi-dimensional array
Multidimensional arrays
● A multidimensional array can be two dimensional array, three
dimensional array etc.
● Two dimensional array
○ int arr[2][3];
○ This array has total 2*3 = 6 elements.
● Three dimensional array
○ int arr[2][2][2];
○ This array has total 2*2*2 = 8 elements.
Two dimensional arrays
1. #include <iostream>
2. using namespace std;
3. int main(){
4. char book[50] = "I can, I must, I will";
5. cout<<book;
6.return 0; 7.
}
8.
Creating Strings as array of characters
● Output:
1. Enter your favorite book name: Rich dad, poor dad
2. You entered: Rich
● The problem here is that only the word “Rich” got captured in
the variable book and remaining part after space got
ignored.
● In order to solve this problem we can use cin.get function,
which reads the complete line entered by user
Getting user input as string
1. #include <iostream>
2. using namespace std;
3. int main(){
4. char book[50];
5. cout<<"Enter your favorite book name:";
6.
7. //reading user input
8. cin.get(book, 50);
9. cout<<"You entered: "<<book;
10. return 0;
11. }
Getting user input as string
● Output:
○ Enter your favorite book name: My life, my purpose;
the president remembers
○ You entered: My life, my purpose; the president
remembers
Getting user input as string
● Size of the char array is fixed, which means the size of the string created
through it is fixed in size, more memory cannot be allocated to it during
runtime.
○ E.g., if you create an array of characters of size 20 and user enters the string
of size 25, the last five characters would be truncated from the string.
○ Also, if you create a larger array to accommodate user input then the
memory is wasted if the user input is small and array is much larger then
what is needed.
● In this method, you can only use the in-built functions created for array which
is not convenient for string manipulation.
Using the string object in creating strings