0% found this document useful (0 votes)
12 views

array

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

array

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

- One-Dimensional Array Example

#include <iostream>
using namespace std;

int main() {
int numbers[5] = {10, 20, 30, 40, 50};
cout << "One-Dimensional Array Elements:" << endl;
for (int i = 0; i < 5; i++) {
cout << "numbers[" << i << "] = " << numbers[i] <<
endl;
}

return 0;
}

- Array of Strings Example

#include <iostream>
#include <string>
using namespace std;

int main() {
// Declare and initialize an array of strings
string fruits[3] = {"Apple", "Banana", "Cherry"};

// Display the elements of the string array


cout << "Array of Strings:" << endl;
for (int i = 0; i < 3; i++) {
cout << "fruits[" << i << "] = " << fruits[i] <<
endl;
}

return 0;
}

- Dynamic Array Example

#include <iostream>
using namespace std;
int main() {
int size;

// Ask user for array size


cout << "Enter the size of the array: ";
cin >> size;

// Dynamically allocate an array


int* array = new int[size];

// Initialize array with values


for (int i = 0; i < size; i++) {
array[i] = i + 1;
}

// Display array elements


cout << "Dynamic Array Elements:" << endl;
for (int i = 0; i < size; i++) {
cout << "array[" << i << "] = " << array[i] <<
endl;
}

// Free dynamically allocated memory


delete[] array;

return 0;
}

- C++ Code for 2D Array


#include <iostream>
using namespace std;

int main() {
// 1. Declare and initialize a 2D array
int array[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// 2. Display the 2D array elements
cout << "2D Array Elements:" << endl;
for (int i = 0; i < 3; i++) { // Iterate over rows
for (int j = 0; j < 3; j++) { // Iterate over
columns
cout << array[i][j] << " ";
}
cout << endl; // Move to the next line after each
row
}

// 3. Modify an element in the 2D array


array[1][1] = 10; // Change the middle element to 10

// 4. Display the updated array


cout << "\nUpdated 2D Array Elements:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << array[i][j] << " ";
}
cout << endl;
}

return 0;
}

You might also like