Programming I en
Programming I en
“The good thing about computers is that they do exactly what you tell
them to do - the bad thing about them is that they do exactly what you
tell them to do.”
The Universe
Programming I en Page 1
Programming I en Page 2
Contents Programming 1
Introduction IDE
Editor
Debugger
Translation process
Control structures
Conditional statement / alternative (if-else)
Control structure case query (switch)
Header and footer-controlled loop (while)
Counting loop (for)
Functions
Return values
Input/return parameters
Data structures
Arrays
Structs
Enums
Memory management
Dynamic arrays
Software Design
Pseudo code
UML: Activity diagram
Design/documentation of methods/algorithms with the
help of design methods
Recursion
Testing
Creating a test plan
Desk test as test protocol
File management
Programming I en Page 3
About me
Programming I en Page 4
Bonus points
The written examination (90 min) determines 100% of the grade for the course.
Bonus points can be earned.
Bonus points
▪ Can only be credited if the exam is passed
▪ Max 15%
▪ 10% assignments (Moodle test, approx. 10 assignments)
▪ 4% code walkthrough of assignment tasks
▪ with comprehension questions
▪ 1% per assignment
▪ Only one assignment per date
▪ 1% presentation of an assignment task to the exercise group
▪ with comprehension questions and hints from the group
▪ Focus is on the use of technical language and constructive dialogue, a
completely correct solution is not required
▪ The bonus points are also valid for the following semester (no more after that)
Programming I en Page 5
Why C as first language
Simple syntax
The syntax of C is comparatively simple and clearly structured. It is
used in a similar way by other programming languages. For example,
in C++, C#, Objective-C, Java, JavaScript, Ceylon, Rust, Perl, Go, Kotlin,
Swift, …
Portability
C code can be used on different platforms and operating systems.
programs written in C can be ported to other systems relatively easily.
Programming I en Page 6
Basis of C++
Building on C, we will learn object-orientation with C++. You can use
the knowledge you have acquired in C.
Programming I en Page 7
How to deal with the Coderunner
Plugin on the Moodle learning platform that compiles and tests code.
Programming I en Page 8
Lectures and exercise groups
Lecture
Course content
Build up and understand basic knowledge
Working on small tasks
Homework
Self-learning with Moodle tests
Programming I en Page 9
External Learning platforms
[Link]
Teaches the basics with small tests, smartphone app available.
Good for the couch or when travelling
[Link]
Enables the solving of coding tasks. Shows rated solutions from
other developers, offers ranking system.
Basic knowledge is required.
Example task: Hello
[Link]
Coding exercises with a strong gamification influence. Enables
online coding competitions against others.
Basic knowledge is required.
Programming I en Page 10
External sources
Englisch
▪ [Link]
▪ [Link]
in-c-january-iap-2010/pages/lecture-notes/
Deutsch
▪ Skript Uni Bochum [Link]
[Link]/[Link]/pic/[Link]
▪ Heimo Gaicher: Programmieren in C, Tredition, 2007
▪ Markus Neumann: C Programmieren für Einsteiger: Der
leichte Weg zum C-Experten, BMU Verlag, 2020
▪ Jürgen Wolf: C von A bis Z: Das umfassende Handbuch für C-
Programmierer,
▪ PaulBarry,DavidGriffiths:CvonKopfbisFuß,O'Reilly
Media, 2012
Videos:
C Programming
Programming I en Page 11
Quiz organizational matters
[Link]
Programming I en Page 12
Programming languages
Programming languages are very precise artificial languages for formulating programs.
They must not allow any ambiguities when creating a programme so that the computer
can execute the programme correctly.
When defining a programming language, the following three parts must be defined:
Lexis
The lexis of a programming language defines the valid characters or words that may be
used to compose programmes in the programming language may be composed of.
Syntax
The syntax of a programming language defines the correct structure of sentences made
up of valid characters or words, i.e. it determines the order in which lexically correct
characters or words may appear in the programme.
Semantics
Semantics defines the meaning/execution of syntactically correct constructs. Syntactically
correct code has exactly one semantics or exactly one way in which it is executed.
Programming I en Page 13
Who talks machine language - Not a single human being!
Programming I en Page 14
Interpreter
Interpretation
The source text is translated line by line and the commands are executed directly.
Advantage
▪ Fast program development
▪ Quick program start
▪ Programme changes are possible during runtime
▪ Processor and platform-independent, provided an interpreter is
available
Disadvantage
▪ Slow runtime
▪ Late error detection
▪ The source code is required to run the program (javascript can be
seen in the browser)
Programming I en Page 15
Compiler
Compilation
The source code is compiled and the machine code is saved in a
file. The linker compiles the machine code of the file and the
function libraries into an executable programme.
E.g. Delphi
C / C++
Advantages
▪ Fast runtime
▪ Syntactic errors are recognised immediately during compilation
▪ The same sometimes applies to simple semantic errors
▪ The source code does not have to be passed on to the user
Disadvantages
▪ Slow translation process
▪ Must be translated individually for different target systems (OS)
Programming I en Page 16
Compiler with runtime environment
Advantages
▪ Platform independence
▪ Security checks are possible before execution
▪ Additional features, such as automatic memory
management and managed code (Microsoft languages)
Disadvantages
▪ A runtime environment is required
Programming I en Page 17
▪ A runtime environment is required
Programming I en Page 18
Quiz programming languages
Programming I en Page 19
IDE (Integrated Development Environment)
1. Start CLion
2. After starting, select the licence server in the licence dialogue
3. enter the following URL of the licence vault under Server address:
[Link]
4. log in to your personal JetBrains account or create one. Only
@[Link] and @[Link] are permitted as e-mail domains.
5. confirm any dialogues that appear
6. After activating the licence, CLion will display: Licensed to: Hamm-
Lippstadt University of Applied Sciences
Programming I en Page 20
CLion
Programming I en Page 21
Rename und Autocomplete
Rename
If variables are to be renamed, the command Refactor->Rename can be
used in Clion.
This renames all variable occurrences in the code at the same time.
Auto-Complete
Ctrl + spacebar calls up a context menu that gives suggestions for the next
element. Tab accepts the suggestion.
Programming I en Page 22
Remove errors or how to avoid frustration
If the programme runs but does not do what it is supposed to, the debugger should always be used first.
Programming I en Page 23
Debugging (important!!1!)
If the programme is running but is not behaving as it should, the debugger allows
you to retrace the process step by step.
1 Start debugger
2 Breakpoint (execution is stopped here)
3 Current state of the variables (programme state)
4 Function stack
5 Watches (have your own expressions evaluated)
6 Control:
▪ To the next breakpoint
▪ Stop running programme
▪ Next line
▪ Jump to function call
Programming I en Page 24
Quiz IDE
Programming I en Page 25
Names of basic elements and basic rules
/**
Program to calculate the year when a person's next big birthday party happens
author: Rosalie Brauer 0
version: 1.0
**/
0 Header comment of the program
#include <stdio.h> 1
10 Calculation operator
int main() { 2 13 Indentation -> expresses affiliation to a block. A block must be defined by {...}.
int birthYear, age, years, partyYear; 3 9 Assignment (date on right-hand side is saved in variable on left-hand side)
3 Declaration of several variables, separated by a comma
// Welcome message 4
printf("Welcome to the Party Year Generator\n"); 5 8 Parameter list, separated by a comma
6 14 Alternative if condition is not true
// Ask for the user's year of birth 11 Keyword for conditional statement / case differentiation
printf("In which year were you born?\n"); 7 Returns a keyboard input
scanf("%d", &birthYear); 7 6 Parameter of the character array data type (instead of string as in other
8 languages)
12 Logical condition (becomes true or false)
5 Function for output to the console
// Calculate the age
1 Integrating a library (header)
age = 2024 - birthYear;
9 10 2 Main-function
4 Single-line comment
if (birthYear > 2005) {
12 15 Exit the function (0 means ok)
11
years = 18 - age;
13 partyYear = 2024 + years;
printf("Your next big party for your 18th birthday will be in: %d\n", partyYear);
} else {
years = age % 10;
partyYear = 2024 + 10 - years;
if (years > 0) {
printf("Your next big party for a milestone birthday will be in: %d\n", partyYear);
} else {
printf(
14 "If you've already had a big birthday party this year, the next chance for a milestone birthday is in: %d\n",partyYear);
}
}
return 0; 15
}
Basic rules
• The program is always run line by line
• Each instruction is terminated with a semicolon
• Each program starts with the main function
• Functions (in C) usually return 0 if no errors have occurred.
• A function is a jump to previously written code and with a return to the call location at the end
• Libraries are other files that contain such functions, among other things
• Functions can also be written and used by the developer
• Blocks {…} contain a set of instructions and can be nested one in another
Programming I en Page 26
Naming conventions
Germanumlautssuchasö,ü,äareusuallyreplacedbyoeueor
ae, although this is now technically possible in most
programming languages.
In C, snake_case is predominant.
Reserved Keywords
Programming I en Page 27
More Details on C-Keywords:
[Link]
Programming I en Page 28
Number Systems
3
+ 8
+ 1516
= 2016
Programming I en Page 29
It's the basis that counts (place value system)
Example: 35010
3 * 10^2 +
5 * 10^1 +
0 * 10^0
Dezimalsystem
Example: 35010
3 * 10^2 +
5 * 10^1 +
0 * 10^0
Example: 3508
chmod file 7 read 1 write 2 execute 4
3 * 8^2 + 20 21 22
5 * 8^1 + 1 0 1
0 * 8^0
= 23210
Hexadecimal system
Programming I en Page 30
Example: 35016
3 * 16^2 +
5 * 16^1 +
0 * 16^0
= 84810
1 * 2^2 +
1 * 2^1 +
0 * 2^0
= 610
Programming I en Page 31
Binary numbers
2 2 0 0 1 0
3 3 0 0 1 1
4 4 0 1 0 0
5 5 0 1 0 1
6 6 0 1 1 0
7 7 0 1 1 1
8 8 1 0 0 0
9 9 1 0 0 1
There are 10 types of people
A 1 0 1 0 1 0 0 those who know the binary system
B 1 1 1 0 1 1
1 those who don't
C 1 2 1 1 0 0
D 1 3 1 1 0 1
E 1 4 1 1 1 0
F 1 5 1 1 1 1
Programming I en Page 32
Floating point numbers
Floating point numbers can be very large or very small. To avoid having to save every digit, the IEEE-754 format
can be used
Format
V * M * 2E
Exponent E
Exponent with which the base is exponentiated -> 2E
Mantissa M
factor with which 2E is multiplied out to represent the numbers between the full powers of two
Sign V
Single Bit for the sign 1 / -1
Example:
V = 0 -> +
After 7 significant decimal digits there is a cut. More precise numbers are not possible with 32 bit floats.
0.110 would be infinitely long as a float --> rounding problems. Actual value is 0.100000001in C
Programming I en Page 33
Quiz naming conventions and number systems
1. SNAKE_CASE
2. CamelCase
3. PascalCase
4. kebab-case
Programming I en Page 34
Data types
Programm
U in V
Programming I en Page 35
Primary data types in C
Primary data types are also referred to as basic or primitive data types.
Minimum and maximum values are defined in the header file ‘limits.h’,
e.g. INT_MIN, INT_MAX
There are other types of data types, some of which are covered later:
Source: GeeksforGeeks
Programming I en Page 36
Primary data types in C++
Programming I en Page 37
Literals
float variable = 1;
Example:
Constants
Each data type can be saved as a constant in a variable.
Constants can no longer be changed during the course of the
programme.
Programming I en Page 38
Pointer
The pointer data type is briefly outlined here without covering it in detail:
Source: [Link]
#include <stdio.h>
int main()
{
int var = 10;
return 0;
}
Programming I en Page 39
In- and output on the console
//Declare variable
int birthYear;
// fill it with input from the console
scanf("%d", &birthYear);
//print it as an int (%d stands for decimal)
printf("Your birthyear is %d!", birthYear);
Explanation
printf("Your birthyear is %d!", name);
%d is a placeholder that also specifies a format (see data types).
The second parameter is the variable that is used.
scanf("%d", &birthYear);
▪ scanf reads a value from the keyboard
▪ Parameter ‘%d’ specifies that the input is interpreted as an
integer number.
▪ Caution: If letters are entered, there is no error message
or warning. The letters are simply interpreted as numbers.
▪ The variable into which the read value is to be saved must
be of the same type as the format specification above (‘%d’
<-> int).
▪ The variable name must be preceded by the & (the reason
for this will be explained later)
Programming I en Page 40
Quiz data types
Which statements about data types are true?
1. Letters are also a data type
2. All data types are stored internally with only 0, 1 or letters
3. There is a data type that contains only the address to one byte
in RAM
Programming I en Page 41
Characters and Strings
Strings
Strings are technically implemented in C with character arrays (series of letters).
Terminated with \0, as the array can be longer than the string.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
'D' 'a' 'r' 'k' '' 'K' 'n ' 'i' 'g' 'h' 't' \n \0
Character
The characters are encoded in various standards, e.g. ASCII, CP1252 or UTF-8 (silver
bullet).
Char in C uses ASCII. There is also wchar_t, with 16 or 32 bits (depending on the
system)
Max Müller
Programming I en Page 42
Max Müller
"Max M�ller" appears on the screen? -> wrong character encoding, use UTF-8 or a
another encoding
Programming I en Page 43
Formatting strings with printf and sprintf
%.2f outputs a decimal number that has two digits after the decimal point (dot)
%08f 0 -> left fill number with 0, 8 -> Number is 8 digits wide
%08.2f Left fill number with 0, but 2 digits are reserved after the decimal point (rounded)
Programming I en Page 44
Formatting strings with strcpy and strcat
#include <stdio.h>
#include <string.h>
int main() {
char result[100] = ""; // Initialize an empty result string
char buffer[10] ; // Temporary buffer for the elements
strcpy(buffer, "Element1\n"); //Fill the buffer with the string and a line break
/* the next line would lead to an error, because buffer is an
array and "Loop1 " is a pointer to (memory address of) an array. */
//buffer = "Element1\n"; // Do not try this
return 0;
} Step Result Buffer
1 ""
What is printed by the program?
2 ? ?
3 ? ?
4 ? ?
5 ? ?
Programming I en Page 45
Quiz Strings
Programming I en Page 46
Exercise repeat name
#include <stdio.h>
int main() {
char name[10] = "";
//use scanf to read name
return 0;
}
Programming I en Page 47
Operators
5 + 3 *7
Description
Operator
Programming I en Page 49
stark
Programming I en Page 50
Comparison Operators
Operator Meaning
Comparison operators return values of the bool data type:
== Equality
!= Inequality int year = 2022;
> Greater than year > 2023; //false
float gradC = 99.5f
< Less than gradC != 127.6; //true
>= Greater or equal
<= Less or equal bool isRetired, isYoung, hasJob, freeEntry;
&& And int age = 22;
hasJob = true;
|| Or isRetired = age >= 65;
^ Exclusive OR (XOR) isYoung = age <= 21;
freeEntry = (isRetired || isYoung) && !hasWork;
! Not
Programming I en Page 51
Operators and data types
Programming I en Page 53
Usage of the %-Operator
Example:
#include <stdio.h>
int main() {
int x = 123;
//Check if x is dividable by 3
if(x%3 == 0) {
printf("x ist durch 3 teilbar\n");
}else{
printf("x ist nicht durch 3 teilbar\n");
}
return 0;
}
Programming I en Page 54
Quiz Operators
Programming I en Page 55
Conditional Statements
#include <stdio.h>
#include <stdbool.h>
int main() {
// could be deliverd by a humidity sensor
bool isRaining = false;
// could be delivered by date check
bool streetCleaning = false; 1 Keyword if
2 Condition must always be resolvable to
// When is the street wet?
true(1) or false(0)
if (isRaining || streetCleaning)
3 The indented block is only executed if
1 2
{ the condition is true
printf("The street is wet\n"); 4 The optional Else part is only executed if
}else the condition is false.
{
printf("The street is dry\n"); 3
}
if(condition1)
{
if(condition2)
{
//instruction
}
}
Programming I en Page 56
If-else variations
if (condition_1) if (condition_1)
{ {
// Executed if condition_1 is true // Executed if condition_1 is true
} }
else if (condition_2) if (condition_2)
{ {
// Executed if condition_2 is true // Executed if condition_2 is true
} }
else if (condition_3) if (condition_3)
{ {
// Executed if condition_3 is true // Executed if condition_3 is true
} }
else
{
/* Executed if none of the above
conditions are met */
} ▪ Each block can be executed
▪ All conditions are checked, no matter which of them are
true
▪ Only one block is executed
▪ Conditions 2 and 3 do not need to be checked if
condition 1 applies
Programming I en Page 57
Ternary Operator
if (motor_switch == true)
instead of
if (motor_switch)
Both are absolutely identical if motor_switch is a boolean / can only have two different cases.
Programming I en Page 58
The Switch Statement
The following code blocks are different in syntax, but identical in their semantics (meaning)
if (motor_mode == 1) { switch (motor_mode) {
printf("Motor running at 50%...\n"); case 1:
} printf("Motor running at 50%...\n");
else if (motor_mode == 2) { break;
printf("Motor running at 100%...\n"); case 2:
} printf("Motor running at 100%...\n");
else if (motor_mode == 3) { break;
printf("Motor stopped...\n"); case 3:
} printf("Motor stopped...\n");
else { break;
printf("Invalid mode selected.\n"); default:
} printf("Invalid mode selected.\n");
} }
int x = 1;
switch (motor_mode) {
case x:
printf("Motor running at 50%...\n");
break;
--> error, x is not a constant
Programming I en Page 59
Quiz conditional statements
Programming I en Page 60
Functions
How can I run a calculation, such as the BMI calculation, several times without having to restart the
program?
How can I create a programme with BMI and BAC calculator that is clearer than having both in the
main function?
Programming I en Page 61
What is a function?
Program state
with variables
y = f(x) = 2x²
Via pointer
(reference)
Copy Copy
Parameter Function body Return value
with instructions
Output
#include <stdio.h>
#include <string.h>
//definition of a function
int area_of_square(int a){
int area = a*a;
return area;
}
int volume_of_cube(int a){
int volume = area_of_square(a) * a;
Programming I en Page 62
int volume = area_of_square(a) * a;
return volume;
}
int main() {
double my_volume = volume_of_cube(5);
//call of a function
printf("Square area: %d", my_volume);
return 0;
}
Programming I en Page 63
Functions with parameters and return values
#include <stdio.h>
1 2
void print_date(){
return 0;
}
Output:
Today is December 1st 2048
2048-12-01
Days: 747881
Programming I en Page 64
Signature, declaration and definition of functions
The signature of
void print_iso_formatted_date(int day, int month, int year) {
printf("%d-%02d-%02d\n", year, month, day);
}
is
print_iso_formatted_date(int, int, int)
Functions must be declared before they are called, the definition may follow later. The
signature serves as declaration:
#include <stdio.h>
// Declaration of the function
void print_iso_formatted_date(int, int, int);
int main() {
// Call of the function
print_iso_formatted_date(01,12,2048);
return 0;
}
// Definition of the function
void print_iso_formatted_date(int day, int month, int year) {
printf("%d-%02d-%02d\n", year, month, day);
}
Programming I en Page 65
Quiz Functions
Programming I en Page 66
Overloaded functions (C++, not C)
In C++ and other languages several functions can have the same name as long as they have
different signatures (function name and parameter type):
Overloaded functions are helpful, for example, if default values are to be used. The ISO date
function always requires the year to be entered.
The current year is usually used. A second function (not overloaded) is possible in C for this
purpose:
To avoid duplicated printf code, the original function should always be reused:
In C++ and other languages, functions can be overloaded. An overloaded function has the same
name but a different signature:
Note: This is not a recursive function call, as the function with two parameters could have a
different name. (Recursion is covered later)
Programming I en Page 67
Call-by-reference vs Call-by-value
Call-by-value
Parameters (actual parameters) are transferred as a copy when called. After the function is completed,
the parameters at the call location are unchanged.
Call-by-reference
Parameters (arguments) are passed as a reference (pointer). After the function is completed, the
parameters at the call location may have changed. The references are still a copy, but there is no need to
change them.
#include <stdio.h>
// Function to demonstrate call by value
void callByValue(int x) {
x = 20; // This will modify only the local copy (stack) of 'x'
printf("Inside callByValue: x = %d\n", x);
}
// Function to demonstrate call by reference using pointers
void callByReference(int *x) {
*x = 20; // This will modify the original variable using its address
printf("Inside callByReference: x = %d\n", *x);
}
int main() {
int a = 10;
printf("Before callByValue: a = %d\n", a); // 10
callByValue(a); // 20 - Passing by value, changes won't affect 'a'
printf("After callByValue: a = %d\n\n", a); //10
Programming I en Page 68
What would happen with this line?
ptrx = 20;
Programming I en Page 69
Return parameter (reference parameter)
One (single) return value is great, but how can I return multiple variables/data types?
-> Parameters can also be used as return parameters if they are pointers.
int create_formatted_dates(char* iso_date, char* local_date, int day, int month, int year) {
sprintf(iso_date, "%d-%02d-%02d\n", year, month, day);
sprintf(local_date, "%02d.%02d.%d\n", day, month, year);
return 0;
}
int main() {
//create two strings to save the results in,
//Note: arrays are pointers with allocated memory
char iso_date[12];
char local_date[12];
Address Value
0x5A20 ‘2‘
0x5A21 ‘0‘
0x5A23 ‘4‘
0x5A22 ‘8‘
0x5A24 ‘-‘
0x5A25 ‘1‘ The stack is available in the debugger
0x5A26 ‘2‘
0x5A27 ‘-‘
0x5A28 ‘0‘
0x5A29 ‘1‘
0x5A2A ‘\0‘
0x5A2B ‘‘
0x5A2C ‘0‘
0x5A2D ‘1‘
0x5A2E ‘.‘
0x5A2F ‘1‘
0x5A30 ‘2‘
0x5A31 ‘.‘
… …
Programming I en Page 70
Global variables (static)
int main() {
char* my_date;
my_date = return_iso_formatted_date(01,12,2048);
printf(my_date);
return 0;
}
date is created on the stack within the function return_iso_formatted_date and destroyed when the
function is terminated.
Solution B: global variable static char date[12]; //outside the main function
Creates the variable on the persistent heap.
-> Global variables should be avoided if possible, as they tie up main memory during the entire
program sequence.
-> Programs with static variables can become messy, as static variables can be modified in any part
of the source code file
Programming I en Page 71
Quiz Functions 2
Global Variables
1. Are declared outside the functions
2. Accessible from any function
3. Each function has its own copy of the variable
Programming I en Page 72
Commenting code
Clever annotation can be used to create documentation with tools such as Doxygen.
/**
* @file commented_gcd.c
* @brief Compute the greatest common divisor (GCD) of integers.
*
* @note This minimal version performs no error handling.
*/
#include <stdio.h>
/**
* @brief Compute the greatest common divisor (GCD) of two integers.
*
* Uses the iterative Euclidean algorithm. Inputs may be negative;
* the result is non-negative.
*
* @param a First value.
* @param b Second value.
* @return The non-negative GCD of @p a and @p b.
*/
static int gcd(int a, int b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
/* Euclidean algorithm, a will be the result */
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
/**
* @brief Program entry point.
*
* Expects at least two integers per keyboard input (e.g. 84 30).
* Computes the GCD of them.
*
Programming I en Page 73
*
* @return 0 on completion.
*/
int main() {
printf("Enter first number: ");
int first;
scanf("%d", &first); /* No checks: assumes input is numeric. */
Programming I en Page 74
###end of lecture 31.10.25
Programming I en Page 75
Git (Source code management)
"I'm an egotistical bastard, and I name all my projects after myself. First Linux, now Git."
– Linus Torvalds
git - In British English, git is a rather friendly insult - not as strong as idiot, but not particularly
nice either.
Programming I en Page 76
Git Functions
This semester, only absolutely basic functions will be taught -> Use for
assignments and your own programmes
Programming II covers collaboration using git.
git
Programming I en Page 77
Git Tutorial für CLion
Mittwoch, 29. Oktober 2025 11:00
[Link]/help/clion/[Link]
Live demo:
- Integrate workspace into git
- commit / push
- pull
- git clone
Programming I en Page 78
Loops
Source: [Link]
Control structures
Programming I en Page 79
While-loop
int counter = 1;
1 2
while(counter <= 5){
4 printf("%d\n", counter); 3
counter++;
}
1 Keyword while
2 Condition (true/false)
3 Loop body
4 The programme always jumps back to the condition of the
loop and checks it again. As long as the condition is true, the
body is repeated.
while (1){
listen(ftp_port);
}
Programming I en Page 80
Do-while-loop
int number;
do {
printf("Enter a positive number: ");
//Read a number from keyboard
scanf("%d", &number);
if (number <= 0) {
printf("Invalid input, please try again.\n");
}
// Keep asking until number is positive
} while (number <= 0);
Programming I en Page 81
Break bricht die Schleife komplett und führt den Code nach Ihr
aus.
Programming I en Page 82
For-loop (Counting-loop)
1 1 2
for (int i = 1; i <= 5; i++)
{ 2 3 4
5
printf("%d\n", i);
} 3
1 for Keyword 5
2 Initialisation of the count variable (i for index)
3 (Termination- or loop-) condition 4
4 Update instruction before checking the condition
again
5 Loop body (block of instructions)
Programming I en Page 83
Break bricht die Schleife komplett und führt den Code nach Ihr
aus.
Programming I en Page 84
Results of for loops
// Case A
for (int a = 10; a < 20; a = a + 1) {
printf("Value of a: %d\n", a);
}
// Case B
for (int a = 10; a < 20;) {
printf("Value of a: %d\n", a);
}
Programming I en Page 85
Transform while to for loop
instructions;
}
Programming I en Page 86
Comparison of loop types
All 3 types of loops have their own intended use. Often more than one type
of loop can be used for a problem.
Basically:
▪ The While loop is the mother of all loops, it can always be used
▪ The For loop is also called a counting loop. If it is known how many runs are
to take place, the code is easier to read than with the While loop.
▪ The Do-While loop covers the case where the first run should always be
executed. In some cases, slightly less code is required as a result.
Programming I en Page 87
Nested Loops
Nested loops are generally used for multidimensional structures -> multidimensional arrays are covered later
A rectangle of points is already a two-dimensional structure. The following function can print a rectangle with any side length:
Programming I en Page 88
Quiz Loops
What is correct?
1. For loops are good when the number of passes is not
exactly predictable.
2. while(1) is an infinite loop
3. For nested for loops, the number of passes adds up
(number of inner + outer passes)
[Link]
Programming I en Page 89
(Pseudo) random numbers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Seed the random number generator with the system time
srand((unsigned int)time(NULL));
▪ Without the seed, the same sequence of pseudo-random numbers is generated each time the programme is
started
○ The same seed can be used to create the same test conditions
▪ If random numbers are frequently used in certain number areas, separate functions should be written (these are
usually available in other languages)
Programming I en Page 90
Modeling algorithms
What is an algorithm?
An algorithm is a clear instruction that leads to the solution of a
type of problem. A recipe, for example, is an (informal)
algorithm. Algorithms can be represented in various forms,
source code is just one of them.
What is modelling?
Models are an abstraction of reality. When modelling,
unimportant details are omitted and only the information of
interest for the case under consideration is shown.
Programming I en Page 91
Activity diagrams
Activity diagrams are a widespread way of creating models for
algorithms.
Activity diagrams are also used for describing business processes. Here
is an example:
4b
4b
4a
Programming I en Page 92
8. each diagram has exactly one starting point. Several end points are permitted. If
an end point is reached, the entire diagram is finished.
9. swim lanes divide the activities into areas of responsibility, e.g. a role,
department or IT system.
Incident
process
Programming I en Page 93
Activity diagram for Lucky Punch
Programming I en Page 94
Desk check
diff = 0
n=2
m=1
Step m n diff
1 1 2 Some embedded systems do not support debugging. The desk
test is used to check an algorithm without a debugger.
2 0
3 1 One line in the table is filled for each assignment.
4 2 Only the value that has been reassigned by the code in the
5 1 latest step is written to the table.
6 1 m n Result
7 1 4 10 2
8 1 2 6 2
9 0 3 5 1
10 1 40 10 10
11 0 1000 250 250
14 35 7
9 6 3
51 34
Programming I en Page 95
Quiz Algorithms
Algorithms
1. Are a description of how certain inputs with certain action
steps lead to a result
2. A recipe is comparable to an algorithm
[Link]
Programming I en Page 96
Arrays
void prime01() {
int prime1 = 2;
int prime2 = 3;
int prime3 = 5;
int prime4 = 7;
int prime5 = 11;
//... Output
printf("prime1: %d\n", prime1);
printf("prime2: %d\n", prime2);
printf("prime3: %d\n", prime3);
printf("prime4: %d\n", prime4);
printf("prime5: %d\n", prime5);
}
Programming I en Page 97
Properties of arrays
void prime02() {
int prime[8] = {2, 3, 5, 7, 11};
1 Declaration with number and data type of the
1 2
elements, the length must be a constant (static array)
2 Literal for an array
3 3 Loop that increments the index i
for (int i = 0; i < 8; i++) 4 Access to element at position i
printf("prime %d: %d\n",i+1, prime[i]);
}
4
Arrays
▪ Collection of data of the same data type
▪ The number of elements is invariable
▪ The array variable itself is a pointer to the first element
▪ The index i allows access to position i of the array,
▪ Index 0 -> first position, n-1 -> last position!
▪ Access in constant time or O(1) (no matter how many elements are in the array, access takes
approximately the same amount of time)
▪ Elementary data types (int, char, ...) and pointers permitted as data types
▪ Multi-dimensional arrays can be managed with an array of pointers to other arrays
▪ Initialisation with int prime[]= {2, 3, 5, 7, 11}; is possible, in this case prime has length
5
Programming I en Page 98
The two biggest problems in programming
###end_of_lecture 21.11.2025
Programming I en Page 99
Traversing Arrays
The array degenerates into a pointer when it is transferred to the new function.
sizeof(array) can only provide the length of the pointer itself (4/8 Byte).
int a[3][2];
Col 0 Col 1
int a[row][column]
Row 0 a[0][0] a[0][1]
Row 1 a[1][0] a[1][1]
Row 2 a[2][0] a[2][1]
#include <stdio.h>
//To use them for the array, these constants must be declared via #define
//the const keyword would not work
#define NUM_ROWS 8
#define NUM_COLS 8
int main () {
//this creates a 2D array with NUM_ROWS * NUM_COLS elements, internally it is 1D
int picture[NUM_ROWS][NUM_COLS] = {
{0, 0, 1, 1, 1, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 1, 0},
{1, 0, 1, 0, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 1, 0, 0, 1},
{0, 1, 0, 0, 0, 0, 1, 0},
{0, 0, 1, 1, 1, 1, 0, 0}
};
Arrays can have many dimensions. All are stored in a contiguous memory block:
How can the size of an array be adjusted during the course of the programme?
Solution: Create (allocate) the storage space of the array with more storage space. --> Dynamic array is
required!
//stock now has to be defined with the malloc function (memory allocation)
int *stock = malloc(len_stock * sizeof(int));
}
//Do some stuff with stock
//Do not forget to free the memory when not needed anymore -> memory leak
free(stock);
Debugging in Clion:
For dynamic arrays, the length must be specified manually for debugging. The following watch can be created
for the dynamic array stock. It then shows 5 or 10 elements of stock:
stock @ len_stock
Memory leaks
▪ if the memory is not released again with free().
▪ The reason is often that the pointer to the allocated memory area has been lost.
Multidimensional arrays
1. Consist of nested arrays
2. In C, for declaration another pair of {} parentheses is used
per dimension
3. Stored internally as a one-dimensional array
Solution
void read_chars_win() {
char a,b;
printf("==========read_chars_win=========\n"); fflush() deletes all characters from the keyboard buffer,
printf("1. Char :"); unfortunately only under Windows
scanf("%c",&a);
fflush(stdin);
printf("2. Char :");
scanf("%c",&b);
fflush(stdin);
printf("\nYou entered : %c %c",a,b);
}
void read_chars_linux() {
char a,b;
printf("==========read_chars_linux=========\n"); getchar() != '\n' consumes all chars up to and including
printf("1. Char :"); the \n, then a new scanf()
do {scanf("%c",&a);} while ( getchar() != '\n' );
printf("2. Char :");
do {scanf("%c",&b);} while ( getchar() != '\n' );
printf("\nYou entered : %c %c",a,b);
}
void buffer_overflow(){
char string[10];
puts("Enter 9 chars at most:");
//The overflow with more input than 9 chars cannot be prevented
scanf("%s", string);
puts(string);
}
Solution:
fgets() requires the maximum length of the string as a parameter and then truncates it:
void buffer_control(){
char string[10];
puts("Enter 9 chars at most:");
//After 9 chars the input is capped by fgets()
fgets(string, 10, stdin);
puts(string);
//other data types can then be read from the string with sscanf
int number;
sscanf(string, "%d", &number);
}
y = f(n):
y = 1*2*3*…*n
Factorial iterative
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
Factorial recursive
natural language recursive definition of the factorial:
- the factorial of a number is the number itself times the factorial of the preceding number
- the factorial of 1 is 1
int factorial_recursive(int n) {
if (n == 1) {
return 1;
}
return n * factorial_recursive(n - 1);
}
f(4) = 4*f(3)
f(3) = 3 * f(2)
f(2) = 2 * f(1)
f(1) = 1
A new function frame is created on the stack for each function call:
Recursive methods usually have the following structure. The data types and number of
parameters are variable:
f(n) 0 1 1 2 3 5 8 13 21 34 55 89 …
n 0 1 2 3 4 5 6 7 8 9 10 11 …
The first Fibonacci number is zero, the second is 1. Each additional nth Fibonacci number is
defined by the sum of the previous Fibonacci number and the Fibonacci number before the
previous number.
f(0) = 0
f(1) = 1
f(n) = f(n-1)+f(n-2)
▪ f(10) can only be terminated when f(9) and f(8) have been calculated
▪ f(10) remains open until all subordinate calls have been completed
▪ The program uses the stack to remember where to jump back to for new calls
▪ If there is no termination condition or if new calls do not lead to it, functions are stored on the stack until it is full.
This is followed by a so-called stack overflow error.
Adaptability Complexity
Recursion can be applied to different types of Recursive code can be more difficult to understand than
problems, including mathematical calculations, data iterative solutions. Recursion can lead to subtle errors,
structures (e.g. trees and lists) and graphical such as infinite loops (recursive calls without a recursion
algorithms. It is a versatile concept. anchor).
110100
Problem
Helper functions for arrays, such as sum and average, are to be used in
various projects. However, the code must not be copied (maintainability).
Solution
Outsourcing to a separate array_utils module and integrating this in all
projects.
Realization
Before a function/variable can be called from another module, it must be
declared (signature only).
-> Combine function and variable declarations into header files (here
array_utils.h).
-> Store implementation in array_utils.c
Header files are copied to C source files with the #include instruction of
the pre-processor (#include array_utils.h)
project1.c
array_utils.h
#include "array_utils.h"
Documentation: [Link]
#include <stdio.h>
#include "array_utils.h"
euclid.h
#ifndef EUCLID_H
#define EUCLID_H main.c
int euclid(int x, int y);
#endif #include <stdio.h>
#include "euclid.h"
int main (void){
int x;
euclid.c int y;
#include "euclid.h" printf("x is: \n");
int euclid(int x, int y) { scanf ("%d", &x);
while (x != y) { printf("y is: \n");
if (x < y) { scanf ("%d", &y) ;
y = y - x; printf ("euclid for %d and %d is: %d\n", x, y, euclid(x, y)) ;
} else { return 0;
x = x - y; }
}
}
return x;
}
#ifndef EUCLID_H_
#define EUCLID_H_
▪ Function declarations
▪ Variable declarations (external)
▪ Global constants (#define, const)
▪ Own type definitions (typedef, struct, union, enum)
Project/
├── include/ # Contains header files
├── lib/ # Contains external libraries
├── src/ # Contains source code (e.g., .c files)
├── [Link] # Main CMake file
The same is also possible with the compiler on console level. the following example shows the usage of
the gcc compiler on Windows with the same setting as above:
Variables have a range of validity, the so-called scope. These are possible:
Initialisation
Global variables are initialised with 0 or NULL depending on their type.
However, local variables are not; they can contain old values.
#include <stdio.h>
int global_var = 10; // Global variable accessible from any file in the program
static int static_global_var = 20; // Static global variable accessible only in this file
extern int extern_var; // Declares an external variable defined in another file
void function1() {
static int static_local_var = 0; // Static local variable retains its value across calls
static_local_var++;
printf("Value of static_local_var in function1 (retains value across calls): %d\n", static_local_var);
}
void function2() {
int local_var = 30; // Local variable in function2
printf("Value of local_var in function2 (local scope): %d\n", local_var);
}
int main() {
printf("Value of global_var in main (global scope): %d\n", global_var);
printf("Value of static_global_var in main (file scope): %d\n", static_global_var);
function1();
function1(); // Calling function1 twice to see static local variable behavior
function2();
// Block scope
{
int block_var = 40; // Block-scoped variable
printf("Value of block_var in block scope: %d\n", block_var);
}
// block_var cannot be accessed here, outside the block
return 0;
}
#include <stdio.h>
/* function declaration */
void func(void);
int main() {
while (count--) {
func();
}
return 0;
}
void func(void) {
static int i = 5; /* local static variable*/
i++;
printf("i ist %d und count ist %d\n", i, count);
}
count i
4 6
3 7
2 8
1 9
0 10
int monat;
register int monat;
For variables that are not to be saved in the main memory but
in a register. Register memory is not enforced.
The maximum size of the variable may not exceed the size of
the register (16 / 32 / 64 bits) on the platform (processor
architecture).
###end_of_lecture 12.12.25
Problem: Natural objects (such as books) consist of a number of variables. Managing these is impractical
We need to represent one or more data sets (books) consisting of a set of attributes
//anonymous struct, requires variable(s) //with name tag, for later use
struct { struct Book{
int books_printed; int books_printed;
char title[80]; char title[80];
char author[80]; char author[80];
}book1, book2 }
-> Name tags (book) and variables after the declaration of the tag are optional, but one of them is always required.
//the next line would go wrong, because book1 is a kind of package with different variables
inside:
//printf("%s\n", book1);
//confusing the two float parameters now leads to a compile time error
velocity v1 = calculate_velocity(t1, d1);
}
Units are not included; a different data type can be introduced for each unit using typedef so that they cannot
be swapped.
Structs can also be defined with the keyword typedef. The only difference to the standard is that struct no
longer needs to be used later:
typedef struct
{
datatype identifier1;
datatype identifier2;
...
datatype identifierN;
} [structure Tag];
//with typedef
typedef struct {
int books_printed;
char title[80];
char author[80];
}Book;
typedef struct {
unsigned int hour; Appointment
unsigned int minute;
unsigned int second; Date
} Time_of_day; ▪ day
typedef struct { ▪ month
unsigned int day; ▪ year
unsigned int month;
int year; Time_of_day
} Date; ▪ hour
typedef struct { ▪ minute
Date d; ▪ second
Time_of_day z;
} Appointment;
//call by value
void printBook(Book book1) {
printf("Title: %s\n", [Link]);
printf("Author:%s\n", [Link]);
printf("Copies: %d\n", book1.books_printed);
}
Pro
The parameter list is clearer if a struct is passed instead of n variables.
Contra
A copy of all variables is transferred, even if only one is required. Cannot change the struct of the caller.
//call by reference
void print_book_ptr(Book* book1) {
printf("Title: %s\n", book1->title);
printf("Author:%s\n", book1->author);
printf("Copies: %d\n", book1->books_printed);
}
Book* return_struct_reference() {
struct Book* ptr_book1; // declare ptr_book1 of type Book pointer
ptr_book1 = malloc(sizeof(struct Book));
ptr_book1->books_printed = 30000000;
strcpy(ptr_book1->title, "1984");
strcpy(ptr_book1->author, "George Orwell");
return ptr_book1;
}
By returning a structs, several variables can be returned within the structs. A copy is passed
on. book1 is destroyed after the function is completed.
return book1;
}
Book library[500];
struct robo {
unsigned int sensor1:1; Note on the example
unsigned int sensor2:1; sizeof(robo) should be 1 byte, but is 4 bytes
unsigned int sensor3:1; Reason: 4 bytes is the smallest possible memory block for a bit field.
unsigned int sensor4:1; In this case, only 1 byte (8 bit) is used and 3 bytes are unused
unsigned int output:4;
} Robo1;
Add the number of bits for the attribute after the colon in the struct:
int attribute:1;
▪ int
▪ unsigned int
_BitInt(1) sensor1;
#include <stdio.h>
enum Direction {
NORTH, Output:
EAST, North: 0, East: 1, South: 2, West: 3
SOUTH,
WEST
};
int main() {
printf("North: %d, East: %d, South: %d, West: %d\n", NORTH, EAST, SOUTH, WEST);
}
Enumerations are named constants. The numbering is ascending and starts at 0, unless otherwise specified.
An enum can also act as a data type. Some compiler versions support warning messages/errors if no suitable value is
transferred.
Targets of C++
Providing object-oriented functions in a C-based language without compromising
efficiency
Header
[Link]
or .h .hpp
Codefile
[Link]
or .cc
Feature C C++
Paradigm Procedural* Multi-Paradigm (Procedural + Object-
Oriented)
Object-Oriented Not Supported Supported (Classes, Objects, Inheritance,
Features etc.)
Memory malloc(), calloc(), free(), no new, delete, no garbage collection
Management garbage collection
Namespaces Not Supported Supported
Function Not Supported Supported
Overloading
Operator Not Supported Supported
Overloading
Exception Handling Error Codes, setjmp(), longjmp() try, catch, throw
Type Safety** Less Type-Safe More Type-Safe
Boolean Data Type int used as default, to be imported with bool Type (true/false)
stdbool.h
String Data Type char arrays are used as strings native string data type
Generics Not supported Supported
Standard Template Not Available Available - the STL provides data types like
Library Lists, Maps etc.
Input/Output printf(), scanf() cin <<
Operations cout >>
Compatibility Specific to C Mostly Backward-Compatible with C, C
libraries can be imported
Main compiler gcc g++ uses the same argument structure as gcc
*Procedural means that the language uses functions, but it is not functional. Functional
programming is the main paradigm of languages such as Haskell, Erlang, F# and Scala.
**Type safety ensures that variables must always have a predefined data type. This means that
the programmer has more work to do, but the compiler can detect errors that would otherwise
only be noticed later.
Type-safe (C)
int number = 12;
number = {12,2} //Early error warning from the compiler
//range requires an int as parameter, the set will crash the program. The compiler
can and will not warn about it:
Definition:
namespace customers
{
int number;
int find_by_name(string s)
{
//...
}
}
Usage
int result = customers::find_by_name("Meier");
//or
using namespace customers;
//...
int result = find_by_name("Meier");
Overloading functions mainly serves the readability and maintainability of the code.
In C++ and other languages, functions may be overloaded. An overloaded function has the same
name but a different signature:
Calls:
print_iso_formatted_date(01,10,2025);
print_iso_formatted_date(01,10);
Streams
stream: a source/destination for reading/writing bytes in sequence.
other iostreams: fstream, stringstream, etc.
Expression Description
cout << Expression Output extraction operator; writes the value of the expression to the
standard output
cin >> Variable Input extraction operator; reads from the standard input and stores it
in a variable
Input with cin: (you can also use getline to read the entire line)
int age;
cout << "Geben Sie Ihr Alter ein: ";
cin >> age;
#include <iostream>
using namespace std;
int main() {
string message = "Hello World!";
cout << message << endl; Prompt
message[0] = 'h'; Hello World!
cout << message << endl; hello World!
return 0;
}
Changeability (Mutability)
Strings can be modified. Access to a string character through brackets
Usability
New functions and the operators + and == are available for std::strings
Function Description
length() Get the length of the string
substr() Extract a substring
find() Find a substring or character
compare() Compares if the letters in two strings are equal
replace() Replaces found substrings by another given string
The previous enum construct can only use each value once. In the example, it is not clear whether Green
comes from Colour or Trafficlight.
With references the programmer can hand over pointer that do not need to be dereferenced. The reference address cannot be
changed (which often happened accidentally).
Syntax
int& my_variable = 50;
Example
#include <iostream>
using namespace std;
void callByReferenceC(int *x) {
*x = 20; // This will modify the original variable using its address
cout << "Inside callByReferenceC: x = " << *x << endl;
}
void callByReferenceCPP(int& y){
y=y+10; // This will modify the original variable but without using *
cout << "Inside callByReferenceCPP: y = " << y <<endl;
}
int main() {
int a = 10;
callByReferenceC(&a); //20 - Passing by reference, changes will affect 'a'
cout << "Inside callByReferenceCPP: a = " << a << endl;
//the variable itself can be used as actual parameter
callByReferenceCPP(a);
cout << "Inside callByReferenceCPP: a = " << a << endl;
return 0;
}
Note: From a technical point of view, there is only call-by-value in C. Passed pointers have been copied.
However, the reference in C++ is also technically a real call-by-reference.
It is often more convenient to specify auto instead of the concrete data type; the compiler then determines the
correct type.
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> students = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
// Without auto (long type name)
for (map<int, string>::iterator it = [Link](); it != [Link](); ++it) {
cout << it->first << ": " << it->second << endl;
}
// With auto (shorter & cleaner)
for (auto it = [Link](); it != [Link](); ++it) {
cout << it->first << ": " << it->second << endl;
}
}
However, the static cast does not work if strings are to be converted into
numbers. There are special sto? functions, for example stoi() or stod().
Exceptions are already thrown with sto? if the string does not fit into the target
format.
Problem
A finished application, such as a self-written encryption program, is
available for use as a compiled .exe. The customer wants to use the
application in a Powershell script or from the cmd terminal. All
entries should be made at the start of the program via the script,
keyboard entries would stop the script.
Solution:
The main method receives parameters that are read in by the .exe
call.
The command line call is either made in the cmd or can be set in
the IDE (for testing):
Call in cmd