Search code examples
c++while-loopreturn

while exercise with return in c++


I've just started coding in c++ and now I have an exercise that I can't do because the code seems to not work. I've to find the max and the min with a sequence of n numbers (in this case i already know that they are 4). I've to use while. I've just started so I don't know how return properly works... there aren't syntactical errors but when I run it ask me the number but then it says that the algorithm ends with 0 value. Here's the code, if you can help me thank you!

#include <iostream>
using namespace std;
main ()
{   float mag,min,i,a;
    mag=0; 
    min=0;
    i=0;
    while (1)
    {
        if (i<5)
        {   cout<<"insert a number"<<endl;
            cin>>a;
            if (i = 0)
            {   mag=a;
                min=a;
            }
            else 
            {   if (a<min)
                {   min=a;
                }
                else
                {   if (a>mag)
                    {   mag=a;
                    }
                }
            }
            i=i+1;
        }
        else
        {   cout<<"maggiore= "<<mag<<endl<<"min= "<<min<<endl;
        }
    return 0;
    }
    system ("pause");
}

Solution

  • I see at minimum one problem:

     if (i = 0)
    

    This is assignment of i to 0 and compare the result of assignment, which is always false if you assign a 0.

    I believe you want only compare and not assign, so you have to use:

     if ( i == 0 )
    

    The next problem is

    return 0;
    

    This will always end the current function, if the function is main(), it will terminate your program. In your case, you can simply remove the return statement, as in main it will return 0 by default if the function ends.

    But if you use

    while (1) 
    

    without any return, your program runs endless. I don't know what is the expected behavior.

    Rest looks fine.

    Hint: Your indentation is a bit special. :-)