CSCA48 2021W Unit1
CSCA48 2021W Unit1
Learning Outcomes
This unit will introduce you to the C programming language, and show you how to do most of what
you can already to in Python in C. By the end of this unit, you will be able to:
Figure 1: Popularity of programming languages by the TIOBE Index (used with permission)
• It is an imperative language, so the structure of a program, and the types of control structures
(such as conditional statements, loops, etc.) will be familiar to you from what you learned of
Python in your A08 course.
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 1
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
• It is a simple language, it provides precisely the support we need to focus on the concepts and
algorithms that comprise our course, without having to become distracted by the richness of
features, syntax, and programming constructs available in more recent languages.
• It will require you to know in detail what each line of your program is doing. Programming
in C will help you strengthen your ability to fully understand what your code is doing at each
step.
• It is a skill that will be required of you in future courses. Whether you are in CS, Math, Stats,
or a different discipline altogether, the ability to think carefully and in detail about what your
code is doing will help you make the most of courses where programming is needed to fully
understand an exciting topic – a good example of this is Machine Learning (CSC C11),where
implementing ML algorithms is essential for fully grasping the course material. If you are in
CS, knowledge of C will be required for courses such as: Operating Systems (C69), Embed-
ded Systems (C85), Computer Graphics (D18), Computer Security (D27), Networks (D58),
Programming on the Web (C09), Programming Languages (C24) and Compiler Optimization
(D70).
• The memory model used by C is very simple, and accurately describes how computer storage
works at a low level. It maps directly to how memory is accessed by the computer’s processor,
and how data and code are processed once a piece of code is translated to the CPU’s machine
language. Together with what you will learn in Computer Organization (B58), it will allow
you to fully understand how a computer works, and how it can execute a program.
2 Structure of a program in C
The basic structure of a C program is very similar to what you already know from Python:
• A program is split into functions, each function carries out a specific task related to imple-
menting a given algorithm.
• Unlike Python, there is no interactive mode for C. All programs start at a function called
main(). This function is in charge of using the rest of the code in the program to carry out
main()
the specified algorithm.
• The program can include and use code from libraries, similar to Python modules, which
provide a wide range of functionality.
• Code that belongs to a specific scope is indicated by delimiters, in C these are curly braces .
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 2
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
• Every variable in C has an associated data type. Just like Python, we can have different
types that represent things such as integer numbers, floating point numbers, strings, and so
on. Unlike Python, once we have associated a data type with a specific variable, the type can
not be changed.
As you can see there is not many! Part of our course will consist of learning how to use these basic
data types to build more complex containers for our information, so we can have things like the
lists and dictionaries you have used in Python.
At the coarsest level, a C program looks like this:
8 // After the libraries, we will find the code that comprises the
9 // program, organized into functions.
10
22
23
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 3
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
39 } // This curly brace indicates where the code for main() ends
Variables declared within a function are local to that function, and can not be accessed
anywhere else in the code. We will learn how to pass information between functions so we can get
work done.
1 /*
2 Hello World!
3 Welcome to programming in C :)
4 */
5
6 #include <stdio.h>
7
8 int main()
9 {
10 printf("***** HELLO WORLD *****\n");
11 return 0;
12 }
NOTES:
The printf function is part of the standard input/output library (which is why we need to include
a file called stdio.h
stdio.h), and prints formatted information to the terminal. It has a large number of
options that we will study later, but for now, suffice it to say that the string to be printed goes
between the quotes, and the ’\n’ at the end is the newline character and tells the function that it
should go to the next line after printing (without it, if you have another print statement, the output
of the second one will be printed immediately after the first one, on the same line).
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 4
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
Windows Instructions
• Open a terminal
• Using the cd command to change your directory to where you have your program. Pay
attention when you save your program to the location where you saved it! You’ll need to cd
to that location.
• Once you have your terminal in the directory that contains your code you can call the compiler
to create an executable for your program.
• Compile your code by typing: gcc hello world.c This will produce an executable file called
a.exe which you can run from your terminal.
• If you want to specify the name of your executable file, you can do so with the -o option:
gcc hello world.c -o hello world
Which will produce hello world.exe
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 5
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
MacOS/Linux Instructions
• Open a terminal
• Using the cd command to change your directory to where you have your program. Pay
attention when you save your program to the location where you saved it! You’ll need to cd
to that location.
• Once you have your terminal in the directory that contains your code (you can type ls to
list the files in that directory and check your program is there), you can call the compiler to
create an executable for your program.
• compile your code by typing: gcc hello world.c This will produce an executable file called
a.out which you can run from your terminal by typing ./a.out
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 6
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
EXERCISE
Write your first C program, called my hello world.c so that when compiled and
run it will tell us a bit about yourself.
The output of your program should look like this (but obviously with your own
answers):
I am going to learn C! :)
Write, compile and run your code. Chances are, the first time you try this out you will run into all
kinds of compiler messages.
Here’s the most important thing about learning to deal with compiler errors:
Do not stress out – they happen often and you can fix them.
Here are some typical problems you may run into:
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 7
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
1 #include <stdio.h>
2
3 int main()
4 {
5 printf("***** HELLO WORLD *****\n") // Missing semi-colon!
6 return 0;
7 }
The compiler is complaining about a missing semi-colon, just before the return statement on line
6 – be careful! The error is actually on the previous line! The printf() statement is missing the
semi-colon.
Here’s another example:
1 #include <stdio.h>
2
3 int main()
4 {
5 printf('***** HELLO WORLD *****\n'); // Wrong quotes!
6 return 0;
7 }
(There’s a lot more messages after, but this is the first one that tells you where the problem is)
Note that the compiler helpfully gives you a ^ to indicate where in the code the problem appears
to be. In C, text is delimited by double quotes, not single quotes.
Have a look at one more typical problem:
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 8
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
1 #include <stdio.h>
2
3 int main()
4 {
5 printf("***** HELLO WORLD *****\n");
6 return 0;
7 }
8
This tells us the compiler was expecting a function declaration (since the printf statement appears
outside any function).
One more classic problem:
1 #include <stdio.h>
2
3 int main()
4 {
5 printf("***** HELLO WORLD *****\n");
6 return 0;
7
The compiler expected to see a closing curly brace somewhere, but instead it found the end of your
file.
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 9
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
• If you have never seen this particular error message, copy the error message onto Google
Note: Do not include the program name, or line number! Google doesn’t know your specific
program, but it probably has seen lots of developers who had the same error before and can
tell you what may be causing it.
• Carefully review the first few hits Google comes up with, chances are the answer you need is
there.
• Google is your best tool when dealing with compiler errors – learn to use it well!
• However, Google is not perfect and sometimes it won’t find the solution to your problem. In
that case, come talk to your TA or course instructor! Or ask for help on our forum.
• Keep a journal of errors you encountered, and what caused them. So you can refer to it in
the future and save time and effort. You will in time remember these things without having
to visit your journal, but while you’re learning, it’s a great tool!
• Done fixing one error? Go on to the next one. Keep going until no errors are left.
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 10
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
You should become familiar with how it works - it should be familiar if you recall f string.format(...)
from python:
printf(" ... formatting string ... ", variables, to, print, separated, by, commas);
The formatting string specifies what printf() is going to do with the list of variables it’s printing,
it tells printf the data type of the variable it is receiving, so that it is printed with the correct
format. Formatting options are specified using the % character as follows:
There are many more formatting options, and you can specify things such as the number of digits
to print for the integer and fractional parts of a floating point number. If you are looking for a way
to give your program’s output a specific format, look at the on-line documentation for printf()
printf().
Chances are the function does what you need, you only need to find the correct format specifier.
Besides these format specifier for variables, the printf() function also makes use of certain control
sequences to print special characters. These are identified by the character. Common control
sequences include:
The result of the above will be to print a line that looks like:
My variables are: 10, 3.14159265, Hello World
And at the end of the string the \n sequence moves to the next line, so anything we print after will
be output to the next row of text in our terminal.
Of course, the data type for your variables must match the format specified in printf()
printf(), otherwise
you will receive a compiler warning.
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 11
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
1 #include <stdio.h>
2 int main()
3 {
4 float pi;
5 pi = 3.14159265;
6 printf("Printing an int, %d\n", pi);
7 }
gcc printf_test.c
printf_test.c: In function ‘main’:
printf_test.c:6:12: warning: format ‘%d’ expects argument of type ‘int’, but
argument 2 has type ‘double’ [-Wformat=]
printf("Printing an int, %d\n", pi);
Keep an eye out for compiler warnings – they indicate that there is something fishy and probably
wrong with your code, but the program still compiles and runs:
$ .\a.exe
Printing an int, 190300824
IMPORTANT NOTE
In general – You must make sure to find out, and clear, any compiler warnings.
Except for very rare instances, they indicate a problem with your code. You have
to be very, very sure you know what you’re doing if you choose to ignore a compiler
warning.
EXERCISE
Write a little program that initializes a variable pi to 3.14159265, then prints out
pi as an integer (should print 3), and as a floating point number with increasing
fractional part lengths. i.e, the output of your program should look like:
3
3.1
3.14
3.141
3.1415
3.14159
3.141592
3.1415926
3.14159265
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 12
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
8.1 Loops
The most common types of loops in C are for loops and while loops. For loops have a simple syntax:
1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6
Note:
• The for loop uses a counter variable to keep track of iterations. In the case above we are using
an integer variable called i which was declared in advance.
• The definition of the for loop has 3 components separated by ;
(i = 0 ; i < 10 ; i = i + 1)
This means:
– Set the initial value for i to 0
– The loop must run for as long as i < 10
– At each iteration, i is increased by 1 (that’s the i = i + 1 part)
• The body of the for loop is delimited by curly braces {, }
EXERCISE
Trace the above code and try to predict the output. Once you are convinced that
you know the output, write the code for yourself and check your intuitions. Can
you write a program that has the same output but in the reverse order?
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 13
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
In C, you can have for loops that use floating point variables as counters, that use non-integer
increments, negative increments, or in fact no increment at all within the body of the for loop!
Examples:
1 float angle;
2 float pi;
3
4 pi = 3.14159265;
5
6 for (angle = 0.0; angle < 2.0 * pi; angle = angle + .01)
7 {
8 printf("%f\n", sin(angle));
9 }
The code above will print the sine of angles between 0 and 2 ∗ pi at intervals of .01 radians.
1 int i;
2
4 for (i = 0; i < 10 ; i = i + 1)
5 {
6 for (j = 0; j < i; j = j + 1)
7 {
8 printf("%d, ", j);
9 }
10 printf("\n");
11 }
A nested loop where the length of the loop on j depends on the value of i.
EXERCISE
Trace the output of the nested for loops above. Then try the code yourself to verify
your answers.
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 14
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
1 while ( condition )
2 {
3 // body of the loop
4 }
The condition is a logic statement that depends on variables accessible to the function the loop is
part of. Logic statements evaluate to either true or false
false. The loop is executed for as long as
condition evaluates to true
true.
8.3 Conditionals
Conditional statements are also quite similar to what you’re familiar with from A08 and Python.
We use if statements to evaluate expressions and execute code that depends on the results. The
structure of if...else statements in C is as follows:
Of course, you can use nested if...else statements. Conditions are specified using the standard
comparison operators:
• a == b - True if a equals b
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 15
CSCA48 - Unit 1 - Introduction to Programming in C Winter 2021
Note: Not all built-in types can be compared in this way. The above comparison operators work
for int, float, double, and char. You can not compare two strings using comparison operators, we
will learn why in the next unit.
In addition to the above, we can use logical operators to form conditional statements that evaluate
multiple relationships between variables. Common logical operators used in if statements include:
• ! - Logical not
1 if ( (a > b && c == d) || e != f)
2 {
3 // Run this code!
4 }
5 else
6 {
7 // Run this code instead!
8 }
IMPORTANT NOTE
Be careful with the way you use operators. A common mistake is to use a single &
or a single | instead of the double symbol. The single & and single | perform an
arithmetic and, and an arithmetic or respectively, the result is a binary number
instead of a true/false value.
EXERCISE
Write a small program that uses a for loop to go over the numbers from 1 to 100,
and prints out any that are perfect squares. The output of your program should
look like:
4 = 2 * 2
9 = 3 * 3
16 = 4 * 4
... (there are more perfect squares printed)
100 = 10 * 10
You will need to use for loops, conditional statements, and printf()
printf().
F.Estrada,
c M.Ahmadzadeh, B.Harrington 2020 16