Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions modules/20-arithmetics/10-basics/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

Print the result of dividing the number *81* by *9*.
117 changes: 117 additions & 0 deletions modules/20-arithmetics/10-basics/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
At the basic level, computers work only with numbers. Even when you write a large application in a modern language, calculations are constantly happening inside. The program adds, subtracts, multiplies, and divides numbers thousands of times per second.

The total of items in an online store's cart, a character's coordinates in a game, the length of a video in seconds. Behind all of this are ordinary arithmetic operations.

Fortunately, ordinary school arithmetic is enough to get started. That's where we'll begin.

## Addition

In mathematics, a sum is written as 3 + 4. In Java, the expression looks the same. On its own, it doesn't show anything on the screen, so the result needs to be printed.

To print, we use the familiar command `System.out.println()`. Here is a whole program that adds two numbers and prints the result:

```java
class App {
public static void main(String[] args) {
System.out.println(3 + 4);
}
}
```

First the sum is calculated, then the resulting number is passed into the print command.

```text
System.out.println(3 + 4);
└─┬─┘
7

System.out.println(7); → 7
```

After running it, the result appears on the screen:

```text
7
```

If you put the same expression in quotes, the result changes. In quotes it becomes text, and the string is printed as is:

Check notice on line 37 in modules/20-arithmetics/10-basics/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/20-arithmetics/10-basics/en/README.md#L37

A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1]) Suggestions: `quotes,` URL: http://englishplus.com/grammar/00000074.htm Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/20-arithmetics/10-basics/en/README.md:37:53: A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1])
 Suggestions: `quotes,`
 URL: http://englishplus.com/grammar/00000074.htm 
 Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1
 Category: PUNCTUATION

```java
System.out.println("3 + 4"); // 3 + 4
System.out.println(3 + 4); // 7
```

In the first line, Java sees text and prints it literally. In the second, it sees arithmetic and calculates.

## Other operations

Check notice on line 46 in modules/20-arithmetics/10-basics/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/20-arithmetics/10-basics/en/README.md#L46

Did you mean “in”? (ON_ADDITION[1]) Suggestions: `In` Rule: https://community.languagetool.org/rule/show/ON_ADDITION?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/20-arithmetics/10-basics/en/README.md:46:9: Did you mean “in”? (ON_ADDITION[1])
 Suggestions: `In`
 Rule: https://community.languagetool.org/rule/show/ON_ADDITION?lang=en-US&subId=1
 Category: GRAMMAR

Besides addition, Java has the whole familiar set of operations:

| Operation | Symbol | Example | Result |
|----------------|--------|---------|--------|
| Addition | `+` | `2 + 3` | `5` |
| Subtraction | `-` | `7 - 2` | `5` |
| Multiplication | `*` | `4 * 3` | `12` |
| Division | `/` | `8 / 2` | `4` |
| Remainder | `%` | `7 % 3` | `1` |

Let's print the result of division, and then the result of multiplication:

```java
System.out.println(8 / 2); // 4
System.out.println(3 * 3 * 3); // 27
```

Java has no separate operator for exponentiation. When the exponent is small, a number is multiplied by itself the required number of times, as in the example above with `3 * 3 * 3`.

## Integer division

There is an important feature related to division in Java. When both numbers are integers, the result is also an integer, and the fractional part is discarded:

```java
System.out.println(8 / 2); // 4
System.out.println(7 / 2); // 3
```

In the second example, a calculator would give 3.5. Java divides 7 by 2 as integers and keeps only the integer part, that is 3. The remainder is lost.

This happens because integers in Java are stored separately from fractional numbers. For working with fractions, Java has a special kind of number. They are called floating-point numbers and are written with a dot, for example `3.5`. For now, integers are enough for us.

## Remainder

The `%` operation extracts what remains after integer division.

```java
System.out.println(7 % 3); // 1
```

Why is it 1? Three fits into seven twice, which gives 6. One is missing to reach seven, and that one is the remainder.

More examples:

```java
System.out.println(10 % 4); // 2, four fits into ten twice, 2 left to reach 10
System.out.println(15 % 5); // 0, five divides 15 evenly
```

The remainder helps in many tasks. It's used to check whether a number divides evenly. If the remainder is zero, it divides. This is how even numbers are told apart from odd ones, since the remainder of dividing by 2 is 0 for even numbers and 1 for odd ones. The remainder also helps to count in a circle. The remainder of dividing by 12 works like a clock face, and `13 % 12` gives `1`, because after twelve the count starts over. This operation appears in code all the time.

Check notice on line 97 in modules/20-arithmetics/10-basics/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/20-arithmetics/10-basics/en/README.md#L97

Did you mean “number of”? (A_NUMBER_NNS[1]) Suggestions: `number of` Rule: https://community.languagetool.org/rule/show/A_NUMBER_NNS?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/20-arithmetics/10-basics/en/README.md:97:52: Did you mean “number of”? (A_NUMBER_NNS[1])
 Suggestions: `number of`
 Rule: https://community.languagetool.org/rule/show/A_NUMBER_NNS?lang=en-US&subId=1
 Category: GRAMMAR

## Formatting expressions

For Java, there's no difference between `3+4` and `3 + 4`. The program understands both variants the same way and adds the numbers in both cases. The difference is only in readability. In programming, it's customary to separate arithmetic operators with spaces, because that makes the expression easier to read:

```java
3 + 4
8 / 2
7 % 3
```

The variant without spaces also works:

```java
3+4
8/2
7%3
```

It looks cramped and is harder on the eyes. Get used to writing with spaces around operators right away.
14 changes: 14 additions & 0 deletions modules/20-arithmetics/10-basics/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
name: Arithmetic operations
tips:
- >-
Separate arithmetic operators from operands with spaces; it's good
programming style. This makes the expression easier to read.
- Division by zero results in an error.
- >-
[Division with remainder](https://en.wikipedia.org/wiki/Euclidean_division)
definitions:
- name: Statement
description: >-
the smallest standalone part of a programming language, a command or a set
of commands. A program is usually a sequence of statements.
111 changes: 91 additions & 20 deletions modules/20-arithmetics/10-basics/es/README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,117 @@
A nivel básico, las computadoras operan solo con números. Incluso en aplicaciones de alto nivel, hay muchos números y operaciones dentro de ellas.
A nivel básico, las computadoras trabajan solo con números. Incluso cuando escribes una aplicación grande en un lenguaje moderno, por dentro se realizan cálculos constantemente. El programa suma, resta, multiplica y divide números miles de veces por segundo.

Afortunadamente, para comenzar, es suficiente conocer la aritmética básica, así que empecemos por ahí.
El total de los productos en el carrito de una tienda en línea, las coordenadas de un personaje en un juego, la duración de un vídeo en segundos. Detrás de todo esto están las operaciones aritméticas comunes.

En matemáticas, para sumar dos números, escribimos, por ejemplo, *3 + 4*. En programación, es lo mismo. Aquí hay un programa que suma dos números:
Por suerte, para empezar basta con la aritmética escolar común. Por ahí empezaremos.

## Suma

En matemáticas, una suma se escribe como 3 + 4. En Java, la expresión se ve igual. Por sí sola no muestra nada en la pantalla, así que el resultado hay que imprimirlo.

Para imprimir se usa el conocido comando `System.out.println()`. Aquí tienes un programa completo que suma dos números e imprime el resultado:

```java
class App {
public static void main(String[] args) {
3 + 4;
System.out.println(3 + 4);
}
}
```

Si ejecutas este programa, se ejecutará en silencio y finalizará. No se mostrará nada en la pantalla. La operación de suma, al igual que las demás operaciones, no hace nada más que sumar.
Primero se calcula la suma, y luego el número obtenido entra dentro del comando de impresión.

Para utilizar el resultado de la suma, debes mostrarlo en la pantalla:

```java
```text
System.out.println(3 + 4);
└─┬─┘
7

System.out.println(7); → 7
```

Después de ejecutarlo, se mostrará el resultado en la pantalla:
Después de ejecutarlo, en la pantalla aparecerá el resultado:

```text
7
```

Además de la suma, están disponibles las siguientes operaciones:
Si tomamos la misma expresión entre comillas, el resultado cambia. Entre comillas se obtiene texto, y en la pantalla saldrá la cadena tal cual:

```java
System.out.println("3 + 4"); // 3 + 4
System.out.println(3 + 4); // 7
```

En la primera línea, Java ve texto y lo imprime literalmente. En la segunda ve aritmética y calcula.

* `*` — multiplicación
* `/` — división
* `-` — resta
* `%` — [módulo](https://es.wikipedia.org/wiki/Operaci%C3%B3n_m%C3%B3dulo)
## Otras operaciones

Ahora, vamos a mostrar en pantalla el resultado de una división y luego el resultado de elevar un número a una potencia:
Además de la suma, en Java existe todo el conjunto habitual de operaciones:

| Operación | Símbolo | Ejemplo | Resultado |
|----------------------|---------|---------|-----------|
| Suma | `+` | `2 + 3` | `5` |
| Resta | `-` | `7 - 2` | `5` |
| Multiplicación | `*` | `4 * 3` | `12` |
| División | `/` | `8 / 2` | `4` |
| Resto de la división | `%` | `7 % 3` | `1` |

Mostremos el resultado de una división y luego el resultado de una multiplicación:

```java
System.out.println(8 / 2);
System.out.println(3 * 3 * 3);
System.out.println(8 / 2); // 4
System.out.println(3 * 3 * 3); // 27
```

```text
4
27
En Java no hay un operador aparte para la potenciación. Cuando el exponente es pequeño, se multiplica el número por sí mismo la cantidad de veces necesaria, como en el ejemplo anterior con `3 * 3 * 3`.

## División de números enteros

Con la división en Java hay una particularidad importante. Cuando ambos números son enteros, el resultado también es entero, y la parte fraccionaria se descarta:

```java
System.out.println(8 / 2); // 4

Check notice on line 72 in modules/20-arithmetics/10-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/20-arithmetics/10-basics/es/README.md#L72

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `El Segundo` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/20-arithmetics/10-basics/es/README.md:72:15: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `El Segundo`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING
System.out.println(7 / 2); // 3
```

En el segundo ejemplo, en una calculadora saldría 3.5. Java divide 7 entre 2 de forma entera y deja solo la parte entera, es decir, 3. El resto se pierde.

Check notice on line 76 in modules/20-arithmetics/10-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/20-arithmetics/10-basics/es/README.md#L76

Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1]) Suggestions: `Entra ID` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1 Category: MULTITOKEN_SPELLING
Raw output
modules/20-arithmetics/10-basics/es/README.md:76:29: Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1])
 Suggestions: `Entra ID`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1
 Category: MULTITOKEN_SPELLING

Esto ocurre porque en Java los números enteros se almacenan por separado de los fraccionarios. Para trabajar con fracciones, Java tiene un tipo especial de números. Se llaman números de punto flotante y se escriben con un punto, por ejemplo `3.5`. Por ahora nos bastan los enteros.

## Resto de la división

La operación `%` extrae lo que queda después de una división entera.

```java
System.out.println(7 % 3); // 1
```

¿Por qué sale 1? El tres cabe dos veces en el siete, lo que da 6. Falta uno para llegar al siete, y ese uno es el resto.

Más ejemplos:

```java
System.out.println(10 % 4); // 2, el cuatro cabe dos veces en el diez, quedan 2 para llegar a 10
System.out.println(15 % 5); // 0, el cinco divide 15 exactamente
```

El resto ayuda en muchas tareas. Con él se comprueba si un número se divide de forma exacta. Si el resto es cero, entonces se divide. Así se distinguen los números pares de los impares, ya que el resto de dividir entre 2 es 0 en los pares y 1 en los impares. Y además el resto ayuda a contar en círculo. El resto de dividir entre 12 funciona como la esfera de un reloj, y `13 % 12` da `1`, porque después del doce la cuenta empieza de nuevo. Esta operación aparece en el código constantemente.

## Formato de las expresiones

Para Java no hay diferencia entre `3+4` y `3 + 4`. El programa entiende ambas variantes de la misma manera y en ambos casos suma los números. La diferencia está solo en la legibilidad. En programación se acostumbra a separar los operadores aritméticos con espacios, porque así la expresión se percibe más fácilmente:

```java
3 + 4
8 / 2
7 % 3
```

La variante sin espacios también funciona:

Check notice on line 109 in modules/20-arithmetics/10-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/20-arithmetics/10-basics/es/README.md#L109

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/20-arithmetics/10-basics/es/README.md:109:37: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

```java
3+4
8/2
7%3
```

Se ve apretada y cuesta más a la vista. Acostúmbrate a escribir desde el principio con espacios alrededor de los operadores.
13 changes: 11 additions & 2 deletions modules/20-arithmetics/10-basics/es/data.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,14 @@
name: Operaciones aritméticas
tips:
- >-
La división por cero produce un error. Para evitarlo, debes conocer las
estructuras condicionales (las aprenderás en las próximas lecciones).
Separa los operadores aritméticos de los operandos con espacios; es un buen
estilo de programación. Así la expresión se lee con más comodidad.
- La división por cero produce un error.
- >-
[División con resto](https://es.wikipedia.org/wiki/División_euclídea)
definitions:
- name: Instrucción
description: >-
la parte autónoma más pequeña de un lenguaje de programación, un comando o
un conjunto de comandos. Un programa suele ser una secuencia de
instrucciones.
2 changes: 2 additions & 0 deletions modules/20-arithmetics/20-operators/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

Write a program that calculates the difference between the numbers `6` and `-81` and prints the answer on the screen.
57 changes: 57 additions & 0 deletions modules/20-arithmetics/20-operators/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
First, let's go over the basic terminology. A sign of an operation like `+` is called an **operator**. An operator specifies an action, for example addition:

```java
System.out.println(8 + 2); // 10
```

Here `+` works as an operator, and the numbers `8` and `2` are called **operands**. Operands are the values to which the operator applies an action.

```text
operand operator operand result
8 + 2 → 10
5 - 3 → 2
4 * 3 → 12
```

Addition has two operands. One is to the left of the sign, the other to the right. Operations with two operands are called **binary**. If you omit at least one operand, the program won't compile and will produce a syntax error:

```java
System.out.println(3 + ); // you can't write it like this
```

Operations aren't always binary. There are also unary ones, with one operand, and ternary ones, with three.

## Unary minus

The same sign sometimes means different operations. Look at the minus:

```java
System.out.println(-3); // -3
```

Here the minus stands before a single number and works as a unary operator. It takes the number `3` and returns its opposite, that is `-3`.

When the minus stands between two numbers, it's already subtraction:

```java
System.out.println(5 - 2); // 3
System.out.println(10 - 7); // 3
```

The difference is especially noticeable with negative numbers:

```java
System.out.println(5 - -2); // 7
```

On the left there's subtraction `5 - (...)`, and on the right the unary minus turns `2` into a negative number. This gives `5 - (-2)`, which results in `7`. Minus times minus gives plus, exactly as in school.

The meaning of the minus depends on its neighbors. Next to two numbers it's subtraction, before a single number it's a sign change. The notation `-3` is both the number itself and an operator with an operand. Many programming languages have the same logic, so it's a familiar thing.

The plus can also be unary. The notation `+5` only emphasizes that the number is positive and doesn't change its value:

```java
System.out.println(+5); // 5
```

The other arithmetic operators `*`, `/`, and `%` are always binary; they need two operands. Only plus and minus can work in two roles at once, both as binary and as unary.
21 changes: 21 additions & 0 deletions modules/20-arithmetics/20-operators/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
name: Operators
tips:
- >-
Separate arithmetic operators from operands with spaces; it's good
programming style.
definitions:
- name: Arithmetic operation
description: addition, subtraction, multiplication, and division.
- name: Operator
description: >-
a special symbol that creates an operation. For example, `+` creates the
addition operation.
- name: Operand
description: 'an object that participates in an operation. `3 * 6`: here 3 and 6 are the operands.'
- name: Unary operation
description: >-
an operation with one operand. For example, `-3` is a unary operation for
getting the number opposite to three.
- name: Binary operation
description: an operation with two operands. For example, `3 + 9`.
Loading
Loading