Sie sind auf Seite 1von 22

Academy Profession Degree

in

IT Network and Electronics Technology


at

KEA, Kbenhavns Erhversakademi,


Copenhagen School of Design & Technology

Subject: Programming and Microprocessor


Semester: 1
Module: 1, C Programming to PC

Target:
The module will give an introduction to the concept of computer programming through the use of
the programming language C. The following subjects will be covered:

The use of Microsoft Visual Studio Express C++ for ANSI C console applications
The use of types and variables, simple and structured
Designing and calling functions
Using loops and selection structures
Using the standard libraries
Development of algorithms

A number of exercises will be made in order to gain understanding of the practical use of the C
language. Emphasize will be placed on the development of a simple, efficient and properly
documented coding style.

By ELR: July 6th, 2015. Revised by GLMU Oct. 4th 2016

1 / 22

Contents
1
2

4
5

The module ................................................................................................................................... 3


C Programming on a PC ............................................................................................................... 3
2.1 Installing Visual C++ ............................................................................................................ 4
2.2 Using the Visual Studio C++ Compiler for Console Applications ....................................... 4
2.3 Your first Program................................................................................................................. 5
The C Language ............................................................................................................................ 6
3.1 Conventions ........................................................................................................................... 7
3.2 Variables ................................................................................................................................ 7
3.3 Number systems .................................................................................................................... 9
3.4 Functions ............................................................................................................................. 12
3.5 Loops ................................................................................................................................... 12
3.6 Operators ............................................................................................................................. 14
3.7 Selections............................................................................................................................. 14
3.8 Libraries............................................................................................................................... 16
Visual C++ Libraries for Input/Output ....................................................................................... 16
Exercises ..................................................................................................................................... 17
5.1 Hello World!........................................................................................................................ 17
5.2 Writing Lines ....................................................................................................................... 17
5.3 Printing mixed text and variables ........................................................................................ 17
5.4 Drivers license.................................................................................................................... 17
5.5 Switch-case branch .............................................................................................................. 17
5.6 Binary to decimal exercise .................................................................................................. 18
5.7 Decimal to binary exercise .................................................................................................. 18
5.8 Decimal to hex exercise ...................................................................................................... 18
5.9 Multiplication table ............................................................................................................. 19
5.10 Functions ............................................................................................................................. 19
5.11 Operators ............................................................................................................................. 20
Mandatory Hand In for module 1 (C-programming) .................................................................. 21
6.1 Pythagorean triplets ............................................................................................................. 21
6.2 Chasing Prime Numbers ...................................................................................................... 22
6.3 Random Numbers and Arrays ............................................................................................. 22

2 / 22

The module

Module 1
Lessons
4
8
4
6
10

C programming on PC

Subject
Installation and using the IDE, your first program
Using printf, scanf and getch, variables, exercises
The function, exercises
Loops & tests, exercises
Algorithms, exercises

C Programming on a PC

The sole purpose of a PC (or any other computer) is to execute programs. These programs are
created by programmers using a programming language which is understood by the computer. That
is why you must learn to use a programming language in order to create programs for your PC.
Inside any computer resides a microprocessor (P). This is a chip or integrated circuit designed to
execute programs. These programs are made up of instructions in a language called machine code;
the language understood by the P. These codes are very basic and are made up of nothing but 1s
and 0s binary stuff. To write a program in machine code would be very cumbersome and
difficult. You would most likely never get the job done! Instead programs are written in so-called
high level languages, in which the different instructions are written in more or less plain English.
There are many different high level languages. We are using one called C. This language is
known for being used especially for technical and system programming and for embedded
programming but it can in principle be used for any general purpose programs.
The Pentium (x86) P in your PC does not understand programs written in C, nor does it understand
any other high-level language programs. These programs must be translated (compiled) into
machine code by a program (the compiler) before they can be executed.
There are a number of different C compilers available. We have chosen the Visual Studio C++
compiler from Microsoft for a number of reasons:

It is fairly easy to master,


it can be used for simple beginners programs,
it can be used for advanced C++ programs,
it can be used for simple text-only console applications
it can be used for professional full graphics Windows programs,
it is well documented,
and finally: it is free very important!!

3 / 22

2.1

Installing Visual C++

The program comes in different versions: The Community version (free) and the Pro/Enterprise
version. Obviously we use the free version.
You must remove any previous versions of Visual C++ before you start the installation.
Go to http://www.visualstudio.com and select Visual Studio 2015 Community SP3.
After using the program for a 30 days trial, you will be asked to register the program. As the
program is free, just follow the instructions.
Good idea: Place a shortcut to the program on your desktop.

2.2

Using the Visual Studio C++ Compiler for Console Applications

Before you start programming you must make a good folder structure such as:

KEA
o 1. semester
Programming
Visual C++
o Exercise 1
o Exercise 2
o Etc.

You should make a new folder every time you start a new exercise. Give the folder a name that
clearly shows what the topic is. One exercise = one project = one folder.

You should set up Visual Studio to work in a special mode. Do the following:

Choose Tools > Options > Text Editor > All languages > Tabs:
o Choose Insert spaces
o Set Tab and Indent size to 3

Choose Tools > Options > Projects and Solutions > General.
Specify the folder of your projects (3 places).

Many other things can be personalized, such as fonts and colors. Look around and try it out.

When started, Visual Studio will always display a welcome page. Close it. You can avoid it.
To make a new project:

Choose File > New > Project

Choose Win32 Console Application and give your project a name (at the bottom)

All your files are saved every time you compile the code.

4 / 22

To open an old / existing project:

Choose File > Open > Project. Browse to your project and click on the *.sln file

Your code is in the *.cpp file.

2.3

Your first Program

Start Visual C++ by clicking the relevant icon on your desktop. If you dont have the icon, create it
by selecting Start > Programs > Microsoft Visual Studio 2015. Right click on Microsoft Visual
C++ 2010 and choose send to > desktop.
Make a new project. The editor window gives you a shell for a new program. Erase the text in the
editor and type the following:
#include
#include
#include

<StdAfx.h>
<stdio.h>
<conio.h>

void main (void)


{
printf("My first program. Press a key to terminate.");
_getch();
}
Try to run the program. You can run a program in three different ways:

Select Debug > Start debugging in the drop-down menu

Press F5

Click the green arrow icon in the tool bar.

Before the program is being run, it will be translated (compiled and linked) into machine-code. If
any errors are detected during the compilation a notice is given to you on the screen. If everything
can be translated, the program will simply be run. A result of the translation process is that an
executable file is generated (*.exe) this file can be run without the C++ environment.
A new window will pop up and display the output text. This is the console window, and it will be
used for all programs in this module.
Lets examine the program line by line in order to understand the structure of a C program.
1.
2.
3.
4.
5.
6.
7.
8.

#include <StdAfx.h>
#include <stdio.h>
#include <conio.h>
void main (void)
{
printf("My first program. Press a key to terminate.");
_ getch();
}

A C-program is made up of functions. There must at least be one function in the program the
main function. The main function (as any function) consists of two parts, the head and the body.

5 / 22

Line 4 is the head of the function. The head specifies the name of the function (main) and any data
that is send to or received from the function in this case no data, hence the void declaration.
Line 5..8 is the body of the function. This is where we write the actual program. In this case the
program is made by simply calling two standard functions, printf() and _getch() from the
C libraries. These libraries are included in lines 1, 2 and 3.

printf() is used to print text on the screen


_getch() is used to wait for an input from the keyboard.

The body of the function is encapsulated by the signs { and } called curly brackets.
During first semester you will be working with two different versions of C compilers. First you will
work with the Microsoft Visual Studio compiler which creates programs that run on a PC platform.
Later on you will work with an embedded system based on a P from Atmel called ATmega328.
Even though the two platforms are very different, the C language is used for both, and you will see
that the differences are very small in practice.

The C Language

The C language is a high level programming language mainly used within embedded design and
system programming.
The C programs cannot be executed directly by the P, since it only understands binary machine
code instructions. A compiler is used to translate the C high level language into machine code.
The development process can be described as:

Define your requirements to your program.

Make an overall design of your program (Design before coding!).

Write the C language source code in an editor.

Compile the source: translate C language into assembly language.

Translate the assembly language into binary machine code.

Link the machine code: Create an *.exe file holding the finished program.

Test and debug the result, verify correct operation.

Any C program is made up of data (stored in variables) and code (placed in functions). The
structure of the C language can be illustrated as shown below:

Figure 1 The structure of the C language


6 / 22

Described in short: A program is made up of data (variables) and code which will manipulate the
variables. The variables are either simple, structured or pointers. All the code will reside in
functions. These are made up of structures (loops and tests). Operators or library functions are used
to manipulate the data.
The language and its use can be described briefly by dividing it into six sections:
1. Variables
2. Functions
3. Loops
4. Operators
5. Selections / tests
6. Libraries

3.1

Conventions

Numbers
Numbers may contain both a whole part, and a decimal part. In order to separate the whole part and
the decimal part, a decimal separator or decimal mark is being used.
Unfortunately, different notations are being used, in different regions. In UK, USA and Australia, a
dot is used as a decimal separator, and a comma is used to group the numbers together, eg.:
123,456.789
In European countries, except UK, the opposite notation is used, eg:
123.456,789
This may lead to confusions and in some cases errors in programs.
To avoid conflicts, the following notation is used:
123 456.789

Billions vs. Billions


When it comes to naming numbers, different are being used. Consider the following table

1 000 000
1 000 000 000
1 000 000 000 000
1 000 000 000 000 000
1 000 000 000 000 000 000

US, UK, Canada,


Million
Billion
Trillion
Quadrillion

Continental EU
Million
Milliard
Billion
Billiard

Therefore exponential notation is being used, when describing numbers larger than 1 million. Eg.:
10^9 = 109 = 1 000 000 000

3.2

Variables

The purpose of any computer program is to control events by manipulating data. Hence we need a
way to store the data used by the program while it is running. Data is stored in variables, which
basically is nothing but a named location in the RAM memory of your computer. The variables
7 / 22

must be declared before they can be used by the program. This is because data for the sake of
efficiency is stored in variables of different types and different sizes.
Variables can be divided into three categories:

Simple variables. Each variable can hold one piece of information only, such as an integer
number, a floating point number or a character (an ASCII or UNI-code value).
Structured variables. Each variable contains a set of sub-variables.
Pointers. A pointer variable holds the address of a location in the memory, a location which
typically stores a function or a variable.

Simple variables, types


The following types are available:
Type name
int
unsigned int
__int8
unsigned __int8
__int16
unsigned __int16
__int32
unsigned __int32
__int64
unsigned __int64
bool
char
signed char
unsigned char
short
unsigned short
long
unsigned long
long long
unsigned long long
float
double

Bytes
4
4
1
1
2
2
4
4
8
8
1
1
1
1
2
2
4
4
8
8
4
8

Other name
signed
unsigned
char
unsigned char
short, short int, signed short int
unsigned short, unsigned short int
signed, signed int, int
unsigned, unsigned int
long long, signed long long
unsigned long long
none
none
none
none
short int, signed short int
unsigned short int
long int, signed long int
unsigned long int
none (but equivalent to __int64)
none (but equivalent to unsigned __int64)
none
long double

Min value
2 147 483 648
0
-128
0
32 768
0
2 147 483 648
0
9 223 372 036 854 775 808
0
false (zero)
-128
-128
0
32 768
0
2 147 483 648
0
9 223 372 036 854 775 808
0
-3.4E +/- 38 (7 digits)
-1.7E +/- 308 (15 digits)

Max value
2 147 483 647
4 294 967 295
127
255
32 767
65,535
2 147 483 647
4 294 967 295
9 223 372 036 854 775 807
18 446 744 073 709 551 615
true (not zero)
127 by default
127 or ASCII
255
32 767
65 535
2 147 483 647
4,294,967,295
9 223 372 036 854 775 807
18 446 744 073 709 551 615
3.4E +/- 38 (7 digits)
1.7E +/- 308 (15 digits)

The term byte, refers to the size of a variable. Computers are generally speaking organized in bytes,
which in term, are made up of 8 bits.
Notice the use of signed and unsigned, to indicate if a negative number can be contained int a given
type.
The notation used for the integer variables in the table above (intx_t / uintx_t) was introduced with
the latest revision of the C language in 1999. In order to use these types in VisualStudio you must
include a special library, named <stdint.h>: This is not necessary in AtmelSudio. By default,
however, Microsoft uses the names listed above. In order to avoid misunderstandings, we will use
the Microsoft names.

Negative integer values are handled as twos complement in the microprocessor.


Floats are stored in exponential notation defined by IEEE754. The format is: F * 10E. The
exponent (E) uses 8 bit in twos complement which gives a range of ~35. The fraction (F) uses one

8 / 22

bit for sign and 23 bit for the value. This gives a typical resolution of ~7 digits. If you need better
resolution, the type double can be used. Doubles has a typical resolution of 15 digits.

Simple variables, usage


char x;

A standard declaration. Should be written at the beginning of the function, where it will be
used. The variable is valid within this function and will usually have the value 0 (zero), but
it depends on the compiler settings.

__int8 x = 87;

An initialized variable. Every time the variable is created, it will be given the initial value.

const char x = A;

A constant variable. It will be stored in the code memory and it is read-only.

static __int8 y = 0;

A static variable will hold its value between successive calls of the function where the
variable is declared. An initialized static variable will only be initialized the first time the
variable is used.

3.3

Number systems

Since humans have 10 fingers, we use a number system called a decimal or base-10.
Imagine a number system, where each number was represented with its own symbol.

Decimal system
The principal in the decimal number system is, that we use 10 different symbols to represent all
numbers.
Consider the following number: 3069
1000 * 3 =
3000
100 * 0 =
0
10 * 6 =
60
1*9=
9
Sum: 3069
Observe, that each time we move to the next figure (right to left), we multiply by 10, the base.

Binary system
Now, since computers do not have fingers, but rather use transistors that can either be turned on or
off (like a switch), they use binary numbers. Binary numbers only consist of zeros and ones. This
system is also referred to as base-2.
The same technique is applied to describe a number. Consider the following value: 231
128 * 1 =
128
64 * 1 =
64
32 * 1 =
32
16 * 0 =
0
8*0=
0
4*1=
4
2*1=
2
1*1=
1
Sum: 231

9 / 22

Observe that each multiplier is twice as big as the one below. In the decimal system, it was ten
times as big.
If you read the ones, and zeros from the top, the binary representation of 231, is 1110 0111b
Notice the use of a lower case b.
Hexadecimal numbers
The binary system is somewhat unhandy, because the tend to become very long due to the number
of figures. Therefore an alternative representation is often used; hexadecimal. Hexadecimal number
means base 16.
This means that 16 different symbols are required to represent hexadecimal numbers: We therefore
use capital letters A through F. So the sequence will become:
0-1-2-3-4-5-6-7-8-9-A-B-C-D-E-F-10-11-12-13-14-15-16-17-18-19-1A-1B-1C-1D-1E-1F-20-21
Notice that when we reach 9, we continue with the letters. Still using a single letter. By doing this,
we can actually represent 16 numbers with just a single figure.
Consider the following:
4C7A
4096 * 4 =
16384
256 * 12 =
3072
16 * 7 =
112
1 * 10 =
10
Sum:
19578
Notice, that each time you move one step up, you multiply by the base number, which is 16. Also
notice, that A translates into 10 (decimal) and C translates into 12 (decimal).

Correlation between base-2 and base-16


So why bother with hexadecimal (or simply hex) numbers? The reason is obvious. If you take a 4bit number, it goes from 0 to 15. The table below shows how it works:
Binary Hex Decimal
0000
0
0
0001
1
1
0010
2
2
0011
3
3
0100
4
4
0101
5
5
0110
6
6
0111
7
7
1000
8
8
1001
9
9
1010
A
10
1011
B
11
1100
C
12
1101
D
13
1110
E
14
1111
F
15
The trick is, that one hexadecimal number can represent 4-bits in a binary number. The same would
not work with the decimal system.

10 / 22

Structured variables
A structured variable is a collection of simple variables which have something in common. E.g. a
text string, which is a set of characters (char) each capable of holding an ASCII character. Together
these characters (the array of chars) can make up a complete sentence.
An array is a number of simple variables of equal type which are united by a common name. The
individual sub-variables are accessed by the use of an index.
Declaration: int x[5]; An array with five elements numbered [0 .. 4] is declared.
Initialization: int x[] = {3, 5, -67, 72, 33}; Each element is assigned an initial value.
You dont have to specify the size of the array if it is initialized.
Reading and writing: x[3] = x[4]; Sub-variable number 4 is read and subsequently written to
sub-variable number 3.
Textstring: char str[20] = This is a string;
Strings have two lengths: the static and the dynamic. The static length is the maximum number of
bytes (chars) that can be stored as it is declared. The dynamic length depends on the length of the
actual string stored in the variable. The string is terminated by the value 0 (zero) in order to inform
the program about the dynamic length. The string str above has a static length of 19 (19 characters
plus the zero termination) and a dynamic length after initialization of 16.
There is no protection in C against writing or reading outside the declared limits of an array. It is the
exclusive responsibility of the programmer to observe this limit. Failure to respect this can lead to
very serious errors with grave consequences like planes falling out of the sky!
A struct is a collection of variables of different types which share a common name. An example:
struct
{
char name[10];
__int8 age;
} person;

You use the sub-variables like this: person.age = 27;

Pointers
A pointer is a variable that holds an address of a location in the memory. This location will typically
be a place where another variable is stored. Using pointers in stead of normal variables can in some
cases result in more efficient code. Examples of pointer usage:
__int8 *p;
__int8 i; p = &i;
__int8 j; j = *p;

A pointer p is declared. It will hold an address for an __int8 - type


variable.
The address (the RAM memory location) of the __int8 - type variable
i is stored in the pointer p.
The __int8 - type variable j is given the value placed at the location in
memory that the pointer p points to.

The disadvantage of using pointers is that the code tends to be quite abstract and difficult to read.
Most programs using pointers can be rewritten without the pointers.

11 / 22

3.4

Functions

A C-program is made up of a number of functions at least one, but typically several. Each
function will be responsible for doing some specific action and a function in a C program is actually
very similar to a function in math. In math you may write y = f (x) = x. This means that the
function is given an input value (x), it calculates the square root of the input and it returns this value
to y. The same operation will in C be written as y = sqrt(x); . This means: call the function
sqrt (short for square root) and give it the input x. The function will return the result of the
calculation and place it in the variable y. The function sqrt() is a member of the math library.
A function has a head and a body. The head holds information about the name of the function and
the data send to and from the function. The body holds the actual program code used by the
function. Together it might look like this:
unsigned int GetBiggest (unsigned int a, unsigned int b)
{
if (a > b)
return a;
else
return b;
}
This example shows a function that will compare two values (a and b), after which it will return the
biggest of the two. The head of the function is line 1 which gives the compiler the name of the
function (GetBiggest), information about data flowing to the function (two __int8 variables
called a and b) and information about the variable type that will be returned. The body is the code
between the curly brackets { and }. In this case an if-statement is used to compare a and b and
return the value of the biggest of the two.
The function might be called like this:
int8 x = 5, y = 7, z;
z = GetBiggest(x, y);
If a function returns no data, the return-type is replaced by the word void. If no data is send to the
function, the inputs are replaced by the word void.
A special function is the main function of your program. This is the function that will actually hold
the start of your program. As such is must always be a part of your program. This function must be
given the reserved name main. No data is (in general) send to or from the main function. The head
of the main function looks like this: void main (void).

3.5

Loops

It is quite common in computer programs that a number of code lines have to be repeated either a
specific number of times or until some event happens. Loops are used for that, and they come in
three different flavours: for, while and do..while.

12 / 22

For loops
For loops are used if you want to repeat one or more code lines a specific number of times. An
example:
int i;
for (i = 0; i < 10; i++)
{
a = i + 5;
}
A for-loop has a counter that will control the number of passes, in this case the int-type i. The
bracket holds the information about how the loop should run.

i = 0; indicates that the counter i will start counting from 0.


i < 10; states that the loop will keep running as long as the counter i is less than 10.
i++ indicates that the counter will be incremented with 1 after every pass.

The code between the curly brackets is the code that will be executed at every pass.

While loops
A while loop will keep executing the loop-code as long as a specific condition is true. An example:
while (
)
{
b = b + c;
}
It reads like this: As long as a is greater than b, you will keep adding the variable c to b. If b is
bigger than or equal to a when entering the loop, the loop-code will not be executed at all.

do .. while loops
A do .. while loop will keep executing the loop-code as long as a specific condition is true. An
example:
do
{
b = b + c;
} while (a > b);
It reads like this: Add the variable c to b. As long as a is greater than b, you will execute the loop
code one more time. The loop-code will always be executed at least one time since the test is done
after executing the loop-code.

13 / 22

3.6

Operators

The C language has a number of operators that can be used to manipulate data (variables). These
are:
Group
Assignment
Arithmetic

Operator
=
+
*
/
%
++
-&&

Logic

&
||
|
^
~
!
>>

Shift

<<

Compare

>
<
==
!=
<=
>=

Function
Assign
Plus
Minus
Multiply
Divide
Modulus
Increment
Decrement
Logic and
Binary and
Logic or
Binary or
Binary xor
Binary negate
Logic negate
Shift right
Shift left
Bigger than
Lesser than
Equal to
Different from
Lesser than or equal to
Bigger than or equal to

Example
a = 17;

b = 5;

a = a + 5;
c = b 3;
c = b * 3;
a = a / 4;
c = a % 5;
a++;
a--;
if ((a > 5) && (c < 8))
a = a & 0x3C;
if ((a > 5) || (c < 8))
a = a | 0x3C;
a = a ^ 0x3C;
a = ~b;
if (!(a > 5))
a = a >> 2;
a = a << 2;
if (a > 5)
if (a < 5)
if (a == 5)
if (a != 5)
if (a <= 5)
if (a >= 5)

The operators are executed in a specific order just like in math. You should always use brackets to
specify the order of execution if you mix two or more different operators within the same statement.

3.7

Selections

Now and then your program will need to make a decision. It will be done by making a logic test
which can only give a true or false result.
if ( .. )
Use if selections if specific code should be executed when a logic condition is true. Example:
if (a > b)
{
b = c;
}

14 / 22

Reads like this: If a is greater than b (if the logic statement is true), b should be given the value of
the variable c. In other cases nothing should happen.

if .. else
The if (..) else construction is a simple expansion of the if (..) command. Example:
if (a > b)
{
b = c;
}
else
{
b = d;
}

Reads like this: If a is greater than b (if the logic statement is true), b will be given the value of the
variable c. In any other cases (i.e. if a is smaller than or equal to b), b will be given the value of the
variable d.

Conditional expression
The following if statement if (a < b) c = 5; else c = 7; can also be written as a
conditional expression: c = (a < b) ? 5 : 7;. The conditional expressions leads to compact
code, but also to code that might be harder to read and understand. So use it carefully!

Switch
In stead of making your selection based on a logic statement (the if-bracket), you can base your
selection on the value of an integer-type variable. This will give you more than two options to
choose between. The switch command is used for this. Example:
switch (a)
{
case 5:
b = 1;
break;
case 7:
b = 2;
break;
case 9:
b = 3;
break;
default:
b = 0;
break;
}
It reads like this: If a = 5, 7 or 9, b will be set to 1, 2 or 3 respectively. In any other case (other
values of a) b will be set to 0 (as indicated by the default option). The program will search the
different case-values to find a match. If a match is found, the code following the case will be
15 / 22

executed. When the program meets a break command, it will abandon the rest of the code within
the switch command. If no match is found, the code following the default option will be
executed.

3.8

Libraries

The C language is a very compact and simple language, making it very fast to learn and master.
Most of the functionality you would expect in a programming language is not a part of the C
language itself, but is placed in external libraries. The libraries contain a number of functions you
can call if you want a specific job done. You must include a library before you can use it, e.g.:
#include <stdio.h>.
Each library module has an H-file (a header file), which describes the contents of the module.

Visual C++ Libraries for Input/Output

The libraries stdio, conio and stdlib holds a number of functions used for simple input /
output.
Input:

_getch(): wait for next keyboard entry, return the ASCII value
_getche(): as getch(), but with echo to the screen
_scanf_s(): read a variable from the keyboard

Output:

printf(): print a string. You can print a mix of fixed text and values placed in variables.
_putch(): prints a single character to the screen
system("CLS"): Clear the screen, place cursor in top-left corner

Example of printf: printf(%4d + %4d = %5d\n, a, b, c);. It means: print an integer


variable using the space of 4 characters [%4d] followed by some text [ + ] and then the next
variable and so on. \n means line-feed. The actual variables are listed in the end of the statement in
the order they are used [a, b, c]. Different types of variables can be printed:

d: signed integer
u: unsigned integer
c: char
s: string
f: float
lld: 64 bit signed integer = int64_t

Examples of scanf_s:
scanf_s("%d", &b);. Reads like this: [%d] means that you want to read a signed integer variable
from the keyboard. This value will be placed in the variable b [&b]. You specify the different types
like you did in printf.

16 / 22

scanf_s("%s", name, 20);. Read a string. The number of entered characters is limited to 20,

to prevent overflow.
Additional information can be found in the Microsoft help, and of course on the Internet.

Exercises

5.1

Hello World!

Make a program that prints a sentence to the screen and waits for a key-press. It basically means
that you simply copy the example from the start of this compendium.

5.2

Writing Lines

Make a program that writes a sentence 5 times below each other and waits for an input from the
keyboard. Make four versions:
1. one using do..while loop
2. one using a while loop
3. one using a for-loop counting from 0 to 4
4. one using a for loop counting from 4 to 0

5.3

Printing mixed text and variables

Make a program that prints 10 lines to the screen including the line number, like
Line number
Line number

5.4

1
2

Drivers license

Make a C-program where the user must enter his/her age. Depending on the age, the program, tells
what drivers license categories he/she is qualified for in Denmark.
Age 16: Tractor
Age 18: Car
Age 21: Truck
Age 24: Bus

5.5

Switch-case branch

Make a C program where the user must enter a number between 1 and 4. Depending on the input,
different outputs must be presented.
1:
Hello
2:
Good morning
3:
Good evening
4:
Good night

17 / 22

5.6

Binary to decimal exercise

Convert the following binary numbers into decimal:


a.
1101 1001
b.
1000 1000
c.
0011 1100
d.
1010 1010
In order to convert a decimal number into a binary, the following steps must be carried out.
Consider the following number: 125:
1.
Is 125 dividable by 128?
NO! First digit is therefore zero
2.
Is 125 dividable by 64? YES! second binary digit is one.
3.
Now 64 must be subtracted from 125, because 125 was dividable by 64: 125- 64 = 61
4.
Is 61 dividable by 32 ? YES!. Next bit is one.
5.
We subtract 32 from 61: 61 - 32 = 29
The result is: 0111 1101
The number of bits vary. It must always be ensured, that the number of bits is big enough to
represent the decimal number.

5.7

Decimal to binary exercise

Convert the following decimal numbers into binary:


a.
23
b.
127
c.
128
d.
200
e.
6

5.8

Decimal to hex exercise

Convert the following decimal numbers to hex:


a. 1234
b. 4096
c. 4095
d. 431
Convert the following hexadecimal numbers to binary numbers:
a. 3F9A
b. 0401
c. FFFF
d. 4009
Convert the following binary numbers to hex:
a. 1001 0110

18 / 22

5.9

Multiplication table

Make four versions showing a multiplication table:


1. Print base-3 table: 2, 4, 6, 8 18, 20
2. As before, but make a multiplication table of 10 * 20
1
2
3
4
5
6 10
2
4
6
8
10
12 20

20 20
30
40
50
60 200
Note the alignment, which is obtained in the formatting.
Hint: Two loops are required

5.10 Functions
Make a program that reads two integers from the keyboard and prints the sum, the difference, the
product, the integer division and the integer modulus like the following example:
Enter the first number: 7
Enter the second number: 3
The sum of 7 and 3 = 10
The difference of 7 and 3 = 4
The product of 7 and 3 = 21
The division of 7 and 3 = 2
The modulus of 7 and 3 = 1

The numbers at the end of line 1 and 2 are entered by the user, the rest is program output.
Each of the five calculations should be made in a function to which you send the two input variables
and from which you receive the result of the operation.

19 / 22

5.11 Operators
a. Try the following code, and explain the different results
int
a, b, c, d;
float f;
printf("Enter a: ");
scanf_s("%d", &a);
printf("\nEnter b: ");
scanf_s("%d", &b );
c = a / b;
d = a % b;
f = a / b;
printf("a: %d, b: %d, c: %d, d: %d, f: %f\n", a, b, c, d, f);
_gettch();

b. Write the following code, and explain what happens


int

a, b, c;

printf("Enter a: ");
scanf_s("%d", &a);
b = a << 1;
c = a << 2;
printf("Decimal:
a: %d, b: %d, c: %d \n", a, b, c);
printf("Hexadecimal: a: %02X, b: %02X, c: %02X\n", a, b, c);
_gettch();

c. Explain the following code snippet:


int a, b, c, d, x;
printf("Enter X: ");
scanf_s("%d", &x);
a = x;
b = a++ + 1;
c = a++ + 1;
printf("a: %d, b: %d, c: %d\n", a, b, c);
a = x;
b = ++a + 1;
c = ++a + 1;
printf("a: %d, b: %d, c: %d\n", a, b, c);
_gettch();

d. Try the following code snippet, and explain the results


int a, b, c;
a = 0x52;
b = 0xF1;
c = a & b;
printf("%2X | %2X = %2X\n", a, b, a | b);
printf("%2X & %2X = %2X\n", a, b, a & b);
printf("%2X ^ %2X = %2X\n", a, b, a ^ b);
printf("~%2X
= %2X\n", a, ~b);
_gettch();

20 / 22

Mandatory Hand In for module 1 (C-programming)

In order to qualify for the exam on 2nd semester, a report must be handed in, for each module.
The report must be handed in as a pdf on Fronter.
The report should contain source code when relevant (You can use Windows Snipping tool (
klippe vrktj) to grab relevant source code and screen dumps.
The following exercises should be included in the report. Each exercise contains a Hand In
section, which describes what you are supposed to hand in.

6.1

Pythagorean triplets

Make a program that can find so-called Pythagorean triplets like 3, 4, 5 or 5, 12, 13. Keep running
till 100. Print the number-sets found to the screen like this (just the start!):
Hint: You need three loops embedded in each other!
5
5
10
10
13
13
15
15

3
4
6
8
5
12
9
12

4
3
8
6
12
5
12
9

Can you improve the program, so the same sets of numbers are not repeated? And written in
increasing order? Like this:
3
5
6
7
8
9
9
10
11

4
12
8
24
15
12
40
24
60

5
13
10
25
17
15
41
26
61

Hand in
Describe your algorithms and how you have tested the program. Include source code.

21 / 22

6.2

Chasing Prime Numbers

Make a program that finds prime-numbers. The first numbers are 2, 3 and 5, all the next ones must
be calculated. The target is to get as far as possible in 30 seconds.
You must make the program with a counter starting at 3. The relevant values must be tested in a
function. If it is a prime-number it must be printed to the screen. Like the following:
5
7
11
13
17
19

// and so on

The program must be written so you can stop it and see the results on the screen.
Hint: The modulus operator (ie. %) yield zero when a division has no decimal fraction

Hand in
Describe the background for your algorithm and it must include each version of the program with
documentation for any improvements.
How long does it take to generate 50 000 primes?
The report must show how you verify correct operation of your program that is: validate it.

6.3

Random Numbers and Arrays

Make a program that generates 100 random numbers in the range [0..999]. These will be written to
the screen in the same order as in which they are generated. Then sort the numbers and write them
to the screen in sorted order.
You must use an array to store the random numbers. Read about arrays in the chapter describing
variables. Two functions from stdlib.h and time.h are used to generate random numbers:
srand() will initialize the random numbers and rand() will return a random unsigned integer.
The easiest way to sort a set of variables, is by using the bubble sort method. The principle is that
you start with comparing the first two numbers [0] and [1] in the array. If they are placed in wrong
order, they must be swapped. Then continue with the numbers [1] and [2] etc. After running through
the entire array the biggest number will be in place. Repeat this a number of times until all numbers
are placed in correct order. It requires an inner and an outer loop.
Using srand():
srand( (int)time(NULL) );

// Initilaizes a random sequence

Using rand():
x = rand() % 6 + 1;

// x = random number, range [1..6]

Hand In
Describe how you have generated the random numbers, and how you carried out the bubble sort.
Finally describe how you have tested the program.

22 / 22

Das könnte Ihnen auch gefallen