find largest number in each row in array c++ using function
Here is an example of how you can find the largest number in each row of a 2D array in C++ using a function:
#include <iostream>
using namespace std;
const int ROWS = 3;
const int COLS = 4;
void findLargestNumber(int arr[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
int maxNum = arr[i][0];
for (int j = 1; j < COLS; j++) {
if (arr[i][j] > maxNum) {
maxNum = arr[i][j];
}
}
cout << "The largest number in row " << i+1 << " is: " << maxNum << endl;
}
}
int main() {
int arr[ROWS][COLS] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
findLargestNumber(arr);
return 0;
}
Explanation:
1. We start by including the necessary header file iostream
and using the std
namespace for convenience.
2. We define two constants ROWS
and COLS
to represent the dimensions of the 2D array.
3. Next, we declare the function findLargestNumber
which takes a 2D array as a parameter.
4. Inside the function, we use a nested loop to iterate over each row and column of the array.
5. We initialize a variable maxNum
to the first element of each row.
6. Then, we compare each element in the row with the current maxNum
and update maxNum
if a larger element is found.
7. After iterating through each element in the row, we print the maxNum
for that row.
8. In the main
function, we declare a 2D array arr
and initialize it with some values.
9. We call the findLargestNumber
function, passing arr
as an argument.
10. Finally, we return 0 to indicate successful completion of the program.
This program will output the largest number in each row of the array:
The largest number in row 1 is: 4
The largest number in row 2 is: 8
The largest number in row 3 is: 12
Let me know if you have any further questions.