473,667 Members | 2,577 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 1952
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 "technicall y correct" English; but since when was rock & roll "technicall y 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 "technicall y correct" English; but since when was rock & roll "technicall y 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.hel sinki.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
4391
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 you are authorized to access the URL "/~group3/cgi-bin/ack.cgi". You either supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.
3
16737
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 environment as in Linux, so that I don't have to write different sourcecode for both OS. Eventhough, I don't understand about Linux much, and I'm still a beginner in programming, I still have to make my program compatible with both OS (Windows...
40
2631
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
2784
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() { int val=5; printf("%d %d %d %d",val,--val,++val,val--); } under turbo compiler its giving
3
37974
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 knows please let me know. Thanks, Joe
14
9733
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
1827
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 such as math functions and file handling provided by sets of library routines
1
27083
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 of using databases very well and is prerequisite reading for this article. Frinny’s article explains how to use a SQL Server in your program, but there are other databases as well. Some of them provide .NET connectors, but for those that don’t,...
0
13327
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 programatically either from UNIX or Oracle PLSQL. In this Section, I will be explaining about calling a Concurrent program from UNIX using the CONCSUB Command. Pre-requisite: 1. Concurrent Program should be registered in oracle Applications...
0
8788
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...
1
8563
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
8646
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
7390
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
6203
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
5675
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
4200
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...
2
2013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1778
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.