The first C program¶
Refer to the course material about the first program in the C language. e.g. Kernigham & Ritchie (K&R) Chapter 1.
The basic blocks of C programming¶
As was promised before, the course proceeds in about the same order as the Elementary Programming course. At least as much as it is possible with C. This time we will refine two basic pieces of programming:
variables
and functions
. Without them it is rather difficult to do any programming, especially in C, which does not even have a main program.A frame in the shape of C¶
Learning objectives: After this portion you will know how to write a C program that can be compiled and executed.
Compulsory symbols¶
Unlike in Python, where a code file may contain just a single line of code that does something, C requires certain basic things. At the end of the previous piece of material there was an example of a very simple C program:
#include <stdio.h>
int main() {
printf("aasisvengaa!\n");
return 0;
}
The actual code to be executed still is only one line, but around it has appeared this and that. We got a preparatory look at these in the previous material. The #-symbol at the beginning does not, by the way, make a line a
comment
(//
does!). All the lines that begin with # are instead lines meant for the precompiler
to handle. In short, a precompiler is a part of the compiler
that format the code file according to the directives
, the lines marked with the #-symbol at their beginning. At this point we will only handle the directive called include, which resembles Python's import command
. In C include is required at the beginning of learning the language, because, unlike Python, C does not have a built-in print function - it has to be separately introduced by adding the library
stdio (Standard Input/Output), which has it included.At the end of the names of libraries is .h, which is short for header. This .h-file is a library's
header file
, which includes the introductions of the functions, constants and possible variables of the library. The actual code of the library is in the stdio.c file. We usually will not be seeing it, since compilers typically deliver the standard libraries as compiled binary files. There will be more about header files later on the course. While perusing the code you might notice one difference to the import of Python: when printf function is called, it is not written stdio.printf, just printf. In C include works actually like Python's from moduuli import *
and separate namespaces are not used. This means you need to be more careful with naming your functions than usually.The library used here, stdio, includes functions that are related to printing and reading input. At this point it will be used in practically every program. Other at this point or soon relevant libraries are at least math and stdlib. When you need these they will be introduced to you so that you know when and how to use them. C does not have a similar friendly documentation base as Python, so we recommend you either use a C book or the ”UTFG” method (just google everything).
Another notable difference is that you can not make a C program without
functions
- the main program like in Python does not exist. Instead a main function
does, and as default is main
and its default return value is int
. The return value's type is int, because the program returns at its end a code, that tells about how it ended - usually only operating systems are interested in this value. We will go deeper within the inner workings of a C function in this material, but not yet. At this point it is enough that you get what this mysterious int main() {
-line is. It defines the main function, which does not have parameters
. At the end of the line the curved bracket is the beginning of a statement block. All the things between this and the closing curly bracket are inside the function.Variables' metamorphosis¶
Learning objectives: After this portion you will have mastered the basics of the variables in C. This includes understanding and defining the types of variables, and some sort of understanding in which way variables reside within the memory of a computer. We will also take a look at how variables can be printed and how their types can be changed.
Refreshing memories¶
Just a reminder about what was said about the
variables of Python
in Elementary Programming before we delve into the inner workings of C's variables
. The basic idea was to connect the name appearing in the program to the value inside the computer's memory
. This familiar animation might work as a fine refresher:So, that was Python, about which was nagged how a
variable
is a reference to a value
and does not actually contain a value. This is demonstrated in the animation at y = x
, where both of the variables point at the same value. It was possible to show this even in the Python interpreter using id function:>>> a = 5
>>> id(a)
10894208
>>> b = a
>>> id(b)
10894208
Here can be seen how a and b are not identical only by their value, they are the same
object
. This does not have much to do with the basic types of variables, like numbers and strings, because these data types
are immutable
in Python. With lists
you could instead see actual repercussions:>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> a
[1, 2, 3, 4]
This behaviour had at least one typical application: the functions were given lists that the function edited but did not return. They were not returned, because that was not necessary - the edited list was the same list the function had been given. As an example of this could work, for example, the collection program example's lisaa function:
def lisaa(kokoelma):
print("Täytä lisättävän levyn tiedot. Jätä levyn nimi tyhjäksi lopettaaksesi")
while True:
levy = input("Levyn nimi: ")
if not levy:
break
kokoelma.append({
"artisti": input("Artistin nimi: "),
"albumi": levy,
"n": kysy_luku("Kappaleiden lukumäärä: "),
"kesto": kysy_aika("Kesto: "),
"vuosi": kysy_luku("Julkaisuvuosi: ")
})
Comparing memories¶
In C
variables
are tied to their values in the sence that you could say the variable contains a value - the variable is a name the programmer has set for the area of the memory
the value is located in. When a new variable is created, a new area of memory is reserved for it. Let us return back to this after a moment, but let us watch an animation about it before we continue.Another way C's variables differ clearly from Python's is how they have a separately defined
type
. Type is defined in the introduction
of the variable, which is always in the form type_of_the_variable variable_name
.Python does not use introduction at all, since the variables are created on the fly when some value is set for them. In C the variables always have to be introduced, reserved memory for them, before they can be used. At the introduction a value can be set for the variable. That is called
initializing
.These both are proper introductions:
int i;
int x = 5;
What happens if you do not initialize a variable? Usually you get very random results.
Types everywhere¶
In C the types of the variables play a bigger part than in Python. C has more basic types. Above you can see an
integer
type int
. Other integer types of C are short
and long
. These types also have modifiers signed
or unsigned
which can determine whether the variable can be negative or not, as a default option all numbers are positive integers, though. For characters there is the variable type char
, which is actually an integer variable, and that will be explained later. Unlike in Python, in C there is no string
of characters variable type. We will later return to how to handle strings.Also
floating point numbers
exist in C, and they work in a similar manner as they do in Python. Not surprisingly, also they are just bits in the memory, they are just interpreted in a different manner. In C there are two float types, float
and double
. It is not relevant to this course to understand how floating point numbers act within memory, but it is good to know that they never are absolutely exact values, just approximates. We will return to variables and floating point number systems later.Now that we know something about variable types, we can take on some exercises so that we will remember something about them later.
These exercises have no effect on course grading.
Types in print out¶
Among all the other fun things, the
types
of variables
are also related to print out. In C the compiler has to be told which type we want to print. To not make things too simple, we can print out variables as different types than they have been introduced as. At this point you only need to know that in C you give the printing function, printf
, as parameters the variables to print and descriptions of how to print them. There's an example of this below.printf("%d\n", x);
In short (we will get back to this later), in the printf call above the value of the variable x is printed on screen as an integer and right after it a newline character. The first parameter of the function is a string, which says how to print, in this case
"%d\n"
. Now %+letter
characters are the same as the placeholders
in Python's format
method and after that the newline character \n
. Actually Python does also have similar syntax - format is only a bit more modern and versatile way of doing the same thing. In the place of every placeholder in the printf
function there will be one of the arguments
after the string in the given order. In the example in the place of %d
will be the value of the variable x in the print out. Unlike in Python, where you could use an empty place holder like "You gave a number {}".format(luku)
, in C the types of placeholders are tied to the types of the variables. Here is a list of the most commonly used ones on this course:placeholder | variable type |
%d | int |
%i | int |
%hi | short |
%li | long |
%u | unsigned int |
%hu | unsigned short |
%lu | unsigned long |
%f | float, double |
%c | char |
%s | char[] |
In addition to these, the standard includers also others you will see in the material, but are not strictforwardly related to one variable type. For example:
placeholder | meaning |
%x | prints the value of the variable in hexadecimal format |
These exercises have no effect on course grading.
Functions' metamorphosis¶
Learning objectives: In this portion we will handle how to define functions in C and what differences they have with Python functions (typed parameters and return values). Prototype is introduced as a new concept.
Danger: Functions devour types!¶
On the base level defining and using
C function
do not differ from defining and using Python function
. Function is defined on its own definition line, on which is presented the function's name and parameters
, and the code of the function follows. The syntax is somewhat different: on the definition line there is no separate keyword like Python's def. Instead of it the definition of the function looks similar to a variable's definition - the brackets after the name tell us that it is a function instead of a variable:int main() {
return 0;
}
Instead of the def-keyword there is a
variable type
. This type defines what type the function's return value
is. The main function's retun value type is int, because it should return a status code of whether the function's execution went well or not. At the end of the function should usually be return 0;
, which says that everything went well. In an error situation the return value is some other number, but we do not need to know much about them yet - right now the most important thing is to remember that there should be that return line at the end of the main function. In the same way the parameters should be defined to have a type:float calculate_distance(float speed, float time) {
return speed * time;
}
If the parameters in the function call are of a wrong type, the
compiler
will return an error message. Function also has to return a value that is of the type it was defined to have - otherwise you get another compiling error. A function that is not meant to return anything can be defined to have the return type void
:void print_instructions() {
printf("This program does not do anything useful.");
}
The most notable functional difference between C functions and Python functions is that C functions can have only one return value. If you want to return more than one value, you need to use references or the variables can be packed in a
data structure
. We will get back to this later.Prototypes¶
In C also functions have to be introduced before using them.
Prototype
is function's introduction and tells the compiler
that the program should include a function with this name that takes these types of variables as parameters and returns that type of value.Prototypes sort of form a table of contents of the functions that appear in the program. If the C program consists of several different code modules, each of the shared functions has to be introduced in their header files so that the table of contents would include all of them. The header file is needed for the preprocessor, because otherwise other modules do not know anything about what functions will be in the other modules. You can include the headerfiles for the preprocessor with the
#include
command. You will learn more about these later.Naturally you can write the whole function in the code before you use it. That way the introduction happens nicely at the same time, except that it will not be seen outside the module unless it is in the header file already.
The defining line for the prototype is identical to the actual function's defining line:
int calculate_sum(int a, int b);
int calculate_sum(int a, int b) {
return a + b;
}
Usually adding prototypes to the code does not require anything else besides copying the definitions of the functions to the beginning of the code (below the
precompiler's
instructions). Prototypes can also be located in a separate header file
, which will be explained more thoroughly later. Using prototypes on this course is not optional - the evaluator's compiler has been instructed to produce an error message
if prototypes are missing.Note that the main function does not require a prototype, but it has to be named main.
These exercises have no effect on course grading.
Give feedback on this content
Comments about this material