KEMBAR78
01 - Introduction To C | PDF | Data Type | Variable (Computer Science)
0% found this document useful (0 votes)
6 views16 pages

01 - Introduction To C

Uploaded by

ol chanthoeun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

01 - Introduction To C

Uploaded by

ol chanthoeun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 1 Introduction to C

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.

Dev C++:
- Download: https://www.bloodshed.net/

Visual Studio Code:


- Download: https://code.visualstudio.com/download
- How to install: https://dev.to/narottam04/step-by-step-guide-how-to-set-up-visual-studio-code-
for-c-and-c-programming-2021-1f0i

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 a message Hello World on the console. We will save
the file as main.c.

Example 01: A C program that displays a message “Hello World” on the console.
/* 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

3
Chea Daly C Programming
If you are using the Dev C++ IDE, you will need to use the getch() function defined in conio.h header
file to hold the output screen.
Example 02: A C program that displays a message “Hello World”.
#include <stdio.h>
#include <conio.h> // to use getch() function

int main(){
printf("Welcome to C programming");

getch(); // getch() function is used to hold the output screen until the user
// passes any key.

return 0;
}

Output
Welcome to C programming

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

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

4
Chea Daly C Programming
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.

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)
int Integer type 4 bytes -2,147,483,648 to 2,147,483,647
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

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;
5
Chea Daly C Programming
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

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.

6
Chea Daly C Programming
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.

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

3.2 printf() function

printf() function sends formatted output to the console.

Example 03: 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 04: You can display multiple outputs using only one printf().
#include <stdio.h>
int main(){
int a = 10;
float b = 20.5;

printf("a = %d, and b = %g", a, b);

return 0;
}

Output
a = 10, and b = 20.5

Example 05: 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 06: 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.

9
Chea Daly C Programming
It is possible to specify the width without setting the precision. As shown in an example below.

Example 07: 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.

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 08: 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.

10
Chea Daly C Programming
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 09: 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.

Example 10: 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

11
Chea Daly C Programming
Example 11: 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

Example 12: 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 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)

12
Chea Daly C Programming
Example 13: 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;
}

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.

13
Chea Daly C Programming
The -- operator works in a similar way to the ++ operator except -- decreases the value by 1.

Example 14: 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

Example 15: 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

14
Chea Daly C Programming
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() {
float x = 9.5;
int sum = x + 1; // 9.5 + 1 = 10.5 --> 10
float division = (int) x / 4; // 9 / 4 = 2 --> 2.0

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


printf("division = %g", division);

return 0;
}

Output
sum = 10
division = 2

Exercises

1. 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.
2. Write a program to ask the 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.
3. Write a program to sum two integers entered by the user.
4. 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.
5. 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 weight 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.

15
Chea Daly C Programming
Reference
[1] Y. Daniel Liang. ‘Introduction to Programming with C++’, 3e – 2014
[2] Dey, P., & Ghosh, M. ‘Computer Fundamentals and Programming in C’, 2e – 2013
[3] https://www.programiz.com/c-programming
[4] https://www.studytonight.com/c/
[5] https://www.onlinetutorialspoint.com/c-program

16
Chea Daly C Programming

You might also like