Lec - 2 C Programming
Lec - 2 C Programming
Lec - 2 C Programming
WITH C LANGUAGE
“Any fool can write code that a computer can understand. Good programmers write
code that humans can understand.” – Martin Fowler.
By Aphrodice Rwagaju
Rwanda Coding Academy
Page 1 of 22
CHAP 2. INTRODUCTION TO C Language
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was
designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the
more familiar languages of that time like PL/I, ALGOL, etc. ANSI C standard emerged in the early
1980s, it took several years for the compiler vendors to release their ANSI C compilers and for
them to become ubiquitous. C was initially designed for programming UNIX operating system.
Now the software tools as well as the C compiler are written in C. Major parts of popular operating
systems like Windows, UNIX, Linux are still written in C. This is because even today when it
comes to performance (speed of execution) nothing beats C. Moreover, if one is to extend the
operating system to work with new devices, one needs to write device driver programs. These
programs are exclusively written in C. C seems so popular because it is reliable, simple and easy
to use. Often heard today is – “C has been already superseded by languages like C++, C# and
Java.”
2.1 Program
There is a close analogy between learning a language like English and learning C language. The
classical method of learning English is to first learn the alphabets used in the language, then learn
to combine these alphabets to form words, which in turn are combined to form sentences and
sentences are combined to form paragraphs. Learning C is similar and easier. Instead of straight-
away learning how to write programs, we must first know what alphabets, numbers and special
symbols are used in C, then how using them. Constants, variables and keywords are constructed,
and finally how are these combined to form an instruction. A group of instructions would be
combined later on to form a program.
So, a computer program is just a collection of the instructions necessary to solve a specific
problem when it is executed by a computer. The basic operations of a computer system form what
is known as the computer’s instruction set. And the approach or method that is used to solve the
problem is known as an algorithm.
A computer program is usually written by a computer programmer and can be written in either
high-level or low-level languages, depending on the task and the hardware being used.
2.2 Programming language
A programming language is a formal language, which comprises a set of instructions that
produce various kinds of output. Programming languages consist of instructions for computers and
they are used in computer programming to implement specific algorithms.
Page 2 of 22
2.3 Ways of classifying programming languages
By considering the types of programming languages by level of access to the hardware, programming
languages are divided into two different levels:
Page 3 of 22
High level languages are not understood by the machine. So, it needs to be translated into machine
level by the translator.
2.3.1.2.1 Translator
A translator is software which is used to translate high level language as well as low level
language in to machine level language.
There are three types of translators namely: Compiler, Interpreter and Assembler.
Compiler and interpreter are used to convert the high-level language into machine-level
language.
The program written in high-level language is known as source program and the corresponding
machine-level language program is called as object program.
Both compiler and interpreter perform the same task but how they work is different. Compiler read
the program at-a-time and searches the error and lists them. If the program is error free then it is
converted into object program. When program size is large then compiler is preferred. Whereas
interpreter read only one line of the source code and convert it to object code. Interpreter checks
error, statement by statement and hence this process takes more time.
An assembler translates assembly language into machine code and is effectively a compiler for
the assembly language, but can also be used interactively like an interpreter.
Assembly language uses words called ‘mnemonics’, such as LOAD, STORE and ADD.
The instructions are specific to the hardware being programmed because different
CPUs use different programming languages.
And finally, every assembly language instruction is translated into a single machine
code instruction.
Page 4 of 22
Difference between Compiler and Interpreter
Compiler Interpreter
Translates the whole program to produce the Translates and executes one line at a time.
executable object code.
Compiled programs execute faster as they are Interpreted programs take more time to
already in machine code. execute because each instruction is translated
before being executed.
Users do not need to have the compile installed Users must have the interpreter installed on
on their computer to run the software. their computer and they can see the source
code.
Users cannot see the actual source code when Users can see the source code and can copy it.
you distribute the program.
Used for software that will run frequently or Used for program development and when the
copying software sold to a third party. program must be able to run on multiple
hardware platforms.
Page 5 of 22
• Specialized high-level languages have been developed to make the programming as quick
and easy as possible for particular applications such as, SQL specially written to make it
easy to search and maintain databases. HTML, CSS and JavaScript were also developed to
help people create web pages and websites.
2.3.1.2.2.2 Advantages of low-level languages
• Assembly language is often used in embeded systems such as systems that control a
washing machine, traffic lights, robots, etc.
• It has features that make it suitable for the following types of applications:
o It gives complete control to the programmer over the system components, so it can
be used to control and manipulate specific hardware components.
o It has very efficient code that can be written for a particular processor architecture,
so will occupy less memory and execute (run) faster than a compiled/interpreted
high-level language.
2.3.2 Interpreted vs. compiled languages
The distinction between interpreted and compiled languages has to do with how they convert high-
level code and make it readable by a computer. With interpreted languages, code goes through a
program called an interpreter, which reads and executes the code line by line. This tends to make
these languages more flexible and platform independent.
Compiled languages go through a build step where the entire program is converted into machine
code. This makes it faster to execute, but it also means that you have to compile or "build" the
program again anytime you need to make a change.
Page 6 of 22
programming languages. Instead, they are text-encoding systems made up of symbols that control
the formatting and structure of content on a page or document.
Back-end languages deal with storage and manipulation of the server side of software. This is the
part of the software that the user does not directly come into contact with but supports their
experience behind the scenes. This includes data architecture, scripting, and communication
between applications and underlying databases.
▪ BASIC
▪C
▪ C++
Page 7 of 22
▪ Java
Rather than focusing on the execution of statements, functional languages focus on the output of
mathematical functions and evaluations. Each function (a reusable module of code) performs a
specific task and returns a result. The result will vary depending on what data you input into the
function.
This type of language treats a program as a group of objects composed of data and program
elements, known as attributes and methods. Objects can be reused within a program or in other
programs. This makes it a popular language type for complex programs, as code is easier to reuse
and scale.
Page 8 of 22
• Ruby
2.5.4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web content,
or support processes in larger applications.
Instead of telling a computer what to do, a logic programming language expresses a series of facts
and rules to instruct the computer on how to make decisions.
Page 9 of 22
CHAP 3: C DATA TYPES
Broadly, there are 5 different categories of data types in the C language, they are:
Category Example
Basic character, integer, floating-point, double.
Derived Array, structure, union, pointer, function.
Enumeration Enums
Bool type true or false
Void Empty value
The C language has 5 basic (primary or primitive) data types, they are:
1. Character - ASCII character set or generally a single alphabet like 'a', 'B', etc.
2. Integer - Used to store whole numbers like 1, 2, 100, 1000, etc.
3. Floating-point - Decimal point or real numbers values like 99.9, 10.5, etc.
4. Double - Very large numeric values which are not allowed in Integer or Floating point
type.
5. Void - This means no value. This data type is mostly used when we define functions.
There are different keywords to specify these data types, the keywords are:
Datatype Keyword
Character char
Integer int
Floating-point float
Double double
Void void
Each data type has a size defined in bits/bytes and has a range for the values that these data types
can hold.
The size for different data types depends on the compiler and processor types, in short, it depends
on the Computer on which you are running the C language and the version of the C compiler that
you have installed.
3.2.1 Character
Page 10 of 22
The char datatype is 1 byte in size or 8 bits. This is mostly the same and is not affected by the
processor or the compiler used.
3.2.2 Integer
There is a very easy way to remember the size for int datatype. The size of int datatype is usually
equal to the word length of the execution environment of the program. In simpler words, for a 16-
bit environment, int is 16 bits or 2 bytes, and for a 32-bit environment, int is 32 bits or 4 bytes.
Unfortunately, this rule is not applicable in 64-bit environment where the size remains as the
same as in 32-bit environment.
3.2.3 Float
The float datatype is 4 bytes or 32 bits in size. It is a single-precision data type that is used to
hold decimal values. It is used for storing large values.
float is a faster data type as compared to double, because double data type works with very large
values, hence it is slow.
3.2.4 Double
The double datatype is 8 bytes or 64 bits in size. It can store values that are double the size of
what a float data type can store, hence it is called double.
In the 64 bits, 1 bit is for sign representation, 11 bits for the exponent, and the rest 52 bits are
used for the mantissa.
The double data type can hold approximately 15 to 17 digits, before the decimal and after the
decimal.
3.2.5 Void
The void data type is 0 bytes means nothing, hence it doesn't have a size.
Before moving on to the range of values for these data types, there is one more important concept
to learn, which is Datatype modifiers.
In the C language, there are 4 datatype modifiers, that are used along with the basic data types to
categorize them further.
Page 11 of 22
For example, if you say, there is a playground, the other person will know that there is a
playground, but you can be more specific and say, there is a Cricket playground or a Football
playground, which makes it even more clear for the other person.
Similarly, there are modifiers in the C language, to make the primary data types more specific.
1. signed
2. unsigned
3. long
4. short
As the name suggests, signed and unsigned are used to represent the signed (+and -) and unsigned
(only +) values for any data type. And long and short affects the range of the values for any
datatype.
For example, signed int, unsigned int, short int, long int, etc. are all valid data types in the C
language.
Now let's see the range for different data types formed as a result of the 5 primary data types along
with the modifiers specified above.
In the table below we have the range for different data types in the C language.
Format
Type Typical Size in Bits Minimal Range
Specifier
Char 8 -127 to 127 %c
unsigned char 8 0 to 255 %c
signed char 8 -127 to 127 %c
Int 16 or 32 -32,767 to 32,767 %d, %i
unsigned int 16 or 32 0 to 65,535 %u
signed int 16 or 32 Same as int %d, %i
short int 16 -32,767 to 32,767 %hd
unsigned short int 16 0 to 65,535 %hu
signed short int 16 Same as short int %hd
long int 32 -2,147,483,647 to 2,147,483,647 %ld, %li
-(263 - 1) to 263 - 1 (Added by
long long int 64 %lld, %lli
C99 standard)
signed long int 32 Same as long int %ld, %li
unsigned long int 32 0 to 4,294,967,295 %lu
Page 12 of 22
Format
Type Typical Size in Bits Minimal Range
Specifier
unsigned long long int 64 264 - 1 (Added by C99 standard) %llu
1E-37 to 1E+37 with six digits
Float 32 %f
of precision
1E-37 to 1E+37 with ten digits
Double 64 %lf
of precision
1E-37 to 1E+37 with ten digits
long double 80 %Lf
of precision
As you can see in the table above, with different combinations of the datatype and modifiers the
range of value changes.
When we want to print the value for any variable with any data type, we have to use a format
specifier in the printf() statement.
Well, if you try to assign a value to any datatype which is more than the allowed range of value,
then the C language compiler will give an error. Here is a simple code example to show this,
#include <stdio.h>
int main() {
// allowed value up to 65535
unsigned short int x = 65536;
printf(“%d\n”, x);
return 0;
}
When a type modifier is used without any data type, then the int data type is set as the default
data type. So, unsigned means unsigned int, signed means signed int, long means long int,
and short means short int.
Page 13 of 22
In simple words, the unsigned modifier means all positive values, while the signed modifier
means both positive and negative values.
When the compiler gets a numeric value, it converts that value into a binary number, which means
a combination of 0 and 1. For example, 32767 in binary is 01111111 11111111, and 1 in binary
is 01 (or 0001), 2 is 0010, and so on.
In the case of a signed integer, the highest order bit or the first digit from left (in binary) is used
as the sign flag. If the sign flag is 0, the number is positive, and if it is 1, the number is negative.
And because one bit is used for showing if the number is positive or negative, hence there is one
less bit to represent the number itself, hence the range is less.
For signed int, 11111111 11111111 means -32,767 and because the first bit is a sign flag to mark
it as a negative number, and rest represent the number. Whereas in the case of unsigned
int, 11111111 11111111 means 65,535.
#include <stdio.h>
int main()
{
return 0;
}
The output:
size of char: 1 bytes
size of signed char: 1 bytes
size of unsigned char: 1 bytes
size of int: 4 bytes
size of short int: 2 bytes
size of long int: 4 bytes
size of long long int: 8 bytes
Page 14 of 22
size of signed int: 4 bytes
size of unsigned int: 4 bytes
size of float: 4 bytes
size of double: 8 bytes
size of long double: 16 bytes
size of an integer number: 4 bytes
size of a real number: 8 bytes
size of "sizeof" result: 8 bytes
While there are 5 primary data types, there are some derived data types too in the C language
which are used to store complex data.
Derived data types are nothing but primary data types but a little twisted or grouped together like
an array, structure, union, and pointers. The derived datatypes will be discussed in detail later.
Page 15 of 22
CHAP 4. ALGORITHM
An Algorithm specifies a series of steps that performs a particular computation or task. It is a step
by step procedure of solving a problem. It was originally born as part of mathematics from the
Arabic writer Muḥammad ibn Mūsā al-Khwārizmī, and now strongly associated with computer
science. A good algorithm means an efficient solution to be developed.
Algorithms are mainly written in three (3) ways, including English-like algorithm, flow charts and
pseudocode.
4.1. English-like algorithm
An algorithm can be written in simple English but this method also has some demerits. Natural
language can be ambiguous and therefore lack the characteristic of being definite. Each step of an
algorithm should be clear and shouldn't have more than one meaning. English language-like
algorithms are not considered good for most of the tasks.
4.2 Flowchart
Flowcharts pictorially depict a process. They are easy to understand and are commonly used in
the case of simple problems.
Page 16 of 22
Flow chart symbols by conventions
4.3 Pseudocode
Most programs are developed using programming languages. These languages have specific
syntax that must be used so that the program will run properly. Pseudocode is not a
programming language, it is a simple way of describing a set of instructions that does not have
to use specific syntax.
Page 17 of 22
Writing in pseudocode is similar to writing in a programming language. Each step of the algorithm
is written on a line of its own in sequence. Usually, instructions are written in uppercase,
variables in lowercase and messages in sentence case.
The pseudocode has an advantage of being easily converted into any programming language.
This way of writing algorithm is most acceptable and most widely used. In order to write a
pseudocode, one must be familiar with the conventions of writing it.
Conventions of writing pseudocode:
1. Single line comments start with //
2. Multi-line comments occur between /* and */
3. Blocks are represented using brackets. Blocks can be used to represent compound statements or
the procedures.
{
statements
}
4. Statements are delimited by semicolon.
5. Assignment statements indicates that the result of evaluation of the expression will be stored in
the variable.
< variable > = < expression >
6. The boolean expression 'x > y' returns true if x is greater than y, else returns false.
7. The boolean expression 'x < y' returns true if x is less than y, else returns false.
8. The boolean expression 'x <= y' returns true if x is less than or equal to y, else returns false.
9. The boolean expression 'x >= y' returns true if x is greater than or equal to y, else returns false.
10. The boolean expression 'x != y' returns true if x is not equal to y, else returns false.
11. The boolean expression 'x = = y' returns true if x is equal to y, else returns false.
12. The boolean expression 'x AND y' returns true if both conditions are true, else returns false.
13. The boolean expression 'x OR y' returns true if any of the conditions is true, else returns false.
14. The boolean expression 'NOT y' returns true if the result of x evaluates to false, else returns
false.
15. if< condition >then< statement >
16. This condition is an enhancement of the above 'if' statement. It can also handle the case where
the condition isn't satisfied.
if< condition >then< statement1 >else< statement2 >
17. switch case
case {
:< condition 1 >: < statement 1 >
.....
.....
.....
:< condition n >: < statement n >
:default: < statement n+1 >
}
18. while loop
Page 18 of 22
while< condition >do {
statements
}
19. do-while loop
repeat
statements
until< condition >
20. for loop
for variable = value1 to value2 {
statements
}
21. input instruction
Read
22. Output instruction
Print
23. The name of the algorithm is < name > and the arguments are stored in the < parameter list >
Algorithm< name > (< parameter list >)
Note: Number 6 to Number 11 use relational operator, Number 12 to 14 uses logical operator,
and Number 15 and 16 uses conditional operator.
A simple program could be created to ask someone name and age, and to make a comment based
on these. This program represented in pseudocode would look like the following two examples:
Example 1:
START
DECLARE name, age
OUTPUT 'What is your name?'
INPUT name
STORE the user's input in the name variable
OUTPUT 'Hello' + name
OUTPUT 'How old are you?'
INPUT age
STORE the user's input in the age variable
IF age >= 70 THEN
OUTPUT 'You are aged to perfection!'
ELSE
OUTPUT 'You are a spring chicken!'
END
Page 19 of 22
Example 2:
START
END
Page 20 of 22
4.6 Programming Examples of Algorithm
a) Calculate the sum of two numbers (A and B) and print the sum to the console
1. Start
2. Declare number type variables: number one A, number two B and the sum
3. Input A
4. Input B
5. Compute A+B into Sum ( Sum ← A+B)
6. Output Sum
7. Stop
Pseudo code
var A,B, Sum;
get A;
get B;
Sum=A+B;
print Sum;
Flow chart
Page 21 of 22
Page 22 of 22