473,765 Members | 2,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An "acceptable " use of break

Hello everyone. I am taking my first course in C and in one of my
assignments
i need to print out an array that could have anywhere from 0 to 100
positive integers in it (a negative integer is used to stop input),
and i have to print 8 integers per line. The code that i have works,
and does exactly that, but i feel a little uneasy because i am using
two breaks. I would like to hear any comments about this approach, and
what i might do to make the code more elegant/readable. Thanks in
advance.

/* output the numbers entered. only print 8 numbers per line */
printf ("Numbers Entered:\n");
for (i = 0; i < MAX/8; ++i) {
for (j = pos; j < pos + 8; ++j) {
if (list[j] >= 0)
printf ("%-6d ", list[j]);
else
break;
}
if (list[j] < 0) {
printf ("\n");
break;
}
else {
printf ("\n");
pos += 8;
}
}

-Chris Potter
"Mind over matter: if you don't mind, then it doesn't matter"
Nov 13 '05 #1
26 2524
Chris Potter <ki**********@y ahoo.com> wrote:
Hello everyone. I am taking my first course in C and in one of my
assignments
i need to print out an array that could have anywhere from 0 to 100
positive integers in it (a negative integer is used to stop input),
and i have to print 8 integers per line. The code that i have works,
and does exactly that, but i feel a little uneasy because i am using
two breaks. I would like to hear any comments about this approach, and
what i might do to make the code more elegant/readable. Thanks in
advance. /* output the numbers entered. only print 8 numbers per line */
printf ("Numbers Entered:\n");
for (i = 0; i < MAX/8; ++i) {
for (j = pos; j < pos + 8; ++j) {
if (list[j] >= 0)
printf ("%-6d ", list[j]);
else
break;
}
if (list[j] < 0) {
printf ("\n");
break;
}
else {
printf ("\n");
pos += 8;
}
}


How about:

for(i = 0; (i < MAX) && (list[i] >= 0); i++)
{
printf("\t%d", list[i]);
if((i + 1) % 8 == 0)
putchar('\n');
}

if((i + 1) % 8 != 0)
putchar('\n');
Alex
Nov 13 '05 #2
Chris Potter wrote:
Hello everyone. I am taking my first course in C and in one of my
assignments
i need to print out an array that could have anywhere from 0 to 100
positive integers in it (a negative integer is used to stop input),
and i have to print 8 integers per line. The code that i have works,
and does exactly that, but i feel a little uneasy because i am using
two breaks.


Just to get a clear definition of what your code must do:

* according to your code, a zero can be printed and does not terminate
the list (i.e., the 'positive' in your problem definition should read
'non-negative'). Is this correct?
* is it already guaranteed that the list will contain a negative
number at the end? In that case, your 'list' array should be
able to hold 101 values, and the compare with MAX is unnecessary.
* should a newline be printed when the list contains zero non-negative
(or positive) elements?
* should a newline be printed at the end when the number of non-negative
(or positive) elements in your list is not divisible by eight?
* how many newlines must be printed at the end when the number of
non-negative (or positive) elements in your list is non-zero, but
divisible by eight?

A big part of the learning experience in exercises like these is
thinking about these boundary cases, and making sure these are properly
handled. If you provide answers, I'll try to come up with the smallest
C program that does this, probably using one 'for' loop and zero
'break's. That way, it's a nice exercise for me as well :-)

Best regards,

Sidney

Nov 13 '05 #3
Chris Potter wrote:
Hello everyone. I am taking my first course in C and in one of my
assignments
i need to print out an array that could have anywhere from 0 to 100
positive integers in it (a negative integer is used to stop input),
and i have to print 8 integers per line. The code that i have works,
and does exactly that, but i feel a little uneasy because i am using
two breaks. I would like to hear any comments about this approach, and
what i might do to make the code more elegant/readable. Thanks in
advance.

/* output the numbers entered. only print 8 numbers per line */
printf ("Numbers Entered:\n");
for (i = 0; i < MAX/8; ++i) {
for (j = pos; j < pos + 8; ++j) {
if (list[j] >= 0)
printf ("%-6d ", list[j]);
else
break;
}
if (list[j] < 0) {
printf ("\n");
break;
}
else {
printf ("\n");
pos += 8;
}
}

-Chris Potter
"Mind over matter: if you don't mind, then it doesn't matter"

i'm kind of new to C also, but how about this code:
is it acceptable, efficient... and so on. thanx.

#include <stdio.h>

#define MAX 101
main()
{
int list[MAX];
int counter = 0;
printf("Enter numbers from 0-100 (-1 or > 100) to exit: ");
do {
scanf("%d", &list[counter]);
}while((list[counter] >= 0)&&(list[counter]<=MAX-1)&&(counter++ < MAX));

int j;
for (j = 0; j < MAX; j++) {
if (j % 8 == 0)
putchar('\n');
if (j > 0 && list[j] <= 0 || list[j] > MAX -1)
break;
printf("%-6d", list[j]);
}
putchar('\n');
}
Nov 13 '05 #4
ki**********@ya hoo.com (Chris Potter) wrote:
Hello everyone. I am taking my first course in C and in one of my
assignments
i need to print out an array that could have anywhere from 0 to 100
positive integers in it (a negative integer is used to stop input),
and i have to print 8 integers per line. The code that i have works,
and does exactly that, but i feel a little uneasy because i am using
two breaks. I would like to hear any comments about this approach, and
what i might do to make the code more elegant/readable. Thanks in
advance.

/* output the numbers entered. only print 8 numbers per line */
printf ("Numbers Entered:\n");
for (i = 0; i < MAX/8; ++i) {
for (j = pos; j < pos + 8; ++j) {
if (list[j] >= 0)
printf ("%-6d ", list[j]);
else
break;
}
if (list[j] < 0) {
printf ("\n");
break;
}
else {
printf ("\n");
pos += 8;
}
}


There's nothing really wrong with that. It just, ah... lacks a
bit in the area of elegance. (But you knew that.)

printf ("Numbers Entered:");
#define NL_MASK 7
for (i = 0;i < MAX; ++i) {
if (list[i] < 0) break;
printf ("%c%-6d", (i & NL_MASK) ? ' ' : '\n', list[i]);
}
printf ("\n");

However, that is not without its quirks. If NL_MASK is defined
as 3, you'll get 4 columns; and if it is defined as 15 you'll
get 16 columns. But other numbers in between do not work. I'll
leave that as an exercise for you to figure out. (Think of
NL_MASK as a bit mask, and pay attention to the least
significant bit, and it will become obvious.)

To make it work with any number of columns, I'd suggest using
another variable, incremented when i is incremented, but reset
to zero when a newline is output. It ends up with two variables
rather than the three you were using, but there will only be one
loop instead of two.

printf ("Numbers Entered:");
#define NL_MASK 8
for (i = 0, j = 0; i < MAX; ++i, ++j) {
if (list[i] < 0) break;
printf ("%c%-6d", j ? ' ' : '\n', list[i]);
if (NL_MASK == j) j = -1;
}
printf ("\n");

--
Floyd L. Davidson <http://web.newsguy.com/floyd_davidson>
Ukpeagvik (Barrow, Alaska) fl***@barrow.co m
Nov 13 '05 #5
Hello Sidney. Sorry about the ambiguity.
* according to your code, a zero can be printed and does not terminate
the list (i.e., the 'positive' in your problem definition should read
'non-negative'). Is this correct?
The Code should permit a zero to be printed, so you are correct that i
should have stated "non-negative".
* is it already guaranteed that the list will contain a negative
number at the end? In that case, your 'list' array should be
able to hold 101 values, and the compare with MAX is unnecessary.
There is not a negative value at the end of list[] by default.The user
enters that whenever they are ready to stop input. (i realize that if the
user only enters a few numbers that the rest of the array would be
"wasted" memory, but we haven't gotten to any memory allocation techniques
yet.)
* should a newline be printed when the list contains zero non-negative
(or positive) elements?
The exercise itself is not that precisely defined. What i think should
happen is that the output will display 8 of the "non-negative" integers
enterd, and then a newline. If there are none to be output then i think
one newline would be correct.
* should a newline be printed at the end when the number of non-negative
(or positive) elements in your list is not divisible by eight?
Again, the exercise was not defined that precisely, but i think that would
be the right way to do it. That is the way the code i have now outputs it.
* how many newlines must be printed at the end when the number of
non-negative (or positive) elements in your list is non-zero, but
divisible by eight?


I'm not sure that i understand your question, but if i do understand it,
there should be one newline per 8 integers printed.

Here is the exact wording of the exercise i am working with:

"Write a program that reads an array of at most 100 positive integers.
The user will indicate the end of input by entering a negative number. The
program should then output the list of numbers, eight numbers per line."

Thanks for the tips/info/help.

-Chris
"Mind over matter: if you don't mind then it doesn't matter"

Nov 13 '05 #6
Chris wrote:
* should a newline be printed when the list contains zero non-negative
(or positive) elements?
Typically, no. This is like asking whether 'echo' should print a newline
when given an empty argument list.

[snip]* should a newline be printed at the end when the number of non-negative
(or positive) elements in your list is not divisible by eight?
Typically, yes, you should always print a newline at the end of each
line of output.

[snip]* how many newlines must be printed at the end when the number of
non-negative (or positive) elements in your list is non-zero, but
divisible by eight?


Typically, just one, at the end of the last full line of output.

/david

--
"As a scientist, Throckmorton knew that if he were ever to break wind in
the echo chamber, he would never hear the end of it."

Nov 13 '05 #7
Floyd Davidson wrote:

[snip - a solution]
There's nothing really wrong with that. It just, ah... lacks a
bit in the area of elegance. (But you knew that.)

printf ("Numbers Entered:");
#define NL_MASK 7
for (i = 0;i < MAX; ++i) {
if (list[i] < 0) break;
printf ("%c%-6d", (i & NL_MASK) ? ' ' : '\n', list[i]);
}
printf ("\n");


Don't confuse elegence with l33t-ness. The 'problem' you are trying to
avoid is modular division. While % is usually regarded as a 'slow'
operation, there is really no sense in sidestepping it when performance
is not an issue. The code above relies on a trick to perform modular
division by 8. However, the code is neither readable, nor robust.

How about simply

/*
* print up to max non-negative numbers from list
* at npl numbers per line
*/
void
show(int list[], int max, int npl)
{
int i, j;

for(i=0, j=0; i < max && list[i] >= 0; ++i){
printf("%d", list[i]);
if(++j == npl){
putchar('\n');
j = 0;
}else
putchar(' ');
}
if(j > 0)
putchar('\n');
}

/david

--
"As a scientist, Throckmorton knew that if he were ever to break wind in
the echo chamber, he would never hear the end of it."

Nov 13 '05 #8
On Wed, 05 Nov 2003 17:13:52 -0800, Chris Potter wrote:
i need to print out an array that could have anywhere from 0 to 100
positive integers in it (a negative integer is used to stop input),
and i have to print 8 integers per line. The code that i have works,
and does exactly that, but i feel a little uneasy because i am using
two breaks. I would like to hear any comments about this approach, and
what i might do to make the code more elegant/readable. Thanks in
advance.

/* output the numbers entered. only print 8 numbers per line */
printf ("Numbers Entered:\n");
for (i = 0; i < MAX/8; ++i) {
for (j = pos; j < pos + 8; ++j) {
if (list[j] >= 0)
printf ("%-6d ", list[j]);
else
break;
}
if (list[j] < 0) {
printf ("\n");
break;
}
else {
printf ("\n");
pos += 8;
}
}


This code has a subtle bug.
Hint: try changing MAX to 12 and entering 10 numbers

As for your question, you are right. The two breaks in the code is a bit
clumsy. One break leaves the inner loop, where you then immediately test
for the break condition again and then break again. A cleaner way to do
this is:

/* Note: this code also has the bug, I'm going to let you find
it yourself with my hint. */

for (i = 0; i < MAX/8; ++i) {
for (j = pos; j < pos + 8; ++j) {
if (list[j] >= 0)
printf ("%-6d ", list[j]);
else
goto end_of_loop;
}

printf ("\n");
pos += 8;
}

end_of_loop:
printf("\n");

Now this approach might give your instructor a heart attack, and it
really is not very nice, but it *is* better than your double break.
An approach better than either of these would be to use a single loop
and just test for when it's time to print a newline:

i = 0;
while (i < MAX && list[i] >= 0)
{
printf("%-6d", list[i]);

i += 1;
if (i % 8 == 0)
putchar('\n');
else
putchar(' ');
}

if (i > 0 && i % 8 != 0)
putchar('\n');

-Sheldon

Nov 13 '05 #9
On Wed, 05 Nov 2003 21:15:12 -0500, Andy wrote:
i'm kind of new to C also, but how about this code:
is it acceptable, efficient... and so on. thanx.

#include <stdio.h>

#define MAX 101
main()
Write it this way:
int main (void)
{
int list[MAX];
int counter = 0;
printf("Enter numbers from 0-100 (-1 or > 100) to exit: ");
do {
scanf("%d", &list[counter]);
}while((list[counter] >= 0)&&(list[counter]<=MAX-1)&&(counter++ < MAX));

int j; ^^^^^
Be careful. Declarations mixed in with code are allowed in the current C
standard, but some compilers do not allow it yet. Why not just put it up
at the top before the declaration of list?
for (j = 0; j < MAX; j++) {
You know that there are exactly 'counter' numbers. Why are you bothering
to loop through the entire array?
if (j % 8 == 0)
putchar('\n');
if (j > 0 && list[j] <= 0 || list[j] > MAX -1)
I would suggest some extra parentheses in this if-condition. I suspect
this condition tests something slightly different that you think it does.

I'm not quite sure why you are testing for j > 0 anyway. If the first
number I type is -1, then your code will print the -1. Is that what you
want?

Lastly, this condition will prevent integers with the value 0 from
being printed. You probably don't want that.
break;
printf("%-6d", list[j]);
}
putchar('\n');
Add this:
return 0;
}


After all that nitpicking, I should say that your code isn't awful. It
works almost (not completely) correctly, and I like that you used a single
loop with the % operator.

-Sheldon
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
3578
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else: print "Empty list" which was supposed to be:
3
4227
by: Hodad | last post by:
I would like to adapt, as much as possible, the appearance and color red of the font in this button: <P><CENTER><BUTTON VALUE="SUBMIT"><A HREF="http://www.familytreedna.com/surname_join.asp?code=Q17978" STYLE="TEXT-DECORATION: NONE;"> <FONT COLOR="RED" FACE="COPPERPLATE GOTHIC BOLD">Right Here</FONT></A></BUTTON></CENTER></P>
28
3427
by: Act | last post by:
Why is it suggested to not define data members as "protected"? Thanks for help!
81
7342
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
2
1720
by: jim_geissman | last post by:
Some columns in transaction tables are "mandatory fields" on the data entry screens, and as a result tend to accumulate junk entries, where the user puts something, anything, in the window in order to get the GUI to accept the screen. This filler isn't as elaborate as Lorem Ipsum, but more likely characters from adjacent keys on the second row of the keyboard, like "lkjkljl". This non-data gets in the way of applications that use the...
20
4320
by: AndyZa | last post by:
Is the following html valid? <p><hr width="50%"></p> Or would the following be more "technically correct"? <p> <hr width="50%"> Do I require the closing </p> tag?
11
1853
by: moltendorf | last post by:
Hey everyone, as I have been by far pleased with some of the top helpers on this forum, I have decided to send another one your way. Even though I am personally having minimal issues with this script I have developed, I am wondering if someone could fix my little bug with it. This script runs perfectly fine, except once in a while, the color changing will "pause" because (according to Mozilla Firefox 3's error console) it is putting out...
13
1945
by: Boris | last post by:
Can anyone tell me if Opera 9.5 is behaving correctly when wrapping the word C++, eg: C+ + Opera 9.2 didn't wrap C++. For those who use Opera 9.5 there is a test case at http://www.highscore.de/browsertest/cpp.html (try different window sizes until Opera 9.5 wraps C++).
18
2457
by: Stephan Beal | last post by:
Hi, all! Before i ask my question, i want to clarify that my question is not about the code i will show, but about what the C Standard says should happen. A week or so ago it occurred to me that one can implement a very basic form of subclassing in C (the gurus certainly already know this, but it was news to me). What i've done (shown below) seems to work all fine and well, and does exactly what i'd expect, but i'm asking about
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.