Greeting Everyone
i am a beginner in C++ . i need your assistance in the below codes i have done the code of finding the max value but i am stuck at finding the location of max value.
// Write a program in C++ to input value into a table and
// Find out the maximum value entered in table
// Print the maximum value and its location in the table.
#include <iostream>
usingnamespace std;
int main()
{
int Max_Array[2][3] , Max ;
// Ask the user to input values into a table
for(int rows = 0; rows < 2; rows++)
{
for(int columns = 0; columns < 3; columns++)
{
cout << "Enter the value in a table: "; cin >> Max_Array[rows][columns];
}
}
// Find the maximum value in a table
Max = Max_Array[0][0];
for(int rows = 0; rows < 2; rows++)
{
for(int columns = 0; columns < 3; columns++)
{
if(Max < Max_Array[rows][columns])
{
Max = Max_Array[rows][columns];
}
}
}
cout << "Maximum value is: " << Max;
}
Each time you save the value of Max, you need to save the value of rows and columns.
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Each time you save the value of Max, you need to save the value of rows and columns.
What abstractionanon is saying is that when you redifine the max value, you have to save the row location and the Colum location, of where that value is. This can be done by adding 2 new into variables and just setting them to row and Colum in the if statement in your nested for loop.
-Also in your two for loops it's best to make new variables like I for the outer loop and j for the inner loop, because often you come across problems when you want to call the row size and instead get the looping row size.
// After line 7
int save_row = 0, save_col = 0;
// After line 27
save_row = rows; // We found a new max. Save current row and col
save_col = columns;
// After line 32
cout << "Location of max is " << save_row << "," << save_col << endl;
#include<iostream>
usingnamespace std;
int main(){
int x, y;
cin>>x>>y;
int max_array[x][y];
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
cin>>max_array[i][j]; //input data in the array
}
}
int answer=max_array[0][0];
int ans_x, ans_y;
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
if (answer<max_array[i][j]){
answer = max_array[i][j]; //answer increases
ans_x = i; //here the coordinates of the answer are saved
ans_y = j;
}
}
}
cout<<answer<<endl<<ans_x<<" "<<ans_y; //outputs the data
}