LESSON: DATA TYPES(3)
TOPICS: MULTIDIMENSIONAL ARRAYS & C-STYLE STRINGS
Adz
2.
WHAT IS AMULTIDIMENSIONAL ARRAY?
A multidimensional array is an array containing other arrays.
The most common type is the two-dimensional (2D) array, which works like a table
or matrix — with rows and columns.
Example Concept:
A 2D array looks like this:
Col 0 Col 1 Col 2
Row 0 10 20 30
Row 1 40 50 60
int numbers[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
3.
Syntax of a2D Array
dataType arrayName[rows][columns];
Example:
int matrix[3][4];
This means a 3x4 array 3 rows and 4 columns.
→
4.
Example Program 1— Displaying a 2D Array
#include <iostream>
using namespace std;
int main() {
int numbers[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
cout << "2D Array Elements:n";
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
cout << numbers[row][col] << " ";
}
cout << endl;
}
return 0;
}
Output:
2D Array Elements:
10 20 30
40 50 60
5.
C-STYLE STRINGS
What isa C-Style String?
A C-style string is an array of characters ending with a null character (‘0’).
Example:
char name[6] = "Hello";
H e l l o 0
6.
Syntax
char stringName[size];
Example:
char city[10]= "Manila";
Example 2: Simple Input/Output
#include <iostream>
using namespace std;
int main() {
char name[20];
cout << "Enter your name: ";
cin >> name; // reads input until space
cout << "Hello, " << name << "!";
return 0;
}
Enter your name: Hello, !
7.
String Library Functions
Touse built-in string functions, include:
#include <cstring>
Function Description Example
strlen(str) Returns length strlen("Hello") → 5
strcpy(dest, src) Copies one string to another strcpy(a, b)
strcat(a, b) Combines two strings
"Hi" + "There" →
"HiThere"
strcmp(a, b) Compares strings 0 if equal
8.
Example Program —String Functions
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
strcat(str1, str2);
cout << "After concatenation: " << str1 << endl;
cout << "Length of string: " << strlen(str1) << endl;
return 0;
}
After concatenation: HelloWorld
Length of string: 10
Output: