# Thread: Need help breaking from a program

1. ## Need help breaking from a program

The code below works out the area under a curve using a series of trapezium's areas. This means that the x coordinates must be in increasing order (y coords dont have to be).

If an x value is entered that is less than the previous the code breaks and doesnt ask for the next x value, but DOES ask for all the y values. How can i rewrite this code so that it breaks completely, asking if the user wants to try again?

Code:
```#include <stdio.h>
int main()
#define N 15
{
int i, sets;
float x[N], y[N], area;
char again='Y';
while(again=='y'||again=='Y')
{
area=0;

printf("This is a program to integrate using the trapezium rule\n");
printf("Enter the number of coordinate sets you wish to use, up to %d\n\n", N);
scanf("%d",&sets);

if(sets<=15 && sets>0)
{
printf("\nType in %d values for the x coordinates\n", sets);
for(i=0; i<=sets-1; i++)
{
scanf("%f", &x[i]);
if(x[i] < x[i-1])
{
printf("The value you entered is less than the previous\n\n");
break;
}
}
printf("Type in %d values for the y coordinates\n", sets);
for(i=0; i<=sets-1; i++) scanf("%f", &y[i]);

for(i=0; i<sets-1; i++)
{
area = area + ((x[i+1]-x[i])*(y[i]+y[i+1]))/2;
}
printf("area is %f\n\n", area);

}
else printf("\nYou have entered an invalid integer\n\n");

printf("Would you like to run the program again?\n");
printf("Type Y or y for yes, anything else for no\n");
again=getchar();
if(again=='\n')again=getchar();
}
return 0;
}```

2. many people might shoot me now but the best solution here is to use "goto"
goto hello;
then before the try again? stuff put
hello:

3. Great, thanks!

4. GOTO?!

Relax, I shall not shoot you. I often see starting programmers using things like break, exit and return on the wrong places, I sometimes even see them using goto. A well-designed program doesn't need to use such things to force exits and that kind of things.

You don't need break here. Introduce a flag. In the conditional part of the for-loop you can check the value of that flag. If the total condition evaluates to FALSE, the for-loop will stop. This flag can be used in other cases.

My suggestion: redesign your program and perhaps use a function. Take pencil and paper and use a flow-chart to visualize the algorithm.

5. >but the best solution here is to use "goto"
While it does get the job done, goto is rarely the best solution. The problem is that it is usually the first and easiest solution that comes to mind with some people and then they don't bother to think of alternatives that are a bit more elegant.

-Prelude

6. I havnt learnt about flags or goto yet, but goto looks very easy. But if it is frowned upon then im uneasy about using it. Can anyone enlighten me on the "proper" methid of rewriting my code using the (all be it basic) standard of coding i have used please?

7. A flag is nothing but a variable which represents a certain state.

A flag could be:

int flag;

You could then decide that 0 is OK and 1 is ERROR. So when checking the value of flag, you check if it's value is 0 or 1. In case of 1, you know that an error occurred.

8. yeah, yeah....
1) a person (me) says "goto" and is not saying "evil" or "that shall not be used" after.
2) all the programers in the world are coming to explain why goto shall be destroyed and why you should build the "perfect" program!

now look here i just said that when you want to break from few loops goto will be much more usefull than this falgs that takes more memory ( goto label statment is only 1 line in assembly!)
and it uses an extra 2 bytes ( very "optimized" programming indeed...)

i suggest that sometimes you (all) should use goto's, breaks and continues, place a comment next to it and it all be clear!

9. i remember that in my school i wrote a program that used a goto (on computers lesson) when the teacher heared this "baaaaaaaaaaaaaaaaaaaaaaaaah" she screamed

so go ahead, take a pen and paper and start breaking your mind for the "optimized" program (that is far from being optimized as explained in my previos post)

i dont like to push people so you all do whatever you want.

10. hell_o:
Please point out where either I or Shiro said that goto was evil. I believe that goto is a simple tool, just like pointers. It has the potential to create bad code, but not if used correctly, just like everything else in the language. A legitimate reason that goto is not often the best solution is in both debugging and in machine code generation.

A program with gotos will be more difficult to debug in the long run and some compilers will not be able to optimize code that uses goto as well or as easily as with alternative methods. Anyone who says to never use goto doesn't know what they are talking about and obviously didn't do any research. Those that intelligently explain why goto should be avoided in a certain situation most likely have a good reason for doing so. So please consider your response before snapping at people who are simply trying to help.

-Prelude

11. Goto is the evilest thing I have come across. Except for bunnies.

12. This seems like a fair enough use of goto, personally. The effect of the goto is clear, it won't involve any magic to modify the program without changing the effect of the goto, and I mean, it's just one goto in the program.

It all really just depends on how you are modelling your program. If you're thinking of your program as a state machine (ie, flowchart), then break; continue; and goto X; are most certainly your friends. State machines are intuitive and good for expressing algorithms that aren't too large.

Personally, I'm skeptical about the use of flags to handle program flow like this, and suggest that if you're not going to use goto, use smaller functions that return a value indicating whether the function completed succesfully, and flow your program based on those returns.

Here is a modularized pseudocode version of your code, which handles a bad input for X
Code:
```#include <stdio.h>
int main()
#define N 15
{
int i, sets;
float x[N], y[N], area;
char again='Y';

while(again=='y'||again=='Y')
{
area=0;

printf("This is a program to integrate using the trapezium rule\n");
printf("Enter the number of coordinate sets you wish to use, up to %d\n\n", N);
if (getNumSets() == SUCCESS)
{
if (getX() == SUCCESS);
{
getY();
doMath();
}
}
else printf("\nYou have entered an invalid integer\n\n");

printf("Would you like to run the program again?\n");
printf("Type Y or y for yes, anything else for no\n");
again=getchar();
if(again=='\n')again=getchar();
}
return 0;
}```
If you want to implement that design without splitting your code into functions, it will have to look something like this (this is the method using flags)...
Code:
```#include <stdio.h>
int main()
#define N 15
{
int i, sets;
float x[N], y[N], area;
char again='Y';

int xFlag; // <-- I added this

while(again=='y'||again=='Y')
{

// Blah blah....

xFlag = 1; // <-- added
for(i=0; i<=sets-1; i++)
{
scanf("%f", &x[i]);
if(x[i] < x[i-1])
{
printf("The value you entered is less than the previous\n\n");
xFlag = 0; // <-- added
break;
}
}

// The flag is now 0 if there was a problem, and 1 if there wasn't

printf("Type in %d values for the y coordinates\n", sets);

// Blah Blah...

printf("area is %f\n\n", area);
} // end if (xFlag) // <-- added

}
else printf("\nYou have entered an invalid integer\n\n");

printf("Would you like to run the program again?\n");
printf("Type Y or y for yes, anything else for no\n");
again=getchar();
if(again=='\n')again=getchar();
}
return 0;
}```

13. Yeah, everyone says that goto is evil, but why??
Right, because it is evil.

Show me one Good Designed Programm that need a goto!

If you want to optimize for speed over readability than use goto. But the programmers who have to work with your Code will kill you, because they will spend hours searching all labels for the gotos...

Don't tell me this isn't true, I had to work on some 'goto'-Codes -> it is like hell.

You never know how your compiler optimizes! Maybe the compiler optimizes the 'flag'-Method better than your goto?

I won't suggest beginners to use goto! It is an evil style...

And I've never seen an commercial Application using goto.

14. >i suggest that sometimes you (all) should use goto's, breaks >and continues, place a comment next to it and it all be clear!

For very small programs it probably will be. But when you're doing this with large programs, you'll create a mess. A very important aspect of programming is to create software that is flexible and easy to maintain. So I would advise using functions to split up functionality. Modern computer systems are equipped with a lot of memory and have a relative high speed micoprocessor, so I wouldn't worry too much about optimisation. Unless you're working on time-critical applications. But in that case one or more flags are not the point, the most important point is: designing an efficient algorithm.

>If you're thinking of your program as a state machine (ie, >flowchart), then break; continue; and goto X; are most certainly >your friends. State machines are intuitive and good for >expressing algorithms that aren't too large.

At work I'm daily working on real-time systems and I'm using state machines a lot. But I never use things like continue and goto, ofcourse I use break in the switch-structures.

In my opinion, when you need continue or goto, you're software is hard to maintain and inflexible.

By the way, you don't always need flags. Ofcourse you could do this:

for (...; ... && x[i] < x[i-1]); ..)

>And I've never seen an commercial Application using goto.

This is not an argument for not using goto. But you could think about: why don't they use goto in commercial applications?

Well, at some time when you have some more programming experience you'll note that there are far better solutions than goto. And you'll see the advantages of not using goto and other such kind of constructions.