Lesson 3: Programming
Algorithms
An algorithm is a step-by-step procedure for solving a problem. It's like a recipe that tells you what steps to take to achieve a specific result. For example, making a sandwich involves a set of steps like getting bread, adding cheese and other fillings.
Computer Science Basics: Algorithms video on YoutubeCreate a solution to the following problem:
Guess a number between 1-100.
Try to have as few steps as possible.
Variables
Variables are containers for storing data. They can hold different types of data, such as numbers, words, or true/false values. Some examples of programming variables in different languages:
# Python
name = "Alice"
age = 25
is_student = True
# JavaScript
let firstName = "Bob";
let lastName = "Smith";
const PI = 3.14;
# Java
String address = "123 Main Street";
int numRooms = 3;
boolean hasPool = false;
Loops
Loops are used to repeat a set of instructions multiple times. For example, you can use a loop to print the numbers from 1 to 10.
# Java
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 11);
# Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Conditionals
Conditionals are used to make decisions based on certain conditions. Some examples include
If-else statements:
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
Switch Statements:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
default:
// code to execute if expression does not match any of the cases
break;
}
Types of Conditions Used Within Condition Statements
Types of conditions used within condition statements
Comparison operators
Comparison operators compare two values and return a Boolean value (true or false) based on whether the comparison is true or false. Examples include:
Operator | Description |
---|---|
== | Equal to |
!= | not equal to |
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
Logical operators
Logic operators combine multiple conditions and return a Boolean value based on the result of the combination. Examples include:
Operator | Description |
---|---|
&& | and |
|| | or |
! | not |
Put all of these together and our program is starting to come together, for example:
# In C#
int num = 7;
if (num < 0) {
Console.WriteLine(num + " is negative");
} else if (num == 0) {
Console.WriteLine(num + " is zero");
} else {
Console.WriteLine(num + " is positive");
}
Functions
Types of conditions used within condition statements
Functions are reusable pieces of code that perform a specific task. They allow you to write a block of code once and use it multiple times. For example, you can write a function to calculate the area of a rectangle and use it whenever you need to calculate the area of a rectangle.
def calculate_rectangle_area(length, width):
"""Calculate the area of a rectangle with the given length and width."""
area = length * width
return area
The function takes two input parameters, length and width, which represent the length and width of the rectangle, respectively. It then calculates the area of the rectangle by multiplying the length by the width and it returns the result.
To call this function and calculate the area of a rectangle with a length of 5 and a width of 3, for example, you would do the following:
area_of_small_rectangle = calculate_rectangle_area (5, 3)
print(area_of_small_rectangle) # Output: 15
area_of_big_rectangle = calculate_rectangle_area(15, 33)
print(area_of_big_rectangle) # Output: 495
It calls the calculate_rectangle_area() function with input parameters of 5 and 3, and assign the result (15) to the area_of_small_rectangle variable. The print() function then outputs the value of area.
Example to Put Your Learning Into Practice
Here is a program in Python that puts all we have learned today into practice. This program prompts the user to input their name and age, uses a conditional statement to check if the user is 18 or older, and then calculates the sum of even numbers up to the user's age using a loop and a function. The program's output varies depending on the user's age.
Define a function to calculate the sum of even numbers up to a given limit
def sum_even_numbers(limit):
total = 0
for num in range(2, limit + 1, 2):
total += num
return total
# Get input from the user
name = input("What is your name? ")
age = int(input("How old are you? "))
# Use conditional statements to customize the program's output based on the user's age
if age < 18:
print(f"Sorry {name}, you must be 18 or older to use this program.")
else:
# Calculate the sum of even numbers up to the user's age
sum_of_evens = sum_even_numbers(age)
print(f"{name}, the sum of even numbers up to your age ({age}) is {sum_of_evens}.")
Here's an example of what the program's output might look like when run
What is your name? John
How old are you? 25
John, the sum of even numbers up to your age (25) is 156.