11.2 Storing Characters in a Repetition

The following example program illustrates how to count each occurrence of characters in the input file. The count for each character is stored in a repetition:

occurrences: [256]@Char;

using the assignment:

occurrences[Ch]+1->occurrences[Ch];

and the occurrences are printed using a for and an if statement:

(for i:256 repeat
        (if occurrences[i]>0 then (* only print if > 0 *)
            i->put; (* notice how a char can be printed *)
            ': '->puttext; 
            occurrences[i]->putint;
            newline;
        if);
   for);

The complete program is as follows:

Program 14: CountChar2.bet

ORIGIN '~beta/basiclib/file'
---- program: descriptor ----

(# (* ------------------------------------------------
    *   count.bet: Simple file handling program
    *              -Counting occurrences of characters-
    * ------------------------------------------------*)
   
   inFile: @file;
   Ch: @char;
   nc: @integer;
   occurrences: [256]@Char;
do
   (if  NoofArguments = 2 then 
   2->Arguments->inFile.name ;
   inFile.openRead;  (* OPENING *)
   Loop: 
     (if inFile.eos//false then
         inFile.Get->Ch; 
         nc+1->nc;
         occurrences[Ch]+1->occurrences[Ch];
         restart Loop
     if);
   NewLine;
   (for i: 256 repeat
        (if occurrences[i]//0 then else (* only print if > 0 *)
            i->put; (* notice how a char can be printed *)
            ': '->puttext; 
            occurrences[i]->putint;
            newline;
        if);
   for);
   'Total '->puttext;
   nc->putint; 
   ' characters in file'->putline;
       inFile.close;
    else 
       'Missing Argument'->putline;
   if)
#)

And below we show the application of CountChar2 to the CountChar2.bet program itself.

nil% CountChar2 CountChar2.bet

 : 241
#: 2
': 8
(: 8
): 8
*: 11
+: 2
-: 117
.: 7
/: 7
0: 2
1: 3
2: 3
4: 1
5: 2
6: 2
:: 9
;: 21
>: 12
@: 4
A: 1
C: 6
E: 1
F: 6
G: 3
I: 3
L: 3
N: 4
O: 2
P: 1
R: 2
S: 1
T: 1
[: 5
]: 5
a: 20
b: 5
c: 34
d: 5
e: 55
f: 13
g: 6
h: 13
i: 41
l: 20
m: 5
n: 39
o: 26
p: 16
r: 34
s: 16
t: 31
u: 15
v: 1
w: 3
x: 2
y: 1
~: 1
Total 952 characters in file
nil%


Libraries Tutorial
© 1994-2004 Mjølner Informatics
[Modified: Thursday January 16th 2003 at 10:23]