Back to main

Lab 1 for C programming

Tips for programming are on How to Think about Programming.

I recommend using the geany python IDE. Write code, save it as a .py file, then press F5 to run it.

Exercises:
Material like this:
foo = bar(baz)
is a code example which can be copy-and-pasted directly into a .py file. Some of these examples will be an entire standalone file; other examples will be an exerpt which must be placed in the appropriate context.

Exercise 1: "Hello, world!" and friends

Background

By convention, the first thing to learn in a new programming language is to print the text "Hello, world!". Although text isn't very exciting by itself, the ability to output text is vital for debugging (fixing programs).

Most programming languages, including python, indicate text with "double quotation marks": the first " indicates the beginning of text. The computer then treates everything until the next " as text.

This causes problems if you want to print an actual " symbol in the output. For that reason, we use escape sequences to represent symbols which are difficult (or impossible) to indicate with plain text.

In addition to telling a compiler how to create an executable file, source code should also tell future programmers why the code does what it does. If anything in the code is unclear, a programmer should add comments which explain the situation.

Technical details

Printing text (complete example):

print "hello world!"

Selected escape sequences:

SequenceName
\nNew line
\tHorizontal tab
\\Back slash
\'Single quotation mark
\"Double quotation mark

Comments:

# this is a comment

print "hello"

# print "this will not be printed"

Your task...

Write a short self-introduction (not necessarily truthful!), and a list of items you would buy if given 1, 10, 100, or 1000 pounds. Example output:

Greetings!  I am \Sir Percival\ of the Round Table, hailing from
Vancouver, Canada.  My fair city lies approximately 4,500 miles to
the West.  In my country, we say `eh?' a lot.

Free money, you say?  Well, let's see...
        Pounds   Purchase
        1        A packet of tea biscuits.
        10       Second-hand DVDs of "Still Game", so I can learn Glasgow patter.
        100      An external hard drive for my laptop.
        1000     A visit to my family next Christmas.

Your program should:


(optional: make it funny. We'll like you more. You won't get any marks for being funny, but hey, you'll make a friend! Looking at these programming exercises gets really boring.)

... show your work to a demonstrator


Exercise 2: Variables and (simple) Math

Background

Computers would be boring if they didn't do any computation, and variables make computation a lot easier.

Variables must be declared before you can use them. Unlike many other programming languages, python does not require that you specify whether the variable is an integer, floating-point number, string, or anything else.

Variables can be more than one letter long; in fact, this is very heavily encouraged! Other than strictly mathematical variables like t or n, you should almost always use long variables names. Use the underscore _ to join multiple words together.


Text variables are called strings, short for "a string of characters". Technically, they are stored as an array of characters, but that detail is not important to us.

Technical details

Declaring and printing variables, and basic math:
x = 3
print "x is currently", x

y = 4.001
print "y is currently", y
print "Make that shorter: %.1f" % (y)
print "Make that longer: %.8f" % (y)

z = x/y
z = x + z*y - y
print "Why does z = %i ?\n" % (z)

animal_name = "cat"
cute_name = "kitty"
combo = cute_name + animal_name
print "We can do \"math\" on strings: %s" % (combo)

print "We can print multiple",
print "variables: %i %f %i %s\n" % (x, y, z, cute_name)
Examine the above program carefully -- there is a lot of good information in it! Try changing the values of variables, and examine the new output.

Your task...

Save your introduction/story program from Exercise 1 with a new file name: we will be modifying it, but you don't want to lose all your hard work.

Modify the new version of your introduction/story so that your program:

(hint: converting units is an easy way to get some math in there. Change between miles / km, pounds / euros, pounds / kg, human years / cat years, etc. You may need to rewrite part of your self-introduction to introduce some units.)

Think about your variable names. Don't write something like:
d = d * 1.609344
Instead, give them more descriptive names, like
distance_km = distance_miles * 1.609344

(optional: invent a new measurement (like "centi-flipsies") and convert into them.)

... show your work to a demonstrator


Exercise 3: Keyboard input

Background

Programs would be pretty boring without user interaction. The easiest way to get information from the user is with the keyboard.

Technical details

Reading strings:

print "Enter an animal name:"
animal_name = raw_input()
print "You typed: %s" % (animal_name)

Reading numbers is slightly more complicated; you need to change the string into an integer or float.

print "Enter your age (as an integer):"
user_input = raw_input()
age = int(user_input)

print "Enter a float:"
user_input = raw_input()
weight = float(user_input)

print "You typed: %i, %f" % (age, weight)
If the user types something other than an int/float, you'll get an error. For now, don't worry about those.

Your task...

Mad libs (similar to "ad-lib") is a popular party game in North America. Somebody writes a story, but removes a few nouns, adjectives, and verbs. Other people must supply words to replace them (often with a clue, such as "an animal name" or "a movement verb"), without knowing the context in which they would be used. The result is nonsensical and sometimes funny. For example:

One day, a ________________ went to _______ and _____________ a ______.
            name of animal           place       verb (past)     noun

(other people supply: "polar bear", "Russia", "ate", and "house".)

Write a program which implements a mad-lib game:


(optional: make it funny)

... show your work to a demonstrator


Exercise 4: Functions

Background

You are familiar with functions in mathematics -- you've handled functions like g(x) = x^2 + 2x - 3. In this case, the function returns a value. The returned value is computed based on the input. You have also seen functions with multiple inputs: h(x,y) = 5x - 6x + x*y.

We use functions like this in programming. We need to specify the number of input variables, do the math, then return the answer.

We also sometimes use functions which do not return any values -- these are useful if we want to repeat a few commands, or simply for program organization.

Functions must be declared before ("higher in the .py file") they are used.

Note that each function has its own scope of variables. In fact, you can re-use the same variable name in different functions!

Technical details

Simple function. Note that functions must be indented with 4 spaces or a tab!

def g(x):
    return x*x + 2*x - 3

a = 3.2
b = g(a)
print "g(%f) = %f" % (a, b)
print "g(5) = %f" % (g(5))
Note the different variables names in the above example!

Various functions:

def cat_years(human_years):
    y = human_years / 7.0
    rounded_y = int(round(y))
    return rounded_y

def sum_of_squares(a, b):
    return a*a + b*b

def p(years, c, animal):
    print "If I were a %s, I'd be" % (animal),
    print "%i years old.\n" % (years)
    print "The sum of squares",
    print "was %f units.\n" % (c)

my_age = 18
x = 3.3
animal = "cat"

years_a = cat_years(my_age)
sum = sum_of_squares(x, 7.4)

p(years_a, sum, animal)

Your task...

As electrical engineering students, you are familiar with Ohm's Law (V = IR) and calculating the value of resistors in series (R = R1+R2) and parallel (1/R = 1/R1 + 1/R2). Consider the following circuit:

Write a program to calculate the overall current in this circuit.


(optional: you can call functions as inputs to other functions, i.e.

z = f( g(x,y), h(x,y) );
Using this, calculate the current from voltage and Rx values in a single line.)

... show your work to a demonstrator

Move on to Lab 2


Creative Commons LicenseUnless otherwise noted, all materials on these pages are licenced under a Creative Commons Licence.