Program Structure

Expressions and Statements

Programming languages are made of expressions. The number 42 is an expression. The string "Hello World" is also an expression. In human languages, like English, each word has a meaning. Words make up sentences. Sentences are used to convey pockets of structured information. Combine sentences into paragraphs, and you have a dialogue. Organize and link enough paragraphs together, and you have a narrative, a story. Expressions in English can be put together to express complex events, emotions and ideas. Like human languages, expressions in programming can also be combined to express complex computations.

Variables

A variable is a representation or a symbol to store information, usually for future use. For example, if you have an array [1,2,3,4,5,6,7,8,9,10] and you want to refer to it 10 times in your program, it should be stored in a variable.

paragraph = "Hello, this is Hello World!"

Here, we have defined a variable paragraph. And, we named it paragraph, so that we can use its name as an expression. For example, if we want to find out how many characters is in that sentence, we can do

paragraph.length

How do you name a variable? Variable names can be any word, but

  • it cannot be a reserved word (such as class)
  • it cannot contain spaces
  • it cannot start with a number

Updating a variable

When you assign a value to a variable (i.e. number = 1), the variable points at a value, but that doesn't mean it is tied to that value forever. The = operator can re-assign another value to a variable (i.e. number = 2).

A variable also doesn't "own" a value. A variable merely points to a value, so you can have multiple variables pointing to the same value:

variable_a = 1
variable_b = 1

Keywords & Reserved Words

Each programming language has words with a special meaning, and they may not be used as variable names. You don't need to memorize them because it will naturally be obvious to you as you progress.

The follow is a list of reserved words for Ruby:

BEGIN END alias and begin break
case class def defined? do else
elsif end ensure false for if
module next nil not or redo rescue
retry return self super then true
undef unless until when while yield

Functions/Methods

What is a function? A function takes inputs and returns an output. That's it. In Ruby, functions are also known as methods.

Defining a function in programming requires 3 things:

  1. name of the function
  2. input(s) the function will take
  3. return an output after processing
def <function name>(<input 1>, <input 2>)
  # <processes>

  # return <output>
end

Here, we define a function for adding two numbers. We call it sum which requires two numbers as inputs.

def sum(a, b)
  return a + b
end
  • def stands for define.
  • sum is the name of the function.
  • (a, b) means that the function takes two inputs. We gave names to these two inputs as a and b, so that we can refer to them during processing them.
  • a + b is the main processing part, where we are adding these two numbers.
  • return a + b combines the expression of return and a + b to return the sum as an output.
  • end means we've completed defining the function.

Executing a function is also known as invoking, running, calling, applying a function. We are going to use the word call to mean executing a function throughout this course.

We call the function sum:

sum(1, 2)
=> 3

When you are calling a function, you need to 1) spell out the name of the function and 2) put values for the inputs. Then, you will expect an output from your function.

We are going to use an analogy for functions. Your microwave is a function. It takes at least one input – the amount of time to cook. It then outputs a total amount of heat to cook.

def microwave(time)
  heat = time * x * y * z # calculations about how much heat it needs

  return heat # output heat to cook your food
end

Now, some functions don't require any input. For example, a water boiler doesn't need any input. You only need to turn it on or, in programming, call the function:

def water_boiler()
  # turn on radiator

  return heat # output heat from radiator
end

Programming has a lot of jargons, and it's sometimes for many good reasons. Remember, there are a lot of different ways of saying "execute a function"? Well, there are also many sayings for the word input. An input is often known as a parameter or an argument. (In this case, argument is NOT an exchange of diverging or opposite views)

So, what is a function? A function takes inputs, do its processes and returns an output.

The puts / print function

Question: will the following function return an output?

def print
  puts "Hello World!"
end

puts only prints out stuff to the screen. It doesn't return an output. Only return defines returning an output. So, in this case, the function print does not return an output.

def yes_output
  return "Hello"
end

def no_output
  puts "Hello"
end

> yes_output
=> "Hello"

> no_output
Hello
=> nil

=> precedes before the function output. In this case, yes_output returns "Hello" and no_output returns nil. Notice that no_output prints out "Hello", but printing is not returning an output.

Control Flow

When your program contains more than one statement, the statements are executed from top to bottom.

Conditional Execution

In our program, we can add conditions to control what code to execute. We can write a program such that only certain code will only run if certain conditions have been met.

For example,

def legal_to_drink(age)
  if age >= 21
    # run the following code if age is >= 21
    return true
  else
    # run the following code if age is < 21
    return false
  end
end

legal_to_drink(22)

In this code, we have defined a function legal_to_drink that takes an input age. The keyword if is followed by a conditional statement age >= 21. If age is larger or equal to 21, then the person is legal to drink, thus returning age >= 21 should be true, and vice versa.

Based on the conditional statement, different code blocks will be executed.

For Loop

If you need to write a program that prints all odd numbers from 0 to 12, how would you do it?

One way to do it is:

puts 1
puts 3
puts 5
puts 7
puts 9
puts 11

This works, but what if I want to print all odd numbers from 0 to 1 million? Then, the previous approach would look insane.

When we need a way to repeat some code, we use a loop. In this case, we use a For Loop:

for i in 0..12
  puts i
end

This will loop / iterate through all numbers from 0 to 12. During each iteration, the i will represent the current number. During each iteration, puts i will run once to print out the current number.

Output:

0
1
2
3
4
5
6
7
8
9
10
11
12

Now, we can print all the numbers from 0 to 12. How do we ONLY print odd numbers? We learnt about conditional statements. We can write the program so that it will only print the number if the condition (being an odd number) is met.

Math Reminder: Any number that is divisible by 2 is an even number. Otherwise, it's an odd number.

In Ruby, the remainder operator % returns the remainder when you divide. For example, 4 % 2 is 0 because 4 = 2 x 2 with no remainder. 5 % 2 is 1 because 5 = 2 x 2 + 1, where 1 is the remainder. So, we can use the % operator to determine whether a number is even or odd.

for i in 0..12
  # determine whether a number is even or odd
  if i % 2 != 0
    puts i
  end
end

Outputs:

1
3
5
7
9
11

There, we have written a loop to help us do repeated tasks. So, if we want to return all odd numbers from 0 to 1 million? Just do:

for i in 0..1000000
  if i % 2 != 0
    puts i
  end
end

Done! Cool, right?

You can also express a for loop in a different way, like this

(0..12).each do |i|
   puts i
end

The two methods are both valid for loops. When there is more than one way of doing something, use the one that makes sense to you the most.

While Loop

Similar to For Loop, the While Loop will execute code as long as the condition has been met. And, its structure looks like the following.

while <conditional> do
  <code>
end

For example,

x = 0

while x < 5 do
  puts x
  x = x + 1
end
0
1
2
3
4

Here, we defined a variable x to be 0. The while loop checks if x is smaller than 5. If so, 1) print the number 2) increment x by 1. The loop stops when the condition (x is smaller than 5) is no longer true.

There is another shortcut for incrementing a variable by 1. You can do x += 1. On the other hand, if you want to decrement a variable, you can do x -= 1, which is the same as x = x - 1.

For more on loops, read this.

Indentations

In programming, we put spaces in front of codes to make it look tidy. With proper indentation, the visual shape of a program corresponds to the shape of the blocks inside it. For Ruby, the standard is to put two spaces for every open block. You can set your text editor such that pressing tab produces 2 spaces. If you prefer 4 spaces, you can do that too.

Naming Convention / under_score

When you are naming a variable, you sometimes want to use multiple words to clearly describe what the variable represents.

carscount
carsCount
CarsCount
Cars_Count
cars_count

Which one should you use? The standard for Ruby is cars_count, which is called the "under_score" way of naming a variable. When you are using multiple words for a variable name, you want to separate each word with an underscore _.

Comments

Sometimes, when you are writing code, you want to explain something in human language. To do that, you can use comments which will NOT be executed for your program. It acts like a footnote.

For example

x = 0
x += 1
# I am incrementing `x` by 1 <-- this is a "comment" that will not be executed.

Summary

You now know that a function takes inputs, process them, and return an output. Returning an output is different from printing. You can add conditional statements. For repeated tasks, you can use for loops and while loops to help you out. Indentation should be 2 spaces by default. Use under_score for naming.

Exercises

Looping a triangle

Write a loop that prints (using puts) the following triangle:

#
##
###
####
#####
######
#######

Fizzbuzz

Write a program that uses puts to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead.

When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those).

1
2
Fizz
4
Buzz
... more

Chess Board

Write a program that creates a string that represents an 8×8 grid, using newline characters \n to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.

Printing this string with puts should show something like this:

 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #
 # # # #
# # # #

When you have a program that generates this pattern, define a variable size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

results matching ""

    No results matching ""