Search code examples
c++arraysalgorithmmaxmin

the value is different inside and outside the for-loop C++


I am a beginner in C++, and I want to write a program that replaces the max value with the min value in an array and vice versa.

    #include<iostream>
    using namespace std;
    int main(){

    int num, arr[200],max,min,max_pos,min_pos;

    cout <<"enter array size: ";
    cin >> num;

    for (int i=0; i<num; i++){
        cout<<"Enter a value in array position "<<i<<" : ";
        cin>>arr[i];
    }

    for(int i=1, max=arr[0], min=arr[0]; i<num; i++){
        if(arr[i]>arr[i-1] && arr[i]>max){
            max = arr[i];
            max_pos = i;
        }

        if(arr[i]<arr[i-1] && arr[i]<min){
            min = arr[i];
            min_pos = i;
        }
    
    cout<<"max_in "<<max<<"||"<<"min_in "<<min<<endl;
    }

    cout<<"max_out "<<max<<"||"<<"min_out "<<min<<endl;



    // arr[min_pos] = max;
    // arr[max_pos] = min;
    // cout<<"max: "<<arr[min_pos]<<" || min: "<<arr[max_pos];

    // cout<<"array is ";
    // for(int i =0; i<num;i++){
    //     cout<<arr[i];}
    }

this is the output

enter how many number you want inside :4
Enter a value in array position 0 : 2
Enter a value in array position 1 : 1
Enter a value in array position 2 : 4
Enter a value in array position 3 : 6
max_in 2||min_in1
max_in 4||min_in1
max_in 6||min_in1
max 561||min -1343285512

I don't know why the values change outside the loop, where is the mistake?


Solution

  • Here

    for (int i=1, max=arr[0], min=arr[0] ;...
    

    You declare 3 variables, they are called i,max and min. max and min shadow the variables of same name declared outside of the loop.

    Do not declare the variables of same name, but use the ones you already declared:

    int max = arr[0];
    int min = arr[0];
    for(int i=1; i<num; i++){
    

    This is a mistake you could have avoided by reading compiler warnings: https://godbolt.org/z/aT753e4nh. Also initializing variables always, and only declare a variable when you can initialize it, would have reduced chances for this kind of mistakes.