C++ Online Compiler
Example: Largest Element using Iteration in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Largest Element using Iteration #include <iostream> #include <limits> // Required for numeric_limits int main() { // Step 1: Declare and initialize an array int arr[] = {12, 45, 9, 78, 23, 56}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate array size // Step 2: Initialize 'maxElement' with the smallest possible integer value // or with the first element of the array. // Using numeric_limits<int>::min() handles cases with all negative numbers. int maxElement = std::numeric_limits<int>::min(); // Alternatively, for non-empty arrays, you can initialize with arr[0]: // int maxElement = arr[0]; // Step 3: Iterate through the array for (int i = 0; i < n; ++i) { // Step 4: Compare current element with maxElement if (arr[i] > maxElement) { // Step 5: Update maxElement if a larger element is found maxElement = arr[i]; } } // Step 6: Display the largest element std::cout << "The largest element in the array is: " << maxElement << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS