0% found this document useful (0 votes)
23 views

C Programming Module Continued

Uploaded by

dykv17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

C Programming Module Continued

Uploaded by

dykv17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

What is C?

✓ C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories


in 1972.
✓ It is a very popular language, despite being old. The main reason for its popularity is because it is
a fundamental language in the field of computer science.
✓ C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Why Learn C?

✓ It is one of the most popular programming languages in the world


✓ If you know C, you will have no problem learning other popular programming languages such as
Java, Python, C++, C#, etc, as the syntax is similar
✓ C is very fast, compared to other programming languages, like Java and Python
✓ C is very versatile; it can be used in both applications and technologies

Get Started With C

To start using C, you need the following:


✓ On an Android smartphone: Coding C IDE for mobile
✓ On an iPhone smartphone: C-programming language for OS IDE
✓ For Windows OS: Code::Blocks. Follow the instructions in the PDF file on how to download and
use it.

QuickStart

Let's create our first C file.

Open Coding C and go to Menu > Hello World.

The following C code will already be written:

#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:

Hello World code explained

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!".

Note that: Every C statement ends with a semicolon ;


Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.

Line 6: return 0 ends the main() function.

Line 7: The closing curly bracket } to actually end the main function.
Statements

A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

The following statement "instructs" the compiler to print the text "Hello World!" to the screen:
Example

printf("Hello World!");

It is important that you end the statement with a semicolon ;

If you forget the semicolon (;), an error will occur and the program will not run:

Example
printf("Hello World!")

Output
Many Statements

Most C programs contain 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

end them with a semicolon to avoid any errors.


Output (Print Text)

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

printf("This sentence will work!");

printf(This sentence will produce an error.);

Many printf Functions


You can use as many printf() functions as you want. However, note that it does not insert a new line
at the end of the output:
Example
#include <stdio.h>
int main()
{
printf("Hello World!");
printf("I am learning C.");
printf("Maka inspired man diay!");
return 0;
}
Output:
New Lines
To insert a new line, you can use the \n character:

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.

Examples of other valid escape sequences are:

Escape Sequence Description

\t Creates a horizontal tab

\\ Inserts a backslash character (\)

\" Inserts a double quote character


Comments in C

Comments can be used to explain code, and to make it more readable. It can also be used to prevent

execution when testing alternative code.

Comments can be singled-lined or multi-lined.


Note: Comments do not display anything when the code is executed.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:


#include <stdio.h>

int main()
{
//This is a comment
printf("Hello World!\n\n");
return 0;
}

C Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

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:

Fullname: Juan Dela Cruz


DOB: April 1, 2001
Contact No.: 0987654321
Address: Sitio Kamangahan, Brgy. Bato, Biliran, Leyte

1-2) Create a program in C to display the first stanza of your favorite Christmas song.
Sample program output:

First stanza of the song “Christmas In Our Hearts”


Whenever I see girls and boys Selling lanterns on the streets I remember the child
In the manger as he sleeps

1-3) Create a program in C to display the names and addresses of your elementary, secondary, and
tertiary schools.
Sample program output:

Elementary School: Culaba Central School


Address: Culaba, Biliran
Secondary School: Bool National High School
Address, Bool, Culaba, Biliran
Tertiary School: Naval State University
Address: Naval, Biliran

1-4) Create a program in C to display your favorite life motto.


Sample program output:

My favorite life motto is:


“Life is a never-ending process of learning.”
1-5) Create a program in C to display the five reasons why you enrolled in the BSCpE program.
Sample program output:

The reasons I enrolled to the BSCpE program are:


1.) I wanted to be able to fix computers.
2.) I wanted to learn how to create software.
3.) I enjoy the challenges in learning new things.
4.) BSCpE careers wages are above average.
5.) I wanted to control hardware using code.
Guide Questions

1. What is a variable in C?

2. Name three different types of variables in C.

3. How do you declare and assign a value to a variable in C?

4. Can you declare a variable without assigning a value to it initially?

5. What are format specifiers in C?

6. How do you print multiple variables of different types in a single printf() statement?

7. What happens if you assign a new value to an existing variable?

8. Can you assign the value of one variable to another?

9. List all arithmetic operators in C.

10. How do you declare multiple variables of the same type in C?

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

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of C types (such as int), and variableName is the name of the variable (such as x or

myName). The equal sign is used to assign a value to the variable.

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:

int myNum = 15;

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;

// Assign a value to the variable


myNum = 15;
return 0;
}
Format Specifiers

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.

A format specifier starts with a percentage sign %, followed by a character.

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

To print other types, use %c for char and %f for float:

#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

You can also assign the value of one variable to another:

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;

// Declare a variable without assigning it a value


int myOtherNum;

// Assign the value of myNum to myOtherNum


myOtherNum = myNum;

// myOtherNum now has 15 as a value


printf("%d", myOtherNum);
return 0;
}
Output

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

+ Addition Adds together two values x + y

- Subtraction Subtracts one value from another x - y

* Multiplication Multiplies two values x * y

/ Division Divides one value by another x / y

% Modulus Returns the division remainder x % y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

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)

All C variables must be identified with unique names.

These unique names are called 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;

// OK, but not so easy to understand what m actually is


int m = 60;
return 0;
}

The general rules for naming variables are:

✓ Names can contain letters, digits and underscores


✓ Names must begin with a letter or an underscore (_)
✓ Names are case-sensitive (myVar and myvar are different variables)
✓ Names cannot contain whitespaces or special characters like !, #, %, etc.
✓ Reserved words (such as int) cannot be used as names
Variables – Examples

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;

// Calculate the area of a rectangle


area = length * width;

// Print the variables


printf("Length is: %d\n", length);
printf("Width is: %d\n", width);
printf("Area of the rectangle is: %d", area);
return 0;
}

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

Basic Data Types


The data type specifies the size and type of information the variable will store.

In this module, we will focus on the most basic ones:

Data Type Size Description Example

int 2 or 4 bytes Stores whole numbers, without decimals 1

Stores fractional numbers, containing one or more


float 4 bytes 1.99
decimals. Sufficient for storing 6-7 decimal digits

Stores fractional numbers, containing one or more


double 8 bytes 1.99
decimals. Sufficient for storing 15 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII values 'A'


Basic Format Specifiers
There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type

%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() {

int myNum = 5; // integer


printf("Integer: %d\n", myNum);
printf("Integer: %i\n", myNum);

float myFloatNum = 5.99; // Floating point number


printf("Floating point: %f\n", myFloatNum);

double myDoubleNum = 19.99; // Double (floating point number)


printf("Double floating point: %lf\n", myDoubleNum);

char myLetter = 'D'; // Character


printf("Character: %c\n", myLetter);

char greetings[] = "Hello World!";


printf("String: %s\n", greetings);
return 0;

}
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;
}

Character Data Types


The char data type is used to store a single character.

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

Tip: A list of all ASCII values can be found here.

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

float vs. double


The precision of a floating point value indicates how many digits the value can have after the decimal
point. The precision of float is six or seven decimal digits, while double variables have a precision of
about 15 digits. Therefore, it is often safer to use double for most calculations - but note that it takes
up twice as much memory as float (8 bytes vs. 4 bytes).
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example

#include <stdio.h>
int main() {
float f1 = 35e3;
double d1 = 12E4;

printf("%f\n", f1);
printf("%lf", d1);
return 0;
}

Output

Set Decimal Precision


You have probably already noticed that if you print a floating point number, the output will show many
digits after the decimal point:

Example

#include <stdio.h>
int main() {
float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%f\n", myFloatNum); // Outputs 3.500000


printf("%lf", myDoubleNum); // Outputs 19.990000
return 0;
}
Output
If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a
number that specifies how many digits that should be shown after the decimal point:

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;
}

Get the Memory Size


We introduced in the data types chapter that the memory size of a variable varies depending on the
type:
Data Type Size

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.

Why Should I Know the Size of Data Types?


Knowing the size of different data types is important because it says something about memory usage
and performance.

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.

There are two types of conversion in C:

• Implicit Conversion (automatically)

• Explicit Conversion (manually)


Implicit Conversion
Implicit conversion is done automatically by the compiler when you assign a value of one type to
another.

For example, if you assign an int value to a float type:

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

You can also place the type in front of a variable:

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;

// The actual score of the user


int userScore = 423;

/* 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;

// Print the percentage


printf("User's percentage is %.2f", percentage);
return 0;
}
Output
Practice problem
Use type conversion to make sure that the result of the following example is 1.5, and not just 1.

#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:

const int minutesPerHour = 60;

This however, will not work:

#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

You have already learned that printf() is used to output values in C.

To get user input, you can use the scanf() function:

Example

Output a number entered by the user:

#include <stdio.h>
int main() {
// Create an integer variable that will store the number we get from the user
int myNum;

// Ask the user to type a number


printf("Type a number: ");

// Get and save the number the user types


scanf("%d", &myNum);

// Output the number the user typed


printf("Your number is: %d", myNum);
return 0;
}
Output

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;

// Ask the user to type a number AND a character


printf("Type a number AND a character and press enter: \n");

// Get and save the number AND character the user types
scanf("%d %c", &myNum, &myChar);

// Print the number


printf("Your number is: %d\n", myNum);

// Print the character


printf("Your character is: %c\n", myChar);
return 0;
}
Output
Real Life Programming 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) 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

Sample program output:

Input adjacent side: 3


Input opposite side: 4
The length of the hypothenuse is: 5

You might also like