2. Variables
En esta lección, aprenderás cómo:
Definir y nombrar una variable.
Utilizar variables para almacenar texto o números.
Utilizar matrices para almacenar varios valores.
3. ¿Qué es una Variable?
Puede utilizar una variable para almacenar diferentes tipos de información, como
texto o un número. Una variable puede contener valores diferentes en diferentes
puntos en el tiempo. La mayoría de las variables pueden contener solamente un
valor a la vez. Sin embargo, las variables especiales, que se llaman matrices,
pueden contener más de un valor. Echemos un vistazo a un programa en el cual se
crea una variable para almacenar el nombre del usuario.
En este ejemplo, el programa
pide al usuario que escriba su
nombre. El programa utiliza una
variable que se llama "nombre"
para almacenar la información.
Haga clic en el botón de la barra
de herramientas.
Cuando se ejecuta el programa,
muestra "Hola" y luego la
información en la variable.
4. ¿Cómo nombrar una Variable?
Debes seguir estas reglas y directrices cuando
creas tus variables.
Siempre deberías empezar los nombres
de variables con una letra.
Puedes utilizar letras, números y
guiones en los nombres de las variables.
Deberías nombrar a tus variables de
modo que describan los valores que se
guardan.
Al asignar un nombre a tus variables, no
debe incluir ciertas palabras reservadas,
tales como IF, FOR y THEN.
No se recomienda que utilices
acentos en los nombres de las
variables.
5. Almacenar valores numéricos en una Variable
Para entender mejor las variables que almacenan números, vamos a escribir un
sencillo programa que calcula el área y perímetro de un rectángulo.
El programa pide al usuario que
especifique la longitud y la anchura
del rectángulo. Cuando el usuario
presiona ENTER, el programa calcula
y muestra los valores de área y
perímetro del rectángulo.
6. Almacenar varios valores en una Variable
Puedes almacenar varios valores del mismo tipo en una sola variable mediante
el uso de una matriz (array). Una matriz es un tipo de variable que puede
contener más de un valor a la vez. Veamos un ejemplo que utiliza una matriz.
En este ejemplo, se crea una matriz que nombra
a los estudiantes, y almacena tres nombres
distintos en ella. Luego puedes recuperar los
valores guardados mediante el uso de las
distintas operaciones del objeto Array.
Puedes utilizar varias otras funciones del objeto Array en tu programa.
Más adelante aprenderá más sobre estas funciones.
7. Vamos a resumir…
¡Felicidades! Ahora ya sabes cómo:
Crear y nombrar variables y escribir comandos que contienen variables.
Utilizar variables para almacenar texto o números.
Utilizar matrices para almacenar varios valores del mismo tipo.
8. Demuestra lo que sabes
Escribir un programa que calcula el área y la circunferencia
de un círculo basado en su diámetro:
Solicitar al usuario que especifique el
diámetro de un círculo.
Crear una variable que se denomina
diámetro y almacenar el valor del usuario en
él.
Crear una variable que se llama radio,
calcular el radio del círculo y almacena el
resultado en esa variable.
Crear variables que se llaman área y
circunferencia, calcular el área y la
circunferencia del círculo y almacenar los
valores de esas variables.
Mostrar el área y la circunferencia del círculo.
Notes de l'éditeur
A variable temporarily stores a value that your program can use later. If you run a program again but assign a different value to the variable, the new value in the variable replaces the old value.
When you run a program, the value in the variable is also used as you specify in the code. You can reuse a variable as many times as your program requires.
Code:
TextWindow.Write("What is your name? ")
name = TextWindow.Read()
TextWindow.WriteLine("Hello, " + name + ".")
You can identify your variables more easily if you give them suitable names.
Code:
number_1 = 20
number_2 = 30
number_sum = number_1 + number_2
TextWindow.WriteLine(number_sum)
In the previous example, you used a variable to store text, which is also known as a string. Now let’s see an example of how to store numerical values in variables.
In this example, you use the Write operation to ask the user to specify the length and width of a rectangle. You also create variables that you name length and width, and you use the ReadNumber operation to instruct the computer to store the user’s answers in those variables. Then you create variables that you name area and perimeter, and you instruct the computer to calculate the area and perimeter of the rectangle and store those values in the appropriate variables. Finally, you use the WriteLine operation to display the results.
After you write the program, you can run it by clicking Run on the Toolbar or by pressing F5.
Code:
TextWindow.Title = "Area and Perimeter"
TextWindow.Write("How long is the rectangle? ")
length = TextWindow.ReadNumber()
TextWindow.Write("How wide is the rectangle? ")
width = TextWindow.ReadNumber()
area = length * width
perimeter = 2 * length + 2 * width
TextWindow.WriteLine("The area of the rectangle is " + area + ".")
TextWindow.WriteLine("The perimeter of the rectangle is " + perimeter + ".")
If you want to store multiple values of the same type, you can use an array instead of creating multiple variables. Then you can perform various operations on the values as a group.
In the example on this slide, you define an array that will contain names of students. Then you use an operation of the Array object to search the array for a specific value.
Code:
TextWindow.Title = "Array Object"
TextWindow.Write("What is the name of the first student? ")
students[1] = TextWindow.Read()
TextWindow.Write("What is the name of the second student? ")
students[2] = TextWindow.Read()
TextWindow.Write("What is the name of the third student? ")
students[3] = TextWindow.Read()
Textwindow.WriteLine("Is ‘Robin' here? " + Array.ContainsValue(students, "Robin"))
You can use the following formulas for calculation:
radius = diameter / 2
area = (3.14) * radius * radius
circumference = (3.14) * 2 * radius
Solution:
TextWindow.Write("What is the diameter of the circle? ")
diameter = TextWindow.ReadNumber()
radius = diameter / 2
area = (3.14) * radius * radius
circumference = (3.14) * 2 * radius
TextWindow.WriteLine("The area of the circle is " + area + ".")
TextWindow.WriteLine("The circumference of the circle is " + circumference + ".")