Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG]

alejos7ven -

Creado con canva

ESP

Las variables


Al momento de programar se hace necesario utilizar datos que vamos recolectando del usuario a medida nuestra aplicación esta funcionando para poder ser reutilizados mas adelante. Para esta tarea llegan a nuestra vida las variables, que son “cajas” de información que nos permiten almacenar datos específicos y poder utilizarlos mas adelante.

Imaginate que eres un profesor y tienes que recopilar los nombres de todos tus alumnos, para ellos pides a cada uno de ellos que te entreguen una caja con un papel por fuera que diga “Nombre”, y dentro de la caja un papel con el nombre escrito del alumno. Algo así funcionan las variables, el nombre de la variable sería “nombre”, y lo que este dentro de la caja sería su valor. Todas las cajas tienen el mismo nombre, pero cada contenido dentro de ellas varia según el alumno.


Tipos de datos


En programación debemos especificar que tipo de información vamos a guardar dentro de las variables, para ello existen 4 tipos de datos fundamentales:

Es importante que al momento de crear una variable identifiques bien que tipo de dato utilizará. Puede que ahora no lo comprendas bien, pero veremos ejemplos prácticos que te ayudarán a comprender mejor este tema mas adelante.


Constantes


Las constantes funcionan igual que las variables, pero estas no se pueden modificar después de haber sido creadas, por ejemplo: el valor de Pi, los grados de una circunferencia, etc.


Declarar variables


Para declarar una variable en pseudo código utilizaremos la palabra clave Definir seguida del nombre de la variable y después la palabra Como seguida del tipo de dato (Entero, Real, Logico, Caracter). el nombre de la variable no debe contener espacios en blanco o caracteres latinos como ñ o acento. A continuación vamos a declarar una variable llamada edad de tipo entero:

Algoritmo datos
Definir edad Como Entero;
FinAlgoritmo

Ahora guardaremos un valor en esa variable en una nueva línea, esto se hace llamando al nombre de la variable, y asignándole el valor con el signo = y la mostraremos en pantalla:

Algoritmo datos
Definir edad Como Entero;
edad=23;
Escribir edad;
FinAlgoritmo

Si en la instrucción Escribir colocamos edad, sin comillas mostrará entonces el valor de esta variable.


Otros elementos importantes a la hora de escribir código


Al momento de programar, es recomendable tener en cuenta algunas cosas para escribir un código comprensible y fácil de leer, por ejemplo:

Algoritmo datos
// Declarando la variable edad como entero
Definir edad Como Entero;
FinAlgoritmo

El comentario “Declarando la variable edad como entero” será ignorado por la computadora y solo será usado por quien vaya a leer el código.


Solicitar (leer) datos del usuario


Ya vimos en la lección anterior como mostrar mensajes en la pantalla, esto se conoce como salidas en programación. Ahora, de forma contraria vamos a ver lo que es una entrada, y para que puede servirnos.

Podemos necesitar información del usuario en determinado punto de nuestra aplicación, imaginemos que tenemos un sistema y un usuario se está registrando, queremos preguntarle su nombre y su año de nacimiento y a partir de allí calcular su edad ¿Como lo haríamos?

La forma mas fácil sera que el mismo usuario nos de esa información, para ello utilizamos operaciones de entrada y guardaremos la información que nos de el usuario en variables. Lo primero que necesitaríamos es crear las variables con sus tipos de datos bien definidos, después necesitaremos pedir los datos al usuario, una vez hayamos rellenado nuestras variables vamos a usar esta información para calcular la edad del usuario y por último mostraremos en pantalla la información procesada. Vamos a crear un algoritmo para esta tarea:

  1. Crear variables
  2. Recopilar datos
  3. Calcular edad (restamos el año actual con el año suministrado por el usuario)
  4. Mostrar resultados

Sabemos que un nombre esta compuesto de letras y el año de nacimiento y edad son un número entero, entonces el primer paso será crear nuestras variables:

Definir nombre Como Caracter;
Definir ano_nacimiento, edad Como Entero;

Podemos crear muchas variables en una sola línea, solo debemos separarlas con comas (,).

Vamos a recolectar los datos, esto podemos hacerlo con la instrucción “Leer” seguida del nombre de la variable donde vamos a guardar la información. Antes de esta instrucción podemos mostrar un mensaje en pantalla para notificarle al usuario que es lo que se está pidiendo:

Imprimir "Ingrese su nombre:”;
Leer nombre;
Imprimir "Ingrese su año de nacimiento:”;
Leer ano_nacimiento;

En esta parte el programa mostrará la pregunta y se detendrá a esperar que el usuario ingrese la información, una vez escriba algo y presione ENTER, el programa continuará su flujo habitual. Esto lo veremos de forma mas clara cuando ejecutemos el código, no te preocupes.

Lo siguiente será calcular la edad, para ello almacenaremos la información dentro de la variable edad que creamos al principio. Colocaremos el nombre de la variable seguida del signo de igualdad (=) y la operación a realizar, de esta forma asignaremos el resultado de la operación en esta variable. Sabemos que vamos a restar el año actual (2024) con el año de nacimiento del usuario que esta en la variable ano_nacimiento esto se logra colocando el 2024 seguido del signo menos (-) y la variable a utilizar.

edad = 2024-ano_nacimiento;

Ya solo nos quedaría mostrar el mensaje con los resultados, podemos hacerlo bonito y mostrar el nombre, y la edad del usuario:

Imprimir "Bienvenido " nombre ", tu edad es " edad " años”;

Cuando colocamos texto fuera de las comillas la computadora reconoce ese texto como variables y muestra su valor. Vamos a ejecutar este ejercicio:

Al ejecutar veremos como el programa nos pide escribir algo. Le daremos mi nombre.

Al hacer click en ENTER el programa seguirá:

Ahora nos pide nuestro año de nacimiento, al hacer click en ENTER el flujo seguirá, veremos el resultado y el programa terminará.

En este caso tuve un error en el mensaje, vamos a corregirlo y usaremos otros datos:


Ejercicio práctico resuelto


1. Escribe un algoritmo en pseudo-código para calcular el promedio de notas de 3 alumnos.

Para resolver este ejercicio vamos a crear si algoritmo primero:

  1. Declarar variables donde almacenaremos las notas.
  2. Pedir datos al usuario y rellenar variables.
  3. Calcular promedio: Esto se hace sumando todos los datos y dividiéndolo entre la cantidad de los mismos.
  4. Mostrar resultados.

En el primer paso declararemos las variables para 3 notas, en este caso las haremos como Real para poder incluir decimales, además una variable del mismo tipo para calcular y almacenar el promedio.

Definir nota1, nota2, nota3, promedio Como Real;

Después solicitaremos los datos al usuario y los guardaremos en las variables correspondientes.

    Imprimir "Ingrese la calificacion del alumno 1:";
    Leer nota1;
    Imprimir "Ingrese la calificacion del alumno 2:";
    Leer nota2;
    Imprimir "Ingrese la calificacion del alumno 3:";
    Leer nota3;

Ahora haremos el calculo necesario, sabemos que estamos trabajando con 3 notas entonces las sumaremos y lo dividiremos entre 3.

promedio = (nota1+nota2+nota3)/3;

Finalmente mostraremos un mensaje en pantalla con el resultado.

Imprimir "El promedio de nota de los tres alumnos es de " promedio;

El algoritmo quedaría así:

Algoritmo promedios
    // 1. Declarar variables
    Definir nota1, nota2, nota3, promedio Como Real;
    // 2. Pedir datos
    Imprimir "Ingrese la calificacion del alumno 1:";
    Leer nota1;
    Imprimir "Ingrese la calificacion del alumno 2:";
    Leer nota2;
    Imprimir "Ingrese la calificacion del alumno 3:";
    Leer nota3;
    // 3. Calcular promedio
    promedio = (nota1+nota2+nota3)/3; 
    // 4. Mostrar resultados
    Imprimir  "El promedio de nota de los tres alumnos es de " promedio;
FinAlgoritmo

Si lo ejecutamos:


Tarea


Es tu turno de brillar pequeño programador Jr. Para asegurarme que hayas entendido el tema te dejo las siguientes tareas:

Algoritmo nombres
    Definir nombre, apellido Como Caracter;
    
    Imprimir  "Ingresa tu nombre:";
    Leer nombre;
    Imprimir "Ingresa tu apellido:";
    Leer apellido;
    
    Imprimir "Hola " nombre " " apellido ", bienvenido";
FinAlgoritmo
  1. Declarar variables precio_steem, total y cantidad_steem.
  2. Solicitar al usuario los datos necesarios.
  3. Calcular de la siguiente manera: total = cantidad_steem*precio_steem.
  4. Mostrar resultado en pantalla.

Estaré resolviendo todas tus dudas en los comentarios, no temas equivocarte, estoy acá para ayudarte.

Cada tarea tiene un valor de 2.5 puntos para sumar un total de 10 puntos. Para presentar tu código puedes escribirlo dentro de tu propia publicación.

Puedes consultar las clases anteriores:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]

Normas



ENG

Variables


At the time of programming it is necessary to use data that we are collecting from the user as our application is working so that they can be reused later. For this task, variables come into our lives, which are "boxes" of information that allow us to store specific data and be able to use them later.

Imagine that you are a teacher and you have to collect the names of all your students, for them you ask each of them to give you a box with a paper on the outside that says "Name", and inside the box a paper with the student's written name. The variables work like this, the name of the variable would be "name", and what is inside the box would be its value. All the boxes have the same name, but each content inside them varies according to the student.


Types of data


In programming we must specify what type of information we are going to save within the variables, for this there are 4 types of fundamental data:

It is important that when creating a variable you clearly identify what type of data it will use. You may not understand it well now, but we will see practical examples that will help you better understand this topic later.


Constants


Constants work the same as variables, but these cannot be modified after they have been created, for example: the value of Pi, the degrees of a circle, etc.


Declare variables


To declare a variable in pseudo code we will use the keyword Define followed by the name of the variable and then the word As followed by the data type (Integer, Real, Logic, Character). The name of the variable must not contain blank spaces or Latin characters such as ñ or accent. Next we are going to declare a variable called integer type age:

Algorithm datas
   Define age As Integer;
EndAlgorithm

Now we will save a value in that variable in a new line, this is done by calling the name of the variable, and assigning the value with the sign = and we will show it on the screen:

Algorithm datas
   Define age As Integer;
   age=23;
   Print age;
EndAlgorithm

If in the Print instruction we put age, without quotation marks then it will show the value of this variable.


Other important elements when writing code


When programming, it is advisable to take into account some things to write an understandable and easy-to-read code, for example:

Algorithm datas
   // Creating age variable
   Define age As Integer;
   age=23;
   Print age;
EndAlgorithm

The comment "Creating age variable" will be ignored by the computer and will only be used by whoever is going to read the code.


Request (read) user data


We already saw in the previous lesson how to display messages on the screen, this is known as programming outputs. Now, on the contrary, let's see what an entry is, and what it can serve us for.

We may need user information at a certain point in our application, imagine that we have a system and a user is registering, we want to ask him for his name and year of birth and from there calculate his age. How would we do it?

The easiest way will be for the same user to give us that information, for this we use input operations and we will save the information that the user gives us in variables. The first thing we would need is to create the variables with their well-defined data types, then we will need to ask the user for the data, once we have filled in our variables we will use this information to calculate the age of the user and finally we will show the processed information on the screen. Let's create an algorithm for this task:

  1. Create variables
  2. Collect data
  3. Calculate age (we supt the current year with the year provided by the user)
  4. Show results

We know that a name is composed of letters and the year of birth and age are an integer, so the first step will be to create our variables:

Define name As Character;
Define year_birth, age As Integer;

We can create many variables on a single line, we just have to separate them with commas (,).

We are going to collect the data, we can do this with the instruction "Read" followed by the name of the variable where we are going to save the information. Before this instruction we can show a message on the screen to notify the user that what is being requested:

Print "Enter your name:";
Read name;
Print "Enter your year of birth:";
Read year_birth;

In this part the program will show the question and will stop to wait for the user to enter the information, once he writes something and press ENTER, the program will continue its usual flow. We will see this more clearly when we execute the code, don't worry.

The next thing will be to calculate the age, for this we will store the information within the variable age that we created at the beginning. We will place the name of the variable followed by the equal sign (=) and the operation to be performed, in this way we will assign the result of the operation in this variable. We know that we are going to subtract the current year (2024) with the year of birth of the user that is in the variable year_birth this is achieved by placing 2024 followed by the minus sign (-) and the variable to be used.

age = 2024-year_birth;

We would only have to show the message with the results, we can make it nice and show the name, and the age of the user:

Print "Welcome " name ", your age is " age " years";

When we place text outside the quotation marks, the computer recognizes that text as variables and shows its value. Let's run this exercise:

When running we will see how the program asks us to write something. We'll give you my name. By clicking on ENTER the program will follow:

Now it asks us for our year of birth, by clicking on ENTER the flow will follow, we will see the result and the program will end.


Practical exercise solved


1. Write a pseudo-code algorithm to calculate the average grades of 3 students.

To solve this exercise we are going to create an algorithm first:

  1. Declare variables where we will store the grades.
  2. Ask the user for data and fill in variables.
  3. Calculate average: This is done by adding all the data and dividing it between the amount of them.
  4. Show results.

In the first step we will declare the variables for 3 grades, in this case we will make them as Real to be able to include decimals, in addition to a variable of the same type to calculate and store the average.

Define grade1, grade2, grade3, avarage As Real;

Then we will request the data from the user and save them in the corresponding variables.

Print "Enter student grade 1:";
Read grade1;
Print "Enter student 2s grade":
Read grade2;
Print "Enter student 3 grade";
Read grade3;

Now we will do the necessary calculation, we know that we are working with 3 notes so we will add them up and divide it by 3.

avarage = (grade1+grade2+grade3)/3;

Finally we will show a message on the screen with the result.

Print "The grade point average of the three students is " average;

The algorithm would look like this:

Algorithm avarage
    // 1. Creat variables
    Define grade1, grade2, grade3, avarage As Real;
    // 2. Collect data
    Print "Enter student grade 1:";
    Read grade1;
    Print "Enter student 2s grade":
    Read grade2;
    Print "Enter student 3 grade";
    Read grade3;
    // 3. Calc avarage
    avarage = (grade1+grade2+grade3)/3;
    // 4. Show results
    Print "The grade point average of the three students is " average;
EndAlgorithm

If we execute it:


Homework


It's your turn to shine little programmer Jr. To make sure you have understood the subject, I leave you the following tasks:

Algorithm names
   Define name, last_name as Character;
   Print "Enter your name:";
   Read name;
   Print "Enter your last name:";
   Read last_name;
   Print "Hello " name " " last_name ", welcome";
EndAlgorithm
  1. Declare variables price_steem, total and amount_steem.
  2. Request the user the necessary data.
  3. Calculate as follows: total = amount_steem*price_steem.
  4. Show result on screen.

I will be solving all your doubts in the comments, don't be afraid to make a mistake, I'm here to help you.

Each task has a value of 2.5 points to add a total of 10 points. To present your code you can write it within your own publication.

You can check the previous classes:
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG]

Rules