Now that we've explored variables, data types, and basic operations, let's see how they come together in some simple, real-world (or at least, algorithm-world!) scenarios. These examples will help solidify your understanding and show you how these fundamental building blocks create the logic of programs.
Imagine you're calculating the area of a rectangle. You need to store the length and width, and then perform a multiplication. This is a perfect candidate for our basic building blocks.
let rectangleLength = 10;
let rectangleWidth = 5;
let rectangleArea = rectangleLength * rectangleWidth;
console.log(rectangleArea);In this example:
rectangleLengthandrectangleWidthare variables of typenumberstoring our dimensions.rectangleAreais anothernumbervariable that holds the result of multiplying the length and width.console.log()is used to display the final calculated area.
Let's visualize this process with a simple flowchart. This diagram shows the steps involved in our rectangle area calculation.
graph TD;
A[Start]
B{Declare rectangleLength}
C{Declare rectangleWidth}
D{Calculate rectangleArea = rectangleLength * rectangleWidth}
E{Display rectangleArea}
F[End]
A --> B
B --> C
C --> D
D --> E
E --> F
Consider another common task: calculating the total cost of items. If you buy multiple items of the same price, you multiply the quantity by the price per item.
let itemQuantity = 3;
let pricePerItem = 2.50;
let totalCost = itemQuantity * pricePerItem;
console.log(totalCost);Here:
itemQuantityis anumberrepresenting how many items we have.pricePerItemis anumber(specifically, a floating-point number) representing the cost of one item.totalCostis anumberthat stores the result of the multiplication.
We can also perform operations with text (strings). Let's say we want to greet someone by name.
let userName = "Alice";
let greetingMessage = "Hello, " + userName + "!";
console.log(greetingMessage);In this string example:
userNameis astringvariable holding a name.greetingMessageis astringvariable created by concatenating (joining) the literal string "Hello, " with theuserName, and then adding "!". The+operator performs string concatenation when used with strings.
These simple examples demonstrate the core idea: algorithms are built by defining containers (variables) to hold information (data types) and then manipulating that information using operations to achieve a desired outcome.