0% found this document useful (0 votes)
16 views19 pages

01 - Introduction To C Programming

This document provides an introduction to C programming. It discusses what programming is, different programming languages, the structure of a C program including main functions and header files, basic data types in C, and variable declaration and initialization. It also covers comments, whitespace, and naming conventions for identifiers in C code.

Uploaded by

vuthivuthy99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views19 pages

01 - Introduction To C Programming

This document provides an introduction to C programming. It discusses what programming is, different programming languages, the structure of a C program including main functions and header files, basic data types in C, and variable declaration and initialization. It also covers comments, whitespace, and naming conventions for identifiers in C code.

Uploaded by

vuthivuthy99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Chapter 1 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.

Top Programming Languages (Jan 2024)

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.

2.1 Code Editor and Compiler


To write and execute C programs, you need a code editor and compiler.

Visual Studio Code:


- Download
- How to set up VSCode for C/C++

Online C compiler: https://www.onlinegdb.com/online_c_compiler


2
Chea Daly C Programming
2.2 A Simple C Program
Let’s begin with a simple C program that displays the message “Hello World” on a console.
Example 01: A C program that displays a message “Hello World”.
/* A Simple C Program
That print out the message "Hello World" */
#include <stdio.h>

int main(){
printf("Hello World"); // display hello world

return 0; // return 0 to operating system


}

Output:
Hello World

Now, let’s look at the structure of C programming by the above example.

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.

2.5 main() Function


A function is a group of statements that performs a specific task. Every C program has a primary function
that must be named main which serves as the starting point for program execution. An operating system
always calls the main() function when executing a program.

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.

2.6 Whitespace, Braces and Semicolon


C does not use whitespace except for separating words and symbols. However, even though the
whitespace is insignificant to the compiler, they are useful to make code readable for human beings. So,
often enough that C programmers would use whitespaces to make their code readable.

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).

Below are sizes and ranges of commonly used data types in C:

Datatype Description Size Range of Values


char Single-character type 1 byte 0 to 255 (ASCII Table)
short Integer type 2 bytes -32,768 to 32,767
int Integer type 4 bytes -2,147,483,648 to 2,147,483,647
long Integer type 4 bytes -2,147,483,648 to 2,147,483,647
long long Integer type 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float Floating-point type 4 bytes 3.4E-38 to 3.4E+38
double Floating-point type 8 bytes 1.7E-308 to 1.7E+308
long double Floating-point type 12 bytes 3.4E-4932 to 1.1E+4932
void Valueless 1 byte

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.

2.8 Declaration and Initialization


All variables in C must be declared to direct the compiler to actually allocate memory for the variable
before the variable is actually used.

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.

Syntax for declaring a variable:


datatype variable_name1 [= value1];

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.

int x = 10; // 10 is an 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.

Some examples of proper or valid identifiers are: employee_number, box_4_weight, monthly_pay,


interest_per_annum, job_number, and tool_4.

Some examples of incorrect or invalid identifiers are: 230_item, #pulse_rate, total~amount,


/profit_margin, and ~cost_per_item.

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:

const int AGE = 18;


AGE = 20; //Error

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

There are benefits of using constants:


- You do not have to repeatedly type the same value if it is used multiple times.
- If you have to change the constant’s value (e.g., from 3.14 to 3.14159 for PI), you need to change
it only in a single location in the source code.
- Descriptive names make the program easy to read.

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

3.1 Format Specifiers for I/O

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().

Below are commonly used format specifiers:

Datatype Format Specifier


char %c
short %hd
int %d, %i
long %ld, %li
float %f, %g
double %lf
long double %Lf
string %s

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.

3.2 printf() function

printf() function sends formatted output to the output screen.

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;

printf("Character = %c\n", chr); // output a character


printf("Age = %d\n", age); // output an integer
printf("PI = %f", PI); // output a floating-point number

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.

Example 05: Formatting a floating-point number.


#include <stdio.h>
int main(){
printf("%9f", 12.455);

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.

Example 06: Formatting floating-point to its nearest two decimal places.


#include <stdio.h>
int main(){
printf("%.2f", 12.455);

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.

3.3 scanf() function

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.

Example 07: Integer Input/Output


#include <stdio.h>
int main(){
int number;

printf("Enter an integer: ");


scanf("%d", &number);

printf("number = %d", number);

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;

printf("Enter a floating-point number: ");


scanf("%f", &number);

printf("number = %f", number);

return 0;
}

Output
Enter a floating-point number: 1.2
number = 1.200000

Example 09: Character Input/Output


#include <stdio.h>
int main(){
char chr;

printf("Enter a character: ");


scanf("%c", &chr);

printf("You entered %c.", chr);

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;

printf("Enter an integer and then a float: ");


scanf("%d%f", &a, &b); // Taking multiple inputs

printf("You entered %d and %g", a, 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)

Example 11: Working of arithmetic operators


#include <stdio.h>
int main(){
int a = 9, b = 4;

printf("a + b = %d \n", a + b);


printf("a - b = %d \n", a - b);
printf("a * b = %d \n", a * b);
printf("a / b = %d \n", a / b);
printf("a %% b = %d", a % b);

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.

Let’s see another exam below. Suppose a = 5.0, b = 2.0, c = 5 and d = 2.

// Either one of the operands is a floating-point number


a / b = 2.5
a / d = 2.5
c / b = 2.5

// Both operands are integers


c / d = 2

4.2 Increment and Decrement Operators


C programming has two operators, increment ++ and decrement --, to change the value of an operand
(variable) by 1.

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.

There is a little difference of using ++ and -- operator as prefix and postfix:


• If you use the ++ operator as a prefix like: ++var, the value of var is incremented by 1; then it
returns the value.
• If you use the ++ operator as a postfix like: var++, the original value of var is returned first;
then the var is incremented by 1.

The -- operator works in a similar way to the ++ operator except -- decreases the value by 1.

Example 12: Using increment operators


#include <stdio.h>
int main() {
int var1 = 5, var2 = 5;
printf("%d\n", var1++); // 5 is displayed. Then, var1 is increased to 6.
printf("%d", ++var2); // var2 is increased to 6. Then, it is displayed.

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

printf("%d %d %d %d", a, b, c, d);

return 0;
}

Output
3334

4.3 Assignment Operators

An assignment operator is used for assigning a value to a variable.

Operator Example Same as


= a=b a=b
+= a += b a=a+b
-= a -= b a=a–b
*= a *= b a=a*b
/= a /= b a=a/b
%= a %= b a=a%b

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;

printf("sum = %d", sum);

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

6. Mathematical Functions and Constants


We can do mathematical calculations on numbers using math features in C. The math.h header defines
various mathematical functions.
All the functions available in this library take double as an argument and return double as the result.

Function Description Example


sqrt(x) square root of x sqrt(4.0) is 2.0
exp(x) exponential (ex) exp(1.0) is 2.718282
log(x) natural logarithm of x (base e) log(2.0) is 0.693147
log10(x) logarithm of x (base 10) log10(10.0) is 1.0
fabs(x) absolute value of x fabs(2.0) is 2.0
fabs(-2.0) is 2.0
ceil(x) rounds x to smallest integer not less than x ceil(9.2) is 10.0
ceil(-9.2) is -9.0
floor(x) rounds x to largest integer not greater than x floor(9.2) is 9.0
floor(-9.2) is -10.0
round(x) rounds x to the nearest integer value. round(2.4) is 2
round(2.5) is 3
pow(x , y) x raised to power y (xy) pow(2,2) is 4.0
fmod(x) remainder of x/y as floating-point number fmod(13.657, 2.333) is 1.992
sin(x) sine of x (x in radian) sin(0.0) is 0.0
cos(x) cosine of x (x in radian) cos(0.0) is 1.0
tan(x) tangent of x (x in radian) tan(0.0) is 0.0

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

Example 20: Rounding numbers to two decimal places.


#include <stdio.h>
#include <math.h>
int main(){
float val = 37.777779;

printf("%g", round(val * 100) / 100);

return 0;
}

Output
37.78

C also provides the following mathematical constants in the header file math.h.

Constant Name Expression Value


M_E e 2.71828182845904523536
M_PI π 3.14159265358979323846
M_PI_2 π/2 1.57079632679489661923
M_PI_4 π/4 0.785398163397448309616
M_1_PI 1/π 0.318309886183790671538

Check a link below for more mathematical constants.


Math Constants | Microsoft Docs

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.

The complete program is shown as below:


#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
int main() {
// Assign a value to radius
int radius = 20;

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

You might also like