FreeBASIC Primer #1
 
This primer is intended for beginning beginners, for those who are just starting to learn how to program and using FreeBASIC do to it.

Learning the language

Learning a programming language means learning the words to write it and knowing what they mean when they are written. We don't need to learn them all at once. But learning a few important words that do something will help us get started. Here we are just going to concentrate on these keywords:

Hello World!

No beginners reference is complete without this example.

Print "Hello World!"

The text between the pair of double quotes is a literal string. The Print statement is used to output text to the display. If you can edit, compile, and execute this example, you are on your way.

Using a Variable to Store Data

Sometimes in a program we will want to store some information somewhere, in memory, and then use it later. To store something in memory we use a variable. All variables in FreeBASIC are of some specific type, like a number or a string. We use the Dim statement to declare a variable name and specify what type of information we want to store in it.

Dim text As String
text = "Hello World!"
Print text

We are using Dim to let the compiler know that we want to use a variable named text in our program and that we will be putting String data in it. We then assign (copy) "Hello World!" in to the variable. Finally, we use Print to output it to the display.

Using a Variable in an Expression

An expression is a generic term for describing a part of the source code that can be evaluated. After an expression is evaluated, we can then do something with it, like assign (copy) it to a variable.

Dim a As String, b As String, text As String
a = "Hello"
b = "World"
text = a + " " + b + "!"
Print text

We are assigning the variables a and b with some data. We are then using the variables a and b in an expression which is then assigned to text. Finally, we output the result to the display.

Getting Input from the User

Often, we have no idea what data is needed for a program unless the user gives it to us. We can't put it in our source code since we won't know what it is until the user runs the program and tells us what it is.

Dim answer As String
Input "Type something and press enter:", answer
Print "You typed: '"; answer; "'"

Here the Input statement will first, output some information to the display, and then wait for the user to give the program some data. In this example, we just output back to the display, exactly what the user typed in.


Doing Some Math

Variables and expressions are not just limited to strings. Most early languages didn't handle strings very well if at all. Writing mathematical expressions is similar to how they might be written with pencil and paper.

Dim a As Integer, b As Integer, c As Integer

a = 5
b = 7
c = a + b

Print "a = "; a
Print "a = "; b
Print "a + b = "; c

We are assigning values to the variables a, b and c. We are using Integer for the variables' data type. An integer can be positive or negative, but not have any fractions.

Doing Some Math with Input

This is similar to the previous example, except we will let the user choose the numbers we are going to add together.

Dim a As Integer, b As Integer, r As Integer
Input "Enter a number:", a
Input "Enter another number:", b

r = a + b
Print "The sum of the numbers is "; r

Dim lets the compiler know which variable names we want to use and that they are going to hold Integer data. We are using Input to get the numbers from the user, and Print to display the results.

Doing More Math with Input

Numeric variables are not limited to just integers. We can also use Single or Double precision data types which can represent fractions. In this example we will take some input from the user to convert a weight in pounds to kilograms.

Dim lb As Single, kg As Single
Input "Enter a weight in pounds:", lb

kg = lb * 0.454
Print lb; " lb. is equal to "; kg; " kg"


Repeating Statements

Using For...Next statement we can tell the program to do something repeatedly a set number of times. For example lets say we wanted to add up all the numbers from 1 to 100.

Dim total As Integer
Dim number As Integer
total = 0
For number = 1 To 100
  total = total + number
Next
Print "The sum of number from 1 to 100 is "; total



Making a Decision

A program can choose which statements to execute using a conditional statement like If...Then. We can use the value of a variable or the result of an expression to decide if we should, or should not, execute one or more statements.

Dim number As Integer
Input "Enter a number : ", number
Print "Your number is ";
If number < 0 Then
  Print "negative"
ElseIf number > 0 Then
  Print "positive"
Else
  Print "zero"
End If


After getting a number from the user, we are going to output a word ( positive, negative, or zero ) based on which condition matches the statement.

Repeating Statements (Again)

Here we will use another looping structure Do...Loop to repeat some statements. How will the program know to stop repeating the statements? We will use If...Then to make the decision when to get out of the loop.

Dim total As Single, count As Single, number As Single
Dim text As String

Print "This program will calculate the sum and average for a"
Print "list of numbers.  Enter an empty value to end."
Print

Do
  Input "Enter a number : ", text
  If text = "" Then
    Exit Do
  End If

  count = count + 1
  total = total + Val(text)

Loop

Print
Print "You entered "; count; " numbers"
Print "The sum is "; total
If count <> 0 Then
  Print "The average is "; total / count
End If


See also

Сайт ПДСНПСР. Если ты патриот России - жми сюда!


Знаете ли Вы, что в 1965 году два американца Пензиас (эмигрант из Германии) и Вильсон заявили, что они открыли излучение космоса. Через несколько лет им дали Нобелевскую премию, как-будто никто не знал работ Э. Регенера, измерившего температуру космического пространства с помощью запуска болометра в стратосферу в 1933 г.? Подробнее читайте в FAQ по эфирной физике.

НОВОСТИ ФОРУМАФорум Рыцари теории эфира
Рыцари теории эфира
 10.11.2021 - 12:37: ПЕРСОНАЛИИ - Personalias -> WHO IS WHO - КТО ЕСТЬ КТО - Карим_Хайдаров.
10.11.2021 - 12:36: СОВЕСТЬ - Conscience -> РАСЧЕЛОВЕЧИВАНИЕ ЧЕЛОВЕКА. КОМУ ЭТО НАДО? - Карим_Хайдаров.
10.11.2021 - 12:36: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от д.м.н. Александра Алексеевича Редько - Карим_Хайдаров.
10.11.2021 - 12:35: ЭКОЛОГИЯ - Ecology -> Биологическая безопасность населения - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> Проблема государственного терроризма - Карим_Хайдаров.
10.11.2021 - 12:34: ВОЙНА, ПОЛИТИКА И НАУКА - War, Politics and Science -> ПРАВОСУДИЯ.НЕТ - Карим_Хайдаров.
10.11.2021 - 12:34: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вадима Глогера, США - Карим_Хайдаров.
10.11.2021 - 09:18: НОВЫЕ ТЕХНОЛОГИИ - New Technologies -> Волновая генетика Петра Гаряева, 5G-контроль и управление - Карим_Хайдаров.
10.11.2021 - 09:18: ЭКОЛОГИЯ - Ecology -> ЭКОЛОГИЯ ДЛЯ ВСЕХ - Карим_Хайдаров.
10.11.2021 - 09:16: ЭКОЛОГИЯ - Ecology -> ПРОБЛЕМЫ МЕДИЦИНЫ - Карим_Хайдаров.
10.11.2021 - 09:15: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Екатерины Коваленко - Карим_Хайдаров.
10.11.2021 - 09:13: ВОСПИТАНИЕ, ПРОСВЕЩЕНИЕ, ОБРАЗОВАНИЕ - Upbringing, Inlightening, Education -> Просвещение от Вильгельма Варкентина - Карим_Хайдаров.
Bourabai Research Institution home page

Боровское исследовательское учреждение - Bourabai Research Bourabai Research Institution