01 - Introduction To C Programming
01 - Introduction To C Programming
1. Introduction
Computers are powerful and have the potential to carry out tasks much faster than a human. But
computers themselves are not smart; they need a human to write instructions and tell them what to do.
However, computers do not understand human languages, so to tell the computer what to do, we must
write the instructions in a language the computer can understand.
Programming is the process of creating a set of instructions that a computer can understand to tell it
how to perform a task. Those program instructions are called Code.
There are hundreds of Programming Languages, such as C, C++, Python, Java, JavaScript, PHP, etc.
The best analogy we can think of are the spoken languages we use today. All languages express the same
idea in different ways to another person, for example:
English: Hello
French: Bonjour
Spanish: Hola
Khmer: សួសីត
All Programming languages also express the same idea in different ways, but to a computer instead. The
following will print out “Hello” in four different programming languages:
C:
#include <stdio.h>
int main() {
printf("Hello");
return 0;
}
C++:
#include <iostream>
int main() {
std::cout << "Hello";
return 0;
}
Java:
public static void main(String[] args){
system.out.println(“Hello”);
}
Python:
print ("Hello”)
1
Chea Daly C Programming
Each programming language has its own Syntax. Syntax is the grammatical structure of words and
phrases to create sentences. In English, we have grammar. The same applies to programming languages –
they each have their own set of rules.
https://statisticstimes.com/tech/top-computer-languages.php
2. C Programming Language
C was developed by Dennis Ritchie in 1972. Many later languages have borrowed syntax/features from C
language. Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on C
language.
int main(){
printf("Hello World"); // display hello world
Output:
Hello World
Multi-line comment
/* A Simple C Program
That print out the message “Hello World” */
Include header file #include <stdio.h>
single-line comment
return type int main() main function
{
printf("Hello World"); // display hello world
braces
return 0; // return 0 to operating system
}
return value
2.3 Comments
In C, you can place comments in your code that are not executed as part of the program. Comments
provide clarity allowing others to better understand what the code was intended to accomplish. Comments
are especially important in large projects containing hundreds or thousands of lines of code or in projects
in which many contributors are working on the code. Adding comments to your C source code is a highly
recommended practice.
In C, there are two types of comments:
- Single-line comment or Comment line starts with two forward slashes (//)
- Multi-line comment or Paragraph comment starts with a slash asterisk /* and ends with an
asterisk slash */.
3
Chea Daly C Programming
2.4 Header Files
A header file is a file with extension .h which contains C function declarations and macro definitions to
be used in any C programs.
You request to use a header file in your program by including it with the #include directive. In the
previous example, we need to include stdio.h header file since the printf(), which prints to the
console, is defined in it.
Some Operating Systems require a return value to check whether the program has successfully executed
or not. The int keyword indicates that the main function will return an integer. If the code was run
successfully, it would return the number 0. A number greater than 0 will mean that the program that we
wrote failed.
A statement is a syntactic construction that performs an action when a program is executed. All C
program statements are terminated with a semicolon (;).
Any sequence of statements can be grouped together to function as a single statement by enclosing the
sequence in braces { }. This grouping is known as statement block or compound statement, and a final
semicolon after the right brace is not needed.
4
Chea Daly C Programming
2.7 Data Types In C
C has five basic data types (also called ‘primitive’ types).
long is equivalent to long int, just as short is equivalent to short int. long long is also equivalent to long
long int.
void is an incomplete type. It means "nothing" or "no type". You can think of void as absent. For
example, if a function is not returning anything, its return type should be void. Note that, you cannot
create variables of void type.
The variable declaration defines the variable's type, specifying whether it is an integer, floating-point
number, character, or some other type.
Once you declare a variable to be of a particular type, you cannot change its type; If the variable x is
declared of type double, and you assign “x = 3;”, then x will actually hold the floating-point value 3.0.
int x;
When a variable is declared, the C compiler does not assign any value to the variable, unless it is
instructed to do so. The value of initialization is called the initializer.
5
Chea Daly C Programming
Syntax for declaring multiple variables:
datatype variable_name1 [= value1] [, variable_name2 [= value2], ...;
int x, y = 5;
Rather than always using x and y as variable names, choose descriptive names to make the program easy
to read. For example, you can use a name “radius” to store the value of the radius of a circle, or you can
use a name “area” to store the value of the area of a circle.
2.9. Identifiers
Identifiers or name is a sequence of characters created by the programmer to identify or name a specific
object such as variables, functions, etc.
Some rules must be kept in mind when naming identifiers. These are stated as follows:
1. The first character must be an alphabetic character or an underscore ‘_’.
2. All characters must be alphabetic characters, digits, or underscores.
3. The first 31 characters of the identifier are significant. Identifiers that share the same first 31
characters may be indistinguishable from each other.
4. Cannot be a keyword. A keyword is word which has special meaning in C.
2.10. Keywords
Keywords, also called reserved words, have strict meanings in C. They cannot be redefined or used for
anything other than their predefined purpose in a C program. They are used by the compiler to compile
the program. Use of variable names with the same name as any of the keywords will cause a compiler
error.
There are 32 words defined as keywords in C. They are always written in lowercase letters. A complete
list of these keywords is given in Table 8.7.
6
Chea Daly C Programming
2.11 Constants
A constant is an identifier that represents a permanent value. The value of a variable may change during
the execution of a program, but a constant represents permanent data that never changes.
One way to create a constant is using the const keyword. For example:
Another way to create constants is by using the #define directive. The #define directive allows the
definition of macros within your source code. Macro definitions are not variables and cannot be changed
by your program code like variables. For example:
#define PI 3.14
7
Chea Daly C Programming
3. Input and Output (I/O)
You can use scanf() function to take inputs from the user, and printf() function to display outputs to
the user. These two functions are defined in stdio.h
The format specifier is used during input and output. It is a way to tell the compiler what type of data is
in a variable during taking input using scanf() or printing using printf().
Note: %s says to print a string. There is no variable type for representing a string, but C does support
some string using arrays of characters which will be introduced in a later chapter.
Example 02: Using the printf() function to output values of variables and constants.
#include <stdio.h>
int main(){
char chr = 'a';
int age = 18;
const float PI = 3.14;
return 0;
}
Output
Character = a
Age = 18
PI = 3.140000
\n is the escape sequence for the new line. Words that come after \n will be pushed to a new line.
8
Chea Daly C Programming
Example 03: To get rid of the trailing zeros, you should use the "%g" format.
#include <stdio.h>
#define PI 3.14000
int main(){
printf("PI = %g", PI);
return 0;
}
Output
PI = 3.14
You can use more than the format specifier %f to format floating-point values. Here is a format you can
use in the printf() function’s formatting text:
%w.pf
The w sets the maximum width of the entire number, including the decimal place. The p sets precision.
Example 04: Round a floating-point number to its nearest two decimal places.
#include <stdio.h>
int main(){
printf("%9.2f", 12.455);
return 0;
}
Output
12.46
In the example above, printf() function outputs three spaces and then 12.46. Those four spaces plus
12.46 (five characters total) equal the 9 in the width. Only two values are shown to the right of the
decimal as the number has been rounded up to its nearest two decimal places.
It is possible to specify the width without setting the precision. As shown in an example below.
return 0;
}
Output
12.455000
In the example above, printf() function adds three zero to the end of 12.455 to make the whole number
width equal the 9 characters.
9
Chea Daly C Programming
And it is also possible to specify the precision value without setting a width, but it must be prefixed by the
decimal point. As shown in an example below.
return 0;
}
Output
12.46
In the example above, printf() function outputs three spaces and then 12.46 as the number 12.455 has
been rounded up to its nearest two decimal places.
scanf() is one of the commonly used function to take input from the user. The scanf() function reads
formatted input from the standard input such as keyboards.
return 0;
}
Output
Enter an integer: 4
number = 4
The scanf("%d", &number) takes an integer input from the user and stores it in the address of
number variable.
The scanf() function does not prompt for an input. It is a good programming practice to always use a
printf() function before a scanf() function for users of the program to know what they should enter
through the keyboard.
10
Chea Daly C Programming
Example 08: Float Input/Output
#include <stdio.h>
int main(){
float number;
return 0;
}
Output
Enter a floating-point number: 1.2
number = 1.200000
return 0;
}
Output
Enter a character: a
You entered a
11
Chea Daly C Programming
Example 10: I/O Multiple Values. Here is how you can take multiple inputs from the user and display
them.
#include <stdio.h>
int main(){
int a;
float b;
return 0;
}
Output
Enter an integer and then a float: 1 1.2
You entered 1 and 1.2
4. Operators
4.1 Arithmetic Operators
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Remainder after division (modulo division)
return 0;
}
12
Chea Daly C Programming
Output
a + b = 13
a-b=5
a * b = 36
a/b=2
a%b=1
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It is because both the
variables a and b are integers.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.
The -- operator works in a similar way to the ++ operator except -- decreases the value by 1.
return 0;
}
Output
5
6
13
Chea Daly C Programming
Example 13: Using decrement operators
#include<stdio.h>
int main(){
int a = 4, b = 4, c, d;
c = --a; // a decreases, then return the value. --> a = 3, c = 3
d = b--; // b return the value, then decreases. --> d = 4, b = 3
return 0;
}
Output
3334
5. Type Casting
Users can type cast the result to make it of a particular data type.
Syntax:
(type) expression
Example 16:
#include <stdio.h>
int main(){
double x = 1.2;
int sum = (int)x + 1;
return 0;
}
Output
sum = 2
14
Chea Daly C Programming
However, this does not work with char. For example,
#include <stdio.h>
int main(){
char chr = (char)1;
printf("%c", chr);
return 0;
}
Output
☺
If you want to convert an integer number into its corresponding character, you can simply add '0' to the
number.
Example 17:
#include <stdio.h>
int main(){
char chr = 1 + 48; //ASCII value of '1' is 49
printf("%c", chr);
return 0;
}
Output
1
You also cannot convert a character into a number using (char) either. For example,
#include <stdio.h>
int main(){
int num = (int)'1';
printf("%d", num);
return 0;
}
Output
49
Because it returns the ASCII value of the character instead of converting the character into an integer
number.
To convert a digit character into its corresponding integer number, you can simply subtract '0' from the
digit character.
15
Chea Daly C Programming
Example 18:
#include <stdio.h>
int main(){
int num = '1' - 48; //ASCII value of '1' is 49
printf("%d", num);
return 0;
}
Output
1
16
Chea Daly C Programming
Example 19: Using Mathematical Functions.
#include <stdio.h>
#include <math.h>
int main(){
printf("%g\n", sqrt(10.0));
printf("%g\n", pow(4.0,0.5));
printf("%g\n", round(5.5));
printf("%g", fmod(4.5, 1));
return 0;
}
Output
3.16228
2
6
0.5
return 0;
}
Output
37.78
C also provides the following mathematical constants in the header file math.h.
17
Chea Daly C Programming
To use Mathematical constants, you must first define _USE_MATH_DEFINES and then include math.h.
Example 21: Rounding numbers to two decimal places.
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
int main() {
printf("PI = %f", M_PI);
return 0;
}
Output
3.141592
7. Writing Programs
Writing a program involves designing algorithms and then translating them into programming
instructions, or code. When you code, you translate an algorithm into a program.
An algorithm describes how a problem is solved by listing the actions that need to be taken and the order
of their execution. Algorithms can help the programmer plan a program before writing it in a
programming language. Algorithms can be described in natural languages or in pseudocode (natural
language mixed with some programming code).
Example 22: Let’s first consider a simple problem of computing the area of a circle. The algorithm for
calculating the area of a circle can be described as follows:
Step 1. Assign a value to the circle’s radius.
Step 2. Compute the area by applying the following formula:
area = radius² * π
Step 3. Display the result.
// Compute area
float area = pow(radius, 2) * M_PI;
// Display results
printf("Area = %.2f cm2", area);
return 0;
}
18
Chea Daly C Programming
Output:
Area = 1256.64 cm2
Exercises
1. Write a program that displays the result of . The result must be a floating-point
number with three decimal places.
2. A runner runs 14 kilometers in 45 minutes and 30 seconds. Write a program that displays the
average speed in miles per hour. (Note that 1 mile is 1.6 kilometers.)
3. The US Census Bureau projects population based on the following assumptions: one birth every 6
seconds, one death every 15 seconds and one new immigrant every 45 seconds. Write a program to
display the population in the next five years. Assume the current population is 312032486, and one
year has 365 days.
4. Write a program to ask a user to enter two integer numbers, store each of them in a variable, then
swap the values of these two variables, and display the result after swapping.
For example, if the user enters 1, and you store this value in a variable called num1, the user enters 2
for second number, and you store this value in a variable called num2. After swapping, the value of
num1 is 2, and the value of num2 is 1.
5. Write a program to sum two integers entered by a user.
6. There are 2.204 pounds in a kilogram. Write a program to ask the user to enter a weight in kilograms
and convert it to pounds.
7. Write a program that reads in the radius and length of a cylinder and computes the area and volume
using the following formulas:
area = radius2 * π
volume = area * length
8. Write a program that calculates the energy needed to heat water from an initial temperature to a final
temperature. Your program should prompt the user to enter the amount of water in kilograms and the
initial and final temperatures of the water. The formula to compute the energy is:
Q = M * (finalTemperature – initialTemperature) * 4184
where M is the weight of water in kilograms, temperatures are in degrees Celsius, and energy Q is
measured in joules.
Reference
[1] Dey, P., & Ghosh, M. ‘Computer Fundamentals and Programming in C’, 2e – 2013
[2] https://www.programiz.com/c-programming
[3] https://www.studytonight.com/c/
[4] https://www.onlinetutorialspoint.com/c-program
19
Chea Daly C Programming