skip to Main Content

I am building a quadratic equation solver using c language and i want to stop the program if the user enters 0 as a value for a. How could i do that?

I have tried using break in switch syntax but it doesnt stop the program.

2

Answers


  1. In the main function of your C program just insert

    return <something>
    

    and return whatever you want. If you are calculating that from an other function you will have to insert the return statement in that function and again in the main function.
    The break statement ends the loops.

    It would probably help to see your actual code

    Login or Signup to reply.
  2. The break keyword in a switch-case statement works merely leaves the switch itself, i suppose you are doing a loop of some kind?
    This would be easier with code, but either way, in these cases, while it is also "correct" to use a return statement, it is more apt to declare a variable called a flag that controls the flow of the program:

    int main()
    {
       int flag = 0;
       while (!flag && other_conditions)
       {
           // get value of a
           if (a == 0)
               flag = 1;
           else
           {
                // do the rest
           }
        }
        return flag;
    }
    

    Were this in a function, it works in a very similar fashion in which you must, for example pass a flag by reference and check if that flag is 1 or 0.

    int func(args, int*x)
    {
        if (a == 0)
             *x = 1;
        else
        {
            //code
        }
        return result;
    }
    

    After which in the main function you’d need to check if that value is 1 or 0 and go to the end of the program if it’s 1 continue if it’s not.

    On an addendum, as some users have mentioned, you can indeed use returns and exit statements, however these are considered bad programming practices, at least for a language such as C that is structured, thus should at least attempt to follow the Single Entry Single Exit rule.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search