Frage deutsch
~~~~~~~~~~~~
Ich will sofort einen 30-minütigen QBasic-Crashkurs!
 
Ich will sofort einen QBasic-Crash-Kurs. Ich kann nicht warten!
Ich bin ungeduldig und will hier und jetzt eine bequeme Kurzeinführung in QBasic. Ich habe keine Lust alle möglichen Internetseiten nach Tutorials zu durchsuchen!
Kann mir jemand in ein paar Sätzen das Wichtigste von QBasic erklären?
 

Question English
~~~~~~~~~~~~~~
Immediately, I want to have a 30-minute QBasic crashcourse!
Give me a QBasic crash course. I wanna jump into QB instantly!
 

Antwort 1
~~~~~~~~~~
[ von Thomas Antoni und Frank Neumann ( "Triton";
www.silizium-net.de ) 15.5.2003 - 18.2.2004 ]
Für eilige QBasic-Neueinsteiger bieten wir hier in der QB-MonsterFAQ "SelfQB" an. Das ist ein Einsteiger-Schnellkurs, der auch im HTML- und im PDF-Format verfügbar ist auf unseren Webseiten
www.qbasic.de (unter "QBasic -> Tutorials", im Download-Paket sind auch alle Beispielprogramme enthalten) und www.silizium-net.de .
 

SelfQB - ein QBasic-Crashkurs, Version 2.0

Von Thomas Antoni und Triton, 2001 - 17.2.2004
*** Inhalt
1. Was ist SelfQB?
2. Was ist QBasic?
3. Wie bekomme ich QBasic auf meinen Computer?
4. Mein erstes Programm
5. Farbcodes
6. Variablen und Datentypen
7. Verzweigungen und Anwendereingaben
8. Schleifen und Abfrage von Einzeltasten-Betätigungen
9. Die QBasic-Onlinehilfe
10. Wartezeiten erzeugen
11. Mathe-Funktionen und FOR...NEXT-Schleifen
12. Zufallszahlen
13. Text bearbeiten
14. Subroutinen
15. Funktionen
16. Grafik
17. Sound
18. Felder
19. Arbeiten mit Dateien
20. Mehrfachverzweigungen mit SELECT CASE
21. EXE-Dateien erstellen
22. Tipps und Tricks
23. Wie steige ich noch tiefer in QBasic ein?
24. Liste der Beispielprogramme
 
 
*** 1. Was ist SelfQB?
SelfQB ist ein QBasic- Selbstlernkurs, der Anfängern einen blitzschnellen Einstieg in QBasic innerhalb von 2 bis 3 Stunden ermöglicht. Du brauchst keinerlei Vorkenntnisse in der Datenverarbeitung und im Programmieren. Der Kurs führt Dich ohne unnötigen theoretischen Ballast anhand leicht nachvollziehbarer Beispiele bequem in die wichtigsten Aspekte der QBasic- Programmierung ein. Für die ganz Eiligen unter euch reicht es aus, zunächst nur die Kapitel 1 bis 11 durchzuarbeiten, was in ca. einer Stunde möglich sein sollte.
 
Die 20 Beispielprogramme sind im letzten Kapitel aufgelistet und
stehen im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/ . Die blaugrün formatierten -> Fachbegriffe sind im LEXIKON der QB-MonsterFAQ näher erläutert.
 
Diesen Kurs gibt es exklusiv nur auf
www.qbasic.de und www.silizium-net.de sowie in der QB-MonsterFAQ. Eine Veröffentlichung auf anderen Webseiten ist nur mit Erlaubnis der Autoren gestattet.
 
 
*** 2. Was ist QBasic?
QBasic ist eine Programmierprache für MS-DOS, die aber problemlos auch unter allen Windows-Versionen lauffähig ist. QuickBasic ist der ältere und größere Bruder von QBasic und dazu 100% kompatibel. QuickBasic hat mehr Befehle als QBasic und beinhaltet einen zusätzlichen Compiler zum Erstellen von EXE-Dateien. QBasic hingegen ist ein so genannter Interpreter und kann erstellte Programme nur mit Hilfe der Entwicklungsumgebung Zeile für Zeile ablaufen lassen. QBasic wurde mit den MS-DOS Versionen 5.0 - 7.0 sowie Windows 95 und 98 kostenlos mitgeliefert. QB ist die Abkürzung für diese beiden Programmiersprachen. QB erfreut sich auch über 10 Jahre nach Erscheinen der letzten offiziellen Version von 1991 immer noch großer Beliebtheit. Im Internet findest Du hunderte von Webseiten zu QB mit Unmengen von Beispielprogrammen, Tutorials und Foren.
 
Doch was heißt eigentlich "BASIC"? ->
BASIC ist eine Abkürzung für: "Beginner's All-purpose Symbolical Instruction Code". Was übersetzt etwa "symbolische Allzweck- Programmiersprache für Anfänger" heißt. Wobei diese Bezeichnung nicht mehr ganz zutrifft, denn auch Profis benutzen heutzutage verschiedene BASIC-Sprachen.
 
Die Geschichte von BASIC beginnt 1960. Die Herren Kemmeny und Kurtz stellen die erste Version vor. Bis heute ist BASIC berüchtigt als Sprache mit der Programme entstehen, die schwer lesbar und voller Fehler (->
Bugs) sind, eine schlechte Bedienung enthalten, sehr langsam sind usw. Diese Vorurteile stammen alle aus der Zeit der Homecomputer. Und die waren bekanntlich ziemlich dürftig ausgestattet. 40 KB RAM und schnecken- langsame Prozessoren gab es da! Das ist natürlich kein Vergleich zu den Resourcen heutiger PCs. Die Programmierer waren damals also gezwungen durch Tricks Anweisungen zu sparen. Das führte schon bald zum sogenannten -> Spagetticode der häufig so extrem unübersichtlich war, dass die Programmierer ihn selber kaum noch verstanden. Und gerade dieser "Spagetticode" ist auch der Grund dafür, dass BASIC- Dialekte auch heute noch bei vielen Informatik-Professoren indiskutabel sind. Und gerade weil BASIC fast jeder hatte, gab es auch mehr BASIC-Spagetti :). Wäre z.B -> Pascal die vorherrschende Sprache geworden, hätte es genauso Pascal-Spagetti gegeben. Auch die Bedienung von BASIC selber war früher sehr schlecht.
 
Das alles hat sich aber mit Erscheinen der Microsoft-BASIC-Varianten ->
QuickBasic und QBasic entscheidend geändert. Nun steht eine sehr leistungsfähige Entwicklungsumgebung zur Verfügung. Ein weiteres Argument gegen BASIC war der geringe Sprachumfang. Das kann man QBasic/QB aber nicht mehr anlasten. Dinge wie -> Prozeduren, -> Unterprogramme, Einbindung von -> Assembler und -> C, Hardware-Programmierung und Ähnliches sind nun selbstverständlich. Bei etwas Disziplin kann man sauber, übersichtlich und ohne -> Spagetticode programmieren. Du siehst also: BASIC ist ein modernes Entwicklungssystem und beliebter denn je. Die alten Vorurteile gegen BASIC treffen alle nicht mehr zu. Vor allem ist BASIC eine Sprache mit Zukunft, denn es gibt immer mehr und leistungsfähigere Dialekte. Besondes erwähnenswert sind hier -> FreeBASIC, -> Blitz Basic, -> PureBasic, -> DarkBasic, -> PowerBASIC und -> VisualBasic.
Heute wird QBasic hauptsächlich von Programmier- Einsteigern und im IT-Unterricht der Schulen verwendet. Stelle bitte nicht all zu hohe Ansprüche daran, und versuche nicht, ein Spiel wie Quake 3 oder einen Internet-Browser damit zu programmieren. QBasic ist nach wie vor die ideale Sprache um die Grundlagen des Programmierens zu lernen. Alles, was Du mit QBasic lernst, kannst Du beim Aufstieg zu einem anderen BASIC-Dialekt oder zu einer ganz anderen Programmierprache sehr gut brauchen.
 
3. Wie bekomme ich QBasic auf meinen Computer?
Die QBasic-Entwicklungsumgebung besteht aus den beiden Dateien QBASIC.EXE und QBASIC.HLP, die insgesamt nur 335 KB groß sind. Du kannst QBasic auf vielen Webseiten herunterladen, z.B. auf www.qbasic.de unter "QBasci -> Download -> Compiler".
Kopiere die Dateien auf Deine Festplatte, z.B. in den Ordner "C:\QBASIC\". Bei der Gelegenheit solltest Du auch gleich einen Unterordner für Deine selbst erstellten QBasic-Programme anlegen, z.B. "C:\QBASIC\PROGS\.
Jetzt noch schnell eine Verknüpfung auf dem Desktop zu QBASIC.EXE eingerichtet und fertig ist die Installation.
Wenn Du willst, kannst Du im Windows-Eigenschaften-Dialog einige Optimierungen durchführen. Klicke dazu mit der rechten Maustaste auf QBasic.exe. Dort solltest Du die folgenden Anpassungen machen:

- Bei Bedarf die Schriftart anpassen, um eine optimale Lesbarkeit zu erzielen
- Über [Bildschirm | Fenster] den Ablauf in einem Teilfenster wählen
- Die "Leerlaufaktivität" auf einen mittleren Wert setzen
- Bei Windows 2000/XP "Ausführen als Symbol" aktivieren und unter "Sonstiges" den Punkt "Hintergrund...immer vorübergehend aussetzen" deaktivieren
- Bei Windows 2000/XP in den Eigenschaften der EXE-Datei (rechte Maustaste auf Qbasic.exe oder dem Kompilierten QBasic-EXE-Programm) unter "Erweitert" die DOS-"Kompatible Hardware-Timer-Emulation" aktivieren.
 
Weitere Tipps zum Betreiben von QBasic unter Windows XP gibt es im FAQ-Eintrag "QBasic unter Windows... -> Ich habe Probleme mit QB unter Windows XP!"
 
 
*** 4. Mein erstes Programm
Fast alle Kurse übers Programmieren beginnen mit einem Programm, das ein simples "Hallo Welt" auf den Bildschirm ausgibt. So wollen wir auch hier verfahren. Starte die QBasic-Entwicklungsumgebung QBASIC.EXE und tippe dort folgende Zeile ein:
print "Hallo Welt"
 
Wenn Du die erste Zeile mit der Eingabetaste abschließt, siehst Du, dass das QBasic- Befehlsschlüsselwort "print" sich automatisch in ein groß geschriebenes "PRINT" verwandelt. Diese automatische "Syntaxkontrolle" ist gerade für Einsteiger eine sehr angenehme Eigenschaft von QBasic. Du siehst jederzeit sofort, ob Du die Befehle richtig hingeschrieben hast. Wenn ein Befehl sich nicht in Großbuchstaben verwandelt, muss irgend etwas faul sein.
 
Wähle jetzt den Menüpunkt [Ausführen | Start] und schwuppdiwupp führt QBasic das Programm aus: Auf dem Bildschirm erscheint der Text "Hallo Welt". Gratulation: Du hast soeben Dein allererstes QBasic-Programm erfolgreich geschrieben und ausgeführt. Diesen Tag solltest Du Dir ganz dick im Kalender ankreuzen. Heute ist der Beginn Deiner Programmierer-Laufbahn :)
 
Um die genaue Bedeutung des Befehls PRINT... wollen wir uns erstmal nicht kümmern. Das wird später noch im Detail erklärt.
 
Mit einer beliebigen Tastenbetätigung kehrst Du zur Entwicklungsumgebung zurück. Da ich Dich für sehr gebildet halte ;-), denke ich, dass wir gleich mit etwas Schwierigerem weitermachen können. Zum Beispiel mit dem folgendem kleinen Progrämmchen:
 
'***********************************************************
' ERSTPROG.BAS - erstes kleines Programm fuer SelfQB
' ============
' (c) by Triton 2001/2002 *g*
'***********************************************************
CLS 'Bildschirm loeschen
texta$ = "Ich sitze hier am Computer und..."
textb$ = "...schreibe Programme, die keinen Sinn machen."
textc$ = "Doch sie sind cool - sie sind ja auch von mir!"
'
COLOR 1, 15 'blaue Schrift auf weissem Grund
LOCATE 8, 20 'Ausgabe ab Zeile 8, Spalte 20
PRINT texta$ 'Inhalt von texta$ anzeigen
'
SLEEP 2 '2 sec warten
LOCATE 10, 20
COLOR 4, 6 'rote Schrift auf braunem Grund
PRINT textb$
'
SLEEP 3
COLOR 15, 1 'weisse Schrift auf blauem Grund
PRINT 'Leerzeile anzeigen
LOCATE 12, 20
PRINT textc$
SLEEP 5
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/erstprog.bas .
 
Wie Du zugeben musst, sind das sehr einfach zu verstehende Zeilen. Wenn Du willst, kannst Du Dir den hier angegeben Code auch in den Windows-Editor kopieren [Makieren | STRG+C | Editor starten | STRG+V | als Datei namens ERSTPROG.BAS speichern] und in QBasic ausprobieren - über "Datei | Öffnen" .
 
Wir können aus diesem Beispiel Folgendes lernen:
 

1. CLS löscht den Bildschirm

2. Je Zeile schreibt man einen QBasic-Befehl hin. Mehrzeilige Befehle sind nicht möglich.

3. Das Hochkomma ' leitet Kommentar ein, das sind Erläuterungen zum Programm, die der QBasic-Interpreter beim Abarbeiten das Programms einfach überliest. Statt des Hochkommas kann man auch REM verwenden, das aber am Zeilenanfang stehen muss.

4. Texta$ ist eine Textvariable - die Fachleute sprechen von "Stringvariable" - und kann Textdaten speichern. Mit Texta$ = "Ich sitze hier am Computer" wird der in Anführungszeichen stehende Text in die Stringvariable Texta$ im RAM eingetragen. Die Namen von Stringvariablen müssen mit einem Dollarzeichen "$" abgeschlossen werden. Mehr über Variablen erfährst Du in Kapitel 6.

5. COLOR setzt die Farbe des Textes, der mit PRINT angezeigt wird, und nach dem Komma die Farbe des Texthintergrundes. Die Bedeutung der hinter COLOR stehenden Farbcodes erfährst Du im nächsten Kapitel. Du kannst sie auch in der QBasic- Onlinehilfe nachschlagen, indem Du mit der rechten Maustaste auf den Befehl COLOR klickst. Dadurch öffnet sich die passende Infoseite der QBasic- Onlinehilfe. Klicke dann unten im Hilfe-Fenster auf "Farbattribute". Wie Du siehst, verfügt QBasic über eine vorzügliche Onlinehilfe. Mehr dazu in Kapitel 9. Mit Esc beendest Du die Hilfe.

6. "LOCATE Zeile, Spalte" setzt die Position des Cursors auf dem Bildschirm für die anschließend folgende Textanzeige ("locate" ist das englische Wort für "lokalisieren", "Position festlegen").

7. PRINT zeigt den nachfolgenden Text an der durch LOCATE festgelegten Stelle auf dem Bildschirm an. Der Text kann direkt in Ausführungszeichen angegeben werden, wie beim obigen "Hallo Welt" - Programm, oder er kann in einer Stringvariablen, z.B. texta$, stehen. Einige Besonderheiten des PRINT- Befehls erfährst Du in Kapitel 13.

8. PRINT ohne nachfolgenden Text überspringt einfach eine Zeile, und auf dem Bildschirm erscheint eine Leerzeile, wie Du bei der letzten ausgegeben Zeile (vor textc$) sehen kannst.

9. SLEEP versetzt den Computer für die hinter SLEEP angegebenen Anzahl von Sekunden in einen schläfrigen Wartezustand und fährt danach mit der Ausführung des Programms fort. In Kapitel 11 erfährst Du, wie Du genauere und kürzere Wartezeiten erzeugen kannst.

10. END beendet das Programm und übergibt die Kontrolle wieder an die QBasic-Entwicklungsumgebung. Man kann END meist auch weglassen. Für eine saubere Programmiertechnik solltest Du es Dir aber angewöhnen, durch ein END den Abschluss Deines Programms eindeutig zu kennzeichnen.
 
Du siehst: Bei vielen Befehlen kann man die Funktion schon aus dem Befehlsnamen
ableiten, wenn man ein wenig der englischen Sprache mächtig ist. CLS bedeutet
z.B. "Clear Screen".
 
Jeder Befehl hat eine sogenannte Syntax. Dieser Begriff bezeichnet ganz einfach
den schematischen Grundaufbau eines Befehls. Wird die Syntax falsch angewendet,
so funktioniert der Befehl entweder gar nicht oder nicht so wie er soll. Das
kann man gut mit der Grammatik eines Satzes vergleichen: "Oder richtig ist Satz
das hier?" *g*. Bei den meisten Syntaxfehlern, wie etwa "SLEEP texta$", zeigt
QBasic beim Beenden der Zeile sofort eine aussagekräftige Fehlermeldung an.
 
 
5. Farbcodes
Programmieren soll keine triste schwarz/weiße Sache bleiben. Lass uns lieber farbige Welten erschaffen. In der folgenden Tabelle findest Du die Codes der 16 in QBasic standardmäßig verfügbaren Farben:
 
0 = Schwarz
1 = Blau
2 = Grün
3 = Türkis
4 = Dunkelrot
5 = Violett
6 = Braun/Oliv
7 = Hellgrau
-------------------
8 = Grau
9 = Hellblau
10 = Hellgrün
11 = Helltürkis
12 = Hellrot
13 = Rosa
14 = Gelb
15 = Weiß
 
Nur die ersten 8 Farben (Codes 0...7) sind als Hintergrundfarben verwendbar. In den später behandelten Grafik-Bildschirmmodi gibt es noch viele weitere Farben.
 
Und in dem folgenden Programm wollen wir gleich ein wenig mit Farben herumspielen:
 
'*****************************************************
' COLOR-1.BAS = Einsatz von Farben im QBasic-Textmodus
' ===========
' Thomas Antoni, 6.1.2004
'*****************************************************
COLOR 12, 1 'hellrote Schrift auf blauem Hintergrund
CLS 'Bildschirm loeschen d.h. in der
'Hintergrundfarbe blau einfaerben
LOCATE 12, 30 'Cursor auf Zeile 12, Spalte 30
PRINT "Die Welt ist farbig!"
PRINT
LOCATE , 25 'Cursor auf Spalte 30
COLOR 14, 2 'gelbe Schrift auf gruenem Hintergrund
PRINT " Und hier gelb auf gruen :) "
COLOR 13 'braune Schrift
LOCATE 20, 26 'Cursor auf Zeile 20, Spalte 22
PRINT "Rosa passt zu gruen ~(r;r)~"
COLOR 15, 0 'normale Farben: weiss auf schwarz
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/color-1.bas .
 
Wie Du siehst, kann man den Kommentar hinter dem Hochkomma hervorragend dazu verwenden, das Programm und die verwendeten Tricks näher zu beschreiben. Die ersten zwei Zeilen zeigen übrigens, dass CLS den gesamten Bildschirm in der vorher aktivierten Hintergrundfarbe (hier 1=blau) einfärbt - eine sehr praktische Sache!
 
 
*** 6. Variablen und Datentypen
-> Variablen sind Plätze im RAM, in denen Du Zahlen oder Textstücke abspeichern und beliebig oft im späteren Programmverlauf verwenden kannst. Du kannst auch den Inhalt der Variablen überschreiben, also z.B den Inhalt von a$ durch den Befehl a$ = "Test" verändern.
 
Es gibt mehrere Typen von Variablen. Im letzten Abschnitt hast Du die Stringvariablen kennengelernt, die durch ein an den Variablennamen angehängtes "$" gekennzeichnet werden und die Text enthalten. Dann gibt es die sogenannten Integer- Variablen, die ganze Zahlen von -32768 bis 32768 (2^15) beinhalten. Integer- Variablen werden durch das nachfolgende Prozentzeichen % gekennzeichnet - z.B. otto%. Dann gibt es die langen Ganzzahlen, die von - 2.147.483.647 bis 2.147.483.647 (2^31) reichen. Sie werden durch die Typbezeichnung & gekennzeichnet. Die nächst größere Kategorie sind die Komma- Variablen einfacher Genauigkeit (Typbezeichung = !) und doppelter Genauigkeit (#). Diese reichen bis zu astronomischen Größen mit jeweils 8 bzw. 16 Nachkommastellen. Benutze immer den niedrigsten Variablentyp der für Deine Anwendung ausreicht, also bitte nicht immer Variablen doppelter Genauigkeit verwenden. Integer-Variablen lassen sich am schnellsten verarbeiten.
 
Und hier noch eine kleine Zusammenfassung der QBasic-Datentypen mit Beispielen für die Variablennamen:
 
Variable...Datentyp................Beschreibung und Wertebereich..........
- anna% : INTEGER, Ganzzahl mit Vorzeichen (16 bit) -32768...32767
- otto& : LONG, lange Ganzzahl mit Vorzeichen (32 bit)
-2147483648...2147483647
- egon! : SINGLE, einfach lange Gleitpunktzahl (32 Bit, 7 Stellen genau)
±2,802597 *10^-45...±3,402823 *10^38
- egon : SINGLE (Das "!" ist bei SINGLE-Variablen weglassbar)
- paul# : DOUBLE, doppelt lange Gleitpunktzahl (64 Bit, 16 Stellen genau)
±4,446590812571219 *10^-323...±1,79769313486231 *10^308
- duda$ : STRING, Text-String (Zeichenkette, max. ca. 32767 Zeichen)
 
Die Kommazahlen werden in der IT-Sprache "Gleitpunktzahlen" genannt. Das Komma erscheint in QBasic - wie in England und USA üblich - als Dezimalpunkt. Ein normales Komma wird von QBasic als Fehler angemeckert.
 

Exponentialdarstellung von Gleitpunktzahlen
QBasic zeigt sehr kleine und sehr große Zahlen in einer Exponentialdarstellung an. Dabei wird der Zehner- Exponent "10^" bei SINGLE-Werten mit einem vorangestellten "E" und bei DOUBLE- Werten mit "D" angezeigt.
Beispiele:
a! = 2 ^ 24 'Einfach lange Gleitpunktzahl 2 hoch 24
PRINT a! 'Anzeige: 1.677722E+07 entspricht 1,677722 * 10^7
b# = 1 / 1234567890 'doppelt lange Gleitpunktzahl
PRINT b# 'Anzeige: 8.10000007371D-10 entspricht 8,10000007371 * 10^(-10)
 

Regeln für Variablennamen
Variablennamen dürfen bis zu 40 Zeichen enthalten und müssen mit einem Buchstaben beginnen. Gültige Zeichen sind A-Z, 0-9 und der Punkt (.). Umlaute, Sonderzeichen und QBasic-Schlüsselworte, wie etwa PRINT, sind als Variablennamen verboten.
 
 
*** 7. Verzweigungen und Anwendereingaben
Obwohl wir mit den bisher kennengelernten Befehlen schon ein paar nette kleine Programme schreiben könnten, würden die Programme schnell langweilig und eintönig werden und immer nach "Schema F" ablaufen. Es muss also mehr Abwechslung in unsere Programme - zum Beispiel durch Verzweigungen.
 
Dies lernen wir im folgenden Abschnitt, ebenso, wie wir den Programmbenutzer in das Geschehen eingreifen lassen können. Stellen wir uns vor, wir schreiben ein kleines Programm, das den Benutzer fragt, wie er heißt und wie das Wetter heute ist. Auf die letztere Frage soll entweder mit "gut", oder "schlecht" geantwortet werden. Das Programm soll die Benutzereingabe dann durch eine passende Bildschirmausgabe kommentieren. Ein solches Programm sieht etwa so aus:
 
'*********************************************************
' INPUTIF.BAS = Demo fuer die Befehle INPUT und IF...THEN
' ===========
' Dieses QBasic-Programm demonstriert
' - Benutzer-Abfragen mit INPUT
' - Verzweigungen mit IF...THEN
'
' (c) Triton, 2002
'*********************************************************
CLS
INPUT "Wie ist Dein Name ?", name$
INPUT "Wie ist das Wetter heute? (gut), oder (schlecht) "; wetter$
'
IF wetter$ = "gut" THEN text$ = ", dann gehen Sie lieber raus an die Luft!"
'
IF wetter$ = "schlecht" THEN text$ = ", dann bleiben Sie lieber hier!"
PRINT "Ok, "; name$; text$
SLEEP
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/inputif.bas .

Aus diesem Programm können wir sogar noch mehr lernen als aus dem ersten. Im Folgenden eine Erläuterung der neuen Befehle:
 

1. Anwendereingaben abfragen mit INPUT
Der Text in den Anführungszeichen "" wird als Frage gestellt, und die Antwort in der Variable hinter dem "," gespeichert. Vielleicht ist Dir aufgefallen, dass bei der 2. Frage ein "?" erscheint, obwohl es gar nicht in der Frage steht. Das kommt vom Semikolon ";" hinter der Frage. Wenn Du das Semikolon durch ein Komma ersetzt, wie bei der ersten Frage, dann erscheint kein Fragezeichen.
 

2. Verzweigung mit IF...THEN
Ganz offensichtlich bewirkt hier die IF...THEN - Anweisung eine Unterscheidung der Handlung. So wird bei der Eingabe von gutem Wetter ein anderer Text ausgegeben als bei schlechtem Wetter.
 

3. Erweitertes PRINT
PRINT wird hier anders verwendet als zuvor. Statt nur den Text in "" Zeichen auszugeben, wird auch der in den String-Variablen name$ und text$ hinterlegte Text 'rangehängt. Hätten wir übrigens statt einem ";" ein "," überall in die PRINT Anweisung gebracht, wären alle Textteile durch Tabulatorenweiten, also 14-er Zeichenschritte, voneinander getrennt! Mehr dazu in Kapitel 11.
 

4. SLEEP ohne Zeitangabe
Auch SLEEP wird hier anders verwendet als vorher. Da kein Zeitraum zum Warten angegeben wurde, wartet SLEEP einfach bis eine beliebige Taste gedrückt wird. Aber Vorsicht: SLEEP löscht den Tastaturpuffer nicht; das kann im nachfolgenden Programm zu unvorhergesehenen Effekten führen. In Kapitel 8 wirst Du eine professionellere Methode zum Warten auf einen Tastendruck kennenlernen, die diesen Mangel nicht hat.
 

5. IF...THEN- Abfrage
Die interessanteste Anweisung ist hier IF...THEN... Damit wollen wir uns jetzt näher beschäftigen.
 
Diese Anweisung lässt sehr vielfältig benutzen. Ihre Syntax kommt fast der eines normalen Satzes gleich:
IF <Bedingung> THEN <Anweisungen> ELSE <Anweisungen>
bzw. auf Deutsch:
WENN dies erfüllt ist MACHE dasunddas ANSONSTEN diesesundjenes
 
Dieses doch recht einfache Prinzip kann in sehr vielen Varianten eingesetzt werden, sodass sich alle möglichen Dinge unterscheiden lassen. Es ist für einen Programmierer wichtig, das Prinzip dieser Anweisung zu verstehen. Beherrscht man diese, dann tut man sich nämlich bei vielen Programmieraufgaben erheblich leichter! Jetzt wollen wir zu einem weiteren Beispiel kommen, das die Möglichkeiten des IF Befehls gut demonstriert:
 
'***********************************************************************
' IFTHEN.BAS = QBasic-Demo fuer IF...THEN-Abfragen
' ==========
' (c) Triton, 2002
'***********************************************************************
CLS
start:
INPUT "Welchen Wochentag haben wir heute (1=Montag...7=Sonntag): ", tag%
IF tag% < 1 OR tag% > 7 THEN
PRINT "Ungueltige Eingabe!"
GOTO start
END IF
IF tag% > 0 AND tag% < 6 THEN
PRINT "Werktag!"
ELSE
PRINT "Wochenende!"
END IF
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/ifthen.bas .
 
Hier gibt es wieder ein paar Neuigkeiten:
 

1. Mehrzeiliger IF...THEN-Befehl
Zum Einen bemerkt man, dass die THEN Anweisungen (also alles nach THEN) nicht in die gleiche Zeile geschrieben werden muss, sondern auch mehrere Zeilen lang sein kann. In solchen Fällen muss die IF...THEN -Anweisung durch eine extra Zeile mit END IF abgeschlossen werden.
 
Es gibt noch sehr viele weitere Verwendungsmöglichkeiten der IF Anweisung, die aber alle zu erklären würde zweifelsohne den Rahmen sprengen. Wenn Du Lust hast, kannst Du ja mal in der QBasic -Onlinehilfe unter "IF" stöbern. Gib dazu in der Entwicklungsumgebung einfach "if" ein und betätige dann die F1-Taste.
 

2. Unbedingte Sprünge mit GOTO
Außerdem entdeckt man GOTO mit einer nachfolgenden "Sprungmarke", in diesem Fall "start". GOTO veranlasst den Computer, den normalen Programmablauf zu verlassen und zu dem Befehl nach der Sprungmarke zu springen. Von dort macht er mit der Programmausführung weiter. Natürlich kann man mit GOTO auch in einen späteren Teil des Programms springen, der noch nicht regulär abgearbeitet wurde. Du solltest GOTO sparsam verwenden. Bei wildem Hin- und Hergespringe verlierst Du sonst schnell die Übersicht. Für die Namen von Sprungmarken gelten dieselben Regeln wie für Variablennamen; siehe Kapitel 6.
 

3. LINE INPUT ermöglicht Eingaben, die Kommas enthalten
Kommen wir zurück zu Abfragen, die den Benutzer betreffen. Wir hatten am Anfang bereits den Befehl INPUT verwendet. Wenn Du schon etwas mit ihm herumexperimentierst hast, hast Du vielleicht bemerkt, dass INPUT keine Kommas "," in den Antworten erlaubt. Das mag auf den ersten Blick zwar nicht schlimm erscheinen, kann Dir aber später große Probleme bereiten. Deshalb lernen wir jetzt noch eine Alternative kennen: LINE INPUT. Dieser Befehl unterscheidet sich von INPUT nur insofern, dass er auch "," in der Antwort toleriert. Die Syntax ist sonst die gleiche.

 
4. Vergleichsoperatoren
Nach IF erscheinen meist Vergleichoperationen. QBasic kennt die folgenden Vergleichsoperatoren:
IF a = b THEN ' a gleich b
IF a < b THEN ' a kleiner als b
IF a > b THEN ' a gr??er als b
IF a <= b THEN ' a kleiner oder gleich b
IF a >= b THEN ' a gr??er oder gleich b
IF a <> b THEN ' a ungleich b
 

5. logische Verknüpfungen AND und OR
Vergleichoperationen können durch die logischen Verknüfungen AND und OR miteinander kombiniert werden z.B.:
IF a >= 10 AND a <= 20 THEN PRINT "a liegt zwischen 10 und 20"
IF a < 10 OR a > 20 THEN PRINT "a liegt außerhalb des Bereichs 10...20"
 
Das erste Beispiel ist eine UND-Verknüpfung. Der THEN-Zweig wird durchlaufen, wenn a größer oder gleich 10 UND kleiner oder gleich 20 ist.
 
Das zweite Beispiel beinhaltet eine ODER-Verknüpfung. Der THEN-Zweig wird durchlaufen, wenn a kleiner als 10 ODER größer als 20 ist.
 
 
*** 8. Schleifen und Abfrage von Einzeltasten-Betätigungen
Ein weiterer Befehl, den man sehr gut gebrauchen kann, ist INKEY$. INKEY$ liest den Tastaturpuffer aus, also die letzte gedrückte Taste. Eine einfache Anwendungen von INKEY$ wäre zum Beispiel, eine Tastenabfrage in einer Schleife. Das kann man ganz einfach so machen:
 
'*************************************
' TIME.BAS = Uhrzeitanzeige in QBasic
' ========
' Die aktuelle Uhrzeit wird solange
' in Zeile 12, Spalte 35 angezeigt,
' bis der Anwender die Esc-Taste
' dueckt (ASCII-Code 27).
'
' (c) Thomas Antoni, 7.1.2004
'*************************************
DO
LOCATE 12, 35: PRINT TIME$
LOOP UNTIL INKEY$ = CHR$(27)
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/time.bas .
 
Dies Programm demonstriert die folgenden neuen Funktionen:
 

1. INKEY fragt eine Tastenbetätigung ab
Hier wird abgefragt, ob die ESC Taste gedrückt wurde, die den ASCII-Code 27 hat. Die in der Klammer angegebenen Codes für die einzelnen Tasten kann man in der QB Hilfe nachlesen unter [Hilfe | Inhalt | ASCII Zeichencodes].
 

2. Mehrere: Befehle: in: einer: Zeile
Wie Du in der 2. Zeile siehst, kannst Du mehrere QBasic-Befehle auch ausnahmsweise in eine Zeile schreiben, wenn Du sie durch Doppelpunkte voneinander trennst. Mach bitte sparsamen Gebrauch davon. Es erhöht nicht gerade die Übersichtlichkeit, besonders wenn die Zeilen dadurch länger als ca. 60 Zeichen werden.
 

3. Uhrzeit ermitteln mit TIME$
Die in QBasic eingebaute Systemfunktion TIME$ ermittelt die aktuelle Uhrzeit und liefert diese als Textstring zurück. In der Schleife wird die Uhrzeit immer wieder neu in der Bildschirmzeile 12 ab Spalte 35 angezeigt.
 

4. Schleife mit DO..LOOP UNTIL
Der zwischen DO und LOOP... stehende Programteil wird solange durchlaufen, BIS (engl. "UNTIL") der Computer ein Betätigen der Esc-Taste erkennt. Diese Programmsequenz stellt eine so genannte "Schleife" dar.

 
5. Weitere Schleifenkonstruktionen
QBasic bietet sehr flexible Schleifenkonstruktionen. Es gibt z.B. die folgenden 5 verschiedenen Methoden, die Zahlen von 0 bis 100 anzuzeigen:
 
'*****************************************************
' LOOP.BAS = 5 Möglichkeiten, die Zahlen von
' ======== 0 bis 100 anzuzeigen
' (c) Thomas Antoni, 7.11.03 - 30.1.2004
'*****************************************************
'
'------- Zaehlschleife mit FOR...NEXT ---------------
'Bei jedem Durchlauf wird i% um 1 erhöht
FOR i% = 1 TO 100 'Zaehlschleife:
PRINT i%
NEXT
'
'------ Fussgesteuerte DO...LOOP WHILE Schleife -----
SLEEP
COLOR 13
i% = 0
DO
i% = i% + 1
PRINT i%
LOOP WHILE i% < 100 'Ruecksprung nach DO, wenn die
'Fortsetzbedingung erfuellt
'------ Fussgesteuerte DO...LOOP UNTIL Schleife ------
SLEEP
COLOR 14
i% = 0
DO
i% = i% + 1
PRINT i%
LOOP UNTIL i% = 100 'Ruecksprung nach DO solange bis
'die Abbruchbedingung erfuellt ist
'------ Kopfgesteuerte DO UNTIL...LOOP Schleife ------
SLEEP
COLOR 8
i% = 0
DO UNTIL i% = 100 'Schleife durchlaufen bis die
i% = i% + 1 'Abbruchbedingung erfuellt ist
PRINT i%
LOOP
'
'------ Kopfgesteuerte DO WHILE...LOOP Schleife ------
SLEEP
COLOR 10
i% = 0
DO WHILE i% < 100 'Schleife solange durchlaufen bis
i% = i% + 1 'die Abbruchbedingung erfuellt ist
PRINT i%
LOOP
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/loop.bas .
 
Die FOR...NEXT-Schleife wird in Kapitel 11 noch genauer erklärt. Die fußgesteuerten DO...LOOP-Schleifen unterscheiden sich von den kopfgesteuerten dadurch, dass der Schleifenkörper auf jeden Fall einmal durchlaufen wird bevor die Fortsetzbedingung abgeprüft wird.
 
Mit UNTIL ("BIS") oder WHILE ("WÄHREND", "SOLANGE WIE") gibt man an, ob die nachfolgende Bedingung als Abbruchbedingung oder als Fortsetzbedingung fungieren soll.
 
 
*** 9. Die QBasic-Onlinehilfe
Wie Du schon gesehen hast, verfügt QBasic über eine hervorragende Onlinehilfe, die Du intensiv nutzen solltest. Sie ersetzt glatt ein viele 100 Seiten dickes Handbuch und enthält zu fast allen Befehlen aussagekräftige Beispielprogramme. Stöbere doch einfach mal ein bisschen darin herum.
 
Die QBasic-Online-Hilfe hat eine sehr komfortable Navigation. Ähnlich wie auf einer Webseite erhältst Du in jeder Situation Zusatzinformationen über eine Fülle von Text-Links, denen Du per Doppelklick mit der linken Maustaste oder - noch bequemer - per Einfachklick mit der rechten Maustaste folgen kannst.
 
Willst Du zu einem bestimmten Befehl mehr wissen, dann brauchst Du nur das Befehlsschlüsselwort in der Entwicklungsumgebung einzutippen und dann die F1-Taste zu betätigen. Oder Du klickst einfach mit der rechten Maustaste auf den fraglichen Befehl im Quelltext.
 
Wenn Du Dir einen Überblick darüber verschaffen willst, welche Befehle für eine bestimmte Problemstellung hilfreich sein könnten, dann wählst Du am besten [Hilfe | Inhalt | Schlüsselwort nach Kontext]. Daraufhin erscheint eine nette, nach Funktionen gegliederte Liste aller QBasic- Befehle. Klickst Du mit der rechten Maustaste auf einen der aufgelisteten Befehle, dann öffnet sich ein Hilfefenster mit detaillierten Informationen zu diesem Befehl.
 
Bei QuickBasic 4.5 ist die Onlinehilfe sogar noch wesentlich ausführlicher und auch etwas anders organisiert. Dort gelangst Du zu der nach Funktionen gegliederten Befehlsliste über [Hilfe | Themen | Schlüsselwortlisten | Doppelklick auf das gewünschte Thema].

 
*** 10. Wartezeiten erzeugen
Den Befehl SLEEP haben wir schon kennengelernt. Mit "SLEEP n" kann man Programmablauf für eine ganze Anzahl von n Sekunden anhalten. SLEEP 3 fügt z.B. eine Pause von 3 sec ein. Als kleinste Pausenzeit kannst Du 1 sec erreichen, indem Du "SLEEP 1" verwendest.
 
Genauere und kleinere Wartezeiten lassen sich mit dem TIMER-Befehl realisieren. Dazu verwendet man die TIMER-Funktion. TIMER liefert den aktuellen Stand der Systemuhr zurück und zeigt die Anzahl der seit Mitternacht vergangenen Sekunden an. TIMER hat eine Auflösung von 18,2 "Takten" pro sec. D.h. TIMER wird alle 0,055 sec (= 55 ms) um den Wert 0,055 erhöht. Wartezeiten unter 0,055 sec sind daher mit TIMER nicht realisierbar.
 
Der TIMER liefert Gleitpunktwerte vom Typ SINGLE zwischen 0.000 und 86400.000 sec (24 x 3600 = 86400; entspricht den in 24 Stunden von 00:00:00 h ... 23:59:59 h verstrichenen Sekunden). Bei der Realisierung von Wartezeiten, Stoppuhren und Countdown-Timern ist der Rücksprung des TIMERs vom Maximalwert 86400.000 auf 0.000 um Mitternacht zu berücksichtigen (genauer gesagt, von 86399.444 auf Null, denn statt der 86400.000 wird um Mitternacht ja die Null zurückgeliefert).
 
Das folgende Progrämmchen zeigt, wie Du Wartezeiten mit TIMER realisieren kannst.
 
'***************************************************************
' TIMER.BAS = Erzeugung von Wartezeiten
' =========
' Der Anwender gibt eine Wartezeit in sec ein.
' Anschliessend wird die TIMER-Funktion
' verwendet, um den Programmablauf fuer diese
' Zeit anzuhalten. Wenn die Zeit abgelaufen
' ist, ertoent ein Piepston.
'
' (c) Thomas Antoni, 12.11.2003
'****************************************************************
CLS
PRINT "Gib eine Wartezeit in [sec] ein; ";
PRINT "Nachkommastellen erlaubt....t = ";
INPUT t!
starttime! = TIMER 'Startzeit merken
'
DO
PRINT TIMER - starttime! 'abgelaufene Zeit anzeigen
LOOP UNTIL TIMER > starttime! + t! 'Warteschleife
'
PRINT "Wartezeit ist abgelaufen"
BEEP
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/timer.bas .
 
 
*** 11. Mathe-Funktionen und FOR...NEXT-Schleifen
QBasic ist ideal geeignet für mathematische Berechnungen jeder Art. Die wichtigsten Mathe-Operationen sind:
 
x = a + b 'Addition
x = a - b 'Subtraktion
x = a * b 'Multiplikation
x = a / b 'Division
x = SQR(a) 'Quadratwurzel von a
x = a^b 'Exponentialfunktion x = a hoch b
x = a^(1/b) 'allgemeine Wurzelfunktion b-te Wurzel aus a
x = ABS(a) 'Betragsbildung "Absolutwert von a"
x = LOG(a) 'Natürlicher Logarithmus von a (zur Basis e)
x = SIN(a) 'Sinus (a im Bogenmaß; 360° entspricht 2 * Pi)
x = COS(a) 'Cosinus (a im Bogenmaß)
x = TAN(a) 'Tangens (a im Bogenmaß)
a = ATN(x) 'Arcus Tangens, Umkehrfunktion des Tangens,
'ergibt den Winkel a, dessen Tangens = x ist
'im Bogenmaß
 
QBasic bearbeitet Winkel grundsätzlich im Bogenmaß. Das Bogenmaß wird in der Mathematik oft auch mit der Einheit "Radian" oder "rad" bezeichnet. Ein Vollkreis von 360° entspricht im Bogenmaß einem Winkel von 2 x Pi = 6,283. Liegt der Winkel im Gradmaß vor, so muss er gemäß der folgenden Formel ins Bogenmaß umgerechnet werden:
 
Winkel im [Bogenmaß] = Winkel in [Grad] * 6,283 / 360
 
Die Arcus-Umkehrfunktionen des sin, cos und cot unterstützt QBasic nicht direkt. Sie sind aber leicht über einfache Formeln zu berechnen. Weitere Infos dazu findest Du in meinem QBasic-Kochbuch, das auf
www.qbasic.de zum Herunterladen bereitsteht.
 
Und nun ein kleines Beispielprogramm, das in einer kleinen Tabelle für die Zahlen i von 1 bis 20 die Wurzel, den Quadratwert, die Potenz i hoch 2 und den Sinus von i (i im Gradmaß) angibt:
 
'*******************************************************
' MathDemo.bas = Kleines QBasic Mathe-Demoprogramm
' ============
' Fuer die Zahlen i=1 bis zwanzig werden folgende
' Berechnungen durchgefuehrt und die Ergebnisse
' angezeigt:
' - Wurzel aus i
' - i hoch 2
' - 2 hoch i
' - sin (i) ;i im Grad (2*Pi = 360 Grad)
'
' (c) Thomas Antoni, 24.10.2003 - 30.1.2004
'*******************************************************
'
CLS
Pi = 3.1416 ' Kreiskonstante
PRINT " i", "Wurzel(i)", "i^2", "2^i", "sin(i)"
PRINT
FOR i = 1 TO 20
PRINT i, SQR(i), i ^ 2, 2 ^ i, SIN(i * 2 * Pi / 360)
'der Klammerausdruck nach SIN rechnet den Winkel
'i vom Gradmass (0..360 Grad ins Bogenmass (0..2*Pi) um
NEXT i
SLEEP
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/mathdemo.bas .
 
Zu den einzelnen Befehlen nun noch ein paar Informationen :
 

1. FOR...NEXT-Schleife
Dieses Programm enthält einen bisher noch nicht näher behandelten Schleifenbefehl, nämlich die FOR...NEXT-Schleife. Beginnend beim Anfangswert "1" wird nach jedem Schleifendurchlauf die Schleifenvariable i um "1" erhöht und die Schleife erneut durchlaufen. Das Programm verlässt die Schleife nachdem sie mit dem Endwert i=20 durchlaufen wurde. Anschließend wird die Verarbeitung mit dem Befehl SLEEP hinter der Schleife fortgesetzt.
Die FOR-Schleife eignet sich besonders gut, wenn man die genaue Anzahl der Schleifendurchgänge schon kennt.
Der FOR...NEXT-Befehl hat noch einige Spezialitäten. Die Beschreibung dazu kannst Du Dir in der QBasic-Onlinehilfe anzeigen lassen. Tippe dazu in der Entwicklungsumgebung einfach "for" ein und betätige dann die F1-Taste.
 

2. Variablennamen ohne Typkennzeichen
Die Variable "i" hat im Namen keinen angehängten Kennbuchstaben für den Datentyp. In solchen Fällen nimmt QBasic den Datentyp SINGLE an (einfach lange Gleitpunktzahl). Wenn Ganzzahlen für eine Aufgabe ausreichen, solltest immer ein Typenkennzeichen verwenden, z.B. % für INTEGER- Werte. Das macht Deine Programme wesentlich schneller.
 

3. Besonderheiten des PRINT-Befehls
Du hast bestimmt die wohlgeordnete Bildschirmanzeige des Programms MathDemo.bas bewundert. Soll der PRINT Befehl mehrere Textstücke anzeigen, so werden diese normalerweise durch Semikolons voneinander getrennt, z.B.
t$ = "sel": PRINT "Wie"; t$ 'Anzeige erfolgt als "Wiesel"
 
Dabei erfolgt die Anzeige ohne trennende Leerzeichen, also im Beispiel als "Wiesel". Ersetzt Du das Semikolon durch ein Komma, so werden dagegen nach jedem Textstück die Spalten bis zum nächsten Tabulatorschritt mit Leerzeichen aufgefüllt. Ein Tabulatorschritt setzt den Ausgabe- Cursor auf den Beginn des nächsten 14er- Spaltenbereichs, also auf die 15., 29., 43., 57. oder 71. Spalte. Ersetze doch mal spaßeshalber in der obigen Befehlszeile das Semikolon durch ein Komma:
t$ = "sel": PRINT "Wie", t$ 'Anzeige erfolgt als "Wie___________sel"
 
Wie Du siehst, erfolgt die Ausgabe von "sel" ab der 15. statt der 4. Spalte. Der Tabulatorschritt ist hier durch Untrstriche ___ dargestellt. Die "tabulierte" Anzeige ist sehr nützlich für Anzeigen in Tabellenform, wie
das obige Programm MathDemo.bas zeigt.
 
Es gibt noch eine weitere Besonderheit beim PRINT-Befehl: Normalerweise wird nach einer Bildschirmausgabe per PRINT- Befehl ein Zeilenvorschub eingefügt. Steht am Ende des PRINT-Befehls aber ein Semikolon, dann unterbleibt der Zeilenvorschub, und ein nachfolgender weiterer PRINT-Befehl zeigt die Zeichen bündig zur ersten Anzeige in derselben Zeile an.
Beispiel:
PRINT "DU ": PRINT "Esel" 'Anzeige in 2 Zeilen
PRINT "DU";: PRINT "Esel" 'Anzeige in 1 Zeile
 
Der feine Unterschied liegt, wie gesagt, in dem Semikolon.
 
*** 12. Zufallszahlen
QBasic hat einen netten eingebauten Zufallsgenerator. Du machst ihn mit dem Befehl RANDOMIZE TIMER scharf. Ein danach folgender RND-befehl liefert Dir dann eine Zufallszahl im Bereich 0 bis 0.999999999. RND steht für engl. "RaNDom number" = Zufallszahl.
 
Was ist aber nun, wenn Du eine ganzzahlige Zufallszahl zwischen 1 und n benötigst? Dann gehst Du einfach nach dem folgenden Rezept vor:
 
'************************************************************************
' WUERFEL.BAS = Elektronischer Wuerfel
' ===========
' Bei jeder Tastenbetaetigung wird eine Zufallszahl zwischen 1 und 6
' erzeugt und angezeigt.
' (c) Thomas Antoni, 28.10.2003 - 7.11.2003
'************************************************************************
CLS 'Bildschirm loeschen
DO
RANDOMIZE TIMER 'Zufallszahlengenerator initialisieren
Wuerfelzahl% = INT(RND * 6) + 1 'ganzzahlige Zufallszahl zwischen 1 u.6
PRINT Wuerfelzahl%
DO
taste$ = INKEY$
LOOP WHILE taste$ = "" 'Warten auf Tastenbetaetigung
LOOP UNTIL taste$ = CHR$(27) 'Wiederholung bis Esc-Taste betaetigt
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/wuerfel.bas .
 
Dies Programm stellt einen "elektronischen Würfel" dar und liefert Zufallszahlen zwischen 1 und 6. Der durch RND erzeugte Zahlenwert 0...0.99999 wird mit 6 multipliziert, um einen Wert zwischen 0 und 5,999999 zu erhalten. Der INT-Befehl erzeugt daraus einen Integer-Wert (Ganzzahl) indem er die Nachkommastellen abschneidet. Der Wertebereich dieser Integerzahl ist 0 ...5. Um den Bereich um 1 auf 1...6 zu erhöhen, muss man noch eine "1" hinzuaddieren.
 
Je Tastendruck wird eine Zufallszahl angezeigt, solange bis der Anwender die Esc-Taste betätigt. Dafür sorgen die letzten 5 Zeilen. Diese solltest Du Dir genau durchlesen, denn sie bilden die Problemlösung für eine sehr häufige Aufgabenstellung: Eine Befehlsfolge soll bei jedem Tastendruck wiederholt und mit Esc abgebrochen werden.
 
 
Und wie erzeugt man eine ganzzahlige Zufallszahl zwischen min% und max%? Das geht nach der folgenden Formel:
RANDOMIZE TIMER 'Zufallsgenerator initialisieren
PRINT INT(RND * (max% - min% + 1)) + min%
'ganzzahlige Zufallszahl zwischen min% und max%
 
 
*** 13. Text bearbeiten
QBasic bietet sehr leistungsfähige Befehle zum Bearbeiten von Text, die wir im folgenden Progrämmchen am Beispiel des Wortes "Wiesel" demonstrieren wollen:
 
'*****************************************************************************
' TEXTBEAR.BAS = Textbearbeitung mit QBasic - die wichtigsten Befehle
' ============
' Dies Programm demonstriert die wichtigsten QBasic-Befehle zum
' Manipulieren von Zeichenketten (Strings). Als Beispiel-String dient das
' Wort "Wiesel". Nach der Erklaerung des jeweiligen Befehls folgt
' immer jeweils ein Anwendungsbeispiel.
'
' (c) Thomas Antoni, 7.1.2004 - 12.2.2004
'*****************************************************************************
CLS
t$ = "Wiesel" 'Die Befehle sind sowohl auf String-Konstanten (z.B. "Wiesel")
'als auch auf String-Variablen (z.B. t$) anwendbar
'
'---- t$ = t1$ + t2$ -> Strings zusammenfuegen
c$ = "Wie" + "sel"
PRINT c$ 'Ergebnis: "Wiesel"
'
'---- LEFT$(String$, n) -> Liefert n Zeichen links aus einem String zurueck
PRINT LEFT$("Wiesel", 5) 'Ergebnis: "Wiese"
'
'---- RIGHT$(String$, n) -> Liefert n Zeichen rechts aus einem String zurueck
PRINT RIGHT$(t$, 4) ' Ergebnis: "Esel"
'
'---- MID$(String$, m, n) -> Liefert n Zeichen ab dem m-ten Zeichen zurueck
PRINT MID$("Wiesel", 3, 2) 'Ergebnis: "se"; das m-te Zeichen zaehlt mit
'
'---- MID$(String$, m, n) = Ersatzstring$ -> n Zeichen eines Strings ab
'---- Zeichenposition m durch einen Ersatzstring ersetzen; ideal zum Ersetzen
'---- von Textpassagen durch einen anderen Text!
a$ = "Wiesel"
MID$(a$, 3, 2) = "rb" 'MID$ steht hierbei links von e. Gleichheitszeichen
PRINT a$ 'Ergebnis: "Wirbel"; "es" wird durch "rb" ersetzt
'
'---- LTRIM$(String$) -> Entfernt fuehrende Leerzeichen aus einem String
PRINT LTRIM$(" Wiesel") 'Ergebnis: "Wiesel" ohne Leerzeichen
'
'---- RTRIM$(String$) -> Entfernt am Ende e.Strings stehende Leerzeichen
PRINT RTRIM$("Wiesel ") 'Ergebnis: "Wiesel" ohne Leerzeichen
'
'---- INSTR(m, String$, Suchstring$) -> Sucht einen Suchstring in einem String
'------ ab dem m-ten Zeichen und meldet die Zeichenposition des ersten
'------ gefundenen Strings zurueck bzw. 0, wenn der Suchstring nicht gefunden
'------ wurde; ideal zum Suchen von Text!
PRINT INSTR(1, "Wiesel", "sel") 'Ergebnis: "4" = Zeichenposition von "sel"
'
'---- LCASE$ -> Gross- in Kleinbuchstaben umwandeln (nicht für Umlaute)
PRINT LCASE$("Wiesel") 'Ergebnis: "wiesel"
'
'---- UCASE$ -> Klein- in Grossbuchstaben umwandeln (nicht für Umlaute)
PRINT UCASE$("Wiesel") 'Ergebnis: "WIESEL"
'
'---- STR$ -> Numerischen Wert in String umwandeln
b$ = STR$(1 / 3)
PRINT "Ergebnis: "; b$ 'Ergebnis: .3333333
'
'---- VAL -> String in numerischen Wert umwandeln
PRINT VAL(".5") * 4 'Ergebnis: 2 (4 x 0,5)
'
'---- SPACE$(n) -> Liefert einen String mit n Leerzeichen
PRINT "Wie"; SPACE$(2); "sel" 'Ergebnis: "Wie__sel" mit 2 Leerzeichen
'
'---- STRING$(n, Text$) -> Liefert einen String, der n mal das erste Zeichen
'------- des angegebenen Textes enthaelt
PRINT STRING$(5, "Wiesel") 'Ergebnis: "WWWWW"
'
'---- LEN(String$) -> Liefert die Zeichenanzahl des angegebenen Strings
PRINT LEN("Wiesel") 'Ergebnis: 6
'
'---- ASC(String$) -> Liefert den ASCII-Code des ersten String-Zeichens
PRINT ASC("Wiesel") 'Ergebnis: 87 = ASCII-Code von "W"
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/textbear.bas .
 
Ich gehe auf die Befehle nicht näher ein, weil ich meine, dass die Beispiele im Programm TEXTBEAR.BAS für sich sprechen. Ich will nur noch erwähnen, dass in allen Befehlen als Text-Operand sowohl ein konstanter String-Wert in Anführungszeichen stehen kann, wie z.B. "Wiesel", als auch eine String-Variable, z.B. t$.
 

*** 14. Subroutinen
Häufig benötigte Programmteile kannst Du in eine Subroutine auslagern, die Du z.B. in einer Schleife immer wieder aufrufst. Subroutinen werden bei QBasic mit "SUB" abgekürzt und gelegentlich auch "Unterprogramme" oder "Prozeduren" genannt.
 
Tippe z.B. mal Folgendes in der QBasic-Entwicklungsumgebung ein:
CLS
FOR i% = 1 TO 20
CALL Quadrat(i%)
NEXT
SLEEP
END
 
Dies ist das Hauptprogramm, das 20 mal per CALL- Befehl die Subroutine "Quadrat" aufruft und an diese den "Parameter" i% übergibt.
 
Um jetzt die Subroutine "Quadrat" einzugeben, wählst Du in der Entwicklungsumgebung den Menüpunkt [ Bearbeiten | Neue SUB | Name: "Quadrat" ]
 
In dem sich jetzt öffnenden Fenster gibst Du die folgenden Befehle ein:
SUB Quadrat (i%)
PRINT i% ^ 2
END SUB
 
Startest Du nun das fertige Programm mit F5 oder [Ausführen | Start], so erscheint auf dem Bildschirm eine Liste der Quadratzahlen von 1^2 = 1 bis 20^2 = 400. Wie Du siehst, ist die als Parameter übergebene Variable i% auch in der Subroutine zugreifbar. Die anderen im Hauptprogramm verwendeten Variablen sind dagegen in der Subroutine unbekannt. Das Gesamtprogramm sieht dann so aus:
 
'********************************************
' SUBQ.BAS - Subroutine zur Quadratbildung
' ========
' (c) Thomas Antoni, 29.10.2003
'********************************************
DECLARE SUB Quadrat (i%) 'SUB deklarieren
'
CLS
FOR i% = 1 TO 20
CALL Quadrat(i%) 'Subroutine aufrufen
NEXT
SLEEP
END
'
SUB Quadrat (i%) 'Subroutine dedefinieren
PRINT i% ^ 2
END SUB 'Rueckkehr zum Hauptprogram
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/subq.bas .
 
Der erste Befehl in dem obenstehenden Programm ist die so genannte ->
Deklaration der Subroutine. Sie wird von QBasic automatisch eingefügt.
 
In der Entwicklungsumgebung wechselst Du zwischen dem Hauptprogramm und den SUBs über den Menüpunkt [Ansicht | SUBs... ] oder die F2-Taste. Das ist eine sehr komfortable Sache, weil Du die einzelnen SUBs ganz bequem durchblättern und annavigieren kannst. Einmal ausgetestete Subroutinen kannst Du in Deinen verschiedensten Programmen immer wieder verwenden, und Du kannst auch auf eine Reihe von SUB- Sammlungen anderer Programmierern zurückgreifen. Einige gute SUB-Kollektionen für häufig vorkommende Programmierprobleme findest Du auf www.qbasic.de unter [Download | Sonstiges]. Scheue Dich nicht, die dort verfügbaren SUBs in eigene Programme einzubauen. Warum solltest Du das Rad zum x-ten Mal neu erfinden? Auch die Profi-Programmierer gehen so vor, um Zeit und Geld zu sparen.
 
Es lässt sich übrigens auch mehr als ein Übergabeparameter an eine Subroutine übergeben. Dann werden die einzelnen Parameter in der Klammer durch Kommas voneinander getrennt aufgeführt, z.B.
CALL Multiplikation (Ergebnis%, Faktor1%, Faktor2%)
 
Für die Namen von Subroutinen und Funktionen gelten dieselben Regeln wie für Variablennamen; siehe Kapitel 6.
 
 
*** 15. Funktionen
Funktionen sind im Prinzip dasselbe wie Subroutinen. Sie können aber zusätzlich einen Zahlenwert oder einen String an das aufrufende Programm zurückliefern. Funktionen werden nicht durch CALL aufgerufen, sondern quasi anstelle einer Variablen hingeschrieben, z.B. rechts von einem Gleichheitszeichen in einer Wertzuweisung. Bei QBasic heißen die Funktionen FUNCTIONs.
 
Da die Funktion wie eine Variable benutzt wird, muss sie auch einen Datentyp haben, damit QBasic weiß, wie es den zurückgelieferten Wert interpretieren muss.
 
Im Folgenden findest ein Programmbeispiel mit einer FUNCTION "Quadrat%" vom Typ INTEGER, erkenntlich an dem Typkennzeichen "%". Es handelt sich dabei um eine Abwandlung des oben stehenden Programms SUBQ.BAS.
 
'***************************************************
' FUNCQ.BAS - Funktion zur Quadratbildung
' =========
' (c) Thomas Antoni, 30.10.2003
'***************************************************
DECLARE FUNCTION Quadrat% (i%) 'FUNCTION deklarieren
'
CLS
FOR i% = 1 TO 20
PRINT Quadrat%(i%) 'FUNCTION aufrufen
NEXT
SLEEP
END
'
FUNCTION Quadrat% (i%) 'FUNCTION definieren
Quadrat% = i% ^ 2 'Wertzuweisung an die Funktion
'Ruecksprung zum Hauptprogramm
END FUNCTION 'und i% uebergeben
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/funcq.bas .
 
In der QBasic-Entwicklungsumgebung "fühlt" sich eine Funktion genauso an wie eine Subroutine. Das Eingeben einer neuen Funktion erfolgt über [Bearbeiten | Neue FUNCTION... ].
 
 
**** 16. Grafik
Bisher haben wir nur den Textbildschirm 0 (SCREEN 0) kennengelernt, der bei QBasic voreingestellt ist und 25 bis 50 Textzeilen mit je max. 80 Zeichen untersützt. Für Mathe- und Business- Programme ist das ganz OK. Wenn Deine Programme aber mehr Spaß vermitteln sollen und Du bunte Bilder und Spiele gestalten willst, dann kannst Du auch vielfältige Grafik- Effekte in QBasic programmieren.
 
Für Grafikanzeigen verwendest Du die Screenmodi (Bildschirmbetriebsarten) SCREEN 1 bis 13, die sich hinsichtlich der Aufösung und der Anzahl Farben unterscheiden. Mehr Infos findest Du in der QBasic-Hilfe unter [Index | SCREEN].
 
Am beliebtesten sind die Screenmodi 9, 12 und 15. Wir wollen hier den Bildschirmmodus SCREEN 9 verwenden, der eine VGA/EGA- Auflösung von 640 x 350 Pixeln bietet. Jeder Bildschirmpunkt ist dabei über seine x- und y- Koordinaten ansprechbar. Die linke obere Ecke hat die Koordinaten (x=0, y=0) und die rechte untere Ecke (x=639, y=199). Du siehst also, die y-Achse zählt von oben nach unten und nicht wie aus der Schule gewohnt von unten nach oben.
 
Das folgende kleine Programm GRAFIK.BAS zeichnet ein Mondgesicht auf den Bildschirm und demonstriert dabei einige wichtige Grafikbefehle von QBasic:
 
'********************************************************
' GRAFIK.BAS = Kleine Demo der wichtigsten Grafikbefehle
' ==========
' Dieses QBasic-Programm zeigt ein Mondgesicht auf dem
' Bildschirm an und demonstriert damit die folgenden
' Grafikbefehle:
' - CIRCLE = Kreis zeichnen
' - PAINT = Flaeche ausfuellen
' - LINE = Linie zeichnen
' - PSET = Bildpunkt zeichnen
'
' (c) Thomas Antoni, 31.10.2003 - 8.1.2004
'********************************************************
SCREEN 9 'VGA-Grafikbildschirm mit 640x350 Pixeln
COLOR 1 'Blauer Bildschirmhintergrund
CLS 'Bildschirm ruecksetzen und blau einfaerben
CIRCLE (320, 175), 150, 14 'Kopf malen
'Kreis um Mittelpunkt M=(320|175) mit Radius r=150 Pixel
'und der Randfarbe 14=gelb zeichnen
PAINT (320, 175), 4, 14 'Kopf rot fuellen
'Kreis ab Mittelpunkt mit der Farbe 4 (=rot) ausmalen
'bis die gelbe Randfarbe (14) erreicht wird
LINE (260, 130)-(290, 130), 14
'Linke Augenbraue als Linie von (260|130) nach (290|130)
'mit Linienfarbe gelb (14) zeichnen
LINE (350, 130)-(380, 130), 14
'rechte Augenbraue
LINE (320, 150)-(320, 200), 14
'Nase
LINE (270, 235)-(370, 235), 14
'Mund
PSET (275, 140), 14
'linkes Auge als Bildpunkt (275|140) mit der Farbe
'gelb (14) zeichnen
PSET (365, 140), 14
'rechtes Auge
SLEEP
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/grafik.bas .
 
Weil ich nun mal kein Künstler bin, ist das Gemälde ausgesprochen schlicht ausgefallen *lol*. Du wirst bestimmt coolere Dinge auf den Bildschirm zaubern.
 
Die einzelnen Grafikbefehle sind im Kommentar erläutert. Hier nochmal die Zusammenfassung:
-
SCREEN n
Bildschirmmodus n = 0 ... 13 aktivieren

-
CIRCLE (x%, y%), r%, f%
Kreis mit dem Mittelpunkt (x%|y%), dem Radius r% und der Randfarbe r% zeichnen (zu dem Farbcode f% siehe Kapitel 5)

-
PAINT (x%, y%), f%, fr%
Fläche ausgehend von dem Punkt (x%|y%) mit der Farbe f% ausfüllen, solange bis die Randfarbe fr% erreicht wird

-
LINE (x1%, y1%)-(x2%, y2%), f%
Linie zeichnen zwischen den Punkten (x1%|y1%) und (x2%|y2%) in der Farbe f%

-
PSET (x%, y%), f%
Bildpunkt zeichnen an der Stelle (x%, y%) mit der Farbe f%
 
Die Komplettinfo zu diesen Befehlen findest Du wie immer in der QBasic-Onlinehilfe.
 
 
*** 17. Sound
QBasic kennt 3 Befehle zur Erzeugung von Soundeffekten mit dem PC-Speaker:
- BEEP - erzeugt einen Piepston
- PLAY - spielt eine oder mehrere Noten der Tonleiter
- SOUND - erzeugt einen Ton wählbarer Frequenz und Länge
 
Zu BEEP brauchen wir nichts weiter zu sagen. Wir können uns also gleich den
andereren beiden Befehlen zuwenden.
 

Der PLAY-Befehl
Wie der PLAY-Befehl funktioniert, demonstriert das folgende Beispielprogramm durch Abspielen von "Alle meine Entchen":
 
'********************************************************
' ENTCHEN.BAS = "Alle meine Entchen" mit QBasic spielen
' ===========
'
' (c) Thomas Antoni, 2.11.2003
'********************************************************
PLAY "MFT160O3L8cdefL4ggL8aaaaL2gL8aaaaL2gL8ffffL4eeL8ggggL4c"
SLEEP
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/entchen.bas .
 
Der PLAY-Befehl hat die Syntax
PLAY <Befehls-String$> .

Der Befehls-String$ kann die folgenden Bestandteile haben:

- M{F | B} - alle folgenden Noten im Vordergrund | Hintergrund abspielen.
Bei der Vordergrundbearbeitung hält das Programm an, bis der Play-
Befehl abgearbeitet ist. Bei der Hintergrundbearbeitung wird während
der Soundausgabe das nachfolgende Programm fortgesetzt

- {A|B|...|G|} - Note a, h, c, d, e, f oder g der Tonleiter in der
aktuellen Oktave spielen

- O<n%> - aktuelle Oktave für die folgenden Noten festlegen (n=0...6)

- L<q%> - Länge der nachfolgenden Töne festlegen (q=1-64; Tonlänge = 1/q;
1 ist eine ganze Note; Vorbesetzung: q = 4 ==> 1/4 Note)

- P<q%> - Pausendauer zwischen den nachfolgenden Töne festlegen (q=1-64;
Pausendauer = 1/q; Vorbesetzung: q = 4 ==> 1/4 Note)

- T<q%> - Tempo der nachfolgenden Noten in Viertelnoten/min festlegen;
(q=32-255); Vorbesetzung: q= 128

- MS - alle nachfolgenden Noten in Staccato spielen (kurz und abgehackt,
nicht mit dem nächsten Ton verbunden)

- ML - alle nachfolgenden Noten in Legato spielen (lang und getragen,
mit der nächsten Note verbunden)

- MN - alle nachfolgenden Noten wieder normal spielen (nicht Staccato
oder Legato)
 
Der folgende Befehl zeigt einige der aufgelisteten Möglichkeiten und lässt einen Big-Ben-Schlag ertönen:
 
- PLAY "MB ML T160 O1 L2 gdec P2 fedc"
im Hinter- | | | | | | | |
grund --+ | | | | | | +-- letzte 4 Noten
Legato -------+ | | | | +------ 1/2 Notenlänge Pause
Tempo 160 --------+ | | +---------- erste 4 Noten
1.Oktave ------------+ +-------------- Notenlänge: 1/2 Note
 

Der SOUND-Befehl
Der SOUND-Befehl hat die Syntax
SOUND <FrequenzInHerz%>, <DauerInSystemtakten%>
 
Es handelt sich dabei um sehr einfache Art der Soundausgabe: Es wird ein Ton mit der angegebenen Frequenz der Dauer in Systemtakten von je 0,056 sec (= 56 ms) ausgegeben.
 

Beispiel 1: 2000Hz-Ton für 336ms (6*56ms) spielen:
SOUND 2000, 6
 

Beispiel 2: Motorengeräusch ausgeben bis eine beliebige Taste gedrückt wird:
DO
SOUND 192, 0.5 'Motorengeraeusch
SOUND 188, 0.5
LOOP WHILE INKEY$ = ""
 

Beispiel 3: Sirene
'********************************************
' SIRENE.BAS = Demo des QBasic-Befehls SOUND
' ==========
' Dieses Programm erzeugt einen Sirenenklang
' (c) Winfried Furrer, 2000
'********************************************
ton = 780
bereich = 650
FOR zaehler1 = 1 TO 6
FOR zaehler2 = bereich TO -bereich STEP -4
SOUND ton - ABS(zaehler2), .3
zaehler2 = zaehler2 - 2 / bereich
NEXT zaehler2
NEXT zaehler1
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/sirene.bas .
 
Dies Beispiel zeigt, wie man den SOUND-Befehl in einer Schleife verwendet und dabei die Frequenz des Tons verändert. Mit dieser Methode lassen sich nette Soundeffekte erzielen.
 
Außerdem demonstriert das Programm noch eine Spezialität des FOR...NEXT-Befehls: STEP -4 bewirkt, dass das Programm die Schleife bei jedem Durchlauf mit einem um 4 reduzierten Wert von zaehler2 durchläuft.
 
 
*** 18. Felder
Ein -> Feld (engl. "Array") ist eine Anordnung mehrerer Variablen gleichen Typs, die in einen zusammenhängenden Speicherbereich abgelegt werden und sich bequem in Schleifen schreiben und lesen lassen. Man kann sich ein Feld wie einen Schubladenschrank vorstellen, der in jeder einzelnen Schublade einen Platz für eine Variable bietet, die auch "Feldelement" genannt wird. Vorne auf den Schubladen stehen Nummern. Jedem Feldelement ist eine solche "Feldelement-Nummer", der so genannte "Index", zugeordnet.
 
Bevor man ein Feld benutzen kann, muss man es über den DIM-Befehl "dimensionieren". Mit
DIM Alter%(100)
 
wird z.B. ein Feld namens "Alter%" vom Typ INTEGER mit 101 Feldelementen (Indices 0 ... 100) dimensioniert, das etwa das Lebensalter von 101 Personen enthalten kann. Die Indices beginnen also normalerweise mit "0" und nicht mit "1".
 
Felder sind hervorragend geeignet zum Speichern und Bearbeiten von Datenbanken, Messdatenreihen, Tabellen, Vektoren, Matritzen und ähnlichen gegliederten Datensammlungen. Der Feldindex steht in einer auf den Feldnamen folgenden Klammer.
 
Einzelne Feldelemente lassen sich über ihren Index bequem und effizient auch in Schleifen bearbeiten, meist in einer FOR...NEXT-Schleife, weil die Anzahl der Bearbeitungsschritte ja oft bereits vorher festliegt. Die folgende Befehlssequenz zeigt beispielsweise alle 101 im Feld Alter%(100) gespeicherten Feldelemente Alter%(0) bis Alter%(100) auf dem Bildschirm an:
FOR i% = 0 TO 100
PRINT Alter%(i%)
NEXT i%
 
Das folgende Programm FELD.BAS demonstriert den Umgang mit Feldern:
 
'*****************************************************
' FELD.BAS - Felder bearbeiten in QBasic
' ========
' Dies Programm demonstriert die Bearbeitung
' von Feldern in QBasic. Der Anwender wird
' aufgefordert, 3 Zahlen einzugeben. Diese werden
' im Feld z%(2) abgelegt. Anschliessend
' berechnet das Programm die Quadratwerte der
' Zahlen und zeigt sie an
'
' (c) Thomas Antoni, 4.11.2003 - 8.1.2004
'*****************************************************
DIM z%(2) 'Feld mit den 3 Feldelementen z%(0)...z%(2)
'deklarieren bzw. "dimensionieren"
CLS
PRINT "Gib drei Zahlen von 1 bis 100 ein"
'
'*** Zahlen eingeben *********************************
FOR i% = 0 TO 2 'Schleife ueber alle Feldelemente
PRINT "Gib die "; i%; ". Zahl ein: ";
INPUT z%(i%)
NEXT
'
'*** Quadratzahlen berechnen und anzeigen ************
FOR i% = 0 TO 2
PRINT "z("; i%; ") ^2 = "; z%(i%) ^ 2
NEXT
SLEEP
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/feld.bas .
 
Auch mehrdimensionale Felder sind möglich. Mit
DIM C#(9,4)
 
wird z.B. ein zweidimensionales Feld vom Typ DOUBLE (doppelt lange Gleitpunktzahl) deklariert (man sagt auch "dimensioniert"), das 10 Blöcke (Index 0...9) mit je 5 Feldelementen enthält (von 0 bis 4). Der Zugriff auf das 3. Element des 4. Blockes erfolgt so:
C# (2,3) = 86 .
 
Dieses zweidimensionale Feld kannst Du Dir quasi als eine Tabelle mit 10 Zeilen à 5 Spalten vorstellen. Mit dem obigen Befehl trägst Du den Wert 86 in Zeile 3, Spalte 4 ein.
 
 
**** 19. Arbeiten mit Dateien
Mit QBasic ist es kein Problem, Dateien anzulegen, auszulesen und zu schreiben. Das folgende kleine Progrämmchen schreibt einen vom Anwender einzugebenden Text in die Datei C:\TMP.TXT und liest ihn wieder aus:
 
'************************************************
' DATEI.BAS = Dateibearbeitung mit QBasic
' =========
' Dieses Programm demonstriert, wie man einen
' kleinen Text in die Datei c:\tmp.txt
' hineinschreibt und wieder ausliest. Diese
' Datei muss nach Beendigung des Programms
' von Hand geloescht werden.
'
' (c) Thomas Antoni, 4.11.2003
'************************************************
'
'-- Datei schreiben --
CLS
OPEN "c:\tmp.txt" FOR OUTPUT AS #1
INPUT "Gib Deinen Namen ein "; name$
WRITE #1, name$
CLOSE #1
'
'--- Datei lesen ---
OPEN "c:\tmp.txt" FOR INPUT AS #1
INPUT #1, t$
CLOSE #1
PRINT
PRINT "Du hast Folgendes eingegeben: "; t$
SLEEP
END
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/datei.bas .
 
Hierbei handelt es sich um eine ->
Sequentielle Datei. Mit jedem WRITE- Befehl wird eine neue Zeile angelegt, die mit einem INPUT-Befehl wieder auslesbar ist.
 
Die einzelnen Befehle wollen wir hier nun kurz erläutern:
 

1.
OPEN <Dateiname$> FOR OUTPUT AS #<Dateinummer>
Damit wird die Datei zum Schreiben geöffnet und ihr für die weitere Bearbeitung eine Dateinummer zwischen 1 und 255 zugewiesen. ACHTUNG: Exisitiert die Datei bereits, dann wird ihr Inhalt beim Öffnen komplett gelöschet!
 

2.
WRITE #<Dateinummer> , <Variable-1> [, Variable-2, ...]
Dieser Befehl schreibt den Inhalt einer oder mehrerer Variablen in die Datei, nach der letzten Variablen gefolgt von einem Zeilenvorschub. Text wird immer in Anführungszeichen abgespeichert und numerische Werte in ASCII- Text- Form. In der Datei erscheinen die Variablen dann ebenfalls durch Kommas getrennt.
 

3.
CLOSE [#<Dateinummer>]
Wenn Du das Schreiben oder Lesen beenden willst, musst Du die Datei jeweils ordnungsgemäß schließen. CLOSE ohne Dateinummer schließt alle offenen Dateien.
 

4.
OPEN <Dateiname$> FOR INPUT AS #<Dateinummer>
Dieser Befehl öffnet die Datei zum Lesen.
 
5. INPUT #<Dateinummer>, <Variable-1> [, Variable-2, ...]
Aus der Datei wird eine Zeile gelesen und die dort durch Kommas getrennten Bestandteile in die einzelnen Variablen eingetragen. Anmerkung: Zum Schreiben und Lesen von Text, der Kommas enthalten kann, verwendet man PRINT und LINE INPUT statt WRITE und INPUT; siehe QBasic- Kochbuch.
Das Lesen und Schreiben der Zeilen ist nur nacheinander ("sequentiell") möglich. Eine Zeile mitten in der Datei lässt sich nicht direkt auslesen. Das ist nur mit einem anderen Dateityp, der "Direktzugriffsdatei" (Random-Datei) möglich. Auf die Details und auf die verschiedenen Dateitypen wollen wir hier nicht weiter eingehen. Die Komplett- Info zur Dateibearbeitung mit QBasic erhältst Du in meinem QBasic- Kochbuch, das auf
www.qbasic.de zum Herunterladen bereitsteht.
 
 
**** 20. Mehrfachverzweigungen mit SELECT-CASE
Häufig ist bei einer Verzweigung der Wert einer einzigen Variablen dafür verantwortlich, welcher Zweig genommen werden soll. Anfänger lösen solche Programmierprobleme mit einer Folge von IF-Abfragen, etwa so:
IF Note% = 1 THEN ...
IF Note% = 2 THEN ...
IF Note% = 3 THEN ...
IF Note% = 4 THEN ...

Wesentlich effizienter und übersichtlicher diese geschachtelten IFs ist die Verwendung des SELECT CASE Befehls. SELECT CASE heißt zu deutsch "wähle einen Fall aus". Es wird abhängig vom Wert der Selektor- Variablen eine Fallunterscheidung gemacht.
 
'*****************************************************
' CASE-1.BAS - Beispiel 1 fuer den SELECT CASE Befehl
' ==========
' Es wird eine Schulnote als Zahl 1...6 abgefragt
' und in eine Textnote "sehr gut...ungenuegend"
' umgewandelt und angezeigt.
'
' von SM, 22.10.03
'*****************************************************
CLS
INPUT "Gib Deine Note ein (1...6): ", Note%
SELECT CASE Note%
CASE 1: PRINT "sehr gut"
CASE 2: PRINT "gut"
CASE 3: PRINT "befriedgend"
CASE 4: PRINT "ausreichend"
CASE 5: PRINT "mangelhaft"
CASE 6
PRINT "ungenuegend"
PRINT "Die Versetzung ist gefaehrdet!!!"
CASE ELSE: PRINT "Diese Note gibt es nicht."
END SELECT
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/case-1.bas .
 
Der Aufbau ist leicht zu verstehen. Hinter dem Befehl SELECT CASE steht der Name der Selektor- Variablen, die abgefragt wird, hier "Note%". Das Programm verzweigt dann zu demjenigen CASE-Zweig, bei dem hinter dem Schlüsselwort CASE der aktuelle Wert der Selektorvariablen aufgeführt ist. Wenn bei dem obenstehenden Programm beispielsweise die Variable Note% den Wert 4 hat, so springt das Programm zu CASE 4 und führt die dahinter bis zum nächsten CASE stehenden Befehle aus, in diesem Falle "PRINT "ausreichend"". Der ganze Block muß mit END SELECT abgeschlossen werden.
 
Sollte die Selektor-Variable einen Wert haben, für den kein CASE vorgesehen wurde, dann springt das Programm zum CASE-ELSE-Block. Wenn CASE ELSE fehlt, dann wird der gesamte SELECT-CASE-Block einfach übersprungen.
 
Wenn ein CASE-Block nur aus einem Befehl besteht, dann kannst Du ihn zusammen mit dem Befehl "CASE..." in eine Zeile schreiben - durch einen Doppelpunkt voeneinander getrennt. Besteht ein CASE-Block aus mehreren Befehlen, dann werden diese ab der Zeile unter dem CASE n hingeschrieben, wie Du bei CASE 6 sehen kannst.
 
Hier noch ein paar weitere Möglichkeiten der CASE-Anweisung:
 
CASE "j"
CASE "j", "J"
Wenn String-Variablen auf einen Text abgefragt werden, dann denke bitte an die Anführungsstriche. Der erste CASE Block wird durchlaufen, wenn in der Selektor-Variablen ein kleines j steht, der zweite CASE Block sowohl beim kleinen j als auch beim großen J. Mit dieser Methode kann man sehr elegante Tastenmenüs realisieren
 
CASE IS < 10
Bei Vergleichen muß das Schlüsselwort IS eingefügt werden. Diese Bedingung ist
erfüllt, wenn die Selektor-Variable kleiner als 10 ist.
 
CASE 5 TO 10
Hier muß die Selektor-Variable einen Wert zwischen 5 und 10 besitzen.
 
Das folgende Programm demonstriert einige der genannten Möglichkeiten:
 
'*****************************************************
' CASE-2.BAS - Beispiel 2 fuer den SELECT CASE Befehl
' ==========
' Dies Beispiel zeigt einige spezielle Moeglickeiten
' des SELECT CASE Befehls
'
' von Thomas Antoni, 6.1.2004 - 1.2.2004
'*****************************************************
CLS 'Bildschirm loeschen
INPUT "Gib eine Zahl zwischen 0 und 10 ein"; z
SELECT CASE z
CASE 0: PRINT "Eingabewert ist 0"
CASE 1 TO 8
PRINT "Eingabewert liegt zwischen 1 und 8"
CASE 9, 10: PRINT "Eingabewert ist 9 oder 10"
CASE IS < 0
PRINT "Falsche Eingabe. Eingabewert ist negativ!"
CASE ELSE
PRINT "Falsche Eingabe. Eingabewert zu gross!"
END SELECT
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/case-2.bas .
 
Und nun noch ein Beipielprogramm, das zeigt, wie Du mit CASE SELECT ein sehr schönes Tasten- basiertes Menü realisieren kannst. Als Selektor- Variable dient dabei das Textzeichen bzw. der ASCII-Code der betätigten Menüauswahl- Taste.
 
'******************************************************
' CASE-3.BAS - Beispiel 3 fuer den SELECT CASE Befehl
' ==========
' Dies Beispiel zeigt, wie man mit Hilfe des SELECT
' CASE Befehls ein Tastenmenue aufbauen kann.
'
' (c) Thomas Antoni, 9.1.2004 - 1.2.2004
'*****************************************************
DO
CLS
PRINT "Was willst Du tun?"
PRINT " (a) = Schlafen"
PRINT " (b) = Essen"
PRINT " (c) = Fernsehen"
PRINT " (Esc) = Abbruch"
PRINT "Waehle die gewuenschte Aktion (Taste a, b, c oder Esc)"
DO: taste$ = INKEY$: LOOP WHILE taste$ = ""
'Warten auf die Betaetigung einer beliebigen Taste
PRINT
'
SELECT CASE taste$
CASE "a": PRINT "Du hast Schlafen gewaehlt"
CASE "b": PRINT "Du hast Essen gewaehlt"
CASE "c": PRINT "Du hast Fernsehen gewaehlt"
CASE CHR$(27) 'Esc betaetigt -> Programm beenden
PRINT " ... und Tschuess!"
SLEEP 2 '2 sec warten
END 'Programm beenden bei Esc-Taste
CASE ELSE
PRINT "Fehler! Nur die Tasten a, b, c und Esc sind erlaubt!"
PRINT "Wiederhole bitte die Eingabe"
END SELECT
PRINT
PRINT "... zurueck zum Hauptmenue mit beliebiger Taste";
DO: LOOP WHILE INKEY$ = ""
LOOP
 
Das obige Programm steht im Verzeichnis Progs\ zur Verfügung sowie online unter www.antonis.de/faq/progs/case-3.bas .
 
Anstelle der Anzeige des gewählten Menüpunktes, z.B. mit PRINT "Du hast Essen gewählt", würde man normalerweise natürlich die zum Menüpukt gehörenden Befehle oder den Aufruf einer entsprechenden Subroutine hinschreiben.
Dieses Menü ist wesentlich eleganter programmiert als die meisten Menüs, die ich in Anfänger- Programmen sonst so finde. Es hat die folgenden Vorteile:
 
Durch die Verwendung von INKEY$ statt INPUT ist nach Eintippen des Buchstabens keine zusätzliche Betätigung der Eingabetaste erforderlich. Du kannst statt der Buchstaben natürlich auch Ziffern verwenden. Das ist oft noch ergonomischer.
Das ganze Menü steht in einer DO...LOOP- Schleife. Daher landet der Anwender nach Abarbeitung eines Menüpunktes wieder in der Menüauswahl und kann einen anderen Punkt wählen, ohne das Programm dafür verlassen und neustarten zu müssen.
Eingabefehler werden abgefangen, und bei Betätigung einer falschen Taste erfolgt eine Fehlermeldung und ein Rücksprung zur Menüauswahl.
Es wird auch ein Menüpunkt für den Programm-Abbruch per Esc-Taste angeboten. Viele Anfänger- Programme kranken leider daran, dass man sie nicht in jeder Situation mit Esc abbrechen kann. Das verärgert den Anwender und nimmt ihm die Lust, das Programm weiterzuverwenden.

Ich will Dir noch einen Trick verraten, der den meisten Anfängern völlig unbekannt ist: Statt der oberen DO...LOOP- Schleife zum Warten auf die Betätigung einer Menü- Auswahltaste kannst Du viel kürzer schreiben
taste$ = INPUT$(1) 'warten auf die Betaetigung einer beliebigen Taste
 
Dadurch wird ein Zeichen von der Tastatur in die Variable taste$ eingelesen und das Programm hält dafür automatisch an.
 
 
*** 21. EXE-Dateien erstellen
Wenn Du aus Deiner .BAS-Datei ein selbständig ablauffähiges EXE-Programm erzeugen willst, benötigst Du einen QuickBasic-Compiler, am besten die mit einer deutschen Bedienungsoberfläche verfügbare Version QuickBasic 4.5, die 100% kompatibel zu QBasic ist.
 
Lade Dir QuickBasic 4.5 Compiler z.B. von
www.qbasic.de herunter [Rubrik "QBasic | Download | Compiler"].
 
Gehe wie folgt vor, um ein BAS-Programm in ein lauffähiges EXE-Programm umzuwandeln :
Starte den QuickBasic-Compiler QB.EXE
Lade das BAS-Programm mit [Datei | Programm laden...]
Kompiliere Dein BAS-Programm mit [Ausführen | EXE-Datei erstellen... | (x) selbständige EXE-Datei | EXE erstellen und beenden]
Die .EXE-Datei wird jetzt erzeugt und im QB 4.5 Programmverzeichnis abgelegt
Die gleichnamige .OBJ-Datei kann ohne Bedenken gelöscht werden
 
Eventuell musst Du vorher in der QB 4.5-Entwicklungsumgebung die Pfadnamen für "Include- und Bibliotheksdateien" im Menüpunkt [Optionen | Suchpfade festlegen] richtig angeben. Du kannst fürs Erste dort überall denjenigen Pfadnamen eingeben, unter dem QB.EXE selber hinterlegt ist.
 
Aufsteiger von QBasic sollten die folgenden Hinweise beachten, um die häufigsten Einsteigerfehler zu vermeiden:
 
Bei Programmen, die den CALL ABSOLUTE Befehle erhalten (z.B. einige Mausroutinen), muss die QuickLibrary QB.QLB mit eingebunden werden. Starte dazu QuickBasic mit einem der folgenden Aufrufe:
 
- QB /L
- QB /L meinprog.bas oder
- QB.exe /L qb.qlb /run meinprog.bas
 
Eventuell kannst Du das entsprechende Kommando mit dem Windows-Editor in eine so genannte Batchdatei eintragen, die Du statt QB.EXE startest. Diese Batchdatei ist eine reine Textdatei mit der Erweiterung .BAT. Nenne sie z.B. "qb45.bat".
 
 
*** 22. Tipps und Tricks
Es gibt einige Tipps und Tricks die Dir das Programmieren in QBasic erleichtern. Eine kleine Auswahl haben wir hier aufgelistet. Unzählige weitere nützliche Tipps bietet die QB-MonsterFAQ auf www.qbasic.de.
 

QBasic mit 50 statt 25 Zeilen starten
Starte Quick Basic immer mit dem Parameter /h, um die Entwicklungsumgebung in einem doppelt großen Fenster zu genießen. Du kannst das entweder im Windows-Eigenschaftendialog von QBasic.exe eintragen oder Du erstellst Dir mit dem Windows-Editor eine Batch-Datei namens QBasic.bat folgenden Inhalts:
@echo off
cls
qbasic.exe /h
cls
 
Kopiere diese Datei in das QBASIC\ -Verzeichnis und starte künftig diese Batchdatei statt QBasic.exe.
 
Auch Deine Programme selber können im Textmodus (SCREEN 0) ein 50 Zeilen großes Fenster nutzen, indem Du vorne im Programm Folgendes hinschreibst:
 
WIDTH 80, 50 'VGA-Auflösung mit 80 Spalten und 50 Zeilen
COLOR 0, 7 'Schwarze Schrift auf hellgrauem Grund
CLS 'Bildschirm löschen
Dabei bewirkt der COLOR-Befehl ein mehr Windows-likes Aussehen des Anzeigebildschirms.
 

Dein Programm ist abgestürzt? Kein Problem!
Oft kommt es vor, dass sich ein Programm "festfährt" und auf Gund eines Programmierfehlers in eine Unendlichschleife eintaucht. Es gibt 3 Möglichkeiten das Programm trotzdem noch zu beenden:
 

1. Du drückst [STRG + PAUSE], um zur QBasic-Entwicklungsumgebung zurückzukehren, ohne Informationen zu verlieren.


2. Wenn das Programm immer bei einer INPUT oder LINE INPUT Abfrage stehen bleibt, kannst Du es mit [STRG + C] abbrechen. Informationen gehen nicht verloren, da man zu QB zurückkehrt.

3. Falls man sich im Vollbildmodus befindet, kann man mit [ALT]+[TAB] zum Windows- Desktop zurückkehren und das Programm auf Betriebssystemebene beenden. Nicht gespeicherte Veränderungen im Quellspracheprogramm gehen dabei allerdings verloren.
 

QB-Programme mit MS Word ausdrucken
QBasic-Quellspracheprogramme haben die Dateierweiterung "BAS" und liegen als "normale" Textdateien im DOS-ASCII-Code vor. Windows verwendet dagegen den so genannten ANSI- Zeichencode. Daher werden die Umlaute und einige Sonderzeichen Deiner BAS- Dateien von Windows- Textbearbeitungs- Programmen nicht korrekt angezeigt und ausgedruckt.
 
Alte MS-Word-Versionen konvertieren Textdateien, die im MS-DOS -ASCII- Zeichencode vorliegen, beim Öffnen automatisch in den Windows-ANSI-Code. Bei Word für Windows ab Version 97 ist dies leider nicht mehr der Fall. Daher werden die Umlaute und viele Sonderzeichen nicht richtig dargestellt und lassen sich nicht korrekt ausdrucken. Dies Problem ist jedoch leicht zu umgehen, wofür es zwei Lösungen gibt:
 

Lösung 1
Ändere die Dateierweiterung "BAS" in "ASC" (für "ASCII"). Dann konvertiert Word die Datei beim Öffnen automatisch in das Windows ANSI-Format.
 

Lösung 2
Der Konverter ist bereits installiert, Du musst ihn in Word nur unter [Extras | Optionen| Allgemein] mit dem Schalter "Konvertierung beim Öffnen bestätigen" aktivieren. Danach fragt Dich Word künftig beim Öffnen einer BAS oder TXT-Datei immer, in welchem Format genau diese vorliegt. "Nur Text", entspricht ANSI-Text, "MS-DOS-Text" entspricht dem bei BAS-Dateien vorliegenden ASCII-Text usw.
 
Jetzt kannst Du Deine BAS- Dateien korrekt ausdrucken. Du darfst sie natürlich nicht in Word abspeichern, wenn Du das ursprüngliche Format erhalten willst. Am Besten, Du erstellst für das Ausdrucken sicherheitshalber eine Kopie Deiner BAS-Datei.
 
 
*** 23. Wie steige ich noch tiefer in QBasic ein?
Du hast jetzt einige der wichtigsten Aspekte von QBasic kennengelernt. Wir hoffen, es hat Dir Spaß und Appetit auf mehr gemacht. Zum Weiterlernen kann ich Dir die folgenden drei Tutorials empfehlen, die Du auf www.qbasic.de unter [QBasic | Tutorials] herunterladen kannst:
 

- Adok's Way to QBasic - Hervorragender großer deutscher QBasic-Kurs von Claus-Dieter Volko, Wien. Mit 51 Beispielprogrammen, 68 Seiten.

- "Das QBasic-Kochbuch" - eine Bauanleitung für QBasic-Programme für Fortgeschrittene mit kompletter QBasic-Befehlreferenz, gegliedert nach Anwendungsgebieten, viele Beispiele, ca. 36 Seiten

- "QB-MonsterFAQ" - eine gigantische Sammlung mit über 800 der am häufigsten zu QBasic gestellten Fragen und deren Antworten. Mit einer sehr übersichtlichen Navigation. Da bleibt fast keine Deiner Fragen unbeantwortet. Ausgedruckt wäre das ein Buch mit weit über 2000 Seiten!
 
 
*** 24. Liste der Beispielprogramme
- ERSTPROG.BAS - Erstes kleines Programm
- COLOR-1.BAS - Einsatz von Farben im QBasic-Textmodus
- INPUTIF.BAS - Demo für die Befehle INPUT und IF...THEN
- IFTHEN.BAS - Demo für IF...THEN-Abfragen
- TIME.BAS - Anzeige der Uhrzeit - eine kleine Digitaluhr
- LOOP.BAS - Schleifen - 5 Möglichkeiten, die Zahlen 0...100 anzuzeigen
- TIMER.BAS - Wartezeiten erzeugen
- MATHDEMO.BAS - Kleines Mathe-Demoprogramm
- WUERFEL.BAS - Elektronischer Wuerfel - Zufallszahlen erzeugen
- TEXTBEAR.BAS - Textbearbeitung - die wichtigsten Befehle
- SUBQ.BAS - Subroutine zur Quadratbildung
- FUNCQ.BAS - Funktion zur Quadratbildung
- GRAFIK.BAS - Die wichtigsten Grafikbefehle - eine kleine Demo
- ENTCHEN.BAS - "Alle meine Entchen" mit dem PLAY-Befehl spielen
- SIRENE.BAS - Sirenengeheul erzeugen mit dem SOUND-Befehl
- FELD.BAS - Felder bearbeiten in QBasic
- DATEI.BAS - Dateibearbeitung mit QBasic
- CASE-1.BAS - Einfaches Beispiel für Mehrfachverzweigungen mit SELECT CASE
- CASE-2.BAS - Spezialitäten des SELECT CASE Befehls
- CASE-3.BAS - Komfortables Tastenmenü mit SELECT CASE
 

---=== Ende von SelfQB ===---
 
 
 
Answer 2
~~~~~~~~~~~~~~~~~
[ By Matthew R.Knight ]
 

INTRODUCTION TO QBASIC SERIES, PART 1
 
This article is dedicated solely to those who have never programmed before or know next to nothing about programming in QBasic. Starting here, the QB Cult magazine begins a step-by-step series that explains, from the beginning all you need to know to be able to create your own top quality programs successfully.
Many people find that after a while, the pre packaged programs and games that they've bought for their computer start to become a little boring and they begin to wonder if they can modify them or even write their own. But a computer can do nothing by itself. It must be given a list of instructions telling it in minute detail exactly what to do and how to go about achieving it. These instructions form what is called a program and the art and science of creating them is called programming.
 
There is nothing difficult about programming. You dont even have to be good at maths, unless of course, you want to write programs to perform mathematical tasks. All you need to begin with is to understand BASIC.
 
In order to write programs you are going to have to get a version of BASIC. As this magazine is dedicated to QuickBASIC users, you are going to have to download it, if you dont already have it. If you have a WINDOWS 95 CD then go to the directory OLDMSDOS and there you will find two files: QBASIC.EXE and QBASIC.HLP. Copy these files onto your hard drive, and then double click on the application QBASIC. You are now ready to write your first program in BASIC!
Let us begin by writing a small program and seeing what happens. This one will ask you to enter a number. It will then add one to that number and display the result. Type in the following program exactly as it is shown here, and once that has been done, push the F5 key to run the program.
 
REM Simple addition program
CLS
PRINT "Type in a number and push the ENTER key"
INPUT n
n = n + 1
PRINT "The number that you typed plus 1 is"; n
 
Let us examine what is actually going on in the above program. The first line of code uses the REM statement. REM stands for REMark. It is used to allow explanatory remarks to be inserted in a program. REM statements are not executed. Once a REM or its abbreviation, an apostrophe (') is encountered, the program ignores everything else until the next line of code.
 
The second line of code uses the CLS command. This stands for 'CLear Screen' and removes everything currently being displayed on the screen.
 
Line three uses a very useful command called PRINT. This command outputs text to the screen. Everything that is in the inverted commas " " will be displayed. For example, if you had to type PRINT "Hello world" and run the program, Hello world would be displayed on the screen.
 
Line four uses the INPUT command. It allows you to enter something into a program. It is followed by what is called a variable. The variable is the name of the place in the computers memory where the information that you typed will be stored. The enter key must be pushed after the information has been entered, as seen in the simple addition program above. Please note that you may call the variable anything you like.
 
Line five tells the computer to add one to the variable named n.
The last line of code once again uses the PRINT command, however, in this case it is used far more cleverly. It displays a message and then displays the value of the variable n. This is done by the adding of a ; sign after the last " sign, and then writing the name of the variable whose contents you wish to display.
 
I will now give you another example. This one is quite simular to the above with the exception that the variables will be used to store letters and words instead of numbers. To achieve this, a dollar sign $ will be added to the end of the name of the variable, for example: W$ In adding a $ sign to the end of the name of the variable, you tell the computer that you wish to store letters/text in the variable instead of numbers. These kinds of variables that store text are called string variables. This program also demonstrates that you can use several letters to form the name of a variable. Type out the following program exactly as shown here, and then run it by pushing the F5 key.
 
REM This program asks for your name and displays it
CLS
PRINT "Enter your name and then press the ENTER key"
INPUT NAME$
PRINT "Hello"; NAME$; "how are you doing?"
 
Okay, now you have learned how to work with variables, and how to display the values they contain. However, so far we have only been able to add and subtract values from the numeric variables, what if we want to multiply and divide numbers? Well, lets see if we can answer that question by means of an example. We will also use INPUT in a slightly better way. Type out the following program exactly as it is seen here, and then push the F5 key when done to see how it works.
 
REM Multiplying and dividing numbers in Qbasic
CLS
INPUT "Enter your first number and then press the ENTER key"; Number1
INPUT "Enter your second number and then press the ENTER key"; Number2
PRINT "Number 1 multiplied by number 2 = "; Number1 * Number2
PRINT "Number 1 divided by number 2 = "; Number1 / Number2
 
Well, that brings us to the end of part one in the series of this helpfull section for beginners. With what you have learned here you can easily create some nice text adventure games, or even some simple business software. Next month we will be looking at loop structures and graphics.
 
Happy programming! (is there any other kind?)
 
 

Introduction to Qbasic Part 2


 
Welcome to part 2 of the Introduction to Qbasic Series, QB newbies! I hope you have been doing some experiments with what you have learnt! Last month we covered only the simplest of Qbasic statements/functions. With that knowledge it would be possible to make some simple programs...pherhaps even a very simple game...but that's not where we're headed with these tuts! We want to make kick @$$ games like Wetspot 2 and Shadow of Power! Yeah! ^_^
 
There is a lot that we have to cover in this series...I want to go over a few more of the Qbasic text handling routines, after which I'd like to cover the basics behind graphics in Qbasic, and the various methods of controlling program flow. I'll bet even at this stage of the tutorial you're confused... don't worry, soon it will all make sense!
 
Okay, to get started, let's make a program similar to the type of programs that we were doing last issue - but with a few enhancements!
 
'Program to test if the product of two numbers is greater than 10.
CLS
COLOR 1
INPUT "Enter your 1st number:", n
INPUT "Enter your 2nd number:", n2
product = n * n2 'Multiply the two numbers together.
COLOR 12
IF product > 10 THEN PRINT "Your 1st number x 2nd number is bigger than 10"
 
Alright, the above program introduces several new concepts of programming in Qbasic. The first thing you're probably wondering about is the COLOR statement. Let me explain...the COLOR statement is used to select the color of the text that will next be PRINTed or displayed from within an INPUT statement.
 
The COLOR statement is always followed by a number. In the example program above, it is 1. The number tells the computer which color to use. The number may range from 0 to 15, and each number displays a different color. Try experimenting with different numbers and see what color is shown!
Okay, now that you've mastered that, lets's do something a bit cooler with COLOR. COLOR not only allows you to select the color of the text being PRINTed, it also allows you to select the background color! Let me demonstrate this by means of an example. Try this:
 
COLOR 2, 5
PRINT "Pretty cool, huh?"
 
Let's get back to the example code we wrote earlier. The last line of the program uses the IF statement. We have never encountered IF before, but it is likely that you can already see how it works. The line of code translated to english means "If number is greater than 10 then print...". Simple no?
There are other ways that you can use IF. It can also be accompanied by the ELSE statement. Let's demonstate this by example:
 
INPUT "Enter a number:", n
IF n = 10 THEN PRINT "Number is 10" ELSE PRINT "Number is not 10"
 
The ELSE statement really has exactly the same meaning in Qbasic as it does in english! Wow! Is Qbasic easy to understand or what?!
 
The last thing you are probably wondering about is the ' character in the code. That means the same as REM. It is slightly more versatile than REM though, since you can also use it like this:
 
PRINT "Hello world" 'Say hi to the world
 
You are advised to use ' instead of REM since it is more versatile and it is obviously much easier to use.
 

Controlling program flow:
Up until now we have only written programs that when run are executed from the first line, down to the last, one after another. Fortunately we are not limited to this. It is infact possible to make the computer go to another line of code, run it, then jump somewhere else in the code, and run code from there, and so on.
 
Before I explain this in any further detail, it is necessary that I explain what line labels are. You may not be aware of it but a programmer is capable of giving a certain line of code in his program a name. There are two ways of doing this:
You can either give it a name which is just a number, like this:
 
10 PRINT "Hello, this is line of code 10"
11 COLOR 2
12 PRINT "Hello world!"
 
Or, you can give your lines of code more meaningfull names like this:
 
FirstLineOfCode: PRINT "MyProg.bas - Written by Joe Soap"
PRINT
PRINT "What is your name"; name$
PRINT "What is your age"; age
WriteName: PRINT name$
WriteAge: PRINT age
EndOfCode: PRINT "Goodbye!"
 
You can also use a combination of the two if you want.
Okay, now let's see how we can make the computer read lines of code in different ways instead of just top to bottom!!!
 
PRINT "Hello"
GOTO EndOfCode
PRINT "This line will be skipped"
EndOfCode: PRINT "Bye"
 
The above program uses a new statement: GOTO. As you probably already guessed, GOTO stands for go to. It is used to GOTO a certain specified line label. Let's try another example just to clarify this further!
 
count = 0
Start: PRINT "This will be PRINTed 10 times"
count = count + 1
IF count <10 THEN GOTO Start
PRINT "That's it!"
 
The above program uses GOTO to perform what is known as a loop. This is a really bad way of performing loops. There are better ways of doing this. Here's a demonstration:
 
FOR n = 1 TO 10
PRINT "This will be PRINTed 10 times"
NEXT
PRINT "That's it!"
 
This program uses a FOR...NEXT type of loop structure. Everything in between FOR and NEXT will be done 1, up until 10 times. Try experimenting with this!
 
What actually happens in the FOR...NEXT loop is that the variable, in this case n, starts at 1, and is then increased by 1 until it reaches 10. When n is equal to 10 then the loop stops! Simple eh?!
 
But what if we didn't want the variable n to increase by only 1 at a time? Well, it is actually possible to make it increase by any number we want!
Let's demonstrate this by means of an example:
 
FOR n = 1 TO 20 STEP 2
PRINT "Another way of doing a FOR...NEXT loop"
NEXT
 
In the above example, n is increased by 2 every loop! You could have made the STEP any number you like. Try it! Experiment! That's the best way to learn about programming!
 
FOR...NEXT loops are not the only kind of loops in Qbasic. There is another type too! Let's demonstrate it as an example:
 
number = 0
DO
PRINT "Loop the loop!"
number = number + 1
LOOP UNTIL number = 10
 
As you can see, the DO...LOOP performs the loop until the variable called number is equal to 10.
What if you wanted to create a loop that would go on forever you ask? Well, it's simple to do with DO...LOOP. Try this:
 
DO
PRINT "This message will go on forever!"
LOOP
 
In the above program the message will continue to be PRINTed for as long as your computer is on, or until you push reset. In order to get out of the program, just press CTRL and BREAK together.
 
It's up to you whether you want to use the FOR...NEXT or DO...LOOP type of loop structures in your code, though, for certain types of programs you will find the one type of loop more useful than the other.
 

Graphics:
Until now we have only written programs that display text. However, text is rather boring, and it would be nice to know how to draw graphics eh?!
Okay, in order to use Qbasic's graphics functions we are first going to have to tell the computer which graphics mode to use. You have probably all heard of CGA, EGA, VGA and SVGA. These are all different graphics modes.
 
CGA is the worst of the graphics modes. It has only a few colors available for its use, and any graphics drawn in this mode will be very blocky.
EGA is a little better than CGA. The graphics will also be blocky, but at least you have 16 colors to play with, which is much better than in CGA!
VGA is the mode used by most Qbasic programmers today. It is also the newest graphics mode supported by Qbasic since it was made quite a long time ago. But don't worry, lots of Qbasic programmers, including myself, are constantly working on new functions for Qbasic, and many of these functions allow you to use graphics modes more up to date than VGA! In VGA you have 256 colors to play with. With this you can do some pretty cool graphics.
 
SVGA is the latest in graphics modes. It is not supported by Qbasic, although new add-on functions have been made for Qbasic which does allow you to use it. SVGA comes in many flavours. We'll discuss this screen mode at a later stage, when we have improved our programming abilities.
 
Okay, in order to tell the computer which screen mode to use, we use the SCREEN statement. SCREEN is followed by a number, and this number tells the computer which screen mode to use. To use CGA we type SCREEN 1. To use EGA we type SCREEN 7. To use VGA we type SCREEN 13
 
There are a number of other numbers that can be put after SCREEN, but the ones that I have listed above are the most commonly used ones.
Now it's time to learn our first graphics drawing function! Let's first type in some code and then we'll explain how it works afterwards...
 
SCREEN 13
PSET (160, 100), 14
 
All that this simple program does is draw a dot (known as a pixel) on the screen in yellow, in SCREEN mode 13(VGA).
 
It is now necessary that I explain what the term screen resolution means. Your monitor is like a grid. Every square on the grid is a place where a pixel can be drawn. In SCREEN mode 13, there are 320 blocks on the grid going across your screen, and 200 going downwards. SCREEN mode 13 is thus said to have a screen resolution of 320x200 since there are 320x200 blocks on the 'grid' in that screen mode.
 
In the example code above, we used the PSET statement to draw a dot on the screen. Let's say we wanted to draw a red dot on the screen 'grid' that is 10 pixels across on the grid (measured from the top left hand corner of the screen), and 100 blocks down on the 'grid'. We would use this code:
 
SCREEN 13
PSET (10, 100), 4
 
As you can see, the syntax for PSET is:
 
PSET (x, y), c
 
where:
x is the horizontal position on the screen 'grid' measured from the top left hand corner of the screen.
y is the vertical position on the screen 'grid' measured from the top left hand corner of the screen.
c is the color of the pixel you want to draw.
 
This is all very good, but it would take a very long time to draw a car, for example, using PSET. Can you imagine trying to draw the whole thing one pixel at a time?! That would take all day!
 
I bet right now you'r thinking "Boy would it be great if there was a Qbasic statement to draw lines!" Well, guess what, there is! And it's called LINE!
LINE is used like this: let's say we wanted to draw a blue line from the PSET position (10,10) to (80,95) then all we would have to do is this:
 
SCREEN 13
LINE (10,10)-(80,95)
 
That's it! Simple eh?!
If you're still confused, take a look at Provgamer's excellent graphics tutorial, which explains these graphics commands in greater depth.
There are a lot of other Qbasic graphics commands, but this entry into the series has got far too big already! We'll cover that another time! Until next issue, experiment with all that you have learned so far! It would not be a bad idea to try make a simple game of some sort - an adventure game, pherhaps. If you make anything, and you would like others to see it, then send it to me via email and I'll include it with the next issue of QBCM!
 
 
 

Introduction to Qbasic Part 3
 
Welcome to the third part in the Introduction to Qbasic Series! We went over quite a lot of information last time, having covered some more of the capabilites of Qbasic with regard to the handling of text, demonstrated how to allow the user input from the keyboard, did some LOOPing, and we even took a brief look at how to display graphics in Qbasic. This time I'd like to cover some more of these simple things before we go onto more difficult areas of programming, hopefully picking up some information that we left out along the way.
 
First of all, let's take a look at what else we can do with Qbasic as far as text handling is concerned. For starters, it would be nice if we could place text at a specific location on the screen wouldn't it? Lucky for us, Microsoft wrote made a nice little routine to do this for us. This is the LOCATE statement. The LOCATE statement tells the computer at which location on the screen the next PRINTed text must be placed. You'll recall that last issue, in order to explain how PSET works, I described the screen as a grid. When using LOCATE you also have to think of the screen as a grid, but it works a little differently. The 'grid' that we're talking about when using LOCATE is not made up of pixel spaces, it is made up of much larger blocks that are basically the same size as your average ASCII character. And what is an ASCII character you ask? Well, all the letters and numbers you see on the screen in DOS are ASCII characters. Apart from the number and letter characters, there are also some other ASCII's which look quite strange. You have seen some of them before. Some of them are used by the Qbasic editor to draw the menu's and the scrollbar, etc. ASCII stands for American Standard
Code for Information Interchange.
 
Another way of thinking about how LOCATE works is like this: suppose you wanted to put some text, for example "Qbasic rulz!", 5 ASCII spaces across the screen, and 10 ASCII spaces down. Then all you'd have to do is this:
 
LOCATE 10, 5
PRINT "Qbasic rulz!"
 
Try experimenting with different numbers and see what results you get. Using LOCATE will make your life much easier when using text! There are some other similar text handling routines, but there is no need to use them since LOCATE is generally capable of doing exactly the same as them, but is easier to use and more versatile.
 
Okay, now onto something more fun ^_^ Last time when we looked at using graphics in Qbasic we really didn't do very much. All we used was PSET and LINE - not too interesting. So we'll cover some better stuff this time round. It is sometimes necessary that you know the color code of a certain pixel on
the screen. You can actually do some pretty cool graphics effects just by knowing this simple information. In Qbasic, we use the POINT statement to obtain the color code of a certain pixel on the screen. The POINT statement is very versatile in the way that it may be used, and this makes it very
easy to understand.
 
For example, if you wish to get the color of a pixel at the coordinates (2,5) on the screen 'grid' into the Col variable then all you do is this:
 
PSET (2, 5), 2 'Place a green pixel at coodinates (2,5)
Col = POINT(2, 5) 'Get the color code of the pixel at (2,5)
 
You can also use POINT like this:
 
IF POINT(2, 5) = 2 THEN PRINT "That pixel is green"
 
Try playing around with this, and maybe you'll figure out how to do something cool using a combination of POINT and one of the other Qbasic drawing routines. I once wrote a little program using PSET and POINT that allowed you to print text on the screen, and it melted what looked like lava around it. There is no reason why you couldn't write a program to do exactly that!
 
Okay, now on to something a bit more cool. You have probably found that using LINE to draw graphics is rather difficult and time consuming. There is another Qbasic command for drawing that is much easier to use. It's called DRAW! It works quite unlike any other Qbasic routines we have covered so
far, as you'll soon see.
 
The DRAW statement has its own commands for doing things. For example, it has the U command for drawing lines up, and the D command for drawing lines down. Let's demonstrate this by means of an example:
 
SCREEN 13
PSET (10, 10), 2 'Start drawing at (10,10) in green
DRAW "U100" 'Draw a line up, 100 pixels in length
PSET (100, 100), 14 'Start drawing at (100,100) in yellow
DRAW "D20" 'Draw a line down, 20 pixels in length
 
There are lots of commands used with DRAW, but you'll probably never use half of them. We'll cover the most commonly used ones. If you want to know the others then you'll have to take a look at the Qbasic help file. You have probably already guessed that in order to draw right, you use the DRAW command R, and to draw left you use L. This should have been obvious. But what if you want to draw diagonally? Well, to draw diagonally up and right you use the DRAW command En, where n is a number specifying the pixel length of the line to be drawn. To draw diagonally down and right you use the commnd, F. To draw diagonally down and left you use G, and lastly, to draw diagonally up and left you use H. Simple no? Okay, here's an example:
 
SCREEN 13
PSET (160, 100), 2 'Start drawing at (160,100) in green
DRAW "H20 E20 F20 G20"
 
Note that I have put a space between each of the DRAW commands in order to make it easier for you to read. You don't have to do it this way though. You could just as easily have left them out, and it would do exactly the same thing. Like this:
 
SCREEN 13
PSET (160, 100), 2 'Start drawing at (160,100) in green
DRAW "H20E20F20G20"
 
It really doesn't make a difference.
 
Another usefull DRAW command is C which sets the DRAWing color. All you do is say Cn where n is the color code of the color in which you'd like to DRAW, and voila - you're DRAWing in that color. Could it really be any easier?! Let's demonstrate this by means of an example:
 
SCREEN 13
PSET (160, 100), 2 'Start drawing at (160,100) in green
DRAW "C2 H20 C3 E20 C4 F20 C5 G20"
 
Once again you can see that I've put spaces between each of the DRAW commands in order to make this easier to read and understand. If I were writing a program in which readability was not a necessity, I'd have left the spaces out since they're a waste of space.
 
There are many other DRAW commands that can be used, but I'm not going to cover it all here, when there is a perfectly good description of all of them sitting right there in the Qbasic help files. One thing that I should mention before we go onto something else is that you are able to use DRAW
with strings instead of specifying it right after the command. This allows you to save a lot of space. To clarify this further, here's an example:
 
Diamond$ = "C2 H20 C3 E20 C4 F20 C5 G20"
SCREEN 13
PSET (160, 100), 2 'Start drawing at (160,100) in green
DRAW Diamond$
 
In the above example you can clearly see that we have used DRAW with a string variable, instead of placing all the commands right after the DRAW statement. You will find this ability very usefull when you find the need to DRAW an object more than once. Without this ability you'd have to specify all those commands to draw the object again, and again, and again, which is really a waste of space.
 
Right. Now we've covered PSET, POINT, LINE and DRAW. With that you can, with some ingenuity, draw some fairly good graphics. But what if you want to draw a circle? Can you imagine writing the DRAW code for all of that! Yeah, it would be a total nightmare! Fortunately there is a Qbasic statement called
CIRCLE which allows you to draw circles. It's actually a bit more versatile than that in the light that it can not only draw circles, but also ellipses, and fractions of circles/elipses. It's a really great little routine. So let's learn how to use it!
 
We'll start off using CIRCLE just to do simple stuff, and then we'll work our way up, step-by-step, finally getting onto some more difficult stuff. Okay. In order to draw a yellow (color code 14) circle with a radius of 15 at the coordinates (160,100) on the screen 'grid' we'd type the following code:
 
SCREEN 13
CIRCLE (160, 100), 15, 14
 
Now that wasn't so hard, was it? Right, now that we've mastered the drawing of circles, I think it's time that we move onto ellipses. You may not have heard of an ellipse before, so this is what it is: an ellipse is, in the most simple terms I can think of, basically like a squashed circle! You can
probably imagine what I mean. It can be squashed from the top, or from the side. It doesn't really matter. Any squashed circle is an ellipse!
 
Let's, for example, say you wanted to have a circle that looked squashed from the top. First thing you have to think about is how squahed you want it to be. If we wanted to squash the circle, from the top, by 50% then we'd do this:
 
SCREEN 13
CIRCLE (160, 100), 15, 14, , , 50 / 100
 
If we wanted it squashed by 70%, from the top, then we'd do this:
 
SCREEN 13
CIRCLE (160, 100), 15, 14, , , 30 / 100
 
Simple no? Unfortunately, although we are able to describe the squashing effect in degrees here, the CIRCLE routine doesn't actually think of it that way, and that makes life quite difficult when we want to squash a circle from the sides - the degrees thing doesn't work anymore. It actually works like this: the division (above it is 29/100) which is actually called the aspect describes the ratio of the x radius to the y radius (x;y). The default aspect ratio depends on the screen mode, but gives a visual circle in any graphics mode, assuming a standard monitor screen aspect ratio of 4:3.
 
Did that make you a little dizzy? Yep? Okay, well, then let's go about it this way...practise! Play around with this until you understand! That's the best way to understand programming. Just to get you started, here's an example program showing you how to squash a circle from the side:
 
SCREEN 13
CIRCLE (160, 100), 15, 14, , , 170 / 100
 
Play around with this and it'll soon make sense.
 
Okay, as I mentioned earlier, it is possible to draw fractions of the circle, but that is slightly mathematical so I'll leave that for another time. I think I've confused you enough for one day!
There are still other graphics routines to cover, but we'll have to leave that for another issue. We have said more than enough about graphics this month!
 
Okay, we'll cover one more aspect of programming before I leave you to play around with what you've learned this issue. Sound in Qbasic! Before we even start this I need to explain one simple thing - Qbasic is, ordinarily, only able to produce sound through the internal PC speaker. You probably didn't even know that you have a speaker inside your computer, but you do. In the old days of computing there was no such thing as sound cards, and sound amplifiers for the computer. Such things were unheard of. In those days everyone used to have to play sound through the little speaker inside the computer. Unfortunately the internal speaker is really junky. Any sound that comes from it sounds terrible. But, as a newbie, it's the only sound that'll be available to you for a while. There are ways to use the sound card in Qbasic, but it's really difficult, so we are not going to cover that
at this stage.
 
Okay, I have rambled on long enough! We have quite a few Qbasic statements at hand which generate sound through the PC speaker. We'll start off with some simple stuff. It's fairly clear that the simplest form of sound we could possibly get the computer to do is just a beep. What could be easier
than that? Well, there is a Qbasic statement called BEEP that does just that!
 
BEEP generates a beep-like noise from the internal speaker at 800hz (800 cycles per second) for one-quarter of a second. It's really easy to use BEEP. Let's test it:
 
BEEP
 
Yep! That's it! That's all you have to type to use BEEP. Could anything be any easier than that?! Well congratulations, you've just mastered yet another Qbasic statement, and it's only taken you two seconds! ^_^
 
Okay, soon you're likely to get bored with BEEP. With BEEP you are not able to specify the pitch of the BEEP and the duration for which it plays. And that is no good. No good at all. Okay, well this isn't much of a problem. There is a Qbasic statement called SOUND which allows you to do exactly
what BEEP won't allow you to do! The syntax of SOUND is:
 
SOUND frequency, duration
 
frequency is the pitch of the sound. For those of you who don't know what this means (get a dictionary!) here's some examples - an example of a low pitch would be thunder. It sounds deep and has a low pitch. An example of a high pitch would be the squeek of a mouse. It has a high pitch. The higher the number is in place of frequency, the higher the pitch of the sound. The frequency may not be lower than 37, and not higher than 32767.
 
duration specifies the amount of time the computer has to spend making the sound. It is measured in clock ticks. Clock ticks occur 18.2 times per second. The duration may not be less than 0, and not higher than 65535.
 
Ah, okay, now is a good time for an example, no?
 
SOUND 300, 70
 
If you really want to give yourself a headache (why would you want to do
that?!) then run the following program:
 
SOUND 5000, 65535
 
I would not advise running that program. You'll get a terrible headache. You could easily write a program that would trick somebody into thinking there's a mosquito in the room ;)
 
Now the problem with this stuff is that it's really hard to write music with it. It's even harder to try and write sound effects. With music we are accustomed to sounds being described as A,B,C,D,E,F and G. Well

Here's a list of the equivelent frequency's for them! ^_^ I took this list from a book I have on Qbasic. For some reason there are a number of different A's, B's, C's...etc. I know nothing about music so I have no idea why this is the case. Those of you who know about music will be able to make more sense of this than I can ;)
 
Note Frequency Note Frequency
C 130.810 C* 523.250
D 146.830 D 587.330
E 164.810 E 659.260
F 174.610 F 698.460
G 196.000 G 783.990
A 220.000 A 880.000
B 246.940 B 987.770
C 261.630 C 1046.500
D 293.660 D 1174.700
E 329.630 E 1318.500
F 349.230 F 1396.900
G 392.000 G 1568.000
A 440.000 A 1760.000
B 493.880 B 1975.500
*Middle C.
 
By doubling or halving the frequency, the coinciding note values can be estimated for the preceding and following octaves.
 
To produce periods of silence, use the following statement: SOUND 32767, duration To calculate the duration of one beat, divide the beats per minute into the number of clock ticks in a minute (1092).
The following table illustrates tempos requested by clock ticks:
 
Tempo Notation Beats/Minute Ticks/Beat
very slow Larghissimo
Largo 40-46 27.3-18.2
Larghetto 60-66 18.2-16.55
Grave
Lento
Adagio 66-76 16.55-14.37
slow Adagietto
Andante 76-108 14.37-10.11
medium Andantino
Moderato 108-120 10.11-9.1
fast Allegretto
Allegro 120-168 9.1-6.5
Vivace
Veloce
Presto
very fast Prestissimo
 
Like I said, I know nothing about music, and I thus have no idea what the above table is talking about. The only thing that I know about music is that it comes out of the radio! ;) Those of you who know about music will probably find the above information very usefull, but as for the rest of you
who know no more about that stuff than me, don't worry about it. It's still possible to do cool stuff with SOUND without any knowledge of music.
 
There's another way to use music with the internal speaker in Qbasic, but we'll cover that (and other things) next issue. Until next month, just play around with what you have learned, and see if you can come up with something
 
Cool. If you make a little program, and you are proud of it and would like others to see it, then email it to me at horizonsqb*hotmail.com and I'll include with the next issue of the QBCM! Have fun with Qbasic!!! ^_^
 
 

Answer 3
~~~~~~~~~~~~~
[
By Sane <sane*telia.com> ]
 

 

The Very BASICs
This is a pretty old tutorial that I wrote about 2 years ago or something, and thanks to Wildcard, I came to think of that it could be used in QBCM, so now it's here, and I hope someone gets something useful out of it. Otherwise it does its job as a filler :)
 
A simple Hello World program...
 
As almost all other programming tutorials for beginners, this tutorial has also got a "Hello World" program.
The program is basically a program printing "Hello World" to the screen, and here it comes:
 
'A simple "hello world" program, made by Sane
PRINT "Hello World"
END

 
If you typed that text into QB, you have already made your first program!
As you can see, if you typed this program into QB, and started it using Shift+F5, the PRINT function in QB prints what is between the quotes.
If you use ' at a line, everything after that sign on the line will be ignored by QB, and thus you can make comments or remarks in your programs, to make understanding your own programs easier.
 
Now you may ask: "Why wouldn't I understand my own programs, I'm not that stupid", or something like that, but if you start getting used to making remarks and comments now when your a beginner at programming, you won't have to learn the hard way, when you make larger projects, why you should use comments. For example, when I started to make a big program about one and a half year ago, and I didn't program on it for about half a year, I couldn't understand what I had been doing in the program, how, or why, when I thought that I should start programming on it again, and thus I was forced to start making comments...
 
My suggestion to you is, as you may have understood, to always make comments in your programs, for your own sake, and to make extra empty lines where you see it needed to make the program code easier to read.
The function END is optional to use in cases as this one, but further on we may want to end the programs when a certain event occurs or so, and thus the END function is useful anyway.
 
Getting a bit more complicated...
 
'A program for getting and printing the users name to the screen
'Made by Sane
INPUT "What is your name"; Name$
PRINT "Your name is "; Name$; "!"
END
 
From now on, it's suggested to type and run every program shown in this tutorial, unless told otherwise.
 
After you have executed this program in QB (using Shift+F5, as always), return to this tutorial.
 
The program shown above introduces three new things:
- the INPUT function
- more on using PRINT
- variables
 
Here comes an explanation:
INPUT is a function that prints the text within quotes, and lets the user type a line of text into a variable.
 
The semicolon after the quotes in this example makes INPUT type a ? sign after the text within quotes.
 
If you do not want a ? sign there, use a comma instead of a semicolon.
Name$ is a variable, which means a place in the memory where information can be stored, that is called using a symbolic name, in this case Name$.
 
The dollar-sign in Name$ means that the variable is of the type STRING, which is a text-variable type, and the only one QB uses.
QB doesn't take any notice wether letters in variablenames are uppercase or lowercase letters, and thus Variable% refers to the same variable as VaRiAbLe%.
 
What symbolic name the variable should have is in general up to you, but there are some rules for variable names:
The variable name may not start with a number. Variable names can't use any characters but A-Z, a-z and 0-9 (except for dollar-signs for example, but dollar-signs and other "type signs" may only be used as last character in the variable) Variable names may not use the same names as existing QB functions. Variable names may not contain more than 40 characters.
A variable uses the same name in the whole program, so if you want to reach the variable blah$, for example, you can't use the name blahahah$ instead.
 
Variables can be of other types too, like integers, long integers and such, but more of that will be discussed later on.
 
If you want to print a variable using the PRINT function, use for example PRINT Variable$
 
If you want to use variables together with text, you may do it like this:
 
PRINT "Text";Variable$
 
When using PRINT, semicolon makes PRINT continue printing directly after the last text printed, and thus, if Variable$ would contain "blah" in the previous example, the text printed would be "Textblah". If you use a semicolon at the end of the PRINT line, the next PRINT call would print its text directly after the previous text printed. If you use a comma instead of semicolon when using print, there will be a TAB space between the text before and after the comma. If you don't understand what I mean, try it out yourself.
 
This is all that should be needed for this section, I think, so let's move on to some more about variables...
 
More about variables
As mentioned earlier, there are other types of variables than string variables.
 
If you have not declared that a variable should be of a certain type, either using for example $, or done it some other way, the variable is of the type SINGLE, which means that it's a "single-precision value" variable, which in turn means that the variable can contain decimal values, but not with as many decimals as "double-precision value" variables.
 
The "type sign" for variables of the type SINGLE, is !, just as $ is the "type sign" for variables of the type STRING. INTEGER variables have the type sign %, LONG(long integer) variables have got the type sign &, and DOUBLE(double-precision) variables have got the type sign #.
All value type of variables can be used in mathematic statements, here are some examples:
 
a%=(a%/2)*1.5
t%=t%+2
 
Note that if you for example do as in the second example above(t%=t%+2), t% becomes what it is, plus 2, so if t% is equal to 4 before, t is equal to 6 after.
 
String variables can also be used with the + sign, like this:
 
S$="Hello"+" "+"World"
 
Note that if you for example do as in the second example above(t%=t%+2), t% becomes what it is, plus 2, so if t% is equal to 4 before, t is equal to 6 after.
 
Here comes a small table with the limits of the different variable types:
 

Type
(Suffix) :Min to Max:
- String ($): length 0 characters to 32,767 characters
- Integers
(%): -32,768 to 32,767
- Long Integers
(&): -2,147,483,648 to 2,147,483,647
- Single precision numbers
(! or missing)
Positive:1.401298 E-45 to 3.402823 E+38
Negative:-3.402823 E+38 to -1.401298 E-45
- Double precision numbers
(#)
Positive: 4.940656458412465 D-324 to 1.797693134862315 D+308
Negative: -1.797693134862315 D+308 to -4.940656458412465 D-324
At first, I was going to write some more boring variable stuff, but then I realized how boring it would be for me if I was a person reading this as a beginner programmer, so I think we'll leave the rest until it's needed later on...
 
Labels, GOTO and GOSUB
In QB there are functions for jumping between different places in your program, and this is what this chapter will be all about...
The first function you'll learn how to use is GOTO.
GOTO is used to jump to the row with the label you specify, here comes an example:
 
Label:
PRINT "This program won't ever stop..."
GOTO Label
 
If you type the program above into QB and run it, you'll notice that it prints "This program won't ever stop..." until you end the program, which is done using Ctrl+Break on the keyboard.
 
The only label in this program is the label named Label, as you might have noticed...
 
Labels are defined by putting a name at the beginning of a row, followed by a colon, or by using a number. When using a number only, you can choose by yourself wether to use a colon, or just a space.
The rules you need to think about when making label names (except for when you use numbers only), are the same as for variable names.
Now on to using GOSUB...
 
GOSUB is a bit different from GOTO, in the way that GOSUB returns to the place where it was if you put RETURN where you want GOSUB to return, here comes an example:
 
GOSUB PrintText
PRINT "GOSUB finished"
END
PrintText:
PRINT "This text is called using GOSUB"
RETURN
 
This program will call the text printing using GOSUB, and then print "GOSUB finished", and end after that.
 
GOSUB is pretty useful for making sub-programs, and there is a better way to do that, but for now we'll stay with GOSUB.
 
Well, seems as if this chapter is already completed... :)
 
So you want to stop making linear programs, huh?
Ok, we'll find something for ya... :)
 
This chapters first command is IF, which is used for condition checking.
And here comes the example, as usual...
 
Start:
CLS
INPUT "Do you like this program?(Yes/No)", Answer$
IF Answer$="No" THEN GOTO Start
PRINT "Oh, so you like my program. Thank you."
 
If you try running this program, then you might notice that it doesn't accept "No" as an answer (even though it accepts "no" or "NO"...).
The IF statement in the program checks if Answer$ is equal to "No", and if it is, it jumps back to the start.
 
Another new command for you is the CLS command, which CLears the Screen, and when I noticed that I had forgotten to write about good ol' CLS, i was pretty shocked :), but at least it's not still in the "land of forgottenness"... :)
 
Back to the IF command, you see that IF is used like this:
 
IF condition THEN statement
 
In the condition part, you may use the following operators:
 

Operator Meaning
= Equals
< Less than
> Greater than
=< Less than or equal
=> Greater than or equal
<> Not equal

Example of another way of using IF:
 
'Made by Sane
INPUT "How old are you?";age%
IF age%<13 THEN
PRINT "You're a child"
ELSEIF age%>=13 AND age%<20
PRINT "You're a teenager"
ELSE
PRINT "You're an adult"
END IF
 
As you saw when you executed this program, it asks for the user to give it his/her age, and using that, tells the user what he/she is: a child, teenager or adult (as if the user didn't know that already :)
 
Some not-so-obvious info about the new things introduced in the example:
In IF commands, you might have use of either AND, OR or XOR. AND is for checking if both conditions of two conditions are true, OR checks if one/both of them are true, and XOR checks if one and no more are true. It's possible to use as many ELSEIF:s as you want to. You don't have to use ELSE/ELSEIF. You always have to use END IF in an IF statement spanning over multiple rows.
 
-
Sane
 
 

Answer 3
~~~~~~~~~~~~~~~~~
[ ]
Author: Maxim Kakitsev
maksim*freeuk.com
Created on 26.03.01
Source URL:
http://www.geocities.com/maxspaceuk
 

Qbasic Tutorial


Chapter I

Basic Commands


 
When you open QBasic, you see a blue screen where you can type your program. Let's begin with the basic commands that are important in any program.

PRINT
Command PRINT displays text or numbers on the screen.
The program line looks like this:

PRINT "My name is Nick."
Type the bolded text into QBasic and press F5 to run the program. On the screen you'll see
My name is Nickos.
Note: you must put the text in quotes, like this – "text". The text in quotes is called a string.
If you put the PRINT alone, without any text, it will just put an empty line.
PRINT can also put numbers on the screen.

PRINT 57 will show the number 57. This command is useful for displaying the result of mathematical calculations. But for calculations, as well as for other things in the program, you need to use variables.

Variables
When you think, you keep words or numbers in your mind. This allows you to speak and to make calculations. Qbasic also needs to keep words or numbers in its memory. To do this, you use variables, pieces of Qbasic memory, which can keep information. A variable can be named with any letter, for example – a. It can also have a longer name, which can be almost any word. It is important to know that there are two main types of variables – that keep a number and that keep a word or a string of words.

· Numeric variables. It's basically variables named with just a letter or a word. You tell this variable to keep a number like this:

a = 15
In other words, you assigned the value 15 to the variable a.
Qbasic will now know that the variable named a keeps the number 15. Now, if you type

PRINT a
and run the program, the computer will show this number on the screen.
· String variables can keep so called "strings", which is basically any text or symbols (like % or £), which you put in the quotes " ". You can also put numbers in a string variable, but again, you must include them in quotes, and QBasic will think that those numbers are just a part of text. The string variables look like this – a$. The $ sign tells Qbasic that this variable contains text.
Example:

a$ = "It is nice to see you"
PRINT a$
On the screen you'll see:
It is nice to see you
The PRINT command can print more that one string on the line. To do this, put the ; sign between the variables. For example, you have two variables – name$, which contains name Rob, and age, which contains the number 34. Then, to print both name and age, you type:

PRINT "Name - "; name$; ". Age - "; age
As you can see, the name of a variable can be more than just one letter – it can be a short word which describes what sort of information does this variable keep.

What you see on the screen when you run the program will look like this:
Name – Rob. Age – 34
Or, you can type the program like that:

PRINT "Name - "; name$
PRINT "Age - "; age
The result is:
Name – Rob
Age - 34


 

*** As you can see, the name of a variable can be more than just one letter – it can be a short word which describes what sort of information does this variable keep.


 

 

INPUT
INPUT is a command that allows you or anybody else who runs the program to enter the information (text or number) when the program is already running. This command waits for the user to enter the information and then assigns this information to a variable. Since there are two types of variables, the INPUT command may look like this – INPUT a (for a number), or INPUT a$ (for a string).
Example (Type this program into Qbasic and run it by pressing F5)

PRINT "What is your name?"
INPUT name$
PRINT "Hi, "; name$; ", nice to see you!"
PRINT "How old are you?"
INPUT age
PRINT "So you are "; age; " years old!"
END
Note: The END command tells Qbasic that the program ends here.
You don't have to use PRINT to ask the user to enter the information. Instead, you can use

INPUT "Enter your name"; name$
and the result will be the same.

GOTO
Quite often you don't want the program to run exactly in the order you put the lines, from the first to the last. Sometimes you want the program to jump to a particular line. For example, your program asks the user to guess a particular number:

~ ~ ~ ~
'some of the program here
INPUT "Guess the number"; n
~ ~ ~ ~
'some of the program there
The program then checks if the entered number is correct. But if the user gives the wrong answer, you may want to let him try again. So you use the command GOTO, which moves the program back to the line where the question is asked. But first, to show Qbasic where to go, you must "label" that line with a number:

1 INPUT "Guess the number"; n 'this line is labelled with number 1
Then, when you want the program to return to that line, you type

GOTO 1
You can use GOTO to jump not only back but also forward, to any line you want. Always remember to label that line. You can have more than one label, but in that case they should be different.


Chapter II

Mathematical Calculations
QBasic was obviously created for us to have fun, play games, draw nice graphics and even make sounds.
But, as you might guess, nothing good comes without a bit of effort that has to be put in it. In the most QBasic programs a bit of math has to be done.
The math… Doh!
If you hate mathematics, don't worry. Qbasic will do it all for you, you just need to know how to tell QBasic to do that.
Qbasic can perform the following mathematical operations:
Operator What it does Example Result

+ Add 7 + 2 9
- Subtract 7 – 2 5
* Multiply 7 * 2 14
/ Divide 7 / 2 3.5
Examples:

1. a = 15 / 4 + 3
PRINT a
Result on the screen –
6
2. PRINT "Enter the first number"
INPUT a
PRINT "Enter the second number"
INPUT b
c = a + b
d = a * b
PRINT a; "+"; b; "="; c
PRINT a; "*"; b; "="; d
END
When you run this program it goes like this:
Computer:
Enter the first number
You: 22
Computer: Enter the second number
You: 18
Computer:
22 + 18 = 40
22 * 18 = 396


Advanced operations:
Operator What it does Example Result
\ divides and turns the result into an integer (the whole number) 7 \ 2 3
^
Raises a number to the power of another number 3 ^ 4 (means: 3 * 3 * 3 * 3) 2.5 ^ 3 (means:2.5 * 2.5 * 2.5) 243 15.625
SQR
Calculates the square root of a number
SQR(9) SQR(16) SQR(5) 3 (because: 3 ^ 2 = 9) 4 (because: 4 ^ 2 = 16) 2.236
MOD
Divides two numbers, and if the result is not an integer (for example - 3.25), finds out how much to subtract from the first number in order to get the integer result. 17 MOD 5 2 (because: 17 / 5 = 3.4 17 – 2 = 15 15 / 5 = 3)
 
The following program explains MOD. Type this program (except my comments) into Qbasic accurately and run it to see how MOD works.

1 CLS this command clears the screen, so it's empty
INPUT "Enter the first number "; a
INPUT "Enter the second number "; b
IF b = 0 THEN
checks if the second number is zero, because you can't divide by zero
PRINT "the second number cannot be 0. Try again."
DO: LOOP WHILE INKEY$ = ""
waits for you to press a key to continue
GOTO 1 then sends you back to line 1
END IF
CLS
clear the screen again
c = a MOD b
d = a / b
e = a - c
f = e / b
PRINT a; "MOD"; b; "="; c
IF c = 0 THEN this checks if the result of a MOD b = 0, because it means that
the result of a / b is integer
PRINT "because"; a; "/"; b; "="; d; " - integer. Try again."
DO: LOOP WHILE INKEY$ = ""
waits for you to press a key to continue
GOTO 1 then sends you back to the line 1
END IF
PRINT "because"; a; "/"; b; "="; d; " -not integer"
The rest of the program executes if the
PRINT "but"; a; "-"; c; "="; e result of a / b is not integer
PRINT "and"; e; "/"; b; "="; f; " - integer"
END
This program may look very complicated for you, but don't worry. Qbasic is a very easy language to learn and soon you'll be having fun with it. I promise you!

QBasic Tutorial

Chapter III

Interacting with QBasic
From the previous chapters you have learned how to create a simple program with INPUT, GOTO and PRINT commands. In such a program, you are asked to type the information, QBasic processes it and then shows the result on the screen. In many programs (for example – games), the user has a choice of what to enter. In this case, QBasic has to check what the user has typed, and to react accordingly. This can be done with the IF…THEN command.

IF…THEN…ELSE
This command checks if an argument involving a variable is true. An argument may look like this: IF a = 15 THEN. If the argument is true (and a really equals to 15), then QBasic executes the command you put after the IF…THEN.
Example;

IF a = 15 THEN PRINT "OK"
If the argument is not true (if a is not equal to 15), QBasic bypasses this line and goes to the next. In some cases, you can use the ELSE command, which tells QBasic exactly what to do if the argument is not true.

IF a = 15 THEN PRINT "OK" ELSE PRINT "It's not 15"
This example means that if a equals to 15, the computer will show
OK on the screen. But if a is not equal to 15, you'll see It's not 15 on the screen.
To check the argument in IF…THEN command, you can use any of these mathematical operators:
operator meaning example
= Equal to IF a = 15 THEN…
<> Not equal to IF a <> 15 THEN…
< Less than IF a < 15 THEN …
<= Less or equal to IF a <= 15 THEN
> More than IF a > 15 THEN…
>= More or equal to IF a >= 15 THEN…

You can make QBasic to execute more than one command if the argument is true. To do this, put those commands after IF…THEN and divide them with : symbol.

IF a = 15 THEN PRINT "OK": GOTO 1
This example means that if a equals to 15, QBasic will first print
OK and then will go to the line labelled 1.
Here is an example of full program (a simple game):

1 CLS
score = 0
PRINT "How many days are there in a week?"
INPUT a
IF a = 7 THEN GOTO 2
PRINT "Wrong answer!"
PRINT "To try again – press 'y'."
INPUT a$

IF a$ = "y" THEN GOTO 1 ELSE END
2 score = 10
PRINT "It's the right answer!"
PRINT "Your score is now"; score; "!"
PRINT "Thanks for playing."
END
Let's analyse how this program works. The first command, CLS, clears the screen so it's empty. Then QBasic makes the variable score to be equal to 0. Then computer shows the question "How many days there are in a week?" You type your answer (a number) and QBasic puts it in the variable a. Then QBasic checks if the number in this variable equals to 7 (because there are 7 days in a week). If it equals to 7, the program goes to the line 2, where the variable score gets equal to 10. You get the message "It's the right answer! Your score is now 10! Thanks for playing." and then the program ends. But if you gave the wrong answer (that is, the number in the variable a is not 7), QBasic bypasses the line with IF…THEN, and shows the message "Wrong answer! To try again – press 'y'." You can then press the key 'y' to try again or press any other key to end the game. The value of the key you pressed goes to the variable a$, which, if you remember, is a string variable (because of the $ symbol), and can contain only strings (letters, words or symbols). So the program checks if the key you pressed is really "y". If it is, the program takes you back to the line labelled 1, where the screen is cleared and the question is asked again. But if the key you pressed is some other key (not "y"), the program ends.
Sometimes you may want QBasic to execute more than two or three commands if the argument is true. Instead of putting all of them on one line, you can make an IF…THEN block:

IF a$ = "y" THEN
PRINT "OK, let's try again."
score = 0
GOTO 1
END IF
Note the END IF command at the end of this example. It tells QBasic that the commands, which should be executed if the argument is true, end here. This is important to separate the IF..THEN block from the rest of the program by putting END IF.
If you want QBasic to check more than one argument at once, use such words as AND and OR. For example – you want QBasic to execute commands in IF…THEN block if a is more than 12 but less than 50, somewhere in between. To program that, you can type;

IF a > 12 AND a < 50 THEN
Or, if you want commands to be executed if a equals either 6 or 12, you type:

IF a = 6 OR a = 12 THEN
 
*** Note: when you use AND or OR, you have to mention the variable each time.
This example is wrong:
IF f = 4 OR 10 THEN
This example is right:
IF f = 4 OR f = 10 THEN
 
Wow! So much said about that simple IF…THEN command in QBasic. It is indeed simple. IF you practise using this command in your programs, THEN you'll get the hang of it
J
 
 

Chapter IV

Looping with QBasic


To make interesting and efficient programs, you can make QBasic to execute a part of a program more than once. This is called looping, when QBasic goes through a part of a program over and over again. This can be done with the GOTO command, but in QBasic there are some good ways to loop the program. One of them is FOR…NEXT command.

FOR…NEXT
This command allows you to execute a part of a program a certain number of times. It looks like this:

FOR i = 1 TO 4
PRINT "I am looping!"
NEXT i
This little stupid program will print on the screen
I am looping! four times:
I am looping!
I am looping!
I am looping!
I am looping!
The letter i can be any other letter, c for example. It is actually a variable, which changes its value each time the program loops (in this example – from 1 to 3). So, if you make a program like this:

FOR a = 1 TO 5
PRINT "This is loop number"; a
NEXT a
this will print:
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4
This is loop number 5
With FOR…NEXT you can use the STEP command, which tells QBasic how to count from one number to another. If you type:

FOR j = 0 TO 12 STEP 2
~ ~ ~
NEXT j
it will count by two: 0, 2, 4, 6, 8, 10, 12

FOR j = 0 TO 6 STEP 1.5
~ ~ ~
NEXT j
This will count: 0, 1.5, 3, 4.5, 6.
You can also count backwards:

FOR d = 10 TO 1 STEP –1
~ ~ ~
NEXT d
Note: when you count backwards, always put STEP –1 there!
Always remember to put the NEXT command to be able to loop!


DO…LOOP
Imagine that you have a program that works like an ordinary calculator: you enter numbers, QBasic calculates the result, and the program ends. The program may be good, but one problem is that you have to run the program each time you want to calculate! That's where the handy DO…LOOP comes in. It's a loop block, which doesn't have to loop a certain number of times, like FOR…NEXT. It can loop indefinitely, while the condition is met (and when it's not met, the loop stops), or until the condition is met (so, when it's met, the loop stops). Condition is basically the same as an argument, for example f < 20
Here is an example:

DO
PRINT "Enter a number."
PRINT "When you want to quit, press 0."
INPUT n
r = n / 2
PRINT n; "/ 2 ="; r
LOOP WHILE n > 0
END
When you run this program, you can enter numbers and get the result as many times as you like. The program loops while numbers you enter are more than 0. Once you've entered 0, the program ends. The condition WHILE n > 0 is put by the LOOP command but you can stick it to the DO command, like that:

DO WHILE n > 0
~~~
LOOP
Or you can use the word UNTIL:

DO UNTIL n = 0
~~~
LOOP
Or:

DO
~~~
LOOP UNTIL n = 0

All these examples have the same effect: the program loops while numbers you enter are more than 0 (or, you can say - until the number you've entered is 0). Then QBasic stops looping and goes to execute commands you put after the DO…LOOP block (if it's END command, the program just ends).
 

Chapter V

More about Variables
So far you know that there are string variables (for holding text) and numeric variables (for holding numbers). But numbers can be very different, and in QBasic there are some different types of numeric variables:
Type of a variable The number it can hold Example of a number Example of a variable
INTEGER A whole number, from -32,767 to 32,767 5 a%
LONG INTEGER A whole number, from more than -2 billion to more than 2 billion 92,345 a&
SINGLE PRESICION A number with up to 6 digits after the decimal point. 3.725 a!
DOUBLE PRESICION A number with up to 15 digits after the decimal point 3.1417583294 a#

As you see, those types of variables have a special symbol as part of their names:

% INTEGER

& LONG

! SINGLE
# DOUBLE
The SINGLE type of variable is the most widely used in QBasic, and you don't have to stick the
! symbol to it. If you put a variable without any symbol, QBasic will know that this is a SINGLE PRESICION variable.
 
 
 
 

QBasic-Einsteigerkurs

"Hilfedatei für QBasic-Programmierer, die nur wenig Erfahrung haben und wenig Programmcodes kennen"

von Herbert Hackelsberger
*** Vorwort
Zuerst ein großes Dankeschön an Thomas Antoni für die vielen Verbesserungsvorschläge! Der Autor dieses Tutorials heißt Herbert Hackelsberger. Ich bin unter folgender Adresse zu erreichen:
 
Dieses Tutorial ist entstanden, da ich allen Qbasic Einsteigern helfen will, selber eigene Programme zu schreiben und sich schnell zu einem erfahrenen Programmierer voran zu arbeiten :-) Allerdings kann ich mit diesem Tutorial nicht einen Profi Programmierer aus Ihnen machen sondern nur einige wenige Grundbegriffe aus der Programmier Sprache Qbasic näher bringen.
 
Nun wünsche ich Ihnen aber viel Spaß beim Lesen dieses Tutorials!
 
*** Allgemeines
Ich sehe es als sinnvoll sich diese Datei ausdrucken zu lassen. Da man die Beispiele nicht in Qbasic einfügen kann, sondern manuell eingeben muss. Außerdem kann bei einem Festplatten Crash das Tutorial nicht verloren gehen... ;-)
 
Beachten Sie aber, dass es egal ist, ob Sie die Befehle GROß, oder klein schreiben! Übrigens: Um ein Programm zu starten, drücken Sie einfach im Qbasic Editor nachdem sie den Source Code (Source Code = Befehle die man eingibt, wie in einen Editor) die Taste F5! Über die Bedienung von Qbasic möchte ich aber hier nicht näher eingehen, da die Seite
www.loku.de das viel besser beschreibt. Diese gehört dem sehr netten und freundlichem Lothar Kuhn! Hier ist die ganze Bedienung von Qbasic beschrieben :-))
 
*** NOCHMAL: Hier finden Sie nicht alles über Qbasic, sondern nur das, was ich selber weiß. ***
 
Wenn Sie bestimmte Fragen zu bestimmten Themen haben, schauen sie doch auch in der Hilfe-Datei QBASIC.HLP von Qbasic nach. Diese ist normalerweise auf jeder Windows CD ROM vorhanden. Wenn Sie aber nicht im Besitz dieser Hilfe Datei sind, dann holen Sie sie ganz einfach z.B. von
www.qbasic.de .
 
Um die Hilfedatei anzeigen zu können, starten sie "Qbasic.exe" und klicken anschließend auf Hilfe. Sie können auch mit der TastenKombination ALT+H und dann das Thema "HILFE" wählen. Ich kann ihnen auch empfehlen, in der Hilfe auf "INDEX" zu klicken, da man hier schön geordnet alle Befehle von Qbasic übersichtlich nach dem Alphabet gegliedert sieht. Hier können Sie nun Informationen über die Schreibweise ( ->
Syntax ) der einzelnen Befehle erfahren.
 
Nun möchte ich Euch aber nicht weiter mit der Bedienung der Qbasic - -> En
twicklungsumgebung quälen sondern möchte gleich mit dem Kapitel 1 - Die Befehle beginnen :-)
 

*** Kapitel 1 - Die Befehle
 

1.) PRINT "text"
Dieser Befehl ermöglicht es Ihnen, zwischen den Anführungszeichen, Zahlen und Buchstaben (Wörter) auf dem Bildschirm auszugeben. Beachte: Nur zwischen beide Anführungszeichen schreiben!
z.B.:
PRINT "Hallo!"
 
Anmerkung: Wenn Sie jetzt auf F5 drücken, erscheint das Wort "Hallo!" ohne Anführungszeichen auf dem Bildschirm. Das ganze sieht dann so auf dem Bildschirm aus:
Hallo!
 
Wenn Sie es mit Anführungszeichen ausgeben wollen, benötigen Sie einen Extra-Befehl, der später erläutert wird. ==> siehe WRITE
 
Übrigens: Wenn Sie die Anführungszeichen nicht angeben, wird das Programm einfach die Zahl 0 ausgeben. Warum das so ist erfahren Sie in Kapitel 2 unter ==> Programmieren mit Variablen!
 
 

2.) CLS
Mit diesem Befehl können sie den Bildschirminhalt löschen.
z.B.:
CLS
PRINT "Hallo!"
Anmerkung: Wenn Sie zuvor schon ein paar mal ein Wort ausgegeben haben mit dem Befehl PRINT "", wird Ihnen auffallen, dass die vorherigen Anzeigen auf dem Bildschirm erhalten bleiben.Das kann ungefähr so aussehen:
Hallo!
Hallo!
Hallo!
Hallo!
Um dies zu vermeiden, wenden Sie den Befehl CLS an.
 
 

3.) SLEEP X
Dieser Befehl ermöglicht es, das Programm für bestimmte Zeit anzuhalten. Das X steht für ganze Zahlen, wobei die 0 ausgeschlossen ist.
z.B.:
CLS
PRINT "Hallo!"
SLEEP 2
PRINT "Test"
SLEEP 3
CLS
PRINT "Ende"
 
Anmerkung: Die Zahl die Sie eingeben, bedeutet, dass das Programm diese Zeit in Sekunden ausgedrückt wartet! Um diese Wartezeit bei einem laufenden Programm zu überspringen, nur die Taste STRG od. CTRL drücken, da bei anderen Tasten das Programm nicht mehr richtig läuft! Wenn Sie SLEEP eingeben, aber keine Zahl hinzufügen, wartet das Programm so lange, bis Sie irgenDeine Taste drücken.
 
 

4.) WRITE "text"
Dieser Befehl ist im Prinzip der selbe wie der Befehl PRINT "", nur dass er die Anführungszeichen mit auf dem Bildschirm ausgibt.
z.B.:
CLS
WRITE "Hallo"
SLEEP 2
CLS
PRINT "Hallo"
 
Dieses Programm führt zu folgender Bildschirmanzeige:
Hallo
"Hallo"
 
Anmerkung: Wenn sie die Anführungszeichen nicht angeben, trotzdem aber einen Text hineinschreiben wird der Computer die Zahl 0 ausgeben. Warum das so ist erfahren sie im Kapitel 2 unter dem Eintrag: ==> Programmieren mit Variablen!
 
Beachte: Wenn sSie eine Direkte Rede snzeigen wollen, müssen Sie beispielsweise Folgendes eingeben:
CLS
PPRINT "Er sprach: ";
SLEEP 2
WRITE "Du Depp"
 
Anmerkung: Der Strichpunkt ist wichtig, damit das Anführungszeichen und das Wort "Du Depp" in der gleichen Zeile wie die Print-Anweisung ausgegeben werden.
 
Man kann aber auch ohne Verwendung des WRITE "" Befehls Anführungszeichen ausgeben lassen. Dazu muss folgendes geschrieben werden:
 
PRINT CHR$(34); "Hallo";CHR$(34)
 
Warum genau die Zahl 34 hergenommen werden muss, möchte ich noch nicht verraten. Das kommt später bei den ASCII Zeichen Codes und den Tastaturabfrage Codes.

 

5.) COLOR X
Dieser Befehl ermöglicht es zusammen mit dem Befehl PRINT "" oder WRITE "" den Text statt weiß auch in Farbe auszugeben.
z.B.:
CLS
COLOR 4
PRINT "Hallo"
Anmerkung: Jetzt sehen Sie das Wort Hallo anstatt von weiß in rot. Die Farbe ist abhängig von der Zahl, die Sie eingeben. Hier eine Liste, die anstatt des X möglich ist:
 
0: schwarz
1: blau
2: grün
3: türkis
4: rot
5: lila
6: orange
7: hellgrau (die Standardfarbe)
8: dunkelgrau
9: Pastellblau
10: Pastellgrün
11: Pastelltürkis
12: Pastellrot
13: Pastelllila
14: gelb
15: weiß
-----------------------------
16: schwarzblinkend
17: blau blinkend
18: grünblinkend
19: türkis blinkend
20: rot blinkend
21: lila blinkend
22: orange blinkend
23: hellgrau blinkend
24: dunkelgrau blinkend
25: Pastellblau blinkend
26: Pastellgrün blinkend
27: Pastelltürkis blinkend
28: Pastellrot blinkend
29: Pastelllila blinkend
30: gelb blinkend
31: weiß blinkend
 
Anmerkungen: In der DOS-BOX von Windows ist es nicht möglich Text blinkend darzustellen. Es kommt dann zu Grafikfehlern. Zusätzlich hat es auch Einfluss auf die Farben, welchen SCREEN-Modus man gewählt hat. Mehr dazu erfahren Sie unter dem Syntax SCREEN X wobei das X für eine bestimmte Zahl steht. Nicht jeder Screen-Modus ünterstützt den Befehl COLOR. Die Farbe schwarz funktioniert nur in ganz wenigen Screen Modis!!! (SCREEN 2)
 
Beachte: Mit dem Befehl COLOR kann man auch eine LINE, CIRCLE, PRESET und PSET Anweisung farbis ausgeben lassen. Was diese Befehle genau bewirken erfährt Ihr später ;-)
 
WICHTIG: Die blinkenden Farben funktionieren NUR bei SCREEN 0, der standardmäßig eingeschaltet ist.
 

[ The QBasic-MonsterFAQ --- Start Page: www.antonis.de/faq ]