Programing With GW-Basic. Related titles. Carousel Previous Carousel Next. Jump to Page. Search inside document. Anurag Goel. Matias Gonzalez. Asif Rasheed Rajput. Rizwan Lateef. Jayden K. Abdul Hadi. Aleeza Khan. Lui Koc. Amjad Ali. Birendra Chauhan. Hilman Abdullah. Gary J. Davis, P. Ashu Bajaj. Nabil Ahmed Khan. Popular in Mathematics. Consider the months of the year. This isn't terribly efficient. We might want to get a total of all incomes in a particular group.
But do you really want to write the equation for 10, people? Luckily we have arrays. An array is a grouping of data that still lets us access individual elements. What's in each one is still up to the programmer and the program, but now we can access a particular item much easier. So far no big change, but look at how easy it is to find a particular value. When you have larger arrays, the savings become spectacular.
These arrays are called singly dimensioned arrays since there is only one index. But we can also think of times we'd like to use several dimensions. Maybe we want to track the production of several product lines over several months. The first method is the one usually preferred.
Think of the array as starting with the larger category here, product type on the left, moving to subcategories on the right months. In reality you'd run out of memory well before using all Each added dimension will raise the required storage by at least a factor of 2. The total memory space that is available to Basic is only 64k. Another problem is the fact that most people have trouble conceptualizing more than 3 or 4 dimensions. Usually it's easier to restate the problem.
In years of programming I can recall only a few instances where more than 3 dimensions made any practical sense. Arrays form the basis of most data processing applications, especially in areas like spreadsheets and statistics. In Basic, an array is considered to start from item 0.
Many programmers forget about this element and though it will take up a little more space, you often can ignore it too. But there are some cases where it comes in handy. Suppose we have a 5 by 5 array and want to get totals in each direction. Using our product by month example, we'd want to get totals for each product for all months and totals for each month for all products.
Without arrays we'd have to construct separate assignment statements for each total. No, this won't be assigned as an exercise. But just think how long it would take to do this, and how many places you could mistype and cause an error! The short program total. Later you can expand this to more rows and columns, but you may run out of space to display it on the screen. Since we're only going to use the elements that have indices greater than 1, we have 3 classes of elements that would otherwise be wasted.
These are all X i, 0 , X 0, j and the single element X 0,0. We'll use these as follows: X i, 0 will store the total for row i X 0, j will store the total for column j X 0, 0 will store the grand total of all rows and columns Line 40 sets the grand total to 0. Since this is just a test, we don't want to burden the user by having them enter all the data, so in line 80 we just fill in a random number from 0 to 9. Then we accumulate the line and column totals in lines That's all there is to it.
To display the results we'll use a pair of reversed loops. This will present the 0 indices in the last rows and columns, so the table will look more like the spreadsheet format you may be used to. In the lower right corner is X 0,0 the grand total. The value will be shown as up to 3 digits with 2 additional places shown after the decimal place. Reduce the total number of spaces used to 6.
Change this program to allow creation of a spreadsheet that will produce a table showing 6 different products in columns, with 12 months as the rows. Include labels for each row and col. You can use something simple like "Month 9" and "Prod 2", but should use a loop rather explicit numbered labels. Few programs of any size can get along without them.
Even small programs benefit. Let's look at another use. BAS shown below defines a series of strings. An alternative is the DATA statement. You can also make DATA statements conditional. The program uses the next sequential DATA element. Having too few data elements will cause a syntax error. Having more data elements than corresponding READ's is allowed, but could cause hard to find errors.
A safety measure would be to print out the last of a series of read when testing so that you can ensure that values are being set the way you intended. Strings in DATA statements cause several additional concerns. When all the strings are single words, they could be read in separated by commas, but if some of them have commas as part of the item, then you'll need to delimit each string by quotes. BAS prints boxes on the screen. First, a slight digression.
ASCII is a set of symbols used in programming. The first characters are rigidly defined. Some computers such as the IBM PC define an additional set for the numbers but these are not standardized. In the IBM system these include the symbols for creating boxes and forms. Thus the upper case 'A' is Most confusion comes with numbers. ASCII 49 is the character '1'. Later we'll see ways of using this numeric feature in sorting and alphabetizing.
Another option would be to write a short Basic program that prints all values. Try writing a program that will format this into 8 columns. Thus the first line would have the 0, 32, 64, 96, You can do this with either one loop and a long print statement or nested loops and a single print statement.
Remember that a semicolon ; after a print line will prevent a skip to the next line. If you use this method, you'll need to have a separate print statement to shift to the next line. Now we're ready to draw a box: 1 ' drawbox1. These are ascii values and We next ask for row and column coordinates. The program draws the upper left corner, a row of horizontal characters and the upper right corner.
For each intermediate line, we draw a vertical section, spaces and another vertical. We finish with the 2 lower corners connected by another horizontal line. Allow user to draw several boxes without erasing them You'll need to keep the input on several lines, eg, lines 21 and Clear each line before prompting for new data. Find the characters that can be used to make a single lined box and add them to the program. Use a 2 dimensional array. More involved: This box is drawn from the top down.
An alternative would be to draw it as if a pen were sketching it. Rewrite the program to draw the first line, then drop down the right hand side, come back along the bottom right to left, then draw up to the original corner.
For the sides you'll need to recalculate the x,y position each time. We've also managed to review many of the constructs that we covered in previous sessions. In the next installments we'll refine these ideas as we start considering how to build larger programs in a structured manner.
Calculate the number of days elapsed since the start of the year and the number of days till the end of the year. Up to now, when we've wanted to repeat a section of code, we've had 2 choices. We could just copy the code over, or we could set up a loop.
Sometimes that still leaves us with a messy solution. But what if we want to input 2 sets of numbers? One way would be to repeat the code. This is a special command that tells the program to jump to a particular line. This lets a whole section of code be used in several places. Note the use of the END statement. Take it out and see what happens. When working with dates for comparison you'll usually want to deal with the number of days past the beginning of the year, so this conversion routine is quite handy.
This notation for dates is called Julian as in Caesar. This is more of a programmer's problem though, not the language's. You can write structured programs in Basic just as you can write spaghetti code in Pascal or unmaintainable trash in C.
Structured methods will produce good code in any of the languages. If you follow these guidelines you'll be able to keep your programs readable and easy to maintain. In older books or articles you may see the suggestion to jump to the end of the program for initializing or other reasons.
This made a small amount of sense in the old days, but modern Basic interpreters are much more efficient and you won't notice any difference.
What you will get is a program that's harder to work on. Functions are even more transportable. By applying these two rules you abide by one of the central dogmas of structured programming -- single input, single output. This ensures that every time the subroutine is used it's used the same.
Thus you won't get unpredictable results. Sometimes you'll have gosubs that finish in the middle of a section. This is an insignificant increase in the amount of code, but results in an immense increase in readability and ease of maintainence. It also makes it easier to trace and isolate problems.
If you know there's only one entry and one exit, you can concentrate on the routine that's causing the problem. You won't have to worry what conditions are where the gosub is called.
If there were multiple entries or exits this would be an additional problem. GOSUB END ' subroutine to do stuff It's much to be preferred to flowcharts. Here we've outline the structure of our entire program without getting bogged down in petty details. Another good feature of this design is that we can prototype.
We could write the initializing section and the final processing section without worrying for the moment about the 2 middle sections. We could just put some print statements in there to alert us to the fact they need to come later. This method, called Top-Down Design starts with the most important elements of the program, the overall structure and works in ever more detail. In this way, the interactions among the program parts is being tested from the start. Try this method with simple programs and you'll find that soon you can tackle more complicated projects.
If you're interested in more on structured programming, look for books by Constantine or Yourdon. Most of the ideas in these books can be applied to any language. This feature alone might be enough to convince you to acquire a compiler. It's especially useful since it takes care to maintain any references you've set up.
The numbers may be different. This is the preferred way of changing numbers. You can do it by hand, but if you miss one, it'll be hard to find. If you have a large file and want to reorder just part you can use RENUM [newnum], [oldnum] This will start at line [oldnum] and change it to [newnum] and continue renumbering from there.
Try this on a practise file until you feel comfortable with the power of this command. There are 2 philosophies about renumbering. As long as you keep current listings, there's no problem.
Others design a program with large separations between gosubs. Thus you might define them as , , , This method keeps the subroutines in the same place, but is more tedious to renumber. The first method is certainly the easiest, and if you're careful to follow the guidelines above your program will still be readable. Design a program that will take 2 dates, prompting for year, month and day. Then calculate the number of days that separate these two dates. Hint: in our first treatment we ignored leap years.
But when you know the year, and are looking over several years you don't have that luxury. You'll need to include a check for leap year in the new elapsed days gosub. The difference is that functions are defined at the start of a program, and, in interpreted Basic, are limited to single lines. The other difference is that there can only be one value returned from a function. You can't use a function on the left hand side though. Actually we've already used several functions. These are system functions since they come as part of the language.
Why don't we print characters 10 to 12? Try taking these out and see why. These allow us to process parts of strings. The length to be used is given as the second parameter.
A final function for now is LEN. This returns the length of a string. Write a gosub that strips multiple blanks from a string, reducing them to single blanks. Strip all trailing blanks. Writing your own functions is straightforward. Any other variables used in the function take the value of the current state of that variable. The values X and are sent to replace a and b. This can cause strange happenings in your programs. It's legal, but not recommended as good technique.
The function first takes the maximum of X or min, then takes the minimum of x or max. Use this in programs like the checkbook program where you can define the expected maximum and minimum values. Function writing is some of the most fun in Basic. You can be quite creative. While normally obscure tricks are frowned upon, in functions, they're almost okay, as long as you comment them.
Once they work, you can use them in many different places. Another advantage, is that, with proper naming conventions your mainline code will be self-documenting.
Which of the following is easier to understand? Comment it. Then put it away and call it when needed. Put a space before and after the name. Even if you don't do the actual programming, it would be worthwhile to design a prototype on paper so that you understand the methods involved. Start with the modified totals program from last time which shows 6 products over 12 months. Write a 2 functions that take as input the I,J coordinates of the array X and return the screen row and column where that element should be printed.
Use a gosub to prompt on lines 23 and 24 for the row and col to update. Check that the row and columns are valid. Give an error message if they're not. Don't allow entry of 0's as we're going to calculate them. Once you have the new row and column, prompt and get a new value, then recalculate the totals and use the functions to redisplay only the fields that have changed. At this point, you've learned enough about Basic to write useful programs. However, we still have no way of preserving the results of a program.
What if we want to keep results from one run to another. The solution is the use of files. We've already used files to save our Basic programs.
When you do a normal save from within Basic, only the Basic interpreter can use it. Then exit Basic and use DIR to look at the sizes of the programs. Notice that the ascii cersion takes up more room. If you use an editor, though, you'll be responsible for putting in your own line numbers. Other common uses of files are to hold data that must remain when the computer is turned off, or to handle large quantities of data. Basic provides 2 ways to handle files -- sequential and random access.
Don't worry about the details. The important thing is to understand the distinctions between the 2 types of files and when each is appropriate. All files contain records.
Records are the repeating elements within a file. They in turn are usually broken down into fields. For example, a file record for a mailing list program might have fields with the name, address and phone number of each person. Sequential and random files handle records and fields quite differently. Each has definite advantages and drawbacks. Sequential files read or write from the start of the file and proceed in an orderly fashion to the end of the file.
Think of them as a cassette tapes. In order to find out what's in the tenth record, we need to read the preceding 9 records. We may not do anything with the information we read, but we have to read it. Random files give you immediate access to any record in the file. A jukebox with its dozens of records is a good example. When you request a record, the mechanical arm goes directly to the record you requested and plays it.
In computer programs, sequential files must always be accessed from the beginning, while random files can select any record at any time. Any additional structure is our logical description for convenience and understanding. We'll set up a simple data record and see how the two types of files deal with it. Our data consists of the following fields: name city age phone The following program asks for the information to make 3 records, then stores them to a file.
It then reads that file and displays the results on the screen. Ignore the actual commands for the moment, and concentrate on what the program is trying to do. First we'll do it sequentially.
BAS We read the name, city, age and phone number lines , then write them to the file lines When we're done, the file physically looks like this: Note that each record takes up a variable amount of space in the file.
Thus we have no way of predicting where a particular record begins. If we start at the beginning and just read one record, field by field that never concerns us. String functions operate on strings. If the current time and date are entered during system start up, the correct time and date are given the internal clock in the computer keeps track.
These functions can be either string or numeric. Certain groups of alphanumeric characters are assigned values and are called variables. These statements are very similar to sentences in English. Statements are then put together in a logical manner to create programs.
Line numbers indicate the order in which the program lines are stored in memory, and are also used as references when branching and editing. Depending on the logic of your program, there may be more than one statement on a line. If so, each must be separated by a colon :. Each of the lines in a program should be preceded by a line number. This number may be any whole integer from 0 to It is customary to use line numbers such as 10, 20, 30, and 40, in order to leave room for any additional lines that you may wish to include later.
Since the computer will run the statements in numerical order, additional lines needn't appear in consecutive order on the screen: for example, if you entered line 35 after line 60, the computer would still run line 35 after line 30 and before line This technique may save your reentering an entire program in order to include one line that you have forgotten.
The width of your screen is 80 characters. If your statement exceeds this width, the cursor will wrap to the next screen line automatically.
The computer will automatically wrap the line for you. Reuse of an existing line number causes all of the information contained in the original line to be lost.
0コメント