Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI Systems

Putting It All Together: Simple Examples

Section 5

Building Blocks of Algorithms: Variables, Data Types, and Basic Operations

Introduction to Computer Algorithm: Data Structures, Complexity, and Optimization for Modern AI SystemsBuilding Blocks of Algorithms: Variables, Data Types, and Basic Operations

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);
チャプターへ戻る