This example is the written version of the first lesson with additional commentary that is intended to support you in going over the code that you built during the class.
This example contains the following
- Part 1 of the hello.c code with linear flow
- Part 2 of the hello.c code with conditional flow
- Syntax and styling in C programs
- UML activity diagrams for both code examples
- Additional commentary on both programs
hello.c part 1: linear flow
In part one, we make a basic calculator to calculate the person’s age. It leaves in some bugs and shortcomings, some of which will be addressed in part 2 and some will need more knowledge in programming before they can be addressed, but it should be a good starting point.
All examples contain additional commentary.
Algorithm for part 1
Algorithms must explain the sequence of actions in a non-ambiguous and detailed manner. They can be represented in different notations. In this class, we mainly focus on UML activity diagrams, but occasionally we will also look at pseudo code. Today both examples will be given
Pseudo code for part 1
Pseudo code describes the steps taken in the algorithm, mixing both informal language and self-explanatory keywords, often used in various programming languages. This should be as human readable as possible, while still being structural. There are no formal rules for pseudo code.
1 2 3 4 |
- Greet user - Ask for user's year of birth - Calculate the likely age of the user - Print the age |
UML activity diagram for part 1
Activity diagrams are often used for visualizing the algorithm. They take longer to compose, but offer many benefits, including standardization and readability for non-developer positions. These are mainly used by large companies and governments, where specification quality, globally accepted certification and standardization are important.
Activity diagrams are typically created programming language agnostic and human readable. In the diagram above, notice the following components
- The algorithm begins with an Initial node
- Arrows indicate control flow (the sequence of actions)
- Action nodes specify actions taken, but not details related to the programming language or formatting
- Algorithm ends with a final node, that has a comment describing the end condition
Program code
In this code, you are introduced to the basic structure of a C program. Most programs start with a list of included libraries that provide sets of functions that can be used within the code. E.g. stdio.h provides basic input and output functionality. Even though our program isn’t using it, adding math.h library would provide access to mathematical functions and so on.
This is followed by the main() function. C programs start executing code from the first statement in the main() function and then continue executing code line-by-line. The main function ends with a return statement, that terminates the function. In this example, it also terminates the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/** * File: hello.c * Author: Risto Heinsar * Created: 01.09.2014 * Edited: 23.07.2025 * * Description: This is the first hello.c example showing program flow without * any conditionals and basic input-output function calls. */ // Includes the standard input-output library (printf, scanf) #include <stdio.h> // The program always starts from the main() function int main(void) { // Print the greeting in the terminal. printf("Hello!\n"); printf("This program determines the approximate age of a person\n\n"); // Variable declaration, type int (integer), variable name "year" int year; // Prompt the user and read the year of birth as integer printf("Please enter your year of birth: "); scanf("%d", &year); // Calculating the rough estimate of the age int age = 2025 - year; // Printing the result printf("You are most likely %d years of age\n", age); // The program finished successfully. Integer 0 indicates success. return 0; } |
Syntax and styling
Syntax sets the rules of the code that are required for it to work. This includes any structural elements set by the programming language in order for the computer to understand what you want to make it do. Most programming languages have different syntax rules, event though there is a lot of overlap (caused by influence of other programming languages, well proven practices etc). The same elements in one language can work differently in another language.
From the example above, some notable ones syntactical elements
- Every statement ends with a semicolon
- All programs must have a main() function. Code starts executing form the main() function
- The statements within the main() function are surrounded by opening { and } closing curly braces. We call the code in between these braces a code block. This also specifies scope, which you will learn about later.
- All strings are surrounded by double quotes, i.e. "This is a string"
- Comments start with two forward slashes // (or can be surrounded with /* and */ )
- Function calls are performed by stating the name of the function, followed by round parenthesis. Function calls we saw were to
printf() and
scanf()
- You can pass arguments to the function within the parenthesis.
- If there are multiple arguments, they are separated by commas
Style is set by us, the programmers, for readability and maintainability of the code. Style does not affect whether the code can be compiled or executed, or how it performs. Most of the time, the style requirements are set by either the team you are working in or by the company you are working for. In this class, the style is set by the teachers of the class. You can check the style guide for more, however here are a few notes from the code above
- Variables are commonly declared right before they are needed
- Every file has a comment in the beginning stating the purpose of the file, author and date
- Empty lines are used between blocks of code to indicate different sections
- Comments are placed right before the code lines they are explaining. There is a space after the two forward slashes. Comments start with an upper case letter.
- Starting and ending curly brace for a block of code are aligned (same distance from the start of the line)
- Curly braces are put on separate lines
- The code within the code block (indicated by curly braces) is indented
- Commas in the argument list for functions are always followed by a space
- Variables are named using camelCase styling, where the first word starts with a lower case character and all other words start with an upper case character.
- Variable name must indicate the purpose of the variable (what it holds)
- All operators are preceded and followed by a space (e.g. mathematical operators such as +, -, /, *. Equation operator =, comparison operators <, >, ==, !=, etc)
- Code line cannot exceed 80 characters. If it’s longer, it must be split over multiple lines.
Hello part 2: conditional flow
In the second part, we introduce a conditional statement to account for whether the user’s birthday for the year has already passed or is it still upcoming. This helps to correct for the bug in the first part of the task, where we couldn’t exactly tell the age.
Note, that while the results are now mostly accurate, there is still one small bug in the edge case. Can you spot it?
Activity diagram
We base the solution on the first diagram. The modifications are following
- We need to know whether the user’s birthday is still upcoming in the calendar year or it’s already passed. We add it as an action statement.
- We add a conditional statement to use a different formula depending on whether the birthday has already occurred. This requires
- a junction node to begin the conditional statement
- a merge node to finish the conditional statement
- a comment to specify the condition
- true/false statements on control flows to specify the correct path depending on the condition
- We also updated the print statement, as now we can determine the correct age in all but one case
Program code
The program code gets modified according to the specification by the algorithm.
We add an additional prompt for information and a conditional statement that accounts for this information to calculate the correct age.
Note the indentation of the code. The contents of the code block is always indented by 1. Since the if/else statements contain code blocks that are already inside the main function’s code block, they get an additional indentation. This means that it’s very easy and quick to for us to glance over and understand the structure of the code, helping code maintainability.
As mentioned before, there is one edge case, where this formula will be incorrect. Can you spot it?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
/** * File: hello_conditional.c * Author: Risto Heinsar * Created: 01.09.2014 * Edited: 23.07.2025 * * Description: This is the second hello example showing conditional program * flow. */ // Includes the standard input-output library (printf, scanf) #include <stdio.h> // The program always starts from the main() function int main(void) { // Print the greeting in the terminal. printf("Hello!\n"); printf("This program determines the approximate age of a person\n\n"); // Variable declaration, type int (integer), variable name "year" int year; // Prompt the user and read the year of birth as integer printf("Please enter your year of birth: "); scanf("%d", &year); int hasCelebratedBirthday; printf("Enter 1 if you've already had your birthday this year\n"); printf("Enter 0 if you have not.\n"); scanf("%d", &hasCelebratedBirthday); // Calculating age depending on the user's birthday // Note: There is a bug in this code that only triggers on an edge case. // Can you find it? int age; if (hasCelebratedBirthday) { age = 2025 - year; } else { age = 2025 - year - 1; } // Printing the result printf("You are %d years of age\n", age); // The program finished successfully. Integer 0 indicates success. return 0; } |