Loading...

Section

Putting It All Together: Simple Examples

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

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:

  • rectangleLength and rectangleWidth are variables of type number storing our dimensions.
  • rectangleArea is another number variable 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:

  • itemQuantity is a number representing how many items we have.
  • pricePerItem is a number (specifically, a floating-point number) representing the cost of one item.
  • totalCost is a number that 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:

  • userName is a string variable holding a name.
  • greetingMessage is a string variable created by concatenating (joining) the literal string "Hello, " with the userName, 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.