By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,207 Members | 1,028 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,207 IT Pros & Developers. It's quick & easy.

Use of nested loops.

P: n/a
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

Nov 13 '05 #1
Share this Question
Share on Google+
46 Replies


P: n/a
Neptune writes:
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? :)


One case that might have some natural appeal is to compute the sum of all
the elements of a two-dimensional array. C only simulates (emulates?
whatever) a two-dimensional array, but the simulation is pretty effective.

Something like:

double sum = 0.0;
for(i=0; i<10; i++)
for(j=0; j<25; j++)
sum = sum + a[i][j];

It is often helpful to hide the nesting. This can be accomplished very
effectively by calling a function. It lets one focus on the thing of most
immediate interest. EG: sum_array() calls sum_columns().
Nov 13 '05 #2

P: n/a
Neptune <neptune@no_spam_here> writes:
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? :)


A typical beginner's example is printing a bar graph,
e.g. (warning: poorly proofread):

#include <stdio.h>

int main (void)
{
int bars[] = {1, 6, 2, 4, 9};
int i;

for (i = 0; i < sizeof bars / sizeof *bars; i++) {
int j;

printf ("%3d ", bars[i]);
for (j = 0; j < bars[i]; j++)
putchar ('*');
putchar ('\n');
}
return 0;
}
--
Peter Seebach on C99:
"[F]or the most part, features were added, not removed. This sounds
great until you try to carry a full-sized printout of the standard
around for a day."
Nov 13 '05 #3

P: n/a
osmium wrote:
Neptune writes:

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? :)

One case that might have some natural appeal is to compute the sum of all
the elements of a two-dimensional array. C only simulates (emulates?
whatever) a two-dimensional array, but the simulation is pretty effective.

Something like:

double sum = 0.0;
for(i=0; i<10; i++)
for(j=0; j<25; j++)
sum = sum + a[i][j];

It is often helpful to hide the nesting. This can be accomplished very
effectively by calling a function. It lets one focus on the thing of most
immediate interest. EG: sum_array() calls sum_columns().


Thanks for replying:
1. I get the idea in terms of the structure of a nested for loop and its
output (e.g. 2 lists of integers from 0 to 10 and 0 to 25) ... but
what does the 'a' stand-for in "sum = sum + a[i][j];"?
2. This is due to my ignorance, but under what conditions would one use
it? In this instance, why would I want a two-dimensional array, anyway?
What would I use it for? That was more to my question.

--
"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.

Nov 13 '05 #4

P: n/a
Ben Pfaff wrote:
Neptune <neptune@no_spam_here> writes:

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? :)

A typical beginner's example is printing a bar graph,
e.g. (warning: poorly proofread):

#include <stdio.h>

int main (void)
{
int bars[] = {1, 6, 2, 4, 9};
int i;

for (i = 0; i < sizeof bars / sizeof *bars; i++) {
int j;

printf ("%3d ", bars[i]);
for (j = 0; j < bars[i]; j++)
putchar ('*');
putchar ('\n');
}
return 0;
}

Cheers Ben
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?
Thanks
--
"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.

Nov 13 '05 #5

P: n/a
Neptune <neptune@no_spam_here> wrote in news:3f******@212.67.96.135:
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?
Thanks


Sizeof is a nice operator (it's not a function) that tells you the size of
any "object".

E.g.

sizeof (int);
- tells you the size of an int on your platform (in bytes). For types you
must use the parenthesis.
struct foo
{
int a;
double d;
long *p;
} fooVar;

sizeof fooVar
- tells you the size of the variable fooVar (a struct) in bytes. You don't
need parenthesis for a variable when uses with the sizeof operator.
int var[64];

sizeof var;
- tells you the size of the var in bytes.

The sizeof operator is calculated at compile time so it has no run-time
performance overhead.

--
- Mark ->
--
Nov 13 '05 #6

P: n/a
Neptune <neptune@no_spam_here> writes:
[...]
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?
Thanks


"sizeof" should be explained in that text book of yours. If it isn't,
you need a better text book.

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.

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #7

P: n/a
Neptune <neptune@no_spam_here> writes:
osmium wrote:
double sum = 0.0;
for(i=0; i<10; i++)
for(j=0; j<25; j++)
sum = sum + a[i][j];
Thanks for replying:
1. I get the idea in terms of the structure of a nested for loop and
its output (e.g. 2 lists of integers from 0 to 10 and 0 to 25) ... but
what does the 'a' stand-for in "sum = sum + a[i][j];"?


It's just the name of an array, perhaps declared as
double a[10][25];
2. This is due to my ignorance, but under what conditions would one
use it? In this instance, why would I want a two-dimensional array,
anyway? What would I use it for? That was more to my question.


Suppose you're calculating a statistical crosstabulation;
e.g. you have a bunch of survey responses from several people,
and the survey includes two questions, one of which has 10
possible answers and another of which has 25 possible answers.
Then it may be interesting to figure out how often each possible
combination of responses (25 * 10 = 250 possibilities) was given
by respondents. A two-dimensional array with cell values
corresponding to a count of people is a natural way to do this.
The sum of all of the cell values is then the total number of
survey respondents.

There are of course many other possibilities, too.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 13 '05 #8

P: n/a
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.
--
"It wouldn't be a new C standard if it didn't give a
new meaning to the word `static'."
--Peter Seebach on C99
Nov 13 '05 #9

P: n/a
Neptune wrote:
double sum = 0.0;
for(i=0; i<10; i++)
for(j=0; j<25; j++)
sum = sum + a[i][j];
[snip] Thanks for replying:
1. I get the idea in terms of the structure of a nested for loop and its
output (e.g. 2 lists of integers from 0 to 10 and 0 to 25) ... but
In this example, a is a (two-dimensional) array, likely defined as

double a[10][25];
what does the 'a' stand-for in "sum = sum + a[i][j];"?
2. This is due to my ignorance, but under what conditions would one use
it? In this instance, why would I want a two-dimensional array, anyway?
What would I use it for? That was more to my question.


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.

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 13 '05 #10

P: n/a
Ben Pfaff wrote:
It's just the name of an array, perhaps declared as
double a[10][25];
OK - thought as much, but wanted to confirm.

Suppose you're calculating a statistical crosstabulation;
e.g. you have a bunch of survey responses from several people,
and the survey includes two questions, one of which has 10
possible answers and another of which has 25 possible answers.
Then it may be interesting to figure out how often each possible
combination of responses (25 * 10 = 250 possibilities) was given
by respondents. A two-dimensional array with cell values
corresponding to a count of people is a natural way to do this.
The sum of all of the cell values is then the total number of
survey respondents.

There are of course many other possibilities, too.


This gels it for me. Thanks Ben. Very useful.

--
"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.

Nov 13 '05 #11

P: n/a
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.

--
"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.

Nov 13 '05 #12

P: n/a
Keith Thompson wrote:
"sizeof" should be explained in that text book of yours. If it isn't,
you need a better text book.
ooops - it is. Right in the next section under "Using conditional
operators".

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.

Thanks :)

--
"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.

Nov 13 '05 #13

P: n/a
Mark A. Odell wrote:
Sizeof is a nice operator (it's not a function) that tells you the size of
any "object".

E.g.

sizeof (int);
- tells you the size of an int on your platform (in bytes). For types you
must use the parenthesis.
struct foo
{
int a;
double d;
long *p;
} fooVar;

sizeof fooVar
- tells you the size of the variable fooVar (a struct) in bytes. You don't
need parenthesis for a variable when uses with the sizeof operator.
int var[64];

sizeof var;
- tells you the size of the var in bytes.

The sizeof operator is calculated at compile time so it has no run-time
performance overhead.


That was a useful summary - thanks. As it so happens it looks like that
is the next section in this book, so I'll keep your precise in mind when
reading.

--
"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.

Nov 13 '05 #14

P: n/a
Ben Pfaff wrote:

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.


Cheers Ben. Your explanation coupled with that given by Mark will be
very useful when I tackle the next section in my book. Much obliged.

--
"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.

Nov 13 '05 #15

P: n/a
"Keith Thompson" <ks*@cts.com> wrote in message
news:lz************@cts.com...
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 :-)

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.
Nov 13 '05 #16

P: n/a
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.


Start with Google. No problem.

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 13 '05 #17

P: n/a
Ben Pfaff <bl*@cs.stanford.edu> 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.

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #18

P: n/a
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?

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 ;)

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

--
Thomas.

Nov 13 '05 #19

P: n/a

"Neptune" <neptune@no_spam_here> wrote in message
news:3f******@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
Nov 13 '05 #20

P: n/a
Peter Pichler wrote:
"Keith Thompson" <ks*@cts.com> wrote in message
news:lz************@cts.com...
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.

Nov 13 '05 #21

P: n/a
Keith Thompson wrote:
Ben Pfaff <bl*@cs.stanford.edu> 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.

Nov 13 '05 #22

P: n/a
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.

Nov 13 '05 #23

P: n/a
Allan Bruce wrote:
"Neptune" <neptune@no_spam_here> wrote in message
news:3f******@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.

Nov 13 '05 #24

P: n/a
Neptune wrote:

Allan Bruce wrote:
"Neptune" <neptune@no_spam_here> wrote in message
news:3f******@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.
Nov 13 '05 #25

P: n/a
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
(ir*******@freenet.de)
Nov 13 '05 #26

P: n/a
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.
Nov 13 '05 #27

P: n/a
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) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #28

P: n/a
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) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #29

P: n/a
pete <pf*****@mindspring.com> wrote:
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


That's the very reason why I wrote:
<unsnipped>
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.

</unsnipped>
But I don't see anything like that, in N869.


The closest I can come up with is this:

ISO/IEC 9899:1999TC1
5.2.4.1 Translation limits
[...]
— 127 nesting levels of blocks
[...]

Regards
--
Irrwahn
(ir*******@freenet.de)
Nov 13 '05 #30

P: n/a
pete <pf*****@mindspring.com> wrote in message news:<3F***********@mindspring.com>...
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.


-- 127 nesting levels of blocks

Would seem to be applicable.

--
Peter
Nov 13 '05 #31

P: n/a
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.
Nov 13 '05 #32

P: n/a
Peter Nilsson wrote:

pete <pf*****@mindspring.com> wrote in message news:<3F***********@mindspring.com>...
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.


-- 127 nesting levels of blocks

Would seem to be applicable.


Except that loops don't always have blocks.

--
pete
Nov 13 '05 #33

P: n/a

"pete" <pf*****@mindspring.com> wrote in message
news:3F***********@mindspring.com...
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


These are minimum requirements, though the compilers may exceed them.

I believe that I have done more then that. I once had them nested pretty
deep to solve a cross number puzzle. Each loop had a continue statement in
it, so the resulting program ran very fast.

-- glen
Nov 13 '05 #34

P: n/a

"Neptune" <neptune@no_spam_here> wrote in message
news:3f******@212.67.96.135...
Peter Pichler wrote:
"Keith Thompson" <ks*@cts.com> wrote in message
news:lz************@cts.com...
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.

(snip)
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.
(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.
Compilers may have stack limits, register limits, or otherwise have a reason
to limit it. The limit should be large enough that ordinary programs don't
run into it.
"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.


This sounds way too much like superstring theory. Did anyone watch NOVA
last week or this week?

Otherwise, I don't think quantum mechanics excludes it as a possibility.

-- glen

Nov 13 '05 #35

P: n/a
pete <pf*****@mindspring.com> writes:
Peter Nilsson wrote:
pete <pf*****@mindspring.com> wrote in message
news:<3F***********@mindspring.com>...
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.


-- 127 nesting levels of blocks

Would seem to be applicable.


Except that loops don't always have blocks.


A block isn't necessarily surrounded by curly braces.

C99 6.8.5 p5:

An iteration statement is a block whose scope is a strict subset
of the scope of its enclosing block. The loop body is also a block
whose scope is a strict subset of the scope of the iteration
statement.

So:

while (1) printf("I will not write infinite loops\n");

actually has two blocks.

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #36

P: n/a
Keith Thompson wrote:

pete <pf*****@mindspring.com> writes:
Peter Nilsson wrote:
pete <pf*****@mindspring.com> wrote in message
news:<3F***********@mindspring.com>...
> 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.

-- 127 nesting levels of blocks

Would seem to be applicable.


Except that loops don't always have blocks.


A block isn't necessarily surrounded by curly braces.

C99 6.8.5 p5:

An iteration statement is a block whose scope is a strict subset
of the scope of its enclosing block. The loop body is also a block
whose scope is a strict subset of the scope of the iteration
statement.

So:

while (1) printf("I will not write infinite loops\n");

actually has two blocks.


Thank you.
Nov 13 '05 #37

P: n/a
pete <pf*****@mindspring.com> wrote:

Except that loops don't always have blocks.


They do in C99.

-Larry Jones

Ha! Wild zontars couldn't drag that information out of me! Do your worst!
-- Calvin
Nov 13 '05 #38

P: n/a
la************@eds.com wrote:
pete <pf*****@mindspring.com> wrote:
Except that loops don't always have blocks.


They do in C99.


Hmmm. How about:

#include <stdio.h>
int main(void)
{ int i,j,k;
for (i=0; i<10; i++)
for (j=0; j<10; j++)
for (k=0; k<10; k++)
puts("Where's the blocks?");
return 0;
}

?
--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c
Read my lips: The apple doesn't fall very far from the tree.

Nov 13 '05 #39

P: n/a
Morris Dovey <mr*****@iedu.com> wrote:
la************@eds.com wrote:
pete <pf*****@mindspring.com> wrote:
Except that loops don't always have blocks.
They do in C99.

Hmmm. How about: #include <stdio.h>
int main(void)
{ int i,j,k;
for (i=0; i<10; i++) <- 1 <- 2 for (j=0; j<10; j++) <- 3 <- 4 for (k=0; k<10; k++) <- 5
puts("Where's the blocks?"); <- 6
return 0;
}


I count 6 block scopes. In C99 you could have declared i, j, and k
within the initialization statement of the for loop. IIRC, the body
of a loop opens a new block scope. This does not necessitate the
use of curly brackets.

Alex
Nov 13 '05 #40

P: n/a
Alex wrote:
Morris Dovey <mr*****@iedu.com> wrote:
la************@eds.com wrote:
pete <pf*****@mindspring.com> wrote:
Except that loops don't always have blocks.

They do in C99.


Hmmm. How about:


#include <stdio.h>
int main(void)
{ int i,j,k;
for (i=0; i<10; i++) <- 1

<- 2
for (j=0; j<10; j++) <- 3

<- 4
for (k=0; k<10; k++) <- 5
puts("Where's the blocks?"); <- 6
return 0;
}

I count 6 block scopes. In C99 you could have declared i, j, and k
within the initialization statement of the for loop. IIRC, the body
of a loop opens a new block scope. This does not necessitate the
use of curly brackets.


I could have, but didn't. I can make a block (with curly braces)
anywhere I can code a statement. Are you telling me that there
/is/ a block everywhere there /can/ be a block, even though I
don't code the curly braces - or are you simply reminding me that
the potential for creating all these blocks is lurking there? Is
there block scope without a block?

--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c
Read my lips: The apple doesn't fall very far from the tree.

Nov 13 '05 #41

P: n/a
Morris Dovey <mr*****@iedu.com> writes:
la************@eds.com wrote:
pete <pf*****@mindspring.com> wrote:
Except that loops don't always have blocks.

They do in C99.


Hmmm. How about:


Larry meant what he said. Read C99 6.8.5:

5 An iteration statement is a block whose scope is a strict
^^^^^^^^^^
subset of the scope of its enclosing block. The loop body is
also a block whose scope is a strict subset of the scope of
the iteration statement.

The corresponding section in C90 doesn't include anything similar.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 13 '05 #42

P: n/a
Morris Dovey <mr*****@iedu.com> wrote:
Alex wrote:
Morris Dovey <mr*****@iedu.com> wrote:
la************@eds.com wrote:

pete <pf*****@mindspring.com> wrote:
>Except that loops don't always have blocks.

They do in C99.


Hmmm. How about:


#include <stdio.h>
int main(void)
{ int i,j,k;
for (i=0; i<10; i++) <- 1

<- 2
for (j=0; j<10; j++) <- 3

<- 4
for (k=0; k<10; k++) <- 5
puts("Where's the blocks?"); <- 6
return 0;
}

I count 6 block scopes. In C99 you could have declared i, j, and k
within the initialization statement of the for loop. IIRC, the body
of a loop opens a new block scope. This does not necessitate the
use of curly brackets.

I could have, but didn't. I can make a block (with curly braces)
anywhere I can code a statement. Are you telling me that there
/is/ a block everywhere there /can/ be a block, even though I
don't code the curly braces - or are you simply reminding me that
the potential for creating all these blocks is lurking there? Is
there block scope without a block?


I am saying that there is /block scope/ at the places which I pointed
out even though there aren't actual physical curly blocks there.

Ben Pfaff just posted a quote from the standard which seems to
support my assertion.

Alex
Nov 13 '05 #43

P: n/a
Morris Dovey <mr*****@iedu.com> writes:
I could have, but didn't. I can make a block (with curly braces)
anywhere I can code a statement. Are you telling me that there /is/ a
block everywhere there /can/ be a block, even though I don't code the
curly braces - or are you simply reminding me that the potential for
creating all these blocks is lurking there? Is there block scope
without a block?


My guess is that C99 has every iteration statement open a block
because `for' statements in C99 can have their own local
variables (declared in the first clause).
--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x1f6},*p=
b,x,i=24;for(;p+=!*p;*p/=4)switch(x=*p&3)case 0:{return 0;for(p--;i--;i--)case
2:{i++;if(1)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
Nov 13 '05 #44

P: n/a
Morris Dovey <mr*****@iedu.com> writes:
[...]
I could have, but didn't. I can make a block (with curly braces)
anywhere I can code a statement. Are you telling me that there /is/ a
block everywhere there /can/ be a block, even though I don't code the
curly braces - or are you simply reminding me that the potential for
creating all these blocks is lurking there? Is there block scope
without a block?


The definition of "block" changed from C90 to C99. In C90, a block is
an optional declaration list, followed by an optional statement list,
all surrounded by curly braces. In C99, not all blocks have curly
braces. So the following:

while (1) printf("I will not write infinite loops\n";

contains no blocks in C90, but two blocks (the loop and its body) in
C99.

I think the change was made because of the addition of declarations
in for loops:

for (int i = 1; i <= 10; i ++) ...

The loop was defined to be a block to provide a scope for the
declaration of i.

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #45

P: n/a
Neptune <neptune@no_spam_here> wrote in message news:<3f******@212.67.96.135>...
Allan Bruce wrote:
"Neptune" <neptune@no_spam_here> wrote in message
news:3f******@212.67.96.135...
I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)"
so by this time you should know it all :-)

(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.


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;
}

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?


note Bubble Sort isn't a very good algorithm (there are faster methods
for
both small and large amounts of data). It is easy to code though.
For real work the standard C library comes with a standard function
qsort().
Unfortunatly qsort() comes with no performance guarantee. It might
even be Bubble sort internally! qsort() is good as a first choice;
replace it if you
know (by measurement) that it is too slow. There are books that
discuss which sort to use when.
--
Nick Keighley

"Beware of bugs in the above code;
I have only proved it correct, not tried it."
-- Donald Knuth
Nov 13 '05 #46

P: n/a
Thanks all. I need to spend more time reading C99, rather than
just looking stuff up from time to time.

Seems like a very strange way to rationalize "anywhere"
declarations/definitions - but perhaps it'll make more sense to
me if I read it enough times...

--
Morris Dovey
West Des Moines, Iowa USA
C links at http://www.iedu.com/c
Read my lips: The apple doesn't fall very far from the tree.

Nov 13 '05 #47

This discussion thread is closed

Replies have been disabled for this discussion.