C Programming Module Continued
C Programming Module Continued
Why Learn C?
QuickStart
#include<stdio.h>
int main()
{
printf("Hello world!");
return 0;
}
Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For
now, focus on how to run the code.
In Coding C, it should look like this:
Then, press Run to run (execute) the program. The result will look something to this:
Congratulations! You have now written and executed your first C program.
Syntax
You have already seen the following code in the previous chapters. Let's break it down to understand
it better:
Line 1: #include <stdio.h> is a header file library that lets us work with input and output functions,
such as printf() (used in line 5). Header files add functionality to C programs. Don't worry if you
don't understand how #include <stdio.h> works. Just think of it as something that (almost) always
appears in your program.
Line 2: A blank line. C ignores white space. But we use it to make the code more readable.
Line 3: Another thing that always appear in a C program is main(). This is called a function. Any code
inside its curly brackets {} will be executed.
Line 5: printf() is a function used to output/print text to the screen. In our example, it will output
"Hello World!".
Line 7: The closing curly bracket } to actually end the main function.
Statements
The following statement "instructs" the compiler to print the text "Hello World!" to the screen:
Example
printf("Hello World!");
If you forget the semicolon (;), an error will occur and the program will not run:
Example
printf("Hello World!")
Output
Many Statements
The statements are executed, one by one, in the same order as they are written:
Example
printf("Hello World!");
printf("Have a good day!");
return 0;
Example explained
From the example above, we have three statements:
1. printf("Hello World!");
2. printf("Have a good day!");
3. return 0;
The first statement is executed first (print "Hello World!" to the screen).
Then the second statement is executed (print "Have a good day!" to the screen).
And at last, the third statement is executed (end the C program successfully).
Note: You will learn more about statements in the later chapters. For now, just remember to always
To output values or print text in C, you can use the printf() function:
Example
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}
Double Quotes
When you are working with text, it must be wrapped inside double quotations marks "".
If you forget the double quotes, an error occurs:
Example
Example
#include <stdio.h>
int main()
{
printf("Hello World!\n");
printf("I am learning C.");
return 0;
}
Output
You can also output multiple lines with a single printf() function. However, this could make the code
harder to read:
Example
#include <stdio.h>
int main()
{
printf("Hello World!\nI am learning C.\nAnd it is awesome!");
return 0;
}
IDE Window
Output:
Tip: Two \n characters after each other will create a blank line:
Example
#include <stdio.h>
int main()
{
printf("Hello World!\n\n");
printf("I am learning C.");
return 0;
}
Output
What is \n exactly?
The newline character (\n) is called an escape sequence, and it forces the cursor to change its position
to the beginning of the next line on the screen. This results in a new line.
Comments can be used to explain code, and to make it more readable. It can also be used to prevent
Single-line Comments
Any text between // and the end of the line is ignored by the compiler (will not be executed).
int main()
{
//This is a comment
printf("Hello World!\n\n");
return 0;
}
C Multi-line Comments
Example
#include <stdio.h>
int main()
{
/* The code below will
print the words Hello World!
to the screen, and it is amazing
*/
printf("Hello World!\n\n");
return 0;
}
Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.
Good to know: Before version C99 (released in 1999), you could only use multi-line comments in C.
Exercises
Note:
✓ This programming exercise is the first quiz requirement.
✓ Your answer will be inspected before the start of the quiz.
✓ Your program code must be handwritten.
✓ Use long bond paper.
1-1) Create a program in C to display your full name, date of birth, contact number and address.
Sample program output:
1-2) Create a program in C to display the first stanza of your favorite Christmas song.
Sample program output:
1-3) Create a program in C to display the names and addresses of your elementary, secondary, and
tertiary schools.
Sample program output:
1. What is a variable in C?
6. How do you print multiple variables of different types in a single printf() statement?
11. Can you assign the same value to multiple variables of the same type in one statement?
C Variables
Variables are containers for storing data values, like numbers and characters.
In C, there are different types of variables (defined with different keywords), for example:
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single quotes
Syntax
Where type is one of C types (such as int), and variableName is the name of the variable (such as x or
So, to create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign the value 15 to it:
You can also declare a variable without assigning the value, and assign the value later:
Example
#include <stdio.h>
int main() {
// Declare a variable
int myNum;
Format specifiers are used together with the printf() function to tell the compiler what type of data
the variable is storing. It is basically a placeholder for the variable value.
For example, to output the value of an int variable, use the format specifier %d surrounded by double
quotes (""), inside the printf() function:
Example:
#include <stdio.h>
int main() {
int myNum = 15;
printf("%d", myNum);
return 0;
}
Output
#include <stdio.h>
int main() {
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
Output
To combine both text and a variable, separate them with a comma inside the printf() function:
Example
#include <stdio.h>
int main() {
int myNum = 15;
printf("My favorite number is: %d", myNum);
return 0;
}
Output
To print different types in a single printf() function, you can use the following:
Example
#include <stdio.h>
int main() {
int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);
return 0;
}
Output
Print Values Without Variables
You can also just print a value without storing it in a variable, as long as you use the correct format
specifier:
Example
#include <stdio.h>
int main() {
printf("My favorite number is: %d\n", 15);
printf("My favorite letter is: %c", 'D');
return 0;
}
Output
However, it is more sustainable to use variables as they are saved for later and can be re-used
whenever.
Practice problem
Use the correct format specifier to output the value of myNum:
#include <stdio.h>
int main() {
int myNum = 15;
printf("__", myNum);
return 0;
}
Change Variable Values
If you assign a new value to an existing variable, it will overwrite the previous value:
Example:
#include <stdio.h>
int main() {
int myNum = 15;
printf("myNum is: %d", myNum);
myNum = 10;
printf("\nmyNum is: %d", myNum);
return 0;
}
Output
Example
#include <stdio.h>
int main() {
int myNum = 15;
int myOtherNum = 23;
printf("myNum is: %d", myNum);
// Assign the value of myOtherNum (23) to myNum
myNum = myOtherNum;
printf("\nmyNum is now: %d", myNum);
return 0;
}
Output
Or copy values to empty variables:
Example
#include <stdio.h>
int main() {
// Create a variable and assign the value 15 to it
int myNum = 15;
Practice problem
Display the sum of 5 + 10, using two variables: x and y.
#include <stdio.h>
int main() {
___ _ = _;
int y = 10;
printf("%d", x + y);
return 0;
}
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example
Example
#include <stdio.h>
int main() {
int x = 12;
int y = 3;
printf("%d\n", x + y); // Addition
printf("%d\n", x - y); // Subtraction
printf("%d\n", x * y); // Multiplication
printf("%d\n", x / y); // Division
x = 5;
y = 2;
printf("%d\n", x % y); // Modulo Division
x = 7;
printf("%d\n", ++x); // Increment
x = 3;
printf("%d\n", --x); // Decrement
return 0;
}
Output
Declare Multiple Variables
To declare more than one variable of the same type, use a comma-separated list:
Example
#include <stdio.h>
int main() {
int x = 5, y = 6, z = 50;
printf("%d", x + y + z);
return 0;
}
Output
You can also assign the same value to multiple variables of the same type:
Example
#include <stdio.h>
int main() {
int x, y, z;
x = y = z = 50;
printf("%d", x + y + z);
return 0;
}
Output
Practice problem
Fill in the missing parts to create three variables of the same type, using a comma-separated list:
#include <stdio.h>
int main() {
___ myNum1 = 10_ myNum2 = 15_ myNum3 = 25;
printf("%d", myNum1 + myNum2 + myNum3);
return 0;
}
Variable Names (Identifiers)
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: It is recommended to use descriptive names in order to create understandable and maintainable
code:
Example
#include <stdio.h>
int main() {
// Good variable name
int minutesPerHour = 60;
Real-Life Example
Often in our examples, we simplify variable names to match their data type (myInt or myNum for int
types, myChar for char types, and so on). This is done to avoid confusion.
However, for a practical example of using variables, we have created a program that stores different
data about a college student:
Example
#include <stdio.h>
int main() {
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);
return 0;
}
Output
Calculate the Area of a Rectangle
In this real-life example, we create a program to calculate the area of a rectangle (by multiplying the
length and width):
Example
#include <stdio.h>
int main() {
// Create integer variables
int length = 4;
int width = 6;
int area;
Output
Data Types
As explained in the Variables chapter, a variable in C must be a specified data type, and you must use
a format specifier inside the printf() function to display it:
Example
#include <stdio.h>
int main() {
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
Output
%d or %i int
%f or %F float
%lf double
%c char
Used for strings (text), which you will learn more about in a later
%s
chapter
Note: It is important that you use the correct format specifier for the specified data type, or the
program may produce errors or even crash.
Example:
#include <stdio.h>
int main() {
}
Output
Practice problem
Add the correct data type for the following variables:
#include <stdio.h>
int main() {
___ myNum = 5;
_____ myFloatNum = 5.99;
____ myLetter = 'D';
return 0;
}
The character must be surrounded by single quotes, like 'A' or 'c', and we use the %c format specifier
to print it:
Example
#include <stdio.h>
int main() {
char myGrade = 'A';
printf("%c", myGrade);
return 0;
}
Output:
Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain characters. Note
that these values are not surrounded by quotes (''), as they are numbers:
Example
#include <stdio.h>
int main() {
char a = 65, b = 66, c = 67;
printf("%c", a);
printf("%c", b);
printf("%c", c);
return 0;
}
Output
Notes on Characters
If you try to store more than a single character, it will only print the last character:
Example
#include <stdio.h>
int main() {
char myText = 'Moshi';
printf("%c", myText);
return 0;
}
Output
Note: Don't use the char type for storing multiple characters, as it may produce errors.
To store multiple characters (or whole words), use strings (which you will learn more about in a later
chapter):
Example
#include <stdio.h>
int main() {
char myText[] = "Hello";
printf("%s", myText);
return 0;
}
Output
For now, just know that we use strings for storing multiple characters/text, and the char type for single
characters.
Practice problem
Add the correct format specifier to print the value of the following variable:
#include <stdio.h>
int main() {
char myLetter = 'D';
printf("__", myLetter);
return 0;
}
Numeric Types
Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.
Example
#include <stdio.h>
int main() {
int myNum = 1000; //integer
printf("%d\n", myNum);
float myNumf = 5.75; //float
printf("%f\n", myNumf);
double myNumd = 19.99; //double
printf("%lf\n", myNumd);
return 0;
}
Output
Example
#include <stdio.h>
int main() {
float f1 = 35e3;
double d1 = 12E4;
printf("%f\n", f1);
printf("%lf", d1);
return 0;
}
Output
Example
#include <stdio.h>
int main() {
float myFloatNum = 3.5;
double myDoubleNum = 19.99;
Example
#include <stdio.h>
int main() {
float myFloatNum = 3.5;
printf("%f\n", myFloatNum); // Default will show 6 digits
// after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits
return 0;
}
Output
Practice problem
Make the output of the following example to only show one digit after the decimal point:
#include <stdio.h>
int main() {
float myScore = 9.5;
printf("____", myScore);
return 0;
}
int 2 or 4 bytes
float 4 bytes
double 8 bytes
char 1 byte
The memory size refers to how much space a type occupies in the computer's memory.
To actually get the size (in bytes) of a data type or variable, use the sizeof operator:
Example
#include <stdio.h>
int main() {
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
return 0;
}
Output
Note that we use the %lu format specifer to print the result, instead of %d. It is because the compiler
expects the sizeof operator to return a long unsigned int (%lu), instead of int (%d). On some computers
it might work with %d, but it is safer to use %lu.
For example, the size of a char type is 1 byte. Which means if you have an array of 1000 char values, it
will occupy 1000 bytes (1 KB) of memory.
Using the right data type for the right purpose will save memory and improve the performance of
your program.
You will learn more about the sizeof operator later in this module, and how to use it in different
scenarios.
Real-Life Example
Here's a real-life example of using different data types, to calculate and output the total cost of a
number of items:
Example
#include <stdio.h>
int main() {
// Create variables of different data types
int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';
// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
return 0;
}
Output
Type Conversion
Sometimes, you have to convert the value of one data type to another type. This is known as type
conversion.
For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But since
we are working with integers (and not floating-point values), the following example will just output 2:
Example
#include <stdio.h>
int main() {
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); // Outputs 2
return 0;
}
Output
To get the right result, you need to know how type conversion works.
Example
#include <stdio.h>
int main() {
// Automatic conversion: int to float
float myFloat = 9;
printf("%f", myFloat); // 9.000000
return 0;
}
Output
As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000.
This can be risky, as you might lose control over specific values in certain situations.
Especially if it was the other way around - the following example automatically converts the float
value 9.99 to an int value of 9:
Example
#include <stdio.h>
int main() {
// Automatic conversion: float to int
int myInt = 9.99;
printf("%d", myInt); // 9
return 0;
}
Output
What happened to .99? We might want that data in our program! So be careful. It is important that
you know how the compiler work in these situations, to avoid unexpected results.
As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. And as you know
from the beginning of this page, if you store the sum as an integer, the result will only display the
number 2. Therefore, it would be better to store the sum as a float or a double, right?
Example
#include <stdio.h>
int main() {
float sum = 5 / 2;
printf("%f", sum); // 2.000000
return 0;
}
Output
Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the division. In
this case, you need to manually convert the integer values to floating-point values.
Explicit Conversion
Explicit conversion is done manually by placing the type in parentheses () in front of the value.
Considering our problem from the example above, we can now get the right result:
Example
#include <stdio.h>
int main() {
// Manual conversion: int to float
float sum = (float) 5 / 2;
printf("%f", sum); // 2.500000
return 0;
}
Output
Example
#include <stdio.h>
int main() {
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%f", sum); // 2.500000
return 0;
}
Output
And since you learned about "decimal precision" in the previous chapter, you could make the output
even cleaner by removing the extra zeros (if you like):
Example
#include <stdio.h>
int main() {
int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%.1f", sum); // 2.5
return 0;
}
Output
Real-Life Example
Here's a real-life example of data types and type conversion where we create a program to calculate
the percentage of a user's score in relation to the maximum score in a game:
Example
#include <stdio.h>
int main() {
// Set the maximum possible score in the game to 500
int maxScore = 500;
/* Calculate the percentage of the user's score in relation to the maximum available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0;
#include <stdio.h>
int main() {
float sum = _______ 3 / 2;
printf("%.1f", sum); return 0;
}
Constants
If you don't want others (or yourself) to change existing variable values, you can use the const keyword.
This will declare the variable as "constant", which means unchangeable and read-only:
Example
#include <stdio.h>
int main() {
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
return 0;
}
Output
You should always declare the variable as constant when you have values that are unlikely to change:
Example
#include <stdio.h>
int main() {
const int minutesPerHour = 60;
const float PI = 3.14;
printf("%d\n", minutesPerHour);
printf("%f\n", PI);
return 0;
}
Output
Notes on Constants
When you declare a constant variable, it must be assigned with a value:
Example
Like this:
#include <stdio.h>
int main() {
const int minutesPerHour;
minutesPerHour = 60;
printf("%d", minutesPerHour);
return 0;
}
Output
Good Practice
Another thing about constant variables, is that it is considered good practice to declare them with
uppercase.
It is not required, but useful for code readability and common for C programmers:
Example
#include <stdio.h>
int main() {
const int BIRTHYEAR = 1980;
printf("%d", BIRTHYEAR);
return 0;
}
Output
Practice problem
Make sure that the value of the following variable is not possible to change:
#include <stdio.h>
int main() {
_____ int BIRTHYEAR = 1980;
printf("%d", BIRTHYEAR);
return 0;
}
User Input
Example
#include <stdio.h>
int main() {
// Create an integer variable that will store the number we get from the user
int myNum;
The scanf() function takes two arguments: the format specifier of the variable ( %d in the example
above) and the reference operator (&myNum), which stores the memory address of the variable.
Multiple Inputs
The scanf() function also allow multiple inputs (an integer and a character in the following example):
Example
#include <stdio.h>
int main() {
// Create an int and a char variable
int myNum;
char myChar;
// Get and save the number AND character the user types
scanf("%d %c", &myNum, &myChar);
Note:
✓ This programming exercise is the first quiz requirement.
✓ Your answer will be inspected before the start of the quiz.
✓ Your program code must be handwritten.
✓ Use long bond paper.
1) Create a C program that takes the radius of a sphere as input and then calculates and outputs its
Volume.
Note: The formula for the Volume of the sphere is
4
𝑉= 𝜋𝑟 3
3
Where:
𝑉 is volume
𝜋 is 3.1416
𝑟 is radius
Sample output
Input the radius of the sphere: 2.56
The Volume of the sphere is 70.276237 units cubed.
2) Create a C program that prints the perimeter of a rectangle base on its height and width as input.
Note: The formula for the perimeter of a rectangle is P=2(height + width)
Sample output
Input the height of the Rectangle: 5
Input the width of the Rectangle: 7
The perimeter of the Rectangle is 24 units
3) Create a C program that converts kilometers per hour to miles per hour.
Note: 1 kilometer per hour is equal to 0.621371 mile per hour
Sample output
Input kilometers per hour: 15
15 kilometer per hour is equivalent to 9.320568 miles per hour
4) Create a C program that takes hours and minutes as input and calculates the total number of
minutes.
Sample output
Input hours: 5
Input minutes: 37
Total is 337 minutes.
5) Create a program in C that takes minutes as input, and display the total number of hours and
minutes.
Sample output
Input minutes: 546
9 Hours, 6 Minutes
6) Create a C program to find the third angle of a triangle if two angles are given.
Sample output
Input the first angle: 50
Input the second angle: 70
The third angle of the triangle is 60
7) Create a C program that takes the side of an equilateral triangle as an input and calculates and
displays its area.
Note: The formula for the area of an equilateral triangle is
√3 2
𝐴= 𝑎
4
Where
𝐴 is the area
𝑎 is the side.
Sample output
Input side: 5
The area is 10.82532 units squared.
8) An employee received an 8% salary increase which is retroactive for the last 6 months. Create a
program in C that takes the old salary of the employee as input and then compute and display the new
salary and the total amount collectible (6 months retroactive includes the current month).
Sample output
Input your old salary: 10000
Your new salary is 10800
The total amount collectible is 14800
9) Create a program to compute the length of the hypothenuse of a right triangle from an input
adjacent and opposite side. The formula for the length of the hypothenuse of a right triangle is
𝑐 = √𝑎2 + 𝑏 2
Where
c is the hypothenuse
a is the length of the adjacent side
b is the length of the opposite side