Lesson 4
Basic Operations in Elixir
Basic Operations in Elixir

Welcome back! You've already explored variables and data types in Elixir. Now, let's delve into basic operations that you can perform with these data types. Understanding these operations is crucial as they form the foundation for manipulating data and performing computations in your programs.

What You'll Learn

In this lesson, you'll learn:

  1. How to perform basic arithmetic operations in Elixir.
  2. How to use these operations to manipulate data.

Let's take a quick look at some simple operations:

Elixir
1number1 = 10.5 2number2 = 20 3 4sum = number1 + number2 5difference = number1 - number2 6product = number1 * number2 7division = number1 / number2 8 9IO.puts "Sum: #{sum}" 10IO.puts "Difference: #{difference}" 11IO.puts "Product: #{product}" 12IO.puts "Division: #{division}"

The code above demonstrates how you can declare two numbers and perform basic arithmetic operations. Here's what each line does:

  • number1 + number2 adds the two numbers.
  • number1 - number2 subtracts the second number from the first.
  • number1 * number2 multiplies the two numbers.
  • number1 / number2 divides the first number by the second.

The results are then printed to the console using the IO.puts function. Notice, that number1 is a floating-point number, while number2 is an integer. Elixir automatically converts the integer to a floating-point number when performing the operations. If both numbers are integers, the result will be an integer as well.

The output of the code above will be:

Plain text
1Sum: 30.5 2Difference: -9.5 3Product: 210.0 4Division: 0.525
Why It Matters

Mastering these basic operations is essential for many reasons:

  1. Data Manipulation: Many programming tasks involve some form of arithmetic. Whether calculating the total price of items in a shopping cart or analyzing data, you'll often need to perform these operations.
  2. Foundation for Complex Operations: Basic operations are the building blocks for more complex calculations and algorithms. Understanding these will help you tackle advanced topics more easily.
  3. Everyday Calculations: Even simple programs often require basic arithmetic. For instance, if you're creating a program to monitor your personal budget, you'll need to sum expenses and compute balances.

By mastering these basics, you'll be well-equipped to handle more complex programming challenges. Excited to get hands-on? Let's dive into the practice section and solidify your understanding of basic operations in Elixir!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.