xdarkestshadow
xdarkestshadow

Reputation: 25

Finding max element which is to the right of column 'k'

I have a task where I am asked to find max element which is to the right of column 'k' (as I understand, I need to find the maximum in k+1 column). I am clearly doing something wrong because when I run the code max value is equal to 0. There has to be a mistake I am missing so any help would be appreciated. This is my code:

#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;

int main() {
 int n,m,k;
 int max=-1000001;
 int  a[10][10];
 cin>>n>>k;
 m=n;
  for (int i=0;i<n;i++) {
   for (int j=0;j<m;j++) {
     cin>>a[i][j];
   }
 }
 for(int i=0;i<n;i++)
{
       for (int j=0;j<m+1;j++)
       {
        if(a[i][j]>max && a[i][j]!=max && j==k+1)
        max=a[i][j];
       } 
}
  if (k>=m)
     cout<<"No";
  else
     cout<<max;    
}

This is the input:

3 2
1 2 3
5 5 2
6 3 4

This is the output I should get:

4

Upvotes: 0

Views: 72

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

To get the expected output you want it is enough to write

int max = a[0][k+1];

for ( int i = 1; i < n; i++ )
{
    if ( max < a[i][k+1] ) max = a[i][k+1];
}

I assume that k + 1 is less than m. That is this check

if (k>=m) cout<<"No";

shall be done before the loop. For example

int max;

if ( k + 1 < m )
{
    max = a[0][k+1];

    for ( int i = 1; i < n; i++ )
    {
        if ( max < a[i][k+1] ) max = a[i][k+1];
    }
}

if ( not ( k + 1 < m ) )
    cout<<"No";
else
    cout<<max;    

And for this input

3 2

the program shall issue "No" because k + 1 when k is equal to 2 yields 3 and 3 is not a valid index. The range of valid indices for this input is [0, 2].

You can get the expected result using the presented code in my answer for this input

3 1

Upvotes: 1

Related Questions