473,800 Members | 3,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

while Vs for loop

Hi

Can any body resolve this..
In what cases one of the loop constructs better than other interms of
speed , space and any other (redability).

thanks
mahesh
Nov 14 '05 #1
7 3208
On 27 Sep 2004 13:51:19 -0700, in comp.lang.c , ma***********@g mail.com
(Mahesh Kumar Reddy.R) wrote:
In what cases one of the loop constructs better than other interms of
speed , space and any other (redability).


Homework question.....

Other than poor optimisation by the compiler? :-)

While and for have different checking conditions, this might make a
difference, depending on the complexity of what you're checking. Also a
do...while loop checks its condition at the end. This might save you a
check. See if you can work out where and when.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #2
Mahesh Kumar Reddy.R wrote:
Hi

Can any body resolve this..
In what cases one of the loop constructs better than other interms of
speed , space and any other (redability).

A better idea is for you to learn some C programming. After you've
written a significant amount of code, you'll pretty know the answer.


Brian Rodenborn
Nov 14 '05 #3
"Mahesh Kumar Reddy.R" <ma***********@ gmail.com> wrote in message
news:f4******** *************** ***@posting.goo gle.com...
Hi

Can any body resolve this..
In what cases one of the loop constructs better than other
When it more closely models the problem being solved than
the others.
interms of
speed , space

'Speed' and 'space' are QoI (quality of implementation)
issues, not defined by the language.
and any other (redability).


See my first answer above.

-Mike
Nov 14 '05 #4
"Mahesh Kumar Reddy.R" wrote:

Can any body resolve this..
In what cases one of the loop constructs better than other
interms of speed , space and any other (redability).


No.

--
Some useful references:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
<http://www.dinkumware. com/refxc.html> C-library
Nov 14 '05 #5
Hi

I checked the following two programs with DDD(digital dispaly
debugger on linux). In for loop, the index variable i is always kept
in EAX
register but in while loop it was kept in EAX register only at the
time where the actual use of index variable(i.e at the time of
incrementing index
variable) and after the increment some other variable using EAX
register. In next iteration variable i is stored back to EAX.

There may be a case that the compiler(will told ahead of time that
increment index variable with each iteration)knows ,ahead of the time,
that the index variable in for loop will be incremented with each
iteration. where as in While loop the incrementing index variable is
known at end of the body the while.
And the compiler won't tell that this index variable will always be
incremented
with each iteration.

So from the above experiment for loop executes faster than while loop.
The above conclusion is based on the assumtion that the register
access is
faster than memory access.

--------------------------------------------------------------------
for.c
-----------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,n=10,sum=0;
for(i = 0; i < n; i++)
{
sum += i;
}

}
----------------------------------------------------------------------------
while.c
--------------------------------------------------------------------------

#include <stdio.h>
int main()
{
int i,n=10,sum=0;
i=0;
while(i < n)
{
sum += i;
i++;
}

}
~--------------------------------------------------------------------------------------


CBFalconer <cb********@yah oo.com> wrote in message news:<41******* ********@yahoo. com>...
"Mahesh Kumar Reddy.R" wrote:

Can any body resolve this..
In what cases one of the loop constructs better than other
interms of speed , space and any other (redability).


No.

Nov 14 '05 #6
*** Rude top-posting corrected ***

"Mahesh Kumar Reddy.R" wrote:
CBFalconer <cb********@yah oo.com> wrote:
"Mahesh Kumar Reddy.R" wrote:

Can any body resolve this..
In what cases one of the loop constructs better than other
interms of speed , space and any other (redability).


No.


I checked the following two programs with DDD(digital dispaly
debugger on linux). In for loop, the index variable i is always
kept in EAX register but in while loop it was kept in EAX
register only at the time where the actual use of index
variable(i.e at the time of incrementing index variable) and
after the increment some other variable using EAX register. In
next iteration variable i is stored back to EAX.


.... snip pointless code ...

So? A MAC, or a CP/M machine, or a VAX, etc. don't have an EAX
register. Your experiment means absolutely nothing in the world
of portable C. The thing that counts is the C standard.

Do not top-post. It is rude, and not generally tolerated here.
Your answer belongs after (or intermixed with) the material to
which you are replying, with anything not germane to your reply
snipped out.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 14 '05 #7
In article <f4************ **************@ posting.google. com>,
I checked the following two programs with DDD(digital dispaly
debugger on linux). In for loop, the index variable i is always kept
in EAX
register but in while loop it was kept in EAX register only at the
time where the actual use of index variable(i.e at the time of
incrementing index
variable) and after the increment some other variable using EAX
register. In next iteration variable i is stored back to EAX.
[snippage]
So from the above experiment for loop executes faster than while loop.
The above conclusion is based on the assumtion that the register
access is
faster than memory access.
As I think Dan Pop noted, that only tests one particular implementation;
the results cannot be generalized to other implementations . I find
it curious, however, given what I know about the internals of gcc,
that you found any difference at all. Here are your two programs
(with some whitespace compression for news-posting-reasons, though
the versions I compiled did not even have that), plus the difference
between the results of compiling them.

Both were compiled with and without optimization, using gcc (3.2.3)
on Linux (Red Hat):
for.c
#include <stdio.h>

int main() {
int i,n=10,sum=0;
for(i = 0; i < n; i++) { sum += i; }
}
while.c
#include <stdio.h>

int main()
{
int i,n=10,sum=0;
i=0; while(i < n) { sum += i; i++; }
}
% cd /tmp
% cc -S for.c while.c
% diff for.s while.s
1c1
< .file "for.c"
--- .file "while.c" 18c18
< jl .L5
--- jl .L4 20c20
< .L5:
--- .L4: % cc -S -O4 -mregparm=3 -fomit-frame-pointer for.c while.c
% diff for.s while.s
1c1
< .file "for.c"
--- .file "while.c" 13c13
< .L6:
--- .L5: 15c15
< jns .L6
--- jns .L5


As this shows, the only difference is the name of the file in
the .file directive, and the name of the local label controlling
the loop. In the optimized code, the actual loop is just:

.Ln: decl %eax; jns .Ln

Since the sum is not used, the variable that holds it has been
discarded, and the loop has been transformed from "i counts up from
0 to 9 inclusive" to "i counts down from 9 to 0 inclusive".
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #8

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

Similar topics

14
15256
by: jsaul | last post by:
Hi there, wouldn't it be useful to have a 'while' conditional in addition to 'if' in list comprehensions? foo = for i in bar: if len(i) == 0: break foo.append(i)
33
3870
by: Diez B. Roggisch | last post by:
Hi, today I rummaged through the language spec to see whats in the for ... else: for me. I was sort of disappointed to learn that the else clauses simply gets executed after the loop-body - regardless of the loop beeing entered or not. So where is an actual use case for that feature? I imagined that the else-clause would only be executed if the loop body
9
9196
by: Ben | last post by:
I have two 'Do While Not' statements, that are getting information from the same recordset. If I comment out the first one I can get the results for the second one, and vice-versa. Why is this happening? Is it because it's already at the EOF? If so how do I get it back to the BOF for the 2nd 'Do While Not' statement? '---------------------------------------- 'Create an ADO recordset object Set rs_Report =...
36
2817
by: invni | last post by:
I have a nested while. How do I go from the inner while to the beginning of the outer while? Can this be done without using goto? while_1() { some codes here while_2() { if true go to the beginning of while_1 }
6
71983
by: John Pass | last post by:
What is the difference between a While and Do While/Loop repetition structure. If they is no difference (as it seems) why do both exist?
12
1986
by: Howard | last post by:
Hello everyone (total VB.NET beginner here), I'm reading the "SAMS Teach Yourself VB.NET In 21 Days" book, and came across an exercise that I can't get to work. The exercise asks that you create a game that makes the user guess a number from 1-100, and you tell the user "lower" or "higher" as they input their guesses, until they guess the correct number, at which point you then tell the user "Correct". I tried using the While Loop, and...
16
3546
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g.
10
2337
by: rohitjogya | last post by:
Can anyone tell me the difference bet for loop and while loop execution? ____________________ for (i=0 ; i<10 ; i++) ; /* Do nothing*/ print i; ___________________ i=0;
5
5057
by: Alex | last post by:
Hi I just want to clear something up in my head with while loops and exceptions. I'm sure this will probably be a no brainer for most. Check this simple pseudo-code out (vb.net): ------------------------------ try
0
9689
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
9550
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
10495
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
10269
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
10032
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
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5597
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4148
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
2942
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.