473,883 Members | 1,521 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use of nested loops.

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
46 9951
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
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
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
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
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
"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
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
Ben Pfaff <bl*@cs.stanfor d.edu> writes:
Neptune <neptune@no_spa m_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_Keit h) 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
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.c om/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

"Neptune" <neptune@no_spa m_here> wrote in message
news:3f******@2 12.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

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

Similar topics

25
12737
by: chad | last post by:
I am writing a program to do some reliability calculations that require several nested for-loops. However, I believe that as the models become more complex, the number of required for-loops will increase. Does Python have a limit on the number of nested for-loops? Thanks.
0
1795
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return dict() print combo2(5)
4
7047
by: dw | last post by:
Hello all. We're doing a site with teams and their members. We've got a page where we need to display people according to who belongs to a which team. I've heard that nested loops are bad, but what's the alternative? Would a group-by clause in the SELECT do the trick? Right now we're doing: (pseudo-code)--------------------------------- For each team print team name For each peson print person name
77
5267
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop. Is this because .NET is inherently slower or does the C# compiler merely produce code that is not as well optimized as the C++ compiler?
9
2862
by: Gregory Petrosyan | last post by:
I often make helper functions nested, like this: def f(): def helper(): ... ... is it a good practice or not? What about performance of such constructs?
5
3129
by: =?Utf-8?B?QUEyZTcyRQ==?= | last post by:
Could someone give me a simple example of nested scope in C#, please? I've searched Google for this but have not come up with anything that makes it clear. I am looking at the ECMA guide and trying to understand Goto in this contect. PS: This is not homework.
4
2348
by: toddlahman | last post by:
I am using two while loops that are nested. The first loop (post name) returns the full column of results, but the second (post modified) only returns the first row of the column. Is there another way I could write this to get both loops to complete fully? I am using the two while loops to pull data from different tables, and insert that data into a list that has html code surrounding each loop. while ($url = mysql_fetch_array($urls,...
13
2711
by: Fredrik Lundh | last post by:
Patrol Sun wrote: so why exactly are you trying to nest 20 or 100 for-in loops? </F>
8
7273
by: Nathan Sokalski | last post by:
I have several nested For loops, as follows: For a As Integer = 0 To 255 For b As Integer = 0 To 255 For c As Integer = 0 To 255 If <Boolean ExpressionThen <My CodeElse Exit For Next If Not <Boolean ExpressionThen Exit For Next If Not <Boolean ExpressionThen Exit For
0
9932
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
11109
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10728
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10405
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
9558
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...
1
7959
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7114
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();...
1
4602
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
3
3227
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.