Dynamic Memory Allocation, Array
Task 1: Read 10 integers from the user and store them in an array[1D array]. Then find the largest element in the array.
#include<iostream>
using namespace std;
int main(){
int array[10];
for (int i = 0; i < 10; i++)
{
cout << "Enter number " << i+1 << ": ";
cin >> array[i];
}
for (int i = 0; i < 10; i++)
{
if (array[0] < array[i])
{
array[0] = array[i];
}
}
cout << "\n\nThe largest element = " << array[0];
return 0;
}
Task 2: Read an integer n from the user. Then, read n integers from the user and store them in an array. You can assume that n will not exceed 50. Then, reverse the order of the elements in the array and print them.
#include<iostream>
using namespace std;
int main(){
int n, arr[50];
cout << "Input the number of elements to store in the array : ";
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "Enter number " << i+1 << ": ";
cin >> arr[i];
}
cout << "\nThe values store into the array are : " << endl;
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ,";
}
cout << "\n\nThe values store into the array in reverse are :" << endl;
for (int i = n-1; i >= 0; i--)
{
cout << arr[i] << " ,";
}
cout << endl << endl;
return 0;
}
Task 3: Read 16 integers from the user and store them in an array [2D array]. Then find the largest element in the array.
#include<iostream>
using namespace std;
int main(){
int array[4][4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cout << "Array [" << i+1 << "][" << j+1 << "]:";
cin >> array[i][j];
}
cout << endl;
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (array[0][0] < array[i][j])
{
array[0][0] = array[i][j];
}
}
}
cout << "\n\nThe largest element = " << array[0][0];
return 0;
}
0 Comments