------------1D.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int arr [5] = {1, 3, 5, 7, 9};
cout<<"The array elements are: \n";
for (int i = 0; i < 5; i++)
{
cout << arr[i] << " ";
}
cout << "\n";
int sum = 0, avg = 0;
int num [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} ;
for (int i = 0; i < 10; i++ )
{
sum = sum + num [i] ;
}
cout << "Sum of all elements is: " << sum ;
avg = sum / 10 ;
cout << "\n Average is: " << avg ;
return 0;
}
------------2D.cpp
// C++ Program to implement Jagged Array
// 1st way: static arrays
#include <iostream>
using namespace std;
int main()
{
// create 3 row arrays having different sizes
// ( no ofcolumns)
int row1[] = { 1, 2, 3, 4 };
int row2[] = { 5, 6 };
int row3[] = { 7, 8, 9 };
// storing base address of each row array
int* jagged[] = { row1, row2, row3 };
int sizes[] = { 4, 2, 3 };
cout << "elements in matrix form as follow" << endl;
for (int i = 0; i < 3; i++) {
// getting current(ith) row
int* ptr = jagged[i];
for (int j = 0; j < sizes[i]; j++) {
// for ith row having sizes[i] no. of
// columns
cout << *(ptr + j) << " ";
// *ptr have base address
// adding j means access jth
// element for particular(ith) row
}
cout << endl;
}
return 0;
}
------------1D_Dynamic.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
int* arr = new int[5]{1, 3, 5, 7, 9};
cout << "The array elements are: \n";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << "\n";
delete[] arr;
int sum = 0, avg = 0;
int* num = new int[10]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 10; i++) {
sum = sum + num[i];
}
cout << "Sum of all elements is: " << sum;
avg = sum / 10;
cout << "\nAverage is: " << avg;
delete[] num;
return 0;
}
------------2D_Dynamic.cpp
#include <iostream>
int main() {
int **arr = new int*[5];
for (int i = 0; i < 5; ++i)
{
arr[i] = new int[5];
}
std::cout << "Enter 2D array elements (5x5):\n";
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
std::cin >> arr[i][j];
}
}
std::cout << "The array elements are: \n";
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
std::cout << arr[i][j] << " ";
}
std::cout << "\n";
}
// Free memory
for (int i = 0; i < 5; ++i)
{
delete[] arr[i];
}
delete[] arr;
return 0;
}
No comments:
Post a Comment
Fell free to write your query in comment. Your Comments will be fully encouraged.