473,769 Members | 4,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is the scope of this while loop?

JS
#include <stdio.h>

main(){

int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n",
nwhite, nother);

}

Where does the above while loop end?? For some reason all the examples I
have read with C code there is no brackets to confine the while loop (like
in Java).

JS
Nov 14 '05 #1
9 4178
here's the bracketed version. i'm pretty sure i got it right, but you
better double check the output of both versions to make sure they
match.

#include <stdio.h>

main()
{
int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
{
ndigit[i] = 0;
}

while ((c = getchar()) != EOF)
{
if (c >= '0' && c <= '9')
{
++ndigit[c-'0'];
}
else
{
if (c == ' ' || c == '\n' || c == '\t')
{
++nwhite;
}
else
{
++nother;
}
}
}

printf("digits =");

for (i = 0; i < 10; ++i)
{
printf(" %d", ndigit[i]);
}

printf(", white space = %d, other = %d\n",
nwhite, nother);

}

Nov 14 '05 #2
Vig


--
--
Vig
"JS" <sf****@asdas.c om> wrote in message
news:d1******** **@news.net.uni-c.dk...
#include <stdio.h>

main(){

int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n",
nwhite, nother);

}

Where does the above while loop end?? For some reason all the examples I
have read with C code there is no brackets to confine the while loop (like
in Java).


I believe the while loop extends till the line just prior to the first
printf statement. This is because only the line immediately after a while
loop is in its scope. However, the if statemnt's scope extends back to the
while loop.

--
Vig
Nov 14 '05 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

JS wrote:
#include <stdio.h>

main(){

int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n",
nwhite, nother);

}

Where does the above while loop end??
In C, a while() statement consists of three parts:
1) the 'while' keyword,
2) a condition, enclosed in parenthesis, and
3) a single statement to be executed if the condition tests true

In C, a series of statements, enclosed in brace brackets, is considered to be a
single statement.

Thus:
while (1) printf("Contini ous loop\n");
and
while (1) { printf("Contini ous loop\n");
are equivalent.

So, to answer your question, the while() statement in your example code extends
from the while() to the ++nother;

Or in other words, the following is a whole while() statement.

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
For some reason all the examples I
have read with C code there is no brackets to confine the while loop (like
in Java).


The implication is that Java requires that the body of a while loop be enclosed
in brace brackets. So?? What's Java got to do with it? Different languages have
different rules.

- --
Lew Pitcher
IT Specialist, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)

iD8DBQFCNen5agV FX4UWr64RAtYqAJ 9n1twwQeQ6KCGK3 9wIEOlIUV9I1wCf bmeI
Nkltw9EMstpO1ko Uwr6u778=
=O1jF
-----END PGP SIGNATURE-----
Nov 14 '05 #4
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Lew Pitcher wrote:
[snip]
In C, a while() statement consists of three parts:
1) the 'while' keyword,
2) a condition, enclosed in parenthesis, and
3) a single statement to be executed if the condition tests true

In C, a series of statements, enclosed in brace brackets, is considered to be a
single statement.

Thus:
while (1) printf("Contini ous loop\n");
and
while (1) { printf("Contini ous loop\n");
Oops. Correction
while (1) { printf("Contini ous loop\n"); }

are equivalent.

[snip]

- --
Lew Pitcher
IT Specialist, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)

iD8DBQFCNepGagV FX4UWr64RAiXPAK CMfxxydswF1zsaB aOf+0bPXLFezgCf YUNg
+b2aWTcHplyJvfa B9cu37sg=
=v6mw
-----END PGP SIGNATURE-----
Nov 14 '05 #5
"JS" <sf****@asdas.c om> writes:
#include <stdio.h>

main(){

int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n",
nwhite, nother);

}

Where does the above while loop end?? For some reason all the examples I
have read with C code there is no brackets to confine the while loop (like
in Java).


A while() always controls a single statement. Typically that single
statement is a compound statement, which is delimited by '{' and '}',
but it can be any statement.

In this case, the single statement is the if-else statement consisting
of the 7 lines following the while().

Note that the indentation on the last two of those lines is incorrect;
the "else" should be directly under the "if", and the "++nother;"
should be directly under the "++nwhite;" . (This isn't incorrect in
the sense that a compiler is going to complain about it, but it's
misleading.)

Personally, I always use braces around sub-statements like this (a
habit I picked up from Perl, which requires them). Mike Deskevich's
fully braced version of your program appears to be correct.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
JS wrote:

#include <stdio.h>

main(){

int c, i, nwhite, nother;
int ndigit[10];

nwhite = nother = 0;

for (i = 0; i < 10; ++i)
ndigit[i] = 0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else
if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n",
nwhite, nother);

}

Where does the above while loop end?? For some reason all the
examples I have read with C code there is no brackets to confine
the while loop (like in Java).


It ends after one statement, which may be a compound statement,
effected via {}. Better indentation and formatting will show
things up clearly, as in:

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9') ++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t') ++nwhite;
else ++nother;

I don't believe in extra braces when the complete condition/action
can be specified on one line of reasonable length.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 14 '05 #7
CBFalconer wrote:
... Better indentation and formatting will show
things up clearly, as in:
.
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9') ++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t') ++nwhite;
else ++nother;
.
I don't believe in extra braces when the complete condition/action
can be specified on one line of reasonable length.


Does that mean you're writing...

while (blah) continue;

....instead of...

while (blah)
{
continue;
}

....these days! ;)

--
Peter

Nov 14 '05 #8
Peter Nilsson wrote:

CBFalconer wrote:
... Better indentation and formatting will show
things up clearly, as in:
.
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9') ++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t') ++nwhite;
else ++nother;
.
I don't believe in extra braces when the complete condition/action
can be specified on one line of reasonable length.


Does that mean you're writing...

while (blah) continue;

...instead of...

while (blah)
{
continue;
}

...these days! ;)


I prefer compound statements with all ifs and loops.
It makes reading simpler.

--
pete
Nov 14 '05 #9
Peter Nilsson wrote:
CBFalconer wrote:
... Better indentation and formatting will show
things up clearly, as in:
.
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9') ++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t') ++nwhite;
else ++nother;
.
I don't believe in extra braces when the complete condition/action
can be specified on one line of reasonable length.


Does that mean you're writing...

while (blah) continue;

...instead of...

while (blah)
{
continue;
}

...these days! ;)


Definitely. Wouldn't have it any other way :-)

int flushln(FILE *f)
{
int ch;

while (('\n' != (ch = getc(f))) && (EOF != ch)) continue;
return ch;
}

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #10

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

Similar topics

6
2355
by: Arthur J. O'Dwyer | last post by:
I was paging through Coplien's book "Advanced C++ Programming Styles and Idioms" this afternoon and found some code that looked something like void sort(vector<foo> a) { int flip; do { for (int i=0, flip = 0; i < a.size(); ++i) {
32
3821
by: Wenjie | last post by:
Hello, We had a code review with the argument of whether "i" is out of scope as illustrated below: for (int i=0; i<2004; i++) { doSomething(i); }
12
3304
by: Steven T. Hatton | last post by:
This is something I've been looking at because it is central to a currently broken part of the KDevelop new application wizard. I'm not complaining about it being broken, It's a CVS images. Such things happen. The whole subsystem is going through radical changes. I don't really want to say what I think of the code just yet. That would influence the opinions of others, and I really want to know how other people view these things,...
2
1161
by: dh | last post by:
Hi all, int a = 1; for(int a = 12; ...) { .... } // Does value of a here have anything to do with "int a = 1;" scope, or the
5
1677
by: elzacho | last post by:
I would like to (and commonly do) define my variables in the most specific scope I can. For example... int foo(int a, int b, int c) { /* don't declare temp here if we can help it */ ... for (i = 0; i < max; i++) {
5
3124
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.
16
1786
by: chutsu | last post by:
Ok Here is a problem, I got a imaginary database program that I need to code, to add a patient I have function inser_patient. but when I try to input the details it doesn't quite work the way I wanted it to. Code: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h>
8
4531
by: Erik de Castro Lopo | last post by:
Hi all, Consider the following code snippet: do { int r = rand () ; } while (r != 0) ; It seems the compiler I'm using (GCC) does realise that the
2
2900
by: ray | last post by:
Hi, all, foreach($array as $k =$v) { $foo = ...; } echo $foo; Is it allowed to access the $foo variable that is created within the loop from outside of the loop? I think it isn't allowed, because according to the rule stated in PHP manual(http://www.php.net/manual/ en/language.variables.scope.php): The scope of a variable is the
0
9423
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
10045
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
9863
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
8872
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
7409
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
6673
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
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3562
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.