473,836 Members | 1,549 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 9945
Alex wrote:
Morris Dovey <mr*****@iedu.c om> wrote:
la*********** *@eds.com wrote:
pete <pf*****@mindsp ring.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
Morris Dovey <mr*****@iedu.c om> writes:
la************@ eds.com wrote:
pete <pf*****@mindsp ring.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[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 13 '05 #42
Morris Dovey <mr*****@iedu.c om> wrote:
Alex wrote:
Morris Dovey <mr*****@iedu.c om> wrote:
la********** **@eds.com wrote:

pete <pf*****@mindsp ring.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
Morris Dovey <mr*****@iedu.c om> 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);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,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)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Nov 13 '05 #44
Morris Dovey <mr*****@iedu.c om> 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_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 #45
Neptune <neptune@no_spa m_here> wrote in message news:<3f******@ 212.67.96.135>. ..
Allan Bruce wrote:
"Neptune" <neptune@no_spa m_here> wrote in message
news:3f******@2 12.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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
12722
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
1794
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
7046
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
5259
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
2860
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
2344
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
2707
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
7269
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
9818
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
9668
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10843
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...
1
10589
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10254
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
6978
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
5825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4448
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
3112
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.