473,513 Members | 2,665 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

explanation of a program required please

Hi guys! Love your work!

The below program is from K&R2, p22.

=================================
#include <stdio.h>

/* count digits, white space, others */
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']; <---------------------- /* where I am
confused */
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for ( i = 0; i < 10; ++i)
printf(" %d", ndigit[i]); <--------------------- /* where I am
confused */
printf(", white space = %d, other = %d\n",
nwhite, nother);
return 0;
}
========================================

I can't get my head around what "++ndigit[c - '0']"
means. I understand what c - '0' is for, but ++indigit[]?
That's not incrementing through elements in an array ie. indigit[i++]
(where is is a declared integer)??
If not, what does it mean? Is it incrementing an actual array(not
elements of the array), which I can't figure out.

I just can't figure out how the program can keep a tab on what
digit(s) were entered and then actually prints the number of times
each digit was entered, spaced correctly along the "index".

Can someone please explain the exact code which achieves this to me?
I think this program does alot for such little code!

Thanks in advance!

Buck.
--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
Nov 14 '05 #1
6 1944
Buck Rogers writes:
The below program is from K&R2, p22.

=================================
#include <stdio.h>

/* count digits, white space, others */
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'];


Say that c has the value '3'.

Then:
++ndigit['3'-0]
yields ++ndigit[3]
ndigit points at ndigit[0] so
ndigit[3] points at ndigit[3]
If this is the first encounter, ndigit[3] has the value 0.
++ndigit[3] increments the value therein, which was 0 on the first encounter
So it works as promised.

Nasty stuff! Following it through a debugger might help.
I think the most effective way to attack things like this, for me, is a
numeric example.

<snip>
Nov 14 '05 #2
begin followup to Buck Rogers:
I can't get my head around what "++ndigit[c - '0']"
means. I understand what c - '0' is for, but ++indigit[]?
++ndigit[c - '0'];

is equivalent to

ndigit[c - '0'] = ndigit[c - '0'] + 1;
[...] I just can't figure out how the program can keep a tab on what
digit(s) were entered and then actually prints the number of times
each digit was entered, spaced correctly along the "index".


int ndigit[10];

This defines ten counters, for each digit.
ndigit[0] is the counter for character '0',
ndigit[1] is the counter for character '1',
ndigit[2] is the counter for character '2',
etc.

The absolute lame way to handle this is

if (c == '0')
ndigit[0]++;
else if (c == '1')
ndigit[1]++;
etc.

Instead you have to realise that there is a 1-to-1 mapping between
character codes ('0' to '9') and array indices (0 to 9).

--
Für Google, Tux und GPL!
Nov 14 '05 #3
On Tue, 23 Dec 2003 21:37:36 +1100, Buck Rogers <wh*@cares.com.au>
wrote:
Hi guys! Love your work!

The below program is from K&R2, p22.

=================================
#include <stdio.h>

/* count digits, white space, others */
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']; <---------------------- /* where I am
confused */
C guarantees that the characters '0' through '9' are represented in
the character set by values that increase by 1 as you pass through the
range. '0'+1 will always equal '1'. (This is not true for letters.
In ASCII, 'i'+1 will equal 'j' but in EBCDIC 'i'+8 is 'j').

Therefore, the if insures that c is a digit character (as opposed to
letter, punctuation, etc) and the expression c-'0' converts the
character for digit n to the integer value n (if c is '3', then c-'0'
is 3).

Since the ten elements of the array ndigit (ndigit[0] through
ndigit[9]) are intended to count the occurrences of the ten digits
('0' through '9'), this insures the proper element is accessed for the
current value of c. The ++ then simply increments this particular
element.
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for ( i = 0; i < 10; ++i)
printf(" %d", ndigit[i]); <--------------------- /* where I am
confused */
ndigit[i] is a count of the number of times the i-th digit appeared in
c. printing it with a %d prints it as a common integer (no leading 0,
only as many spaces as needed, etc).
printf(", white space = %d, other = %d\n",
nwhite, nother);
return 0;
}
========================================

I can't get my head around what "++ndigit[c - '0']"
means. I understand what c - '0' is for, but ++indigit[]?
That's not incrementing through elements in an array ie. indigit[i++]
(where is is a declared integer)??
Correct, it is not. It is accessing one particular element of the
array and incrementing it.
If not, what does it mean? Is it incrementing an actual array(not
elements of the array), which I can't figure out.
You cannot increment an array, only an element of the array.

I just can't figure out how the program can keep a tab on what
digit(s) were entered and then actually prints the number of times
each digit was entered, spaced correctly along the "index".


I give up, what is "index"? The printf statement makes no effort to
space text "correctly". If ndigit[i] is less than 10, it will print
in one column. If it is less than 100, then 2 columns. Etc. In
fact, you could argue that this printf is designed to be "ragged". If
you want each ndigit[i] to be properly spaced, you would need to put a
length modifier in the %d.

<<Remove the del for email>>
Nov 14 '05 #4
Groovy hepcat Buck Rogers was jivin' on Tue, 23 Dec 2003 21:37:36
+1100 in comp.lang.c.
explanation of a program required please's a cool scene! Dig it!
The below program is from K&R2, p22.

=================================
#include <stdio.h>

/* count digits, white space, others */
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']; <---------------------- /* where I am
The expression c - '0' converts the (digit) character value in c to
its numerical value. Next, the coresponding element of the array
ndigit is incremented. So, if c is '3', for example, then c - '0' is
3, then ndigit[3] (the fourth element of ndigit) is incremented.
confused */
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits =");
for ( i = 0; i < 10; ++i)
printf(" %d", ndigit[i]); <--------------------- /* where I am
Well, what don't you understand about that? It simply prints the
element of the array indicated by the index i. When i is 0 it prints
the value of ndigit[0] (the first element). When i is 1 it prints the
value of ndigit[1] (the second element). And when i is 2 it prints the
value of ndigit[2] (the third element). And so on.
confused */
printf(", white space = %d, other = %d\n",
nwhite, nother);
return 0;
}
========================================

I can't get my head around what "++ndigit[c - '0']"
means. I understand what c - '0' is for, but ++indigit[]?
That's not incrementing through elements in an array ie. indigit[i++]
(where is is a declared integer)??
ndigit[c - '0'] is the declared integer. It's one of the elements of
the array ndigit.
If not, what does it mean? Is it incrementing an actual array(not
elements of the array), which I can't figure out.
Of course not. You cannot increment an array. That doesn't make
sense. It is incrementing an element of the array.
I just can't figure out how the program can keep a tab on what
digit(s) were entered and then actually prints the number of times
each digit was entered, spaced correctly along the "index".
It's simple. Each element in the array represents a digit. Each
element is initialised to 0 indicating that no digits have been
entered yet. As a digit is entered, the array element that represents
that digit is incremented. At the end, you have an array containing
the number of times each element has been entered.
Can someone please explain the exact code which achieves this to me?
As I said above, the expression c - '0' converts a digit to its raw
numerical value. For example, it converts '1' to 1, '7' to 7 and '0'
to 0. I'm sure I don't have to explain this further, since you say you
understand it.
An expression such as x[y], where x is the name of an array and y is
an integer expression (or vice versa, but I don't want to confuse you
further, so just don't worry about that), yields the element of the
array x numbered y (the y+1'th element). So, ndigit[2], for example,
is the third element of the array ndigit. And ndigit['2' - '0'] is the
third element of ndigit. So, if c contains the digit '2', then
ndigit[c - '0'] also gives us the third element of ndigit. Are you
with me so far?
So, basically what this does is finds the array element that
coresponds to the entered digit.
Now, the ++ operator increments its operand. That's simple enough.
In the code you posted, its operand is the element of the array
coresponding to the entered digit (ndigit[c - '0']). Now do you
understand?
I think this program does alot for such little code!


It doesn't really do much. It just calculates which array element to
increment based solely on the entered digit. It's the simplest
calculation to find the right array element. There's nothing to it.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 14 '05 #5
Groovy hepcat osmium was jivin' on Tue, 23 Dec 2003 07:16:49 -0800 in
comp.lang.c.
Re: explanation of a program required please's a cool scene! Dig it!
ndigit points at ndigit[0] so
ndigit[3] points at ndigit[3]


Sorry, but no. You're wrong. Perhaps it's just your terminology, but
still, if your terminology's off it can confuse people.
ndigit[3] does not point at ndigit[3]. It doesn't point at anithing.
ndigit is an array of int, and ndigit[3] is the fourth int in that
array.
For that matter, ndigit doesn't point at anithing either, since it
is an array, not a pointer. It is converted to a pointer in certain
contexts, of course, but still, you don't want to confuse people. It's
an array and does not point. The value it is converted to points at
ndigit[0]. And I'm sure that's what you meant. But, like I said, your
terminology needs to be right, otherwise it can be confusing.
Sorry for being overly pedantic, but you know how we are in this
news group. :)

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 14 '05 #6
Alexander Bartolich <al*****************@gmx.at> scribbled the following:
begin followup to Buck Rogers:
I can't get my head around what "++ndigit[c - '0']"
means. I understand what c - '0' is for, but ++indigit[]?
++ndigit[c - '0']; is equivalent to ndigit[c - '0'] = ndigit[c - '0'] + 1;


Nitpick: Not *exactly* equivalent. For the purposes of this K&R sample
program, it's equivalent, but generally, it's not. There is a difference
on how many times ndigt[c - '0'] is evaluated. If it involves side
effects, the latter form might cause undefined behaviour.

To the OP: you don't have to care about this until you try programs that
return pointer values from functions.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"You have moved your mouse, for these changes to take effect you must shut down
and restart your computer. Do you want to restart your computer now?"
- Karri Kalpio
Nov 14 '05 #7

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

Similar topics

1
4377
by: Mike S. Nowostawsky | last post by:
I am getting this error when I try to run a program in my cgi-bin directory (don't know what I'm still missing to make it work): *** Authentication required! This server could not verify that...
3
16718
by: Abby | last post by:
I'm now using Cygwin as my compiler for C code. I use Dev-c++ as my editor. The reason why I chose Cygwin compiler instead of the compiler that came with Dev-C++ is that I believe it uses the same...
40
2597
by: findmadhav | last post by:
I need a program in C (something like a TSR) which will automatically press the function key F6, say about every 5 seconds. Can anyone provide me with an exe of such a program? Thanks in advance.
70
2737
by: rahul8143 | last post by:
hello, 1) First how following program get executed i mean how output is printed and also why following program gives different output in Turbo C++ compiler and Visual c++ 6 compiler? void main()...
3
37958
by: Joe | last post by:
Dear Friends, How to run the C# Console application as services? I have a console application.I want run this application as background services.User don't want see the command propmt. If anyone...
14
9716
by: Akhil | last post by:
plz c d following code #include<stdio.h> void main() { int x=4,y=1; y=x++++; //gives error message lvalue required y=x++ + ++y;//no errors
4
1820
by: aarklon | last post by:
Hi all, In the article http://en.wikipedia.org/wiki/C_language it is written as follows C has the following important features: 1) A simple core language, with important functionality...
1
27051
Curtis Rutland
by: Curtis Rutland | last post by:
How To Use A Database In Your Program Part II This article is intended to extend Frinny’s excellent article: How to Use a Database in Your Program. Frinny’s article defines the basic concepts...
0
13290
amitpatel66
by: amitpatel66 | last post by:
There is always a requirement that in Oracle Applications, the Concurrent Program need to be execute programatically based on certain conditions/validations: Concurrent programs can be executed...
0
7257
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,...
0
7157
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...
0
7535
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...
1
7098
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...
0
5682
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,...
1
5084
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...
0
3221
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1591
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 ...
0
455
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...

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.