Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

error: ‘imax’ was not declared in this scope

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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;
}

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading