Sample basic programs visual basic
Most were developed by students who are no longer present. Our current students have moved onto programming in C , and thus no longer use VB. Please do not contact us for further help, although feel free to tell us that this page was useful to you!
These tutorials contain step by step graphical guides to several visual basic programming concepts and tools. Note that they are not necessarily in progressive order! Complete with instructions on how to pass information back and forth and also how to remotely invoke Flash methods right in VB!
The left figure shows when it looks like when the program is executed, while the right shows what happens after the user has clicked the button 3 times and selected the checkbox, and moved the mouse over the form. Try to program this yourself. It uses a command or button , a label, and a checkbox. James Tam vbImages These two vb Projects illustrates two ways to cycle through images stored in a local directory.
Each demonstrates different controls for accessing files, while both show a control for displaying images. Saul Greenberg vbMarquee A marquee an automatically scrolling text region is used to illustrate a Timer, a status bar and a checkbox control, and simple graphical repositioning, Saul Greenberg vbMoveList An example of how to use listboxes as well as how to put images into buttons. This example lets you move items between lists. Don't be intimidated: its two lines of code!
Saul Greenberg vbSketchpads Illustrates two simple sketchpads. The first one is only about 6 lines of code, and just illustrates some very basic graphics and event handling.
The second shows how one can dynamically create controls at run time the items on the palette , how controls can be positioned at runtime, and how controls can be resized when the window is resized. Its a longer program, but well worth going through to see how these features work. See Tutorial 2 for step by step instructions for how these programs work. Saul Greenberg vbDrawpad A simple object-oriented drawing editor that allows a user to create, move and erase squares.
You can easily extend this to include different graphical classes e. The program illustrates how to do simple object-based interactive graphics in VB how to use a collection how to use a class Saul Greenberg vbDynamicQueries This program is similar to the drawing editor above, but used for completely different purposes.
It illustrates how to do dynamic queries on city attributes, where cities on a map are filtered immediately as a person moves a slider or checks a checkbox.
While the example is simple, the possibilities of how you can enhance it are endless. Click on the image to view it in full size. Saul Greenberg vbTableLens Illustrates how to create a very simple table lens that toggles cells between graphical and textual views. Rod Stephens vbDragPicture Illustrates how to Bitblit a picture on another picture, and how to drag it around. Rod Stephens vbDragTreeNode Illustrates how to use the Tree control and how to drag items around different parts of the tree Rod Stephens vbMoveControls An example application that lets a user interactively move different kinds of controls on a display.
Illustrates interactive graphics. Saul Greenberg vbclassexample Illustrates how to create a simple class that raises events Saul Greenberg vbFlexdata-example Illustrates a database with the flex control. The database just has two fields: name and phone. This example lets you add and remove records. The record is just added to the end of the file, but the flex grid shows it sorted.
See also Tutorial 3 and Tutorial 4 for other ways to access databases. Shaun Kaasten vbShapedControls Illustrates how you can clip the shape of a control or form to a variety of regions. It just contains a label saying "Hello World" and has no code attached to it. However, it does have a toolbox control icon. Please Note : even though I encourage you to try any examples provided in this tutorial, all materials on this page, including the BASIC source code, are copyrighted and cannot be reproduced somewhere else without explicit reference to this page.
What this tutorial is NOT Getting started. BASIC program line numbers. INPUT command. Floating-point calculations. Random numbers Randomizing random numbers Using random numbers to conduct experiments Using random numbers to create a screensaver Mixing colors in hi-res graphics mode Recursion Sierpinski carpet Binary search More uses of binary search. In this tutorial I am trying to teach a young person how to start programming. For this, you should use official manuals and references.
Any Applesoft BASIC program consists of a number of lines, each beginning with a non-negative integer number referred to simply as "line number". Empty lines are also allowed and are frequently used in this tutorial to visually separate code sections. When BASIC program runs, it is normally executed according to the line numbers, in the ascending order.
When program is created, line numbers are typically separated by It is common to see lines numbered 10, 20, 30, 40 and so on. This is done on purpose: often you will need to insert a new line or several new lines between already existing ones.
If there's a space left between the line numbers, it's easier: we can put a new line number 15 between existing lines 10 and If we used 1, 2, 3 as original lines, we would have to re-number all of them in order to insert just one new line between lines 1 and 2. Some programmers prefer making line numbers multiple of 20, 40, 60, 80 and so on, to allow even more space for inserting new lines.
The following small program prints all Fibonacci numbers from 1 to All line numbers are spaced by 10, except for line It was added at the end when the program was already written to include the program description.
Example 1. Fibonacci numbers program output:. All line numbers must be unique. If you accidentally include two or more lines with the same number, BASIC will run only the first such line it will find in the program text.
As a result, you may find your program not running as you expect. Important Note : when inserting new lines, try keeping line numbers in order. In other words, don't include line number 55 between lines 40 and Include line 55 between lines 50 and Your program will be normally executed according to line numbers not according the order they appear in text.
Putting a line number that is out of order will not result in any warning but will most definitely cause a confusion to anyone looking at your program and trying to understand its logic. More often than not it will be you. TO, IF.. Each of these commands has a special meaning. Don't try to memorize them right away - you will learn them gradually as you learn BASIC with this tutorial. A single line can contain multiple commands separated by colon. Also, you can include a comment by adding REM command and placing text after it.
REM commands and comments themselves are ignored when program runs; however they are useful for description of what we want to do for other programmers or for ourselves. Leaving meaningful comments in your program is a good habit, regardless of which language you are programming in.
Most examples in this tutorial use comments to provide a description of what is being done. The method for finding GCD is known as the Euclidean algorithm. LINE 05 contains a comment explaining what the program does. REM keyword indicates the comment; all text following the REM command until the end of the line is comment text.
Note that we could place these two commands on separate lines; in this case we put 2 commands on the same line for better readability , separating them with colon.
For this we use optional LET keyword. Just as on previous line 10, note that two commands are contained in one line, separated by colon. LINE 30 is important one. We compare values of variables A and B. Condition is followed by a required THEN keyword. All commands listed after THEN, until the end of the line, will be executed only if condition is met.
Note : BASIC will go to line 40 after line 30 not because it's listed on the following line in the body of the program, but because it is the smallest line number that exists in the program greater than current line number This is not necessary, but is done so that we could see values of A and B on each iteration step of the algorithm.
Since C was smaller than B after line 50, after these assignments, A is guaranteed to be greater than B. LINE 70 checks if we reached the end of the algorithm. If B is still bigger than zero, we jump back to line 40 using GOTO command and continue the program execution.
After a number of iterations this number depends on the initial values of A and B the condition on line 70 will NOT be met B becomes equal to zero , so we know that program will reach line 80 at some point. It is followed by GOTO. LINE 90 is the shortest one. These lines contain so-called subroutines.
To separate the main program from the subroutines, and to prevent the program from entering the subroutines when we don't intend it to, we must include the END command.
Below is the result:. In out recent example we calculated the greatest common divisor of numbers and What if we need to calculate the GTD for a different pair of numbers? INPUT is followed by one or more argument which indicate the variables to fill with user-supplied values. Here is the modified Euclidean algorithm program which gets A and B from the user: Example 2. To make the program more user-friendly easier to understand INPUT command can optionally provide text explaining the user what type of input it expects.
This text is followed by a semicolon and corresponding variable name. In our case we just show the user that we want variables A and B. This is because our variables A and B are declared as numeric in order to make them accept strings, not just numbers, we have to append a dollar sign to their name; but in our case we need numbers. Before we proceed with finding the GCD value, we still have to check for A and B being valid: they both have to be natural numbers , but the user could have entered any numbers A and B.
This check is done on new line If condition is not met, we clear the screen with HOME command and return to line The IF command we used in Example 2. The conditions we used in Example 2.
On line 70 we compared B and zero. If B is greater than zero, program continues from line If condition is not true, all commands until the end of the line are skipped. In Example 2. In example 2. This IF command checks if any of the statements separated by OR keyword is true. In this case we check if A is less or equal than zero, or B is less than equal than zero.
If any is true we want to ask user to re-enter the values; also we check for both A and B being integer numbers. We can re-write the IF statement in example 2. Conditions using boolean operators can get quite complex. Below for your study is a program demonstrating how they work, with output:. Often in our program we want to execute one set of commands following IF-THEN when condition is met, and a different set of commands otherwise.
Let's look at a particular example. In our program we ask user for an input value A. If A is less than 10, we want to add 10 and print new value of A; otherwise we subtract 10 from A and print new A:. In order to accomplish this, we have two IF conditions, on LINES 30 and 40, checking for supposedly mutually exclusive opposite conditions: when A is less than 10 and when A is greater or equal to And by line 40 it may become greater than On line 40 we therefore will subtract 10 from A.
This is not what our intention was! We also can fix this issue by introducing a temporary variable called T in our example below on line 25, which is then used in both IF commands on line 30 and GOTO", which directs program to different line numbers depending on the value 1,2, In our example above we ask the user to enter value for A. GOTO construct to direct the program to line , or depending on value of A. It's worth noting that A in this case must be 1,2 or 3 since we list only 3 options after GOTO command.
If A is not equal to one of these values, we will get an error. GOTO contruct can be useful when we want to branch our program execution into several sections, depending on a condition, for which we can easily set a numeric variable ranging from 1 to N, when N is the number of branches. In the program calculating the GCD shown above we saw that the same sequence of commands is performed several times.
The process of repeating the same action again and again is called a loop or, more formally, an iteration ; loops are very common in programming, in fact this is one reason why computers are so helpful: they can loop through a lot of information quickly, much faster than a human can. TO command. When using a loop, we must make sure that at some point we exit stop the loop. The loop continues only when B is greater than zero. If we don't include a conditional statement ending the loop when using GOTO loop, the loop will never finish, and the program will be running forever.
This is not something we want in this example. Here is another example of using a loop with GOTO. The program calculates a sum of all integers from 1 to 10, and prints the result on each step:. Let's look at the program which does the same computes the sum of integers using FOR.. TO loop:. Notice the changes: on line 30 we put the FOR command, which sets the initial value of N and also sets the final value of N. The final value is the last value that N is allowed to have.
NEXT also can have an optional variable name in our case it is N , telling the program which variable to increment. If included, this variable must match the name of the variable we specified in FOR.. If we don't include STEP parameter, it is set to 1. Check out the different output we get:. We get the different result because this time we are adding only odd numbers: 1,3,5,7 and 9. STEP parameter can also be negative, as in the following example:.
We will set them initially to 10 and 1. In the loop we will increment values of both variables and check the result:. Even though variables F and D get changed inside the loop, it has no effect on the loop itself: the step remains equal to 1, and the loop ends when N reaches Look at the following piece of code: even though N is initially set to 1 and LOOP must finish when it reaches zero, it executes one time, until it reaches NEXT command. It means that commands within the FOR loop, unless we specifically include a condition to exit the loop, will be performed at least once, regardless of the initial and final values used for the FOR variable.
This is different compared to other languages such as C :. All the parameters in the FOR loop must be numbers, but they don't have to be whole integers.
In the following example we add numbers starting from 0. The last number which gets added is 9. We can exit the FOR loop if necessary even before the loop variable reaches its final value by calling GOTO and redirecting the program somewhere outside the loop.
In the example below we add values but make sure that resulting sum does not exceed In the following example we add only values of N greater than 5. The following program prints 10 rows of numbers, row by row, with about one-second delay.
If you want to increase or decrease the duration of the delay, set a different upper value for B:. To finish this rather tedious section on FOR.. When your loop contains a variable, which gets incremented by a constant value either positive or negative in every cycle of the loop, FOR loops are preferred. They do the initial assignment, incrementing and the finishing condition check for you automatically. If you know the number of cycles ahead of time, you can use a counter as FOR loop variable and increment it by 1 in every cycle.
In other cases, you can use a loop created with GOTO commands. WHILE commands, where loop can be exited when a logical condition is met. Variables: numeric vs. BASIC variables can hold numbers or strings. String variables have dollar sign at the end of the variable name. Variable names may contain numbers, but must begin with English letter.
It means that when used, they are visible everywhere in the program, including in subroutines discussed later. Numeric variables are initially set to zero by default; string variables are initially set to contain empty string no symbols and have length of zero.
CLEAR command resets all variables to their initial default values: numeric variables to zero, strings variables to empty strings. Also, any previously declared arrays get reset to the default size 10 and filled with zeros. Because of this, you should be careful with declaring variables with similar names.
AppleSoft BASIC will not warn you about the name conflict; instead it will simply assign a value to a variable where you don't expect it, resulting in errors that are hard to find. Take a look at this example:. To switch between them use PR 0 and PR 3 commands.
Why do we need two different text modes? Sometimes we want to be able to fit more information in one screen. Most examples in this tutorial don't depend specifically on which text mode they run in; however in cases where it matters you should not forget to set the proper mode. To switch to text mode from graphics mode, use TEXT command. These commands are often combined in one line, separated by colon.
Coordinates increase as we move right and down, the bottom right corner having position 24,40 in characters-per-line mode and 24,80 in characters-per-line mode. Text modes don't support colors; they are black and white in our case black and green , however you can swap these colors to print black text on green background with INVERSE command. A common question asked about the TEXT mode is whether it is possible to place text at a specific position on screen rather than in the top left corner.
So in order to print something starting on third line from top of the screen, at the leftmost position, you set cursor position with "VTAB 3 : HTAB 1". The following program takes input string from user and outputs the same string in the center of the screen.
If string is less than 30 character long, it uses 40x24 mode, otherwise it switches to 80x24 mode. Keep in mind that valid values for VTAB are Each of them has two sub-modes: for full-screen graphics and partial screen graphics also called "mixed" mode, where upper part of the screen contains graphics, and lower part of the screen can contain text, which can be outputted with PRINT command, for example; essentially in the mixed mode the bottom part of the screen works in TEXT mode.
Mixed graphics mode is 40x40 pixels, full-screen mode 40x48 pixels; both lo-res submodes support 16 colors including black, which has index of zero. HGR2 resolution is x pixels. Hi-res modes have just eight colors including black, which has index of zero. As we move right, X coordinate increases; as we move down the screen, Y coordinates increases. To start printing on them, move text cursor first to one of the four bottom lines for example: VTAB To fill quickly entire screen in hi-resolution mode with current color, use "CALL " Note: you must plot at least one pixel with HPLOT after setting current color in order for this to work.
Here X and Y are coordinates of the pixel you want to plot. The following tiny program draws a hyperboloid , a complex 3-dimensional geometric shape, using only straight lines:. Don't try to parse everything in this program unless you are familiar with trigonometric functions COS and SIN, which are used in this program. We will get down to the details of this program later.
Then we call HGR2 to initialize Hi-res full-screen mode with x resolution. HGR2 also clears the screen with black. Unless we explicitly set the current color, it will be black and we would not be able to see anything we draw on a black background. Low-resolution mode has resolution of 40 by 48 pixels in full-screen sub-mode and supports 16 colors.
Let's check how these colors and pixels actually look:. Let's look at this program line by line. C will be changing from 0 to LINE 30 sets current color to C. In low-res mode we have 48 vertical coordinates; we have 16 colors, so I want to draw 16 horizontal lines each using its own color, 3 pixels in height 16 times 3 is LINE 80 starts another loop, to draw individual pixels of all 16 colors along the horizontal line I just painted.
I use another FOR loop with variable X. X is used to both set current color and control the coordinate of a pixel I plot in this loop. From the resulting image you can see that GR mode indeed supports 16 different colors, except gray colors 6 and 11 are not distinguishable one from another; also the size of a single pixel is very large.
Plus, the pixels are not square: the visible pixel's width is almost twice as big as its height. We will look at colors of the hi-res mode later in this tutorial. What we already can conclude, however, is that for any graphical images requiring a level of detail we need to use BASIC's hi-res mode. The low-res mode has two advantages: twice as many colors, and ability to fill rectangular areas on screen quickly with a solid color. But the low-res graphics are not as refined, plus it lacks the function to draw a line between two arbitrary points.
If you are serious about learning programming, you know that computers save all information as ones and zeros. Individual ones and zeros are called bits, and bits are grouped in bytes, 8 bits per byte. So how computer stores number 45, for example?
To store a number, it converts it into special format having only 1s and 0s. This format is called binary, and numbers written in this format are called binary numbers. Decimal number 5 is written as in binary format. The system most of us familiar with for writing numbers is called decimal. This is because its base is ten: we use ten different symbols digits from 0 to 9 to write the value of a number.
When we want to write a value greater than 9, we use a sequence if decimal digits, for example 57 means a number equal to "five, multiplied by ten, plus seven". The binary system uses 2 as the base. It means that any natural number or zero in it can only use combination of 0s and 1s. In this lesson we look at BASIC program which converts any natural number we enter in decimal form into binary format.
Then we will write a program which converts a binary to decimal. This contains an admin section which controls all the functions of the system. Visual Basic 6 is a third-generation event-driven programming language first released by Microsoft in In VB 6, there is no limit of what applications you could create, the sky is the limit. You can develop educational apps, financial apps, games, multimedia apps, animations, database applications and more.
The team at vbtutor. You are welcome to use the sample codes as a reference for your assignments and projects. However, the usage of the sample codes for commercial purposes without prior consent from the webmaster is strictly prohibited. It comprises pages of captivating contents and 48 fascinating Sample Codes. Perfect source of reference for your VB projects.
0コメント