
-----------------------------------
wtd
Tue May 06, 2008 10:34 pm

Exercise: Beeping!
-----------------------------------
In the language of your choosing, write a program that gets a line of input from the user, then print it character by character.  After each character is printed make the computer beep, then wait one second.

Please state the language you're using.

-----------------------------------
HeavenAgain
Tue May 06, 2008 10:45 pm

Re: Exercise: Beeping!
-----------------------------------
using java, not sure about which beeping sound...
import java.awt.*;
import java.util.*;
public class Beeping {
  public static void main(String args

-----------------------------------
Zampano
Tue May 06, 2008 10:50 pm

Re: Exercise: Beeping!
-----------------------------------
var word: string
get word
for c: 1 .. length (word)
    put word (c)
end for
Music.Sound (400,200)
Music.SoundOff
delay (1000)

Can I take this opportunity to ask something? In these for loops, is the value c is to be compared to determined once at the initiation of the for loop, or is it done each time the loop cycles? If it was done in C++:
for (int c = 0; c != word.size (); c++)
You would do well to define a const to hold word.size () because you need to call the member method size each time you want to check the condition, creating a redundancy. In Turing, is the value represented by word.size () here created once or many times?

-----------------------------------
HeavenAgain
Tue May 06, 2008 10:57 pm

RE:Exercise: Beeping!
-----------------------------------
In these for loops, is the value c is to be compared to determined once at the initiation of the for loop, or is it done each time the loop cycles? If it was done in C++: if you are asking about the order of the for loop structure, it goes something like this, 
initialize first, then check, if true then run, and then do the 3rd block (normally increment/decrement), then check, then run, if false then stop and move on.

and yes, it is better if you use a variable to keep track of length, instead of having to call to another method/function every time, and i think it goes the same for turing as well :roll:

After each character is printed make the computer beep, then wait one second. thats probably the tricky part.....  :cry:

-----------------------------------
Zampano
Tue May 06, 2008 11:13 pm

Re: Exercise: Beeping!
-----------------------------------
Thank heavens and thank you HeavenAgain for the help. I guess I ought to revise my answer to accomodate for my misunderstanding, right?
var word:string
get word
for c:1..length (word)
    put word(c)
    Music.Sound(400,200)
    Music.SoundOff
    delay (1000)
end for
But since Turing finds the value of length (word) right at the beginning and only at that time, do I need to use that const? I think not.

-----------------------------------
wtd
Tue May 06, 2008 11:53 pm

RE:Exercise: Beeping!
-----------------------------------
Io

outputWithBeepingAndDelay := method(msg, delay,
    msg foreach(c, 
        (c asCharacter .. "\a") print
        System sleep(delay)
    )
    "" println
)

userInput := File standardInput readLine
delay := 1

outputWithBeepingAndDelay(userInput, delay)

-----------------------------------
rdrake
Wed May 07, 2008 1:38 am

Re: Exercise: Beeping!
-----------------------------------
This probably counts as more than one line, but here's Ruby:
gets.chomp; scan(/./m).each do |c| print c + "\a"; sleep(1) end

EDIT:  What the hell, here's Python too:
import time
str = raw_input("")
for c in str:
     print c + "\a"
     time.sleep(1)

-----------------------------------
btiffin
Wed May 07, 2008 2:06 am

Re: Exercise: Beeping!
-----------------------------------
REBOL using console beepREBOL []

charbeep: func [str] [foreach ch str [prin ch prin #"^G" wait 00:00:01]]
charbeep ask "? "

; As a gui
view layout [field [charbeep get-face face] button "Close" [unview/all halt]]

REBOL using soundcardREBOL []
; Generate a ping waveform as a binary value:
ping: #{}
for amplitude 200 1 -1 [
    for phase 1 360 16 [
        val: 128 + to-integer 127 * sine phase
        val: amplitude * val / 200
        append ping to-char val
    ]
]
; Set up the sound sample parameters
sample: make sound [
    rate: 44100 / 2
    channels: 1
    bits: 8
    volume: 0.5
    data: #{}
]
append sample/data ping
beep: does [
    sound-port: open sound://
    insert sound-port sample
    wait sound-port
    close sound-port
]

; The task at hand, delay as function arg this time
charbeep: func [str delay] [foreach ch str [prin ch beep wait delay]]
charbeep ask "? " 00:00:01

; As a go function gui
go: does [view layout [field [charbeep get-face face 00:00:01] button "Close" [unview/all halt]]] go

-----------------------------------
michaelp
Wed May 07, 2008 4:14 pm

RE:Exercise: Beeping!
-----------------------------------
C++:
#include 
#include 

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
    cout > word;
    for( int i = 0; i < word.length(); i++ )
    {
        cout  print(c + "\07"); Thread sleep 1000}
}

-----------------------------------
rizzix
Wed May 07, 2008 10:18 pm

RE:Exercise: Beeping!
-----------------------------------
public class Test {
	public static void main(String

-----------------------------------
rizzix
Wed May 07, 2008 10:20 pm

RE:Exercise: Beeping!
-----------------------------------
Hmm why is it that the syntax tags are messing up the "case" of the class names. :s

-----------------------------------
btiffin
Thu May 08, 2008 12:30 am

Re: Exercise: Beeping!
-----------------------------------
Heres one in SNOBOL4
***************************************************************
* Program to output a line, char by char with beeps and delays
*
* Associate TUBE with terminal mode OUTPUT; no newline
        OUTPUT('TUBE', 6, 'T')
* Define specs for CHBEEP and WAIT
        DEFINE('CHBEEP(STRING,DELAY)')
        DEFINE('WAIT(DELAY)')
* BEEP is Control-G
        &ALPHABET LEN(7) LEN(1) . BEEP
* Fetch a line from stdin, end on eof, or beep it out
        LINE = INPUT                            :F(END)
        CHBEEP(LINE,1)                          :(END)
* CHBEEP function peels off characters, displays, beeps, waits
CHBEEP  LINE LEN(1) . CH =                      :F(RETURN)
        TUBE = CH BEEP
        WAIT(DELAY)                             :(CHBEEP)
* WAIT function pauses for DELAY seconds
WAIT    T = TIME()
WAITING LT(TIME() - T, DELAY * 1000)            :S(WAITING)F(RETURN)
* The end
END

-----------------------------------
btiffin
Thu May 08, 2008 3:38 am

Re: Exercise: Beeping!
-----------------------------------
more c..!
#include 

int main()
{
    char lineis there a way to get around the lineWell, yes there is; look into fgets and realloc (or fread or ...) or loop across getch, and then google "buffer overflow" as to why it is not just a limit the number of characters problem.  Code like this is susceptible to attack.  Learn early and learn often.  Potential buffer overflow in C is bad.  Very very bad.  Learn to avoid it.  Write a safe gets for yourself and then carry it with you through your programming career.  Bosses will love you and you will help to make the world a better place for everyone.  And anyone reading this and thinking, but stdin only accepts 128 or 256 keystrokes; ponder what happens if someone redirects input from a file with 1000 characters and no newline.  Then ponder what might happen if those 1000 characters are hand crafted to look like machine instructions.

Sorry for the interruption, but this is an important thing to learn.  And when you do, bosses (and co-workers) really will love you for it.  :)

Cheers

-----------------------------------
wtd
Thu May 08, 2008 8:36 am

Re: Exercise: Beeping!
-----------------------------------
A little C#:
public class Test
{
    public static void Main(string

public class Test 
{
   public static void Main(string

-----------------------------------
btiffin
Thu May 08, 2008 12:48 pm

Re: Exercise: Beeping!
-----------------------------------
One in D 1.0 (by a D noob)
// read a line, output each char with a beep and a wait
import std.stdio;
import std.c.time;

void main() {
    char
Dang wtd; this is a fun exercise.  Great way to waste away coffee breaks.
Edit: trying the syntax tag

-----------------------------------
apomb
Fri May 09, 2008 12:14 am

Re: Exercise: Beeping!
-----------------------------------
#! /usr/bin/perl
#prints each letter of a word along with a beep and a one-second delay
#using "length" to find the length of the string

if ($ARGV !=0) {
    print "usage: beeptest word\n";
    exit;
}

$word = $ARGV

-----------------------------------
wtd
Fri May 09, 2008 12:28 am

RE:Exercise: Beeping!
-----------------------------------
Pascal!

program BeepTest;
uses crt;
    procedure Beep;
    begin
        write(stdout, #7)
    end;
var
    UserInput : String;
    LenOfUserInput, I : Integer;
begin
    ReadLn(UserInput);
    LenOfUserInput := Length(UserInput);

    for I := 1 to LenOfUserInput do
    begin
        write(UserInput[I]);
        delay(1000);
        beep
    end
end.

-----------------------------------
apomb
Fri May 09, 2008 12:40 am

RE:Exercise: Beeping!
-----------------------------------
variation to my previous one: 


#! /usr/bin/perl
#prints each letter of a word along with a beep and a one-second delay
#using "length" to find the length of a string
$| = 1;

if ($ARGV != 0) {
    print "usage: beeptest word";
    exit;
}

$word = $ARGV

as you can see in the first one, i forgot to take the comment out when i took out the array and foreach loop. this is what my original idea looked like, and it stil works, its just a little longer

-----------------------------------
wtd
Fri May 09, 2008 12:46 am

RE:Exercise: Beeping!
-----------------------------------
$| = 1; map { print "$_\a"; sleep(1) } split //, #ARGV[0]

-----------------------------------
btiffin
Fri May 09, 2008 9:07 pm

Re: Exercise: Beeping!
-----------------------------------
The palindrome exercise made me think about Icon, so heres a beeper in Icon
###############################################################
# Program to read a line; display each char with beep and delay
procedure main()
    every writes(!read(), char(7), delay(1000))
end

-----------------------------------
btiffin
Sat May 10, 2008 7:51 pm

Re: Exercise: Beeping!
-----------------------------------
Here's one if Forth, gforth in particular
: chbeep  pad dup 80 accept  + pad  do i c@ emit 7 emit 1000 ms loop ;  chbeep

-----------------------------------
michaelp
Sun May 11, 2008 7:56 am

RE:Exercise: Beeping!
-----------------------------------
Some of this code looks so confusing to me! Although Pascal looks very straightforward. :D

-----------------------------------
btiffin
Sun May 11, 2008 11:31 am

Re: RE:Exercise: Beeping!
-----------------------------------
Some of this code looks so confusing to me! Although Pascal looks very straightforward. :D
Never fear michealp.   :)  The compsci arena is so vast, that you have to carefully pick and choose the areas of expertise.  No one knows it all.  Don't even try, imho.  But, I would suggest exploring as much as you can.  All the different angles will make you better in the areas you do build up expertise in.  Programming languages are much like human languages.  No one knows them all.

My choice of well-rounded knowledge;   Assembler, AWK, bash, BASIC, Logo, Smalltalk, Pascal, Lisp, COBOL, Fortran, Prolog, C, C++, D, Java, Eiffel, Erlang, Python, perl, Ruby, Oz, J, R, SNOBOL, Icon, Forth, REBOL.   Those environments cover a lot (but not all) of the bases and paradigms.   Given those, picking up the syntax of any other language becomes a lot easier.  And those are my personal opinions.  Your mileage will vary.  For instance; learning Java is far more than just the syntax.  There are common mistakes, idioms, thousands of ready made classes and entire libraries to learn on the way to mastery.  This applies to most programming environments.

This weekend I'm playing in Inform 7 (pretty much programming in English ... and I dozed off too much in English class; relearning basic sentence structure and concise grammar; but it is kinda fun).  Luckily, just about every language now has open and free implementations so exploring won't cost you anything but time.

Note; my list is fairly long, but I've been doing this for 30 years now.  Don't think you need to have all this under your belt the first week.  My short list is Assembler, bash, AWK, C, Icon, Forth, REBOL (again a very personal list choice - and I don't do Windows - again personal choice, but it means I can't/don't apply for the plethora of .NET jobs out there).

If you ever get bored, check out http://en.wikipedia.org/wiki/Categorical_list_of_programming_languages and try and pick one or two languages from each of the categories (over time - there are 40 of them, last I looked).  You don't have to explore the breadth and depth of each, but getting past Hello World and then a small exercise or two should do to make you a world class coder able to take on anything and everything in whatever environment management may throw at you.

Cheers

-----------------------------------
michaelp
Sun May 11, 2008 11:47 am

RE:Exercise: Beeping!
-----------------------------------
I know C++. But all of the other stuff is very confusing to me. 
Thanks for that though + that link. :D

-----------------------------------
btiffin
Wed Jun 11, 2008 10:10 pm

Re: Exercise: Beeping!
-----------------------------------
I can't leave this one alone.  It has become my language refresher exercise.  :)
This would have looked shorter, but DISPLAY char WITH BELL NO ADVANCING END-DISPLAY was no good
OpenCOBOL 1.1  http://www.opencobol.org/
      * Beeper.cob for compsci.ca exercise
      ** Read a line of user input, display each character with a
      ** 1 second delay and a beep.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. beeper IS INITIAL.
       AUTHOR. Brian Tiffin.
       SECURITY. None.
       INSTALLATION. http://www.compsci.ca.
       DATE-WRITTEN. 11-June-2008.
       DATE-COMPILED.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 USER-DATA                    PIC X(80) VALUE SPACES.
       01 CHAR-COUNT                   PIC 99 VALUE ZEROES.
       01 CHAR-INDEX                   PIC 99 VALUE ZEROES.

       PROCEDURE DIVISION.
       BEGIN.
      * Fancy up the screen; work around for display
       DISPLAY SPACE WITH
           FOREGROUND-COLOR 3
           BACKGROUND-COLOR 1
           BLANK SCREEN
       END-DISPLAY
      * get the input   
       DISPLAY ": " WITH NO ADVANCING.
       ACCEPT USER-DATA.
      * get the user input length by scanning back for non space
       PERFORM VARYING CHAR-COUNT FROM 80 BY -1
           UNTIL USER-DATA(CHAR-COUNT:1) NOT = SPACE
       END-PERFORM
      * output each character with a beep and then pause
       PERFORM VARYING CHAR-INDEX FROM 1 BY 1
           UNTIL CHAR-INDEX > CHAR-COUNT
           DISPLAY USER-DATA(CHAR-INDEX:1)
               LINE 3 COLUMN CHAR-INDEX WITH BELL
           END-DISPLAY
           CALL "C$SLEEP" USING "1"
       END-PERFORM.
       EXIT PROGRAM.

I hope no one minds if I reopened a month-old.

And yes COBOL is indented 8 spaces, column 7 is * for comment, and the first 6 spots are reserved for punch card deck numbers.  When a coder dropped a box of cards (one line per card, 80 spaces) on the floor before getting them loaded into a reader ... think of playing 52 card pick up with 2000 cards and you have to pick them up in order ... so they "numbered" the lines of source code in the source code, just in case.  :)

And a stupid trivia (myth?) item; the size of a punch card had something to do with the size of the American dollar bill for easy access to cutting machines and boxes.

Nowadays COBOL can be freeform, removing the 1-6, 7, 8-72 special columns, making edits easier.  OpenCOBOL defaults to FIXED form, unless you $ cobc -free -x beeper.cob

And don't fear the COBOL.  Boomers are at 60, the COBOL crunchers get paid top dollar, there are billions of lines of legacy, you may get to play with big-iron on top-secret stuff, and well, it can make for a lucrative gig.  OpenCOBOL is free, supports a lot of the COBOL 85 standard, a fair chunk of 2002, other common extensions, links with C; so learning COBOL only costs time.

Reserved word heavy the COBOL is. My OC 1.1 build has 510 show up with cobc --list-reserved | wc.  To me thats titillating; wanting to know what all the words can help me with or teach me, before I even crack open any libraries.

Cheers

-----------------------------------
r691175002
Wed Jun 11, 2008 10:48 pm

Re: Exercise: Beeping!
-----------------------------------
Actionscript 3.0:
import flash.events.*;

var tField:TextField = new TextField();
tField.width = 550;
tField.height = 400;
tField.type = TextFieldType.INPUT;

var sInput:String;
var nIndex:Number = 0;
var nFrame:Number = 0;

function keyListener(e:KeyboardEvent):void {
	if (e.keyCode == Keyboard.ENTER) {
		tField.type = TextFieldType.DYNAMIC;
		sInput = tField.text;
		tField.appendText("\n");
	}
}
function frameListener(e:Event):void {
	if (sInput != null) {
		nFrame++;
		if (nFrame >= 30) {
			tField.appendText(sInput.substr(nIndex,1));
			nIndex++;
			if (nIndex > sInput.length)
				sInput = null;
			nFrame = 0;
		}
	}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyListener);
stage.addEventListener(Event.ENTER_FRAME, frameListener);
stage.addChild(tField);
stage.frameRate = 30;
A pretty roundabout way of doing it, flash is way too high level for this kind of stuff.  Also, you cannot generate sounds or output the bell character using only code.

-----------------------------------
alex.john95
Thu Jul 31, 2008 11:52 am

RE:Exercise: Beeping!
-----------------------------------
Very Funny...
