C++ Online Compiler
Example: FindLargestDynamicArrayManual in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// FindLargestDynamicArrayManual #include <iostream> using namespace std; int main() { int size; // Step 1: Get array size from user cout << "Enter the number of elements: "; cin >> size; // Step 2: Validate size if (size <= 0) { cout << "Array size must be positive." << endl; return 1; // Indicate an error } // Step 3: Dynamically allocate memory for the array int* arr = new int[size]; // Step 4: Get elements from the user cout << "Enter " << size << " elements:" << endl; for (int i = 0; i < size; ++i) { cout << "Element " << i + 1 << ": "; cin >> arr[i]; } // Step 5: Find the largest element int largest = arr[0]; // Assume the first element is the largest initially for (int i = 1; i < size; ++i) { if (arr[i] > largest) { largest = arr[i]; } } // Step 6: Display the largest element cout << "The largest element is: " << largest << endl; // Step 7: Deallocate the dynamically allocated memory delete[] arr; arr = nullptr; // Good practice to set pointer to nullptr after deletion return 0; }
Output
Clear
ADVERTISEMENTS