Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Use of nested loops.

Reply
Thread Tools

Use of nested loops.

 
 
Neptune
Guest
Posts: n/a
 
      11-04-2003
Peter Pichler wrote:
> "Keith Thompson" <(E-Mail Removed)> wrote in message
> news:(E-Mail Removed)...
>
>>BTW, another example of a nested loop might be reading lines from a
>>file, and processing each character in each line. You might use a
>>triple-nested loop to open each of the files named on the command
>>line, reading each line from each file, and processing each character
>>on each line.

>
>
> Neptune, in many cases you use multiple nested loops without even knowing
> it.
>
> Let's look at Keith's a modified example. Open a text file and read and
> print
> each line. You need a loop in which to read a line, test you have
> successfully
> read it and then print it. Inside that loop, you would probably use fgets
> for
> reading and puts or printf for printing. Each of these functions contains at
> least one loop, possibly more than one. So, you may get nested loops simply
> by
> calling a function in a loop. Isn't programming fun


It is fun - that's the attraction (once I get my head around some basic
constructs that is ). I like your example Peter - it makes sense and
touches on something that I will be coming to in due course, but was
already curious about: readin in text files, so this will pre-'arm' me
so to speak.


> To answer your original question, nested loops are used whenever an
> algorithm
> asks for it. Processing more than one-dimensional entities is the most
> common
> example. My example is one of them: the line number could be considered the
> vertical and the position of a character in a line the horizontal dimension.
>


It appears then that (theoretically speaking anyway), there are no
limits to the number of loops one can nest? I cannot think of any
example to illustrate this, but was wondering if one can nest one or two
or five loops, is there a maximum to which one can go before it
discombobulates entirely. I can imagine that there would be logistical
nightmares (indentation running off of the page or line wrapping
endlessly, trying to keep the iterations straight in one's head, even
finding a value to engage in that kind of exercise, etc), so the query
really is theoretical.

Anyway, thanks for your thoughts.


--
"Today a young man on acid realised that all matter was really energy
condensed to a slow vibration, that we are all one consciousness
experiencing itself subjectively, there's no such thing as death,
life is only a dream, and we're the imaginations of ourselves.
Here's Tom with the weather ..." - Bill Hicks.

 
Reply With Quote
 
 
 
 
Neptune
Guest
Posts: n/a
 
      11-04-2003
Keith Thompson wrote:
> Ben Pfaff <(E-Mail Removed)> writes:
>
>>Neptune <neptune@no_spam_here> writes:
>>
>>
>>>Ben Pfaff wrote:
>>>
>>>> int bars[] = {1, 6, 2, 4, 9};
>>>> int i;
>>>> for (i = 0; i < sizeof bars / sizeof *bars; i++) {

>>
>>>That was helpful. Gives me an idea of its usage outside of text book
>>>example. I haven't come across "sizeof" before. I presume that it is
>>>some standard way of referencing the length of the array?

>>
>>sizeof yields the number of bytes in its operand. `sizeof bars'
>>is the number of bytes in array bars[]; `sizeof *bars' is the
>>number of bytes in a single element of bars[]. Thus, the
>>quotient of those two expressions is the number of elements in
>>bars[]; in this case, 5.

>
>
> This is, of course, quite correct.
>
> One thing to watch out for is the distinction between arrays and
> pointers. They are *not* the same thing (though some people might try
> to tell you they are), but there are some contexts in which a pointer
> name and an array name can be used in the same way. There are times
> when you have to be very careful to know whether you're applying
> sizeof to an array object or to a pointer.
>
> Section 6 of the C FAQ at <http://www.eskimo.com/~scs/C-faq/top.html>
> covers this well.
>

Thanks for the link Keith. I've added this link to my list of things to
check into over the next couple of days. Is it true that pointers have a
certain unpopularity in terms of the trouble they pose new students of
C? Is that a justified reputation?

--
"Today a young man on acid realised that all matter was really energy
condensed to a slow vibration, that we are all one consciousness
experiencing itself subjectively, there's no such thing as death,
life is only a dream, and we're the imaginations of ourselves.
Here's Tom with the weather ..." - Bill Hicks.

 
Reply With Quote
 
 
 
 
Neptune
Guest
Posts: n/a
 
      11-04-2003
Thomas Stegen wrote:
> Neptune wrote:
>
>> David Rubin wrote:
>>
>>>
>>> Two-dimensional arrays are useful in many circumstances; numerical
>>> programming is an obvious one. For example, this is how you would do
>>> matrix addition, transposition, multiplication by a scalar, etc.

>>
>>
>>
>> Thanks David. I wouldn't know where to start with the examples you
>> list, but I get the basic idea. Cheers.
>>

>
> A simpler more concrete example. Consider an othello game
> <http://www.ugateways.com/bof4.html>
>
> You have a board which is made up of 8 by 8 squares. You decide
> to represent the state of a squares as an integer.
>
> #define UNOCCUPIED -1
> #define BLACK 0
> #define WHITE 1
>
> Bonus question, why is it a good (and is it good?) idea to make
> black 0 and white 1 instead of any other two numbers?


This is an interesting example Thomas. I'd hazard a guess that one would
use 1 and 0 to represent true/false values, but this is only a guess?



> Now you need the board
>
> #define SIZE 8
>
> int board[SIZE][SIZE];
>
> To start of the game you need some simple code
> int i;
> int j;
>
> for(i = 0;i < SIZE;i++)
> {
> for(j = 0;j < SIZE;j++)
> {
> board[i][j] = UNNOCCUPIED;
> }
> }
>
> board[3][3] = WHITE;
> board[3][4] = BLACK;
> board[4][3] = WHITE;
> board[4][4] = BLACK;
>
> Ok, You are now ready to start the game. (And that you can do
> yourself


Thanks for the vote of confidence Thanks for the example - nice one.


> <OT>
> I saw your signature. Tool fan? Or "just" Bill Hicks?
> IMNSVHO they both rock!
> </OT>
>

Both - and Tool still rocks and Bill died too damn young!!! I'm now
waiting for Tool's next release. As it so happens it was Tool that
steered me in the direction of Hicks's work courtesy of the Aenema album.

--
"Today a young man on acid realised that all matter was really energy
condensed to a slow vibration, that we are all one consciousness
experiencing itself subjectively, there's no such thing as death,
life is only a dream, and we're the imaginations of ourselves.
Here's Tom with the weather ..." - Bill Hicks.

 
Reply With Quote
 
Neptune
Guest
Posts: n/a
 
      11-04-2003
Allan Bruce wrote:
> "Neptune" <neptune@no_spam_here> wrote in message
> news:3fa6a878@212.67.96.135...
>
>>Hello.
>>
>>I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)"
>>(Sam's series), and for nested loops, he writes (p116) "It's often
>>necessary to create a loop even when you are already in a loop." Then he
>>goes on to portray a contrived example that doesn't tell me under what
>>conditions a nested loop might be favoured as a solution? i.e. what are
>>nested loops useful for? What kinds of algorithms are served by nested
>>loops? etc. Is any of this making sense?
>>
>>Anyway - thoughts welcomed.
>>
>>- Andy
>>

>
>
> One example you may come across in your book is a basic bubble-sort which
> will sort an array of elements, e.g.
>
> for (i=0; i<MAX-1; i++)
> for (j=0; j<MAX-1-i; j++)
> if (ELEMENT[j+1]>ELEMENT[j])
> {
> /*swap the elements*/
> TEMP = ELEMENT[j+1];
> ELEMENT[j+1] = ELEMENT[j];
> ELEMENT[j] = TEMP;
> }
>
> HTH
> Allan
>
>

Thanks Allan. I have heard about bubble sort but have not yet
encountered it. That pleasure yet awaits me!!! The code you have
listed here, would this be the standard algorithm for the bubble-sort
method, or are there also other ways of tackling this problem?

--
"Today a young man on acid realised that all matter was really energy
condensed to a slow vibration, that we are all one consciousness
experiencing itself subjectively, there's no such thing as death,
life is only a dream, and we're the imaginations of ourselves.
Here's Tom with the weather ..." - Bill Hicks.

 
Reply With Quote
 
Mark Gordon
Guest
Posts: n/a
 
      11-04-2003
On Tue, 04 Nov 2003 22:48:05 +0000
Neptune <neptune@no_spam_here> wrote:

> Thomas Stegen wrote:


<snip>

> > A simpler more concrete example. Consider an othello game
> > <http://www.ugateways.com/bof4.html>
> >
> > You have a board which is made up of 8 by 8 squares. You decide
> > to represent the state of a squares as an integer.
> >
> > #define UNOCCUPIED -1
> > #define BLACK 0
> > #define WHITE 1
> >
> > Bonus question, why is it a good (and is it good?) idea to make
> > black 0 and white 1 instead of any other two numbers?

>
> This is an interesting example Thomas. I'd hazard a guess that one
> would use 1 and 0 to represent true/false values, but this is only a
> guess?


Close. Any non-0 value is true. However, (!0 == 1) && (!1 == 0) allowing
you to pass either to a function then simply do checks and assignment
like

if (cell == yours) {
/* cell is mine */
cell = !yours; /* you don't own it no more */
}
--
Mark Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spamtrap, it is real and I read it.
 
Reply With Quote
 
pete
Guest
Posts: n/a
 
      11-04-2003
Neptune wrote:
>
> Allan Bruce wrote:
> > "Neptune" <neptune@no_spam_here> wrote in message
> > news:3fa6a878@212.67.96.135...
> >
> >>Hello.
> >>
> >>I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)"
> >>(Sam's series), and for nested loops, he writes (p116) "It's often
> >>necessary to create a loop even when you are already in a loop." Then he
> >>goes on to portray a contrived example that doesn't tell me under what
> >>conditions a nested loop might be favoured as a solution? i.e. what are
> >>nested loops useful for? What kinds of algorithms are served by nested
> >>loops? etc. Is any of this making sense?
> >>
> >>Anyway - thoughts welcomed.
> >>
> >>- Andy
> >>

> >
> >
> > One example you may come across in your book is a basic bubble-sort which
> > will sort an array of elements, e.g.
> >
> > for (i=0; i<MAX-1; i++)
> > for (j=0; j<MAX-1-i; j++)
> > if (ELEMENT[j+1]>ELEMENT[j])
> > {
> > /*swap the elements*/
> > TEMP = ELEMENT[j+1];
> > ELEMENT[j+1] = ELEMENT[j];
> > ELEMENT[j] = TEMP;
> > }
> >
> > HTH
> > Allan
> >
> >

> Thanks Allan. I have heard about bubble sort but have not yet
> encountered it. That pleasure yet awaits me!!! The code you have
> listed here, would this be the standard algorithm for the bubble-sort
> method, or are there also other ways of tackling this problem?


It's the simplest form of bubblesort.
A more sophisticated form,
records the location of the last swapped pair,
and uses that information to tighten the loops.
There is also a "cocktail shaker" variation.

But you can only optimize the number of comparrisons made.

All sorting functions which work by swapping pairs of
adjacent out of order elements, will sort any given array order,
with the same number of swaps.

If you modify bubblesort to the point where it does something
else besides swap adjacent out of order elements,
then it wouldn't be bubblesort any more.
 
Reply With Quote
 
Irrwahn Grausewitz
Guest
Posts: n/a
 
      11-04-2003
Neptune <neptune@no_spam_here> wrote:
<snip>
> It appears then that (theoretically speaking anyway), there are no
> limits to the number of loops one can nest? I cannot think of any
> example to illustrate this, but was wondering if one can nest one or two
> or five loops, is there a maximum to which one can go before it
> discombobulates entirely. I can imagine that there would be logistical
> nightmares (indentation running off of the page or line wrapping
> endlessly, trying to keep the iterations straight in one's head, even
> finding a value to engage in that kind of exercise, etc), so the query
> really is theoretical.


Theoretically it's of course possible to nest loops the deep you like,
but for common programming tasks two or three levels of loop nesting
should suffice. If you are exceeding five levels of nesting you should
rethink your algorithm and/or code structure.
[ I recently wrote a tiny test-suite for an interpreter for a language
with C-like syntax, and in the loop-test part I got a serious headache
at level nine. ]
Note that real-world implementations have limitations on how many levels
of loop nesting are possible, but usually the limits are far beyond what
a sane programmer would actually use.

Regards
--
Irrwahn
((E-Mail Removed))
 
Reply With Quote
 
pete
Guest
Posts: n/a
 
      11-04-2003
Irrwahn Grausewitz wrote:

> Theoretically it's of course possible to nest loops the deep you like,


My copy of the C89 last public draft, has limits for that:

2.2.4.1 Translation limits
* 15 nesting levels of compound statements, iteration control
structures, and selection control structures

But I don't see anything like that, in N869.
 
Reply With Quote
 
Keith Thompson
Guest
Posts: n/a
 
      11-05-2003
Neptune <neptune@no_spam_here> writes:
[...]
> Thanks for the link Keith. I've added this link to my list of things
> to check into over the next couple of days. Is it true that pointers
> have a certain unpopularity in terms of the trouble they pose new
> students of C? Is that a justified reputation?


Yes, pointers can be pretty confusing to newbies. It can be far too
easy to get misleading ideas about how pointers work.

Suggestion: Read the FAQ from start to finish. You probably won't
understand a lot of it; that tells you where you need further study.
Later on, read it from start to finish again; it will make a lot more
sense.

Having said that, the FAQ is not intended as a tutorial; it's designed
more to correct misconceptions than to present the underlying ideas in
the first place. You might be better off diving into the FAQ after
you've finished whatever text book or tutorial you're using (though
you should probably read 18.10, "What's a good book for learning C?",
right away.)

--
Keith Thompson (The_Other_Keith) http://www.velocityreviews.com/forums/(E-Mail Removed) <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
 
Reply With Quote
 
Keith Thompson
Guest
Posts: n/a
 
      11-05-2003
Neptune <neptune@no_spam_here> writes:
[...]
> It appears then that (theoretically speaking anyway), there are no
> limits to the number of loops one can nest? I cannot think of any
> example to illustrate this, but was wondering if one can nest one or
> two or five loops, is there a maximum to which one can go before it
> discombobulates entirely. I can imagine that there would be logistical
> nightmares (indentation running off of the page or line wrapping
> endlessly, trying to keep the iterations straight in one's head, even
> finding a value to engage in that kind of exercise, etc), so the query
> really is theoretical.


Quick answer: Yes.

The standard requires an implementation to handle at least 127 nesting
levels of blocks (the actual statement is more complicated than that,
but the details aren't important for this discussion). Realistically,
most compilers don't use fixed-size data structures internally, so the
number of nested loops is going to be limited by the compiler running
out of memory, not by any fixed upper bound.

The compiler will let you have far more levels of nested loops than
you should.

Note that nested loops don't have to be physically nested. It's very
common for a function to be called from within a loop, and for the
function itself to execute a loop, and so on to arbitrarily many
levels. Done properly, this can avoid the discombobulation you're
quite rightly concerned about.

--
Keith Thompson (The_Other_Keith) (E-Mail Removed) <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Nested friend class in nested template problem tonvandenheuvel@gmail.com C++ 3 12-07-2007 03:02 PM
dealing with nested xml within nested xml within...... Ultrus Python 3 07-09-2007 09:00 PM
Is nested class automatically friend of class that it is nested in? request@no_spam.com C++ 5 09-25-2006 08:31 AM
Nested Vector Nester Classes are Nested in my Brain Chad E. Dollins C++ 3 11-08-2005 04:46 AM
Nested iterators (well, not nested exactly...) Russ Perry Jr Java 2 08-20-2004 06:51 PM



Advertisments