# More BASICs And Personalizing Spells with User Input

This entry is part 2 of 2 in the series Coding For Kids

#### Post Stastics

• This post has 4318 words.
• Estimated read time is 20.56 minute(s).

Greetings young wizards and enchanters! Welcome back to the mystical realm of QB64, where the secrets of programming unfold like magical scrolls. In our previous journey, we delved into the basics of QB64, casting simple spells in the language of the computer. Today, prepare yourselves for an even greater adventure as we explore Numerical Data Types, Arrays, String Operations, Loops, and the enchanting power of User Input. Get ready to personalize your spells, create interactive programs, and witness the magic of the INPUT command!

## Numerical Data Types

Let’s start by expanding our magical knowledge of Numerical Data Types. Just like different potions require specific ingredients, QB64 offers various types of numerical data for your spells.

### Integer (INT)

Imagine you’re in a magical world where you have enchanted stones. Each stone has a number written on it. Now, these numbers can be a bit different from what you use every day because they don’t have any parts after the point. That means, no decimal or fraction parts.

So, if you have stones with numbers like 1, 2, 3, 4, and so on, those are called integers! They are like the magical building blocks of numbers, perfect for counting whole things in the magical kingdom.

For example, let’s say you have a spell that makes colorful balloons appear. If you want to make five balloons appear, you would use the integer 5! Or if you have a potion that makes you grow taller, and you want to grow three times your height, you would use the integer 3.

Integers are like the simplest magic numbers because they are complete and whole, without any pieces left over. They’re the foundation for all kinds of magical spells and calculations in the wizarding world of numbers.

So, the next time you’re counting magical creatures or casting a spell that needs a whole number, remember the enchanted world of integers â€“ the magical stones that make your spells whole and complete!

Now imagine you’re counting magical creatures. Declare an integer variable and assign it a value:

```Dim magicalCreatures as Integer
magicalCreatures = 5
Print "There are "; magicalCreatures; " magical creatures in the forest."```

Let’s explore the magical code step by step:

### Step 1: Introducing a Magical Creature Counter

`Dim magicalCreatures as Integer`

In the enchanted world of programming, we’re creating a special place to keep track of the magical creatures in the forest. We call this place “magicalCreatures.” It’s like having a magical counter that can only count whole numbersâ€”no fractions or decimals.

• The “Dim” statement tells the computer to set aside a container to store our count in. Dim is short for Dimension.
• magicalCreatures is the name of our container, where we will store our count. If you recall from Part 1, these containers are called “Variables”.
• You learned in Part 1 that variables store data and data has a type. Our container (variable) also has a type. The variable type is tells the computer what type and size of data the container needs to hold.

### Step 2: Giving the Counter a Starting Value

`magicalCreatures = 5`

Now, we’re saying, “Hey magical counter, start with the number 5.” It’s like having 5 magical creatures already in our forest. You can imagine them as friendly pixies or mystical unicorns.

• giving the magicalCreatures variable a starting (initial) value is known as initializing the variable.
`{"question":"What does the semicolon do in a Print statement?","answers":["Changes the page size","Glues together the parts before and after it","nothing"],"correctAnswer":1}`
`{"question":"Which number is an integer?","answers":["3.2","7\/8","4.0","3"],"correctAnswer":3}`

### Step 3: Letting Everyone Know

`Print "There are "; magicalCreatures; " magical creatures in the forest."`

Finally, we want to tell the whole magical world how many creatures are in our forest. The “Print” command helps us do that. We say, “Print this message: ‘There are,’ then the number of magical creatures, and finally, ‘magical creatures in the forest.'”

• the semicolon tells the PRINT command to glue the parts before and after it together.
• magicalCreatures variable is an Integer and Print can only display characters and string types. Behind the scene, Print converts other types like integers to string values so they can be displayed.

When we run this magical code, it will proudly announce to the entire enchanted land that there are 5 magical creatures in our forest!

We created a magical counter, set it to 5, and then used a spell (Print) to tell everyone about the magical creatures in our enchanted forest. The magic of programming helps us share our fantastical world with others!

### Single and Double Precision (SNG/DBL)

For more precise calculations involving magical energies, single and double precision are your go-to ingredients.

```Dim energyLevel as Single
energyLevel = 7.5
Print "My magical energy level is: "; energyLevel```

Let’s dive into the magical world of Single and Double precision values in QB64.

### Single Precision:

Imagine you have a magical potion cauldron, and you want to mix a potion with a special ingredient like “Glowing Stardust.” Now, the Single Precision value is like using a potion cauldron that allows you to be very precise but only with a limited number of ingredients.

So, if you need to measure something like the exact amount of Glowing Stardust, a Single Precision value would be perfect! It’s like saying, “I need 3.14 drops of Glowing Stardust.” You can be super accurate, but you have a limit on how many digits you can use after the point.

### Single Precision:

In QB64, Single precision values are 32-bit floating-point numbers. The term “floating-point” means that these numbers can represent both integers and fractions. The precision of Single precision values is approximately 7 decimal digits. This precision is often sufficient for a wide range of applications, making it a versatile choice for many numeric calculations.

```Dim potionStrength as Single
potionStrength = 3.141592```

In the example above, `potionStrength` is a Single precision variable, and it can hold a value like 3.141592 with reasonable accuracy.

### Double Precision:

On the other wand, Double precision values in QB64 are 64-bit floating-point numbers. They provide a higher level of precision compared to Single precision, with approximately 15 decimal digits. Double precision is useful in scenarios where extremely accurate calculations are required, especially when dealing with very large or very small numbers.

```Dim cosmicConstant as Double
cosmicConstant = 6.67430E-11```

In this example, `cosmicConstant` is a Double precision variable, and it holds a value in scientific notation, representing the gravitational constant with a high degree of precision.

### Choosing Between Single and Double Precision:

When selecting between Single and Double precision, consider the requirements of your magical spells. If your calculations involve large numbers, very small fractions, or demand high accuracy, then Double precision might be the wand of choice. However, for general-purpose numeric computations, Single precision often provides a good balance between precision and memory efficiency.

In summary, Single precision in QB64 offers approximately 7 decimal digits of precision, while Double precision extends this to around 15 decimal digits. The choice depends on the specific needs of your magical algorithms and the level of precision required in your enchanted computations. May your calculations be precise and your spells powerful!

### Double Precision:

Now, let’s talk about the Double Precision value. It’s like having a magical potion cauldron that can handle even more precise measurements and can accommodate a larger number of ingredients.

Imagine you’re brewing a potion that requires extremely accurate measurements, like “Sparkling Crystal Essence.” With Double Precision, you can say, “I need 3.1415926535 drops of Sparkling Crystal Essence.” It allows you to be super-duper accurate, and you can use more digits after the point.

### In Simple Terms:

• Single Precision: Precise like measuring with a ruler, but you can only use a few numbers after the point.
• Double Precision: Even more precise, like using a magical measuring tape, and you can use a lot of numbers after the point.

In your magical spells, you might not always need super-duper precision. Sometimes, Single Precision is perfectly fine, like when counting the number of magical creatures. But for those extra special spells that require the utmost accuracy, Double Precision comes to the rescue!

So, in the magical land of QB64, you can choose the perfect potion cauldronâ€”Single or Double Precisionâ€”to make sure your spells are just right!

## Arrays

Arrays are like magical scrolls where you can store multiple pieces of information. Let’s create an array to store the names of spells.

```Dim spells(3) as String
spells(0) = "Fireball"
spells(1) = "Levitation"
spells(2) = "Invisibility"
spells(3) = "Healing"```

Now, you can access these spells using their positions in the array:

`Print "My favorite spell is: "; spells(1)`

Arrays in QB64 are like magical scrolls that allow you to organize and store multiple pieces of information. Let’s unravel the mystery of arrays using your enchanting code:

### Array Definition:

`Dim spells(3) as String`

Here, we are creating a magical book of spells called “spells.” This book can hold four spells in total. The number inside the parentheses, in this case, ‘3,’ represents the maximum index or location where we can store spells. It’s like saying, “I have a spellbook with four pages, and I can write a different spell on each page.”

### Indexing Spells:

Now, let’s fill our magical spellbook with enchanting spells:

```spells(0) = "Fireball"
spells(1) = "Levitation"
spells(2) = "Invisibility"
spells(3) = "Healing"```
• spells(0): This is like turning to the first page of our spellbook and writing down the spell “Fireball.” In the magical world of arrays, we start counting from 0!
• spells(1): Turning to the second page, we inscribe the spell “Levitation.”
• spells(2): Moving on to the third page, we jot down the spell “Invisibility.”
• spells(3): Finally, on the fourth page, we record the spell “Healing.”

### Types of Arrays:

In QB64, you can have different types of arrays based on what you want to store. In our case, we used an array of strings, meaning each spell is a sequence of characters. However, there are other types like arrays of numbers (integers, single precision, double precision), and even arrays of custom types!

For example, if you want to store the magical powers of each spell, you could use an array of integers:

```Dim spellPowers(3) as Integer
spellPowers(0) = 10
spellPowers(1) = 5
spellPowers(2) = 8
spellPowers(3) = 15```

Here, each number represents the power level of a spell. So, the “Fireball” spell has a power level of 10, and “Healing” has a power level of 15.

### Summary:

• Array Definition: It’s like creating a magical book with a certain number of pages to store different pieces of information.
• Indexing Spells: Each page of the book has a number (starting from 0), and we use that number to store or retrieve information. It’s like turning to a specific page in your spellbook.
• Types of Arrays: You can have arrays of different types, like strings for words, integers for numbers, or even custom types for more complex information.

Now, with your magical spellbook of arrays, you can organize and access spells, powers, or any other magical information in a structured and enchanting way!

## Multi-Dimensional Arrays

QB64 provides the magical ability to work with multi-dimensional arrays. A multi-dimensional array is like having a magical spellbook with pages organized into multiple layers, allowing you to store information in a structured way.

In QB64, you can create arrays with more than one dimension, like a magical grid or a stack of spellbooks. Let’s explore a simple two-dimensional array:

`Dim magicalGrid(3, 3) as Integer`

Here, we have created a magical grid with 4 rows and 4 columns. Each cell in this grid can hold an integer value, much like casting a spell with a numeric power.

Now, you can access and manipulate the magical energies in this grid using two indices â€“ one for the row and another for the column. For example:

`magicalGrid(2, 1) = 10`

This spell places the magical power of 10 in the cell located at the third row (index 2) and second column (index 1).

You can even cast a looped spell to fill the entire magical grid:

```For row = 0 To 3
For column = 0 To 3
magicalGrid(row, column) = row * 10 + column
Next column
Next row```

This enchanting script fills each cell in the magical grid with a unique magical power based on its row and column indices.

• When a loop is placed inside another loop, the inner loop is said to be “nested” inside the outer loop
• You can nest multiple loops but beware, doing so can drastically slow down a program!

Multi-dimensional arrays in QB64 provide a powerful way to organize and manipulate information, especially when dealing with structured data or creating complex magical simulations. Whether you’re exploring a magical landscape or managing the properties of enchanted creatures, multi-dimensional arrays are your trusty companions in the world of programming magic. Happy coding, young sorcerer!

## Loops (Iteration)

Let’s embark on a new magical journey into the realm of loops in QB64. Loops allow us to repeat certain magical incantations or actions in our spells. There are three main types of loops: For, Do, and While.

### For Loop:

Imagine you have a magical wand, and you want to cast a spell three times. The For loop is perfect for this!

```For castSpell = 1 To 3
Print "Casting spell number "; castSpell
Next castSpell```

Here, we’re saying, “Cast the spell from 1 to 3.” The loop starts at 1, goes up to 3, and repeats the magical command inside the loop each time. It’s like saying, “Cast the spell 1,” then “Cast the spell 2,” and finally “Cast the spell 3.”

### Do Loop:

Now, let’s talk about the Do loop. Imagine you have a magical potion, and you want to keep mixing it until it’s perfect. The Do loop is your magical assistant!

```Dim potionQuality as Integer

Do
Input "How good is the potion? "; potionQuality
If potionQuality < 5 Then
Print "Keep mixing until it's perfect!"
End If
Loop Until potionQuality >= 5```

Here, we’re saying, “Keep asking how good the potion is until it’s at least 5.” The loop will keep going as long as the potion’s quality is less than 5. It’s like telling your magical assistant, “Keep asking me until the potion is just right!”

### While Loop:

Remember Boolean values and the IF, THEN, and ELSE statements from Part 1? The While loop is like an extended enchantment of those concepts.

```Dim counter as Integer

While counter < 5
Print "Casting spell number "; counter
counter = counter + 1
Wend```

Here, we’re saying, “Keep casting spells as long as the counter is less than 5.” The loop will continue as long as the condition (counter < 5) is true. It’s like telling the magical universe, “While the counter is less than 5, keep casting spells.”

In QB64, young sorcerer, you have access to several magical loops to weave your enchanting spells. Here are the primary types of loops available:

1. FORâ€¦NEXT Loop:
• Syntax:
`QB64 FOR variable = start TO end [STEP step] ' Magical Spells Here NEXT variable`
• Description: The FORâ€¦NEXT loop is like a magical incantation that repeats a set of spells a specific number of times. You start with a variable, give it a beginning value (`start`), an ending value (`end`), and an optional step value (`step`) to control the increments. The loop continues until the variable reaches the end value.
1. DOâ€¦LOOP:
• Syntax:
`QB64 DO ' Magical Spells Here LOOP UNTIL condition`
• Description: The DOâ€¦LOOP is a spell that repeats a set of enchantments until a specified condition becomes true. The loop executes at least once, and it keeps going until the condition is satisfied.
1. DOâ€¦LOOP WHILE:
• Syntax:
`QB64 DO WHILE condition ' Magical Spells Here LOOP`
• Description: Similar to the DOâ€¦LOOP, this magical iteration keeps going while a specified condition is true. The difference is that the condition is checked at the beginning of each iteration, so if it’s false initially, the loop won’t execute.
1. DOâ€¦LOOP UNTIL:
• Syntax:
`QB64 DO UNTIL condition ' Magical Spells Here LOOP`
• Description: This is another version of the DOâ€¦LOOP, where the loop continues until a specified condition becomes true. The condition is checked at the beginning of each iteration.
1. WHILEâ€¦WEND Loop:
• Syntax:
`QB64 WHILE condition ' Magical Spells Here WEND`
• Description: The WHILEâ€¦WEND loop is a magical enchantment that repeats a set of spells as long as a specified condition is true. The condition is checked at the beginning of each iteration.

These loops provide you with the tools to create intricate and powerful magical programs. Whether you need to repeat a set of spells a specific number of times or until a certain condition is met, these loops will serve you well in the enchanted land of QB64. May your loops be ever enchanting! 🌟🧙‍♂️

### Combining Loops and Conditions:

You can mix loops with Boolean values and conditions to create even more powerful spells. For example:

```Dim magicalPower as Integer

For magicalPower = 1 To 10
If magicalPower < 5 Then
Print "Casting a weak spell with power "; magicalPower
Else
Print "Casting a strong spell with power "; magicalPower
End If
Next magicalPower```

In this enchanted script, we’re using a For loop to cast spells from power 1 to 10. Depending on the power level, it will print a message about casting either a weak or a strong spell.

Loops in QB64 are like magical circles that allow you to repeat actions until a certain condition is met. Whether it’s casting spells, mixing potions, or any other magical endeavor, loops are your key to efficiency and elegance in your enchanted code.

`{"question":"What three types of loops are available QB64?","answers":["From, Until, and Do","Infinite, Curbed, and Timed","For, While, Finite","For, While, Do"],"correctAnswer":3}`
`{"question":"Conditional Statements (IF, Then, Else) cannot be used in any loop. True or False?","answers":["False","True"],"correctAnswer":0}`
`{"question":"Loops can't be nested. True or False?","answers":["False","True"],"correctAnswer":0}`
`{"question":"Nesting loops makes them faster! True or False?","answers":["False","True"],"correctAnswer":0}`

## String Operations

Strings are sequences of characters and must be enclosed in quotes, like the magical incantations you use to cast spells. QB64 allows you to manipulate strings with powerful operations.

### Length of a String

```Dim spellName as String
Print "The length of my spell is: "; Len(spellName)```

### Concatenation

Hello young spellcasters! Let’s talk about a magical concept called “string concatenation.” Imagine you have a spellbook, and each page has a special word written on it. Now, if you want to combine these words to create a powerful incantation, that’s what we call string concatenation!

String concatenation is like weaving words together to make a longer, more powerful spell. In the enchanted world of programming, strings are sequences of characters, just like the magical words in your spellbook.

Here’s a simple spell to illustrate string concatenation:

```Dim spellPart1 as String
Dim spellPart2 as String
Dim completeSpell as String

spellPart1 = "Abraca"
spellPart2 = "dabra"

completeSpell = spellPart1 + spellPart2
Print "Magical incantation: " + completeSpell```

In this magical script, we have two parts of a spell, “Abraca” and “dabra.” By using the plus sign (+), we concatenate or join these two parts into a complete spell. The result is a powerful incantation, “Abracadabra!”

String concatenation is like taking individual words or phrases and combining them to create a more magical and meaningful whole. It’s a way to build longer and more enchanting spells in the language of the computer. Happy conjuring, young wizards! 🧙‍♂️✨

Combine strings to create powerful incantations:

```Dim firstPart as String
Dim secondPart as String

firstPart = "Wingardium"
secondPart = "Leviosa"

Print "Combined spell: " + firstPart + " " + secondPart```

## Functions

Now, let’s unlock the secrets of Functions, the magical rituals of programming. Functions allow you to organize your spells and reuse them in different enchantments.

### Defining a Function

```Function castSpell(spellPower as Integer)
Print "Casting spell with power: "; spellPower
End Function```

### Calling a Function

Invoke the function with a specific spell power:

`castSpell(15)`

### Passing Arguments

You can pass information to a function, like the ingredients of a potion:

```Function mixPotion(ingredient1 as String, ingredient2 as String)
Print "Mixing potion with "; ingredient1; " and "; ingredient2
End Function

mixPotion("Dragon Scale", "Phoenix Feather")```

## User Input

The most thrilling part of our magical journey is User Input. With the INPUT command, you can interact with the computer and personalize your spells using your own words.

```Dim wizardName as String
Input "Enter your wizard name: "; wizardName
Print "Welcome, Wizard " + wizardName + "!"```

### Personalizing Spells with User Input (FUNCTIONS)

Let’s combine the magic of User Input with Functions to cast personalized spells using names.

```Function personalizeSpell(spellName as String, wizardName as String)
Print "Wizard " + wizardName + " casts " + spellName + "!"
End Function

Dim chosenSpell as String
Input "Choose a spell: "; chosenSpell

personalizeSpell(chosenSpell, wizardName)```

## Simple Program Exercises

Let’s conjure four magical programs to showcase the enchanting powers of the `INPUT` and loop commands in QB64. Type the following four programs into your QB64 editor and run them. Inspect the code for each program and experiment by changing them. If you see commands you don’t know or understand, look them up either by Googling “QB64 <command>” or by going to www.babyprogrammer.com, or QB64.com/wiki.html.

### Program 1: Greeting Spell

```Dim wizardName as String
Input "Enter your wizard name: "; wizardName
Print "Welcome, Wizard " + wizardName + "!"```

#### Line by Line Discussion:

1. `Dim wizardName as String`: This line declares a variable named `wizardName` of type String, which means it can hold a sequence of characters.
2. `Input "Enter your wizard name: "; wizardName`: The `INPUT` command prompts the user to enter their wizard name. The semicolon (;) is used to keep the input on the same line as the prompt, making it look neat.
3. `Print "Welcome, Wizard " + wizardName + "!": The`Print`command displays a welcome message, addressing the wizard by the name they entered. Here,`+` is used for string concatenation, combining the fixed part of the message with the wizard’s name.

### Program 2: Potion Mixing Spell

```Dim potionIngredient as String
Input "Enter the potion ingredient: "; potionIngredient
Print "Mixing potion with " + potionIngredient```

#### Line by Line Discussion:

1. `Dim potionIngredient as String`: Declares a variable `potionIngredient` to store the magical ingredient for the potion.
2. `Input "Enter the potion ingredient: "; potionIngredient`: Asks the user to enter the potion ingredient. The entered value will be stored in the `potionIngredient` variable.
3. `Print "Mixing potion with " + potionIngredient`: Displays a message indicating that the potion is being mixed with the entered ingredient.

### Program 3: Numeric Spell

```Dim favoriteNumber as Integer
Input "Enter your favorite number: "; favoriteNumber
Print "Your favorite number multiplied by 2 is: "; favoriteNumber * 2```

#### Line by Line Discussion:

1. `Dim favoriteNumber as Integer`: Declares a variable `favoriteNumber` of type Integer to store a whole number.
2. `Input "Enter your favorite number: "; favoriteNumber`: Prompts the user to enter their favorite number, which will be stored in the `favoriteNumber` variable.
3. `Print "Your favorite number multiplied by 2 is: "; favoriteNumber * 2`: Displays a message showing the result of multiplying the entered favorite number by 2.

Now, let’s create a magical Adding Machine program using a `WHILE` loop and the `INPUT` command in QB64.

```' Adding Machine Spell
' Keep adding numbers until the user enters 0

Dim totalSum as Integer

Print "Welcome to the Adding Machine Spell!"
Print "Enter numbers to add, and I'll keep a running total."
Print "Enter 0 to stop the magic."

While True
Input "Enter a number (0 to stop): "; numberToAdd

Exit While ' Exit the loop if the user enters 0
End If

Print "Running Total: "; totalSum
Wend

Print "Thank you for using the Adding Machine Spell!"```

#### Line by Line Discussion:

1. `Dim numberToAdd as Integer`: Declares a variable `numberToAdd` to store the user’s input.
2. `Dim totalSum as Integer`: Declares a variable `totalSum` to keep track of the running total.
3. `Print "Welcome to the Adding Machine Spell!"`: Welcomes the user to the Adding Machine Spell.
4. `Print "Enter numbers to add, and I'll keep a running total."`: Provides instructions to the user.
5. `Print "Enter 0 to stop the magic."`: Informs the user that entering 0 will stop the addition magic.
6. `While True`: Begins an infinite loop.
7. `Input "Enter a number (0 to stop): "; numberToAdd`: Prompts the user to enter a number. The loop will continue until the user enters 0.
8. `If numberToAdd = 0 Then ...`: Checks if the entered number is 0.
9. `Exit While`: Exits the loop if the user enters 0.
10. `totalSum = totalSum + numberToAdd`: Adds the entered number to the running total.
11. `Print "Running Total: "; totalSum`: Displays the updated running total.
12. `Wend`: Ends the `WHILE` loop.
13. `Print "Thank you for using the Adding Machine Spell!"`: Thanks the user for using the Adding Machine Spell.

Now, the Adding Machine Spell will keep adding numbers until the user decides to stop the magic by entering 0. May your sums be precise and your spells ever calculating! 🌟🧙‍♂️

## Conclusion

Congratulations, young wizards! You’ve now embarked on a magical journey through Numerical Data Types, Arrays, String Operations, Functions, and the enchanting power of User Input. Let’s review what we’ve learned:

• Numerical Data Types: Used for different kinds of magical numbers.
• Arrays: Magical scrolls to store multiple pieces of information.
• String Operations: Manipulating strings for powerful incantations.
• Functions: Magical rituals to organize and reuse spells.
• User Input: The enchanting power to interact with the computer.

## Going Further

To enhance your magical prowess, here are some exercises to practice your skills:

1. Magical Inventory: Create a program that uses arrays to manage your magical inventory, including items and quantities.
2. Spellbook Upgrade: Design a spellbook program that lets you add, edit, and cast spells using user input and functions.
3. Magical Calculator: Develop a calculator program that performs basic magical calculations using numerical data types. Include the following operations on two numbers: Adding, Subtracting, Multiplying, and Dividing.

## Resources

Explore these magical resources to deepen your understanding of QB64 and QBASIC:

Happy coding, young wizards! May your programs be as enchanting as the spells you cast. Until next time, may your code be bug-free and your magic flourish! 🌟🧙‍♂️

Series Navigation<< An Adventure in Coding with QB64: A Beginner’s Guide for Young Minds