Basic programming course: Lesson #3 Operations [ESP-ENG]
Creado con canva
ESP
Cuando estamos programando se hace muy común utilizar la programación para resolver problemas matemáticos por lo que resulta necesario operar variables entre sí para obtener resultados deseados.
En programación podemos realizar distintas operaciones que se clasifican en: Operaciones aritméticas, Operaciones de comparación y operaciones lógicas.
Operaciones aritméticas
Las operaciones aritméticas son operaciones matemáticas básicas como por ejemplo: suma (+), resta (-), multiplicación (*) división (/) y modulo (%). Supongamos que tenemos el siguiente código, en el cual declaramos 2 variables para 2 números distintos y una variable para almacenar el resultado de cada una de las operaciones aritméticas que mencionamos:
Definir n, n2, suma, resta, multiplicacion, division, modulo Como Real;
n=7;
n2=2;
Vamos a realizar nada una de las operaciones planteadas entre n y n2. Después mostraremos un mensaje en pantalla con los resultados.
- Suma: utilizaremos el símbolo + para operar 2 variables enteras o reales entre sí:
// 1- Suma
suma = n + n2;
Imprimir "La suma de " n " con " n2 " es igual a " suma;
- Resta: utilizaremos el símbolo - para operar 2 variables enteras o reales entre sí:
// 2- Resta
resta = n - n2;
Imprimir "La resta de " n " con " n2 " es igual a " resta;
- Multiplicación: utilizaremos el símbolo * para operar 2 variables enteras o reales entre sí:
// 3- Multiplicacion
multiplicacion = n * n2;
Imprimir "La multiplicacion de " n " con " n2 " es igual a " multiplicacion;
- División: utilizaremos el símbolo / para operar 2 variables enteras o reales entre sí:
// 4- Division
division = n / n2;
Imprimir "La division de " n " con " n2 " es igual a " division;
- Modulo: El modulo de 2 números es el valor restante que queda después de dividir a los mismos, por ejemplo, si dividimos 7 entre 2 no es una división exacta, en este caso resultaría 3 y el modulo sería el restante, en este caso 1. Utilizaremos el símbolo % para operar 2 variables enteras o reales entre sí:
// 5- Modulo
modulo = n % n2;
Imprimir "El restante de dividir " n " con " n2 " es igual a " modulo;
Si ejecutamos este código veremos lo siguiente:
Operaciones de comparación
Los operadores de comparación se usan para determinar la veracidad de una operación. Usando este tipo de operaciones podemos comparar 2 o mas variables y obtener un resultado lógico (VERDADERO/FALSO).
Por ejemplo, imaginemos que tenemos una aplicación que requiere que nuestros usuarios sean mayores a 18 años, para ello podríamos evaluar si la edad que nuestro usuario proporcionó es mayor o igual a 18 y permitirle o no usar nuestra aplicación.
Veamos las operaciones de comparación, para ello hemos declarado 3 variables enteras para almacenar 3 números, vamos a compararlas.
Definir n, n2, n3 Como Real;
n=5;
n2=8;
n3=5;
- Igual a: Podemos evaluar si dos variables contienen el mismo valor utilizando dos símbolos de igualdad (==). En caso de que ambas variables sean iguales tendremos un resultado VERDADERO, si no, recibiremos un FALSO. Por ejemplo, vamos a comparar la variable n con n2 y n3 por separado:
// 1- Igual a
Imprimir "El numero " n " es igual a " n2 "? " n==n2;
Imprimir "El numero " n " es igual a " n3 "? " n==n3;
En la primera instrucción n tiene un valor de 5 y n2 de 8, entonces resultará FALSO nuestra expresión; en el segundo caso sabemos que n3 tiene un valor de 5, entonces veremos que es VERDADERO, porque ambas son iguales.
- Diferente de: Podemos evaluar si dos variables contienen valores diferentes utilizando el símbolo de exclamación junto a la igualdad (!=). En caso de que ambas variables sean diferentes tendremos un resultado VERDADERO, si no, recibiremos un FALSO. Por ejemplo, vamos a comparar la variable n con n2 y n3 por separado:
// 2- Diferente de
Imprimir "El numero " n " es diferente de " n2 "? " n!=n2;
Imprimir "El numero " n " es diferente de " n3 "? " n!=n3;
En este caso es lo contrario a lo anterior, si las variables contienen valores diferentes recibiremos un VERDADERO, si no un FALSO.
- Mayor que: Podemos evaluar si una primera variable contiene un valor mayor que una segunda variable usando el símbolo correspondiente (>). En caso de que la primera sea mayor conseguiremos VERDADERO, si no FALSO. Por ejemplo, vamos a comparar la variable n con n2 y n2 con n por separado:
// 3- Mayor que
Imprimir "El numero " n2 " es mayor que " n "? " n2>n;
Imprimir "El numero " n " mayor que " n2 "? " n>n2;
primero evaluamos si n2 es mayor que n, y después si n es mayor que n2.
Si comparamos dos variables iguales, el símbolo mayor que (>) arrojará FALSO, si queremos que cuando sean iguales también arroje verdadero podemos usar la operación de mayor o igual que que se consigue con el símbolo mayor que y la igualdad (>=). Vamos a comparar n con n3 para demostrarlo:
Imprimir "El numero " n " mayor o igual que " n3 "? " n>=n3;
- Menor que: Podemos evaluar si una primera variable contiene un valor menor que una segunda variable usando el símbolo correspondiente (<). En caso de que la primera sea menor conseguiremos VERDADERO, si no FALSO. Por ejemplo, vamos a comparar la variable n con n2 y n2 con n por separado:
// 4- Menor que
Imprimir "El numero " n2 " es menor que " n "? " n2<n;
Imprimir "El numero " n " menor que " n2 "? " n<n2;
primero evaluamos si n2 es menor que n, y después si n es menor que n2.
Si comparamos dos variables iguales, el símbolo menor que (<) arrojará FALSO, si queremos que cuando sean iguales también arroje verdadero podemos usar la operación de menor o igual que que se consigue con el símbolo menor que y la igualdad (<=). Vamos a comparar n con n3 para demostrarlo:
Imprimir "El numero " n " menor o igual que " n3 "? " n<=n3;
Vamos a ejecutar nuestro código:
Operaciones lógicas
Las operaciones lógicas sirven para evaluar 2 operaciones comparativas al mismo tiempo. Por ejemplo, imagina que queremos evaluar que la edad de un usuario sea mayor o igual a 18 años y que su estado civil sea soltero, podemos evaluar cada expresión individualmente, o hacerlo las 2 al mismo tiempo.
En este caso vamos a definir la variable edad como entero, y la variable estado_civil como caracter. Vamos a pedir estos valores al usuario para hacerlo mas dinámico:
Definir edad Como Entero;
Definir estado_civil Como Caracter;
Definir es_mayor, es_soltero Como Logico;
Imprimir "Introduce tu edad: ";
Leer edad;
Imprimir "Introduce tu estado civil (soltero/casado):";
Leer estado_civil;
Una vez rellenamos las variables procedemos a realizar las operaciones comparativas:
es_mayor = edad>=18;
es_soltero = estado_civil=="soltero";
Ahora, veremos las distintas operaciones lógicas que se pueden hacer:
- Y lógico: Se usa para evaluar que 2 expresiones se cumplan, si una de ellas no se cumple el resultado general es FALSO. Se puede usar el símbolo ampersang (&) o la palabra y (AND) literalmente. Siguiendo el ejemplo anterior, si el usuario es mayor o igual a 18 años y es soltero entonces la expresión completa es VERDADERO.
// 1- Y
Imprimir "El usuario cumple con ambas condiciones? " es_mayor y es_soltero;
- Ó lógico: Se usa para evaluar que al menos una de las 2 expresiones se cumplan, si ambas no se cumplen el resultado general es FALSO, si no siempre será verdadero. Se puede usar el símbolo or (||) o la palabra o (OR) literalmente. Siguiendo el ejemplo anterior, si el usuario es mayor o igual a 18 años o es soltero entonces la expresión completa es VERDADERO.
// 2- O
Imprimir "El usuario cumple con al menos una condicion? " es_mayor o es_soltero;
Vamos a ejecutar este programa y le diremos que tenemos 23 años y que estamos casados.
En este caso, no se cumplen ambas condiciones porque aunque somos mayores de edad, estamos casados entonces el Y no se cumple, sin embargo como en el O se cumple una condición en este caso si es VERDADERO.
Ahora vamos a decirle que somos menores de edad, y que estamos casados.
En este caso ambos son falsos porque ninguna condición se cumple. Ahora si, vamos a decirle que tenemos 23 y que estamos solteros.
En este caso ambas se cumplen, porque en el Y se deben cumplir todas y en el O con al menos una ya es suficiente.
Orden de las operaciones
Como es habitual en matemáticas cuando tenemos varias operaciones las mismas suelen tener un orden claro. Primero se realizarán las multiplicaciones y divisiones y por último las sumas y restas.
Es posible modificar este orden utilizando paréntesis. Por ejemplo, no es lo mismo: 4+5* 2 que (4+5)* 2
En el primer caso se resuelve primero la multiplicación por lo que da 10, y el resultado final 14; en la segunda se hace primero la suma, entonces queda 9*2 lo que es igual a 18.
Ahora supongamos que tenemos una expresión matemática real cualquiera y queremos convertirlo a una expresión que la lea la computadora:
En la primera expresión quedaría así:
x=(2*5)/10;
Resolvemos primero la multiplicación, y después hacemos la división global.
En la siguiente expresión quedaría de la siguiente manera:
x=((4+5*8)-2)/5;
Primero se van resolviendo los paréntesis más internos, en este caso se realizaría la multiplicación de 5 × 8, y después la suma; después la resta y por último la división global.
Si ejecutamos este programa podemos ver los resultados deseados en ambos casos:
Tarea
- Da un breve resumen de para que sirven las operaciones aritméticas, de comparación y lógicas.
- Haz un programa que pida al usuario 2 números y evalúe si ambos números son iguales.
- Transforma las siguientes expresiones matemáticas a expresiones aritméticas en tu computadora:
Evalúa si los resultados de las 3 operaciones son mayores o iguales que 0 (>=) y muéstralo en pantalla.
Las primeras 2 preguntas tendrán un valor de 3 puntos, y la última 4 puntos.
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG] | |
Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG] |
Normas
- El contenido debe ser #steemexclusive.
- El artículo debe contener la etiqueta #devjr-s20w3.
- El plagio no está permitido.
- El link de tu tarea debe ser agregado en los comentarios de esta publicación.
- El curso estará abierto durante 7 días a partir de las 00:00 UTC del 23 de Septiembre. Después de la fecha limite los usuarios podrán seguir participando sin optar a premios con el objetivo de permitir a mas personas en el tiempo de aprovechar este contenido.
ENG
When we are programming, it becomes very common to use programming to solve mathematical problems, so it is necessary to operate variables with each other to obtain the desired results.
In programming we can perform different operations that are classified into: Arithmetic operations, Comparison operations and logical operations.
Arithmetic operations
Arithmetic operations are basic mathematical operations such as: addition (+), subtraction (-), multiplication (*) division (/) and modulus (%). Suppose we have the following code, in which we declare 2 variables for 2 different numbers and one variable to store the result of each of the arithmetic operations that we mentioned:
Define n, n2, addition, subtraction, multiplication, division, module As Real;
n=7;
n2=2;
We are going to perform nothing one of the operations raised between n and n2. Then we will show a message on the screen with the results.
- Addition: we will use the symbol *+ to operate 2 integer or real variables with each other:
// 1- Addition
addition = n + n2;
Print "The sum of " n " with " n2 " is equal to " addition;
- Subtraction: we will use the symbol - to operate 2 integer or real variables with each other:
// 2- Subtraction
subtraction = n - n2;
Print "The subtraction of " n " with " n2 " is equal to " subtraction;
- Multiplication: we will use the symbol * to operate 2 integer or real variables with each other:
// 3- Multiplication
multiplication = n * n2;
Print "The multiplication of " n " with " n2 " is equal to " multiplication;
- Division: we will use the symbol / to operate 2 integer or real variables with each other:
// 4- Division
division = n / n2;
Print "The division of " n " with " n2 " is equal to " division;
- Module: The module of 2 numbers is the remaining value that remains after dividing them, for example, if we divide 7 by 2 it is not an exact division, in this case it would result in 3 and the module would be the remaining, in this case 1. We will use the symbol % to operate 2 integer or real variables with each other:
// 5- Module
module = n % n2;
Print "The remainder of dividing " n " with " n2 " is equal to " module;
Si ejecutamos este código veremos lo siguiente:
Comparison operations
Comparison operators are used to determine the veracity of an operation. Using this type of operation we can compare 2 or more variables and obtain a logical result (TRUE/FALSE).
For example, let's imagine that we have an application that requires our users to be over 18 years old, for this we could evaluate if the age that our user provided is greater than or equal to 18 and allow him or not to use our application.
Let's look at the comparison operations, for this we have declared 3 integer variables to store 3 numbers, let's compare them.
Define n, n2, n3 As Real;
n=5;
n2=8;
n3=5;
- Equal to: We can evaluate if two variables contain the same value using two equality symbols (==). In case both variables are the same we will have a TRUE result, if not, we will receive a FALSE. For example, let's compare the variable n with n2 and n3 separately:
// 1- Equal to
Print "The number " n " is equal to " n2 "? " n==n2;
Print "The number " n " is equal to " n3 "? " n==n3;
In the first instruction n has a value of 5 and n2 of 8, then our expression will be FALSE; in the second case we know that n3 has a value of 5, then we will see that it is TRUE, because both are the same.
- Different from: We can evaluate if two variables contain different values using the exclamation mark next to the equality (! =). In case both variables are different we will have a TRUE result, if not, we will receive a FALSE. For example, let's compare the variable n with n2 and n3 separately:
// 2- Different from
Print "The number " n " is different from " n2 "? " n!=n2;
Print "The number "n" is different from "n3"? " n!=n3;
In this case it is the opposite of the above, if the variables contain different values we will receive a TRUE, if not a FALSE.
- Greater than: We can evaluate if a first variable contains a value greater than a second variable using the corresponding symbol (>). In case the first is older we will get TRUE, if not FALSE. For example, we will compare the variable n with n2 and n2 with n separately:
// 3- Greater than
Print "The number " n2 " is greater than " n "? " n2>n;
Print "The number " n " greater than " n2 "? " n>n2;
First we evaluate if n2 is greater than n, and then if n is greater than n2.
If we compare two equal variables, the symbol greater than (>) will throw FALSE, if we want when they are equal also to throw true we can use the operation of greater or equal that is achieved with the symbol greater than and the equality (>=). Let's compare n with n3 to demonstrate it:
Print "The number " n " greater than or equal to " n3 "? " n>=n3;
- Less than: We can evaluate if a first variable contains a value less than a second variable using the corresponding symbol (<). In case the first is lower we will get TRUE, if not FALSE. For example, we will compare the variable n with n2 and n2 with n separately:
// 4- Less than
Print "The number " n2 " is less than " n "? " n2<n;
Print "The number " n " less than " n2 "? " n<n2;
First we evaluate if n2 is less than n, and then if n is less than n2.
If we compare two equal variables, the smaller symbol that (<) will throw FALSE, if we want it to be true when they are the same we can use the operation of less or equal to what is achieved with the symbol less than and the equality (<=). Let's compare n with n3 to demonstrate it:
Print "The number " n " less than or equal to " n3 "? " n<=n3;
Let's run our code:
Logical operations
Logic operations are used to evaluate 2 comparative operations at the same time. For example, imagine that we want to evaluate that a user's age is greater than or equal to 18 years and that his marital status is single, we can evaluate each expression individually, or do the 2 at the same time.
In this case we are going to define the age variable as integer, and the civil_state variable as a character. We are going to ask the user for these values to make it more dynamic:
Define age as Integer;
Define civil_state as Character;
Define is_older, is_single As Logical;
Print "Enter your age: ";
Read age;
Print "Enter your marital status (single/married):";
Read civil_state;
Once we fill in the variables, we proceed to perform the comparative operations:
is_older = age>=18;
is_single = civil_state=="single";
Now, we will see the different logical operations that can be done:
- And logical: It is used to evaluate that 2 expressions are fulfilled, if one of them is not met the general result is FALSE. You can use the ampersang symbol (&) or the word and (AND) literally. Following the previous example, if the user is over or equal to 18 years old and is single then the full expression is TRUE.
// 1- AND
Print "Does the user meet both conditions? " is_older and is_single;
- Or logical: It is used to evaluate that at least one of the 2 expressions is met, if both are not met the general result is FALSE, if not it will always be true. You can use the symbol or (||) or the word or (OR) literally. Following the example above, if the user is over or equal to 18 years old or is single then the full expression is TRUE.
// 2- O
Print "Does the user meet at least one condition? " is_older or is_single;
We are going to run this program and we will tell you that we are 23 years old and that we are married.
In this case, both conditions are not met because although we are of legal age, we are married then the Y is not fulfilled, however as in the O a condition is met in this case if it is TRUE.
Now we are going to tell him that we are minors, and that we are married.
In this case both are false because no condition is met. Now yes, let's tell him that we are 23 and that we are single.
In this case both are fulfilled, because in the Y all must be fulfilled and in the O with at least one is already enough.
Order of operations
As usual in mathematics when we have several operations they usually have a clear order. First the multiplications and divisions will be carried out and finally the additions and subtractions.
It is possible to modify this order using parentheses. For example, it is not the same: 4+52 that (4+5)2
In the first case, the multiplication is solved first by what gives 10, and the final result 14; in the second case, the addition is done first, then 9*2 is left which is equal to 18.
Now let's assume that we have any real mathematical expression and we want to convert it to an expression that the computer reads:
In the first expression it would look like this:
x=(2*5)/10;
We first solve the multiplication, and then we do the global division.
In the following expression it would be as follows:
x=((4+5*8)-2)/5;
First the innermost parentheses are solved, in this case the multiplication of 5 × 8 would be performed, and then the addition; then the subtraction and finally the global division.
If we run this program we can see the desired results in both cases:
Homework
- Give a brief summary of what arithmetic, comparison and logical operations are for.
- Make a program that asks the user for 2 numbers and evaluates if both numbers are the same.
- Transform the following mathematical expressions into arithmetic expressions on your computer:
Evaluate if the results of the 3 operations are greater than or equal to 0 (>=) and show it on the screen.
**The first 2 questions will have a value of 3 points, and the last 4 points. **
Basic programming course: Lesson #1 - Introduction to programming [ESP-ENG] | |
Basic programming course: Lesson #2 - Variables and Types of Data [ESP-ENG] |
Rules
- The content must be #steemexclusive.
- The article must contain the tag #devjr-s20w3.
- Plagiarism is not allowed.
- The link of your task must be added in the comments of this publication.
- The course will be open for 7 days from 00:00 UTC on September 23. After the deadline, users will be able to continue participating without applying for prizes with the aim of allowing more people in time to take advantage of this content.
For the past few years, I have always wanted to participate in these types of tutorial that will exposed me to coding. Just quite a pity now that I don't have a laptop to participate and I doubt whether one can use a phone to try out these assignments. Is it possible? Well I will work earnestly to make sure in the couple of weeks, I will definitely try to get a laptop to participate.
I must say thank you so much for the effort you put in preparing this course. It was so simple enough for one to understand and the fact that you took it step by step is also a top notch for me. As I was actually reading through, I was really able to learn quite a lot of new things even though I have not fully tried out the assignment out. Thank you for what you did.
TEAM 4
Congratulations! Your Comment has been upvoted through steemcurator06. We support good comments anywhere..Hi @alejos7ven!
Should I add any conditions to check the entered numbers are equal or not? Or just I need to get the input from the user and to display it on the screen and explain by myself in the description of the program in the post that the numbers are equal or not.
I am confuse in this question what actually you are wanting. Should I write a separate program for each expression to get the expression result and then apply the check condition on that result if it is greater than or equal to (>=0).
Or should I calculate the expressions without writing code and determine if the result is >=0
I am hoping your response on these questions.
Hi!
Let the user set both numbers and use a Boolean (logic) variable to compare them. Then show a message like "Are the numbers the same?" And show the Boolean value (true/false)
No, do a very single program where you add the three operations and then evaluate the theee results at the same time, something like
are_greater_zero= (x>=0 and z>=0 and y>=0);
Then show the bool on the screen.
If you still have doubts don’t hesitate to ask!
PD: Don’t use conditionals for this lesson
Thank you so much for the clarification. It is highly appreciated.
Thank you boss for always be very attentive to guide others.
Here is my entry: https://steemit.com/devjr-s20w3/@mohammadfaisal/basic-programming-course-lesson-3-operations
As my father passed away last week I could not attend any engagement. Hopefully I will participate again from this week.
So sad to hear the news about your father. May Allah forget him and gave patience to you. Best of luck
I am so sorry to hear about your loss. May you find comfort in the love and support of those around you.
Very sad to know about this, And I can really really understand your pian from the core of my heart. Because I also face this situation. And I know its very difficult time for you and your family. I pray that your father may rest in peace. Well good luck for your back again and for your life . best wishes with you
May Allah Almighty give him place in Jannah and give patience and comfort to all of you. It is the biggest loss which cannot be recovered in any way. I have faced this already last year when my father left me alone.
My link.
https://steemit.com/devjr-s20w3/@josepha/basic-programming-course-lesson-3-operations
Here is my entry:
https://steemit.com/devjr-s20w3/@ahsansharif/4gsvmo-basic-programming-course-lesson-3-operations
https://steemit.com/hive-145157/@sergeyk/basic-programming-course-lesson-3-operations
More math! I was never a big fan. Now it looks like it's impossible for me to avoid it anymore.
😅😅😅
Haha if you need help don’t hesitate to let me know
Mi entrada teacher:
https://steemit.com/devjr-s20w3/@damisvilladiego/basic-programming-course-lesson-3-operations
My entry:
https://steemit.com/devjr-s20w3/@kouba01/basic-programming-course-lesson-3-operations