Home > Net >  error: ‘imax’ was not declared in this scope
error: ‘imax’ was not declared in this scope

Time:11-22

I'm getting the (main.cpp:15:13: error: ‘imax’ was not declared in this scope) error while compiling this code.

Here's the task:

Given k number and kxk z matrix. Get new b[i] vector which elements are taken from the product of the elements preceding the last max element

#include <iostream>
using namespace std;


int indexMax (int z[20][20], int k){
    for (int i = 0; i < k; i  ){
        int max = z[i][0];
        int imax = 0;
        for(int j = 0; j < k; j  ){
            if (z[i][j]>=max)
            max=z[i][j];
            imax=j;
        }
    }
     return imax;
}
 
int product(int z[20][20], int k){
    int imax=indexMax(z,k);
    int i;
    int P=1;
    for(int j = 0; j < imax-1; j  ){
        P*=z[i][j];
    }
    return P;
}
 
int main()
{
    int z[20][20],b[20],k;
    cout << "k=";
    cin >> k;
    
    cout << "Matrix " << k << "x" << k << ":\n";
    for (int i = 0; i < k; i  ){
        for (int j = 0; j < k; j  ){
            cin >> z[i][j];
        }
    }
    cout << "b[i]:\n";
    for (int i = 0; i < k; i  ){
        b[i] = product(z, k);
        cout << b[i] << " ";
    }
return 0;
}

CodePudding user response:

imax is scoped by the outer for loop and hence not accessible outside it. The fix is to move the declaration outside the for loop (I initialized it here in case k == 0 but leaving the assignment imax = 0 in the loop as to not change behavior):

int indexMax (int z[20][20], int k){
    int imax = 0;
    for (int i = 0; i < k; i  ){
        int max = z[i][0];
        imax = 0;
        for(int j = 0; j < k; j  ){
            if (z[i][j]>=max)
            max=z[i][j];
            imax=j;
        }
    }
    return imax;
}
  •  Tags:  
  • c
  • Related