Programming Concepts and Logics Unit 5 … 283.
7. Useful for both small and large Useful for adding small sections of a
programs. They are used for program at a time and testing them
professional programming. quickly. They are useful for students
for developing programs interactively.
8. Most of the high-level programming Few high-level programming
languages have compiler program. languages have Interpreter program.
9. It is not required to translate the It is required to translate the program
program each time you want to run each time you want to run the
the program. program.
10. Examples: C, C++, JAVA etc. Examples: LISP, Scripting languages,
HTML and BASIC etc.
Here, we will discuss about the differences between program and software for a conceptual basis.
S.N. Programs Software
1. A set of instructions in sequence for A program or a group of programs
the computer to execute is called designed to perform tasks is called
program. software.
2. A program is what a computer runs. Software is a set of programs that
reside in memory.
Table 5.1 3. A program can be written for Software can be written for third party.
Difference 4. ourselves.
between 5. Program consists of coding only. Software consists of not only coding,
Program and but also program documentation and
manual.
Software
It may perform a single task. It may perform a set of tasks.
6. Small in size and consumes less Large in size and consumes large
memory. memory.
7. Developed by individual. Developed by a group of professionals.
8. Has limited functionality. Has wide range of functionality.
9. It takes less time to develop. It is time consuming.
CONCEPT OF PROGRAMMING STATEMENTS
Every program consists of a set of statements. A statement is a single command given to the computer to
perform a single well defined task. A statement is a smallest standalone element of a programming
language. ADD, START, STOP, SAVE are some of the simple statements, each of them can perform a
single task. The statements may have other components, and it can be simple or compound. The syntax
and semantics of statements depends on the programming language. Therefore, the number of necessary
steps and their level of details do controlled by the programming language.
As mentioned, a statement enables a program to take action. The actions can be declaring a variable,
assigning values, looping, branching etc. A statement may consist of a single line of code and called simple
statement or a series of statements in a block called compound statement. The statement is also known as
expression as well as sentence in English.
Approved by Curriculum Development Centre (CDC), Nepal
.284 … Computer Science–I
For example;
Simple or expression statements;
Assignment statement : A = 5
S=B+C
Increment statement : ++i
Return statement : Return 7
Goto statement : goto 10 etc.
A compound statement embeds statements within other statements. It contains several individual
statements within the block, and the individual statements may themselves be expression statements or
compound statements. For example;
i. Block
{L = 5;
B = 4;
Perimeter_of_Rectangle = 2 * (L + B);
Area_of_Rectangle = L * B;}
In this example, the set of individual statements enclosed within a pair of braces { } constitute a
compound statement (Curly braces and semicolons are used in C language syntax).
ii. IF-ELSE
IF condition THEN
Do Statement
ELSE
Do Statement
ENDIF
iii. WHILE Loop
WHILE Condition
Do Statement
ENDWHILE
There is one more statement called 'control statement', which is used for logical testing, branching or
looping, and control the flow of program control or execution. The above two examples fall under
this category as well.
SYNTAX AND SEMANTIC ERRORS
Every programming language has a set of vocabulary or key words and a set of rules or procedures that
must be followed while developing a program. This is called syntax of a language. 'Syntax' is more or less
synonymous with 'grammar'. It is a surface form or structure of the language. It refers to the ways symbols
may be combined to create well-formed sentences (or programs) in the language. Therefore, syntax defines
the formal relations between the constituents of a programming language to make the legal strings in the
program. Syntax deals solely with the form and structure of symbols in a language without any
consideration given to their meaning.
A program consists of a set of commands or expressions. An expression is a combination of variables,
constants and operators arranged as per the syntax (grammar) of the language. Any deviation from the
syntax or mismatch in the key words of the language in the program results in errors called syntax errors.
The syntax errors are detected by the compiler during compilation process, and the program terminates by
displaying these errors.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 285.
Let's consider an example in DOS. The command for copying a file "Matrix" from a folder "Math" in C:
drive to floppy disk is;
C:\>copy C:\Math\Matrix A:
copy C:\Math\Matrix A: is the syntax required to copy a file named Matrix in Math folder of C: drive to a
floppy disk. But, if we write the above syntax as;
C:\> copy C:\Math\Matrix A (missing colon:)
The computer will display an error message" ……………………".
This is called syntax error, because it was generated due to error(missing colon, A instead of A:) in the
format of the command.
If we write the above syntax as;
C:\>copy C:\Math\Matrix K:
Then, again, the syntax is correct; because the file can be copied to drive indicated by K. But, since we
couldn't find any drive named 'K' in any computer, there will be an error while copying the file. This is
called semantic error, because 'K' doesn't have any meaning in computer as storage drive.
Semantics is the study of the meanings of linguistic expressions. Semantics reveals the meaning of
syntactically valid strings in a language. Semantics describes the behavior that a computer follows when
executing a program in the language. A syntactically correct program may have semantic errors due to
wrong path, wrong condition, incorrect order of operation etc.
Let’s consider a simple example in natural language;
If we want to find the sum of two numbers A and B, in which B must be greater than zero and less than or
equal to five, then we can write;
If B > 0 and B < = 5
Then
Sum = A + B
This will give the correct result, because the above expressions are syntactically and semantically correct.
But, if we write the above expressions as;
If B > 0 and B < 5
Then
Sum = A + B
This expression is also syntactically correct, and will also give the result. But, the result may not be correct,
because the meaning of B < = 5 and B < 5 is different. The first expression can accept B = 5; and any
number less than equal to 5 and greater than zero. But, the second expression will not accept the number
B = 5, because the syntax used is B < 5. Hence, this is called semantic error for the given problem. The
program having semantic error will be compiled, but the result will be wrong.
The semantic errors can be run time error, logical error or latency error.
1. Run time error: Run time errors are detected only while running the program. The program can be
compiled and run, but the result will be erroneous. The errors caused by mismatch of data types (eg.
use of integer instead of float), not enough memory to run etc is called run time errors. These errors
are difficult to isolate.
2. Logical Error: The errors related with the logic of the program are called logical errors. These errors
can be caused due to a wrong path, elimination of some conditions or inclusion of unnecessary
conditions, incorrect order of statements in the program, improper order of use of operators etc.
Approved by Curriculum Development Centre (CDC), Nepal
.286 … Computer Science–I
Therefore, they are not syntax errors, and are related with the semantics of the program. The logical
errors are not detected by the compiler, and no error message is displayed during compilation. They
can only be found out when the program runs and produces wrong result.
For example;
while (A!=B) is a syntax for a loop and is correct. But, while executing the program, it may cause an
infinite loop and the program may not terminate.
3. Latency Error: This is also a kind of semantic error. This error is generally called "hidden error" that
is displayed only when a particular set of data items are used. For example;
R=A+B/X–Y
In computer calculation, there will be error only when X and Y become equal, and division by zero
occurs.
Because, all types of semantic errors are related with the logic of the program and meaning of the
syntax of program, they are commonly also known as "logical errors".
S.N. Syntax errors Semantics error
1. Syntax is related with the Semantics is related with the correct
vocabulary or keywords and rule to meaning of the 'grammar' or syntax.
use those keywords; i.e the
'grammar' of the language.
2. Syntax of a language describes the Semantics handles the meaning given to
Table 5.1 possible combinations of symbols a combination of symbols.
Difference that form a syntactically correct
between Syntax program.
Errors and 3. Syntax errors are detected by the Semantics errors aren't detected by the
compiler. compiler.
Semantic Errors
4. The error message will be Incorrect result will be displayed while
displayed while compilation. running the program.
5. Also called 'lexical' error. Also called 'logical error'.
6. Easy to find the syntax errors. Difficult to find the semantic errors.
7. Syntactically correct program may Semantically correct program can be
not be semantically correct. syntactically correct.
PROGRAM CONTROL STRUCTURES
We have already discussed about the concept of program and software. Any program consists of a set of
instruction arranged in a logical sequence according to the syntax of the programming language. Every
syntactically and semantically correct program has start and end point. A large program can be divided
into number of smaller program segments called modules. Each module is an entity that defines specific
processing activities and executes a single task. The modules can be organized into a hierarchical
structure, similar to organization chart of any organization, as shown below.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 287.
Figure: 5.3 Hierarchical Structure
Depart. 1
Section 1 Section 2 Section 2 Section 3
Section 1 Section 2
The breaking down of a large program into simple, easily understandable smaller modules in a
hierarchical order is a top down approach, called structured programming. In structured
programming, every program module has one entry point and one exit point, and this makes the
program run in logical sequence. It avoids the indiscriminate use of control statements.
Every program must follow some standard structure. A program consists of a number of statements
which are usually executed in sequence. Programs can be much more powerful if we can control the
order in which statements are run. A program is usually not limited to a linear sequence of
instructions. The program may need to bifurcate, repeat code or take decisions. For this purpose, the
program must be able to decide what has to be done, when and under which circumstances. The
control structure provides this capability to the program. The one entry and one exit concept of
structured programming uses three basic structures (statements):
1. Sequential: The statements in code are sequential (even when the sequences are run in parallel or
concurrently)
2. Selection: Program control may be transferred from one sequence to another sequence of
instructions
3. Iteration: A given sequence is repeated.
These three structures are also called basic programming constructs.
Sequential Structure
The sequential structure is also known as 'straight line' structure. It doesn't have any jump, branch or
looping statements. The flow of control passes from one statement to the next in sequence. That means the
control flows in a straight line, generally executing statements one after another sequentially from top to
bottom and left to right as shown in the fig. 5.5.
For example;
START
LOAD A
LOAD B
SUM A, B
STORE SUM
END
Approved by Curriculum Development Centre (CDC), Nepal
.288 … Computer Science–I
Figure: 5.4 Sequence Structure
Entry
Statement 1
Statement 2
Statement 3
Exit
Selection or Branching Structure
It is a control structure. Selection structure is a two-way branching structure because the flow of control
follows either one of two paths. The control first tests the condition and makes decision. If the condition is
satisfied (turns out to be TRUE), then the control follows PATH1, and if the condition doesn't satisfy
(FALSE) then the control follows PATH2 as shown in fig. 5.5. Therefore, Selection is a method of selecting
one of two or more paths of computations. The decision can be based on comparison of two variables or
sign of a variable etc. The branching statement may include a single statement or a group of statements
can be included in selection statements.
Figure: 5.5a Figure: 5.5b
ENTRY ENTRY
FALSE Test ? TRUE Test ? PATH1
PATH1
PATH2 PATH2
Statement(s) Statement(s) Statement (s)
Exit Exit
In fig. 5.5a, the condition is first tested, and if the condition is TRUE, statements in PATH1 executed. But, if
the condition is FALSE, the statements in PATH2 are executed. Similarly, in fig. 5.5b, the condition is
tested first, and either of the two paths is selected depending on the condition. PATH1 by passes some
steps, while PATH2 executes the statement(s) on the path. The branches in each figure may join later, and
exit from the same point. This type of branching is called 'forward jump'.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 289.
The selection structure is similar to IF-THEN-ELSE statements as shown below.
IF Percentage > = 60
THEN
Division = "First"
ELSE
Division = "Second"
(Here, IF-THEN indicates PATH1 and ELSE indicates PATH2)
Iteration or Looping Structure
It is control statement or structure. The simple meaning of iteration is 'repetition'. Therefore, iteration or
looping means repeated execution of one or more steps. In this type of structure, the condition is tested,
and the statement(s) are executed until the condition is met. Once the condition is satisfied, the control
exits the loop and executes other statements.
There are two types of loops. If the operation is repeated for a fixed number of times, then the loop is
called 'fixed loop'. In a fixed loop, the values of the variables inside the loop do not have any effect on the
number of iterations. The second loop is called 'variable loop' in which the operations are repeated until a
specified condition is met. In variable loop, the number of iterations may vary. For example; searching a
number within a group of numbers organized randomly.
Since the looping or iteration executes the statement(s) repeatedly, the control must flow back to execute
the same statement(s) Therefore, the iteration control structure is also called 'backward jump'.
Figure: 5.6 Iteration Control Structure
Entry
Entry
Test Condition False
Statements
True True
Statements
Test Condition
False Exit
b. Test and Do
Exit
a. Do and Test Approved by Curriculum Development Centre (CDC), Nepal
.290 … Computer Science–I
Fig. 5.6(a) shows a looping structure in which the statement(s) is executed at least once before checking the
condition, and the control enters into the loop until the condition is satisfied. This type of loop is also
called post tested loop, because the condition is tested only after executing the statement(s) first. But, fig.
5.6(b) is known as 'pre-tested loop', because the condition is checked first and then only the statements are
executed until the condition is satisfied. Otherwise, the control skips the statements within the loop.
FOR, WHILE, DO-WHILE are some of the control functions to carry out the looping structure. For
example;
WHILE (Percentage > = 80)
Distinction = Distinction + 1
ENDWHILE
PROGRAM DESIGN TOOLS
A computer can be used to solve varieties of problems or make decisions. It can be used in any field such
as education, science and engineering, mining, space exploration, business, industries and automation,
home and office, communication and data processing, travel and tourism, research, design and
development etc. We can find hardly any area where computer is not used. But, we know that computer is
a useless and dead machine without human intervention or instructions. We give instructions to the
computer in the form of program. A program is a set of step-by-step instructions that directs the computer
to do the tasks you want it to do and produce the results you want. Therefore, the computer must be
provided with the method and detail procedure to solve the problem or make decision.
The development of program is not as straight forward as it seems at first sight. The programmer must
have a detailed knowledge of the programming language, understand the facts and problems, objectives
and users of the program, have deductive and reasoning skills to solve the problem. The programmer
must understand the different ingredients involved in the problem, create logical link between them,
analyze the cause and effect, and break down the problem into logical sequence. The actual development
of the program or using the computer to solve the problem comes at last. All the remaining works
including preparatory tasks should be performed by the programmer before hand. The most important
task is representing the problem into easily understandable format in order to develop the program. There
are various tools which can be used to represent the program in logical order before starting actual coding
of the program.
Program development process follows almost the same steps as any problem solving task. There are five
major steps in the process of program development. They are;
1. Defining the problem
2. Planning the solution
3. Coding the program
4. Testing/modifying the program
5. Documenting the program
The first step involves problem analysis, and specifying the input, process, and output required. In the
planning phase, computer related work begins. It is a structure or detail design phase. We plan the
solution to the given problem using standard program development tools. Program development tools
help to visualize what the program is going to do, and how it is going to do it. It is a blue print of a
computer system solution to a given problem having the same components and inter-relationship as the
original problem. Input, output and processing specifications are drawn up in detail. The commonly used
program development tools are algorithm, flow chart and pseudo code. One or more of these tools can be
used while developing a program.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 291.
Algorithm
The logical, concise list of procedures or steps required for solving the problem is called algorithm. It
consists of a finite set of rules giving a sequence of operations expressed in simple English like sentences
for solving a specific type of problem.
General features of an algorithm
• Includes clear specification of inputs
• Uses internal variables
• Provides clear prior specification of program steps
• Uses 'goto' to transfer the control to a step other than next.
• Uses conditionals (if .. then ... else), and looping (bounded loops, while & until loops)
• Uses of subroutines to perform subtasks
• Uses termination condition
Characteristics of an algorithm
• Finiteness: An algorithm uses finite number of logical steps, and terminates after executing those
steps.
• Definiteness: Each step must be defined precisely and unambiguously, and must be self explanatory.
• Input: An algorithm may have zero or more legal or valid inputs sets.
• Output: An algorithm may have one or more outputs as a function of input and process.
• Effectiveness: Every step should be executed exactly and in finite time, and give the desired result.
• Design Aid: An algorithm is a basis for developing the flow chart, and helps designing the solution
effectively and efficiently.
• No Standard Format or Syntax.
• Language Independent:
Example 1
An algorithm to convert temperature in centigrade into Fahrenheit.
Step 1 : Start
Step 2 : Read the temperature in centigrade.
Step 3 : Store the value in C
Step 4 : Set F to 32+(9× C/5)
Step 5 : Print the value of C , F
Step 6 : Stop
(Here, we can omit step 3, & still get the same output)
Example 2
An algorithm to find the sum of a list of salaries.
Step 1 : Start
Step 2 : Set TOTAL SALARY to 0.
Step 3 : Proceed through salary list adding each persons SALARY to TOTAL SALARY.
Approved by Curriculum Development Centre (CDC), Nepal
.292 … Computer Science–I
Step 4 : At the end of list, Output TOTAL SALARY.
Step 5 : Stop
The above algorithm can also be written as;
Step 1 : Start
Step 2 : Set TOTAL SALARY to 0, I to 0, Read Total number of Persons N in the list.
Step 3 : Read the Salary of Ith person
Step 4 : Set TOTAL SALARY = TOTAL SALARY + Salary of Ith Person, I = I +1
Step 5 : Check whether I > N. If I > N then goto step 5 ELSE goto step 3
Step 6 : Output TOTAL SALARY.
Step 7 : Stop
Flow Chart
The algorithm must be converted into program in order to use the computer to solve the problem. Instead
of directly converting the algorithm into program, an intermediate step called flow chart, is used before
developing the program. The pictorial representation of the programs steps or the algorithm is known as
flowchart. It is nothing but a diagrammatic representation of the various steps involved in designing a
solution to the given problem. It uses graphical symbols, and the operating steps are placed in the boxes
interconnected by arrows which indicate the sequence of flow of execution or control.
Flowcharts facilitate communication between programmers and business people. These flowcharts play a
vital role in the programming of a problem and are quite helpful in understanding the logic of complicated
and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high
level language. Often, flowcharts are helpful in explaining the program to others. Hence, it is correct to say
that a flowchart is a must for the better documentation of a complex program.
Some of the symbols which are used in flowcharts are:
Figure: 5.7 Flow Chart Symbols
Start and Stop Input and Output Process
Flow of data
Document Connector Decision
Each symbol contains information about what must be done at that point & the arrow shows the ‘flow of
execution’ of the algorithm i.e. they show the order in which the instructions must be executed. The
purpose of using flowcharts is to graphically present the logical flow of data in the system, and defining
major phases of processing along with the various media to be used.
Flowcharts are of three types:
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 293.
• System flowcharts
• Run flowcharts
• Program flowcharts
a. System Flowcharts: System flowchart describes the data flow for a data processing system. It
provides a logical diagram of how the system operates. It represents the flow of documents, the
operations performed in data processing system. It also reflects the relationship between inputs,
processing and outputs. Following are the features of system flowcharts:
• the sources from which data is generated and device used for this purpose
• various processing steps involved
• the intermediate and final output prepared and the devices used for their storage
Figure: 5.8 System Flow Chart
Start
Prompt
the user
Store the value
in C
Is C=0 True
False
Store
32+(9C/5) to F
Print C,F
Stop
b. Run flowcharts: Run flowcharts are used to represent the logical relationship of computer routines
along with inputs, master files, transaction files and outputs. Figure5.9 illustrates a run flowchart.
Approved by Curriculum Development Centre (CDC), Nepal
.294 … Computer Science–I
Figure: 5.9 Run Flow Chart
Input Input
data transaction
Run 1
Display
temperature in C
Run 2
Calculate F
Run 3 Forms with C
Print C and F value
c. Program flowcharts: A program flowchart represents, in detail, the various steps to be performed
within the system for transforming the input into output. The various steps are logical/ arithmetic
operations, algorithms etc. It serves as the basis for discussions and communication between the
system analysts and the programmers. Program flowcharts are quite helpful to programmers in
organizing their programming efforts. These flowcharts constitute an important component of
documentation for an application. Figure 5.10 represents a program flowchart for finding the sum of
first five natural numbers ( i.e. 1,2,3,4,5).
Figure: 5.10 Program Flow Chart
Start
S=0
I=1
S=S+I
I = I+1
True Is I > S? False Print
"SUM=";S
Exit
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 295.
Figure: 5.11 A Flow Chart to Convert Temperature in Centigrade into Fahrenheit
Start
Enter
Temperature C
F = 32 + (C*9/5)
Output C, F
Stop
Advantages of Flow Chart
The benefits of flowcharts are as follows:
1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem can be analyzed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part
Limitations of Flow Chart
1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
4. The essentials of what is done can easily be lost in the technical details of how it is done.
Approved by Curriculum Development Centre (CDC), Nepal
.296 … Computer Science–I
Example 3
Draw a flowchart to find the sum of first 50 natural numbers.
Figure: 5.12 Flowchart for computing the sum of first 50 natural numbers
Start
SUM = 0
N=0
N=N+1
SUM = SUM + N
False IS N=50?
True
PRINT
SUM
Exit
Example 4
Draw a flowchart to find the largest of three numbers A, B, and C.
Figure: 5.13 Flowchart for finding out the largest of three numbers
START
READ three
numbers A, B, C
True Is B>C False Is A>B True Is A>C True
False
False
Print B is Print C is Print A is
greater greater greater
STOP
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 297.
Example 5
Draw a flow chart for computing factorial N (N!); Where N! = 1 ´ 2 ´ 3 ´ …… N .
Figure: 5.14 Flowchart for computing factorial N
Start
READ N
M=1
F=1
F=F*M
False IS M=N?
M = M+1
True
PRINT F
Stop
Pseudo code or Structured English
Pseudo means 'not genuine or pretended'. Therefore, pseudo code means not a true program code, but is a
code that gives some reflection of guide line for actual coding. Structured English is a concept adopted
from structured programming, and used as program design tool. It uses logical constructions and
imperative sentences designed to carry out instructions for action. The sentences are similar to simple
sentences in English. Therefore, structured English is the use of English language with the syntax of
structured programming. Decisions are made through IF, THEN, ELSE and SO statements. Therefore,
structured English aims at getting the benefits of both the programming logic and natural language.
Program logic helps to attain precision while natural language helps in getting the convenience of spoken
languages.
Elements of Structured English: Structured English consists of the following elements:
1. Operation statements written as simple English phrases executed towards bottom starting from the
top. It contains simple English statements such as add, multiply, move, etc. (uses strong, active,
specific verbs)
2. Conditional blocks indicated by keywords such as IF, THEN, and ELSE
3. Repetition blocks indicated by keywords such as DO, WHILE, and UNTIL
Use the following guidelines when writing Structured English:
1. Statements should be clear and unambiguous.
2. Use one line per logical element.
3. All logic should be expressed in sequential, decision or repetition structure blocks.
Approved by Curriculum Development Centre (CDC), Nepal
.298 … Computer Science–I
4. Logical blocks should be indented to show relationship and hierarchy.
5. Keywords like IF, ELSE, THEN, SO, WHILE, LT, LE, TRUE, FALSE, AND, OR, CREATE, DELETE,
EXIT, UNTIL, END, REPEAT, BEGIN, START, STOP etc. should be capitalized.
6. When words or phrases have been defined in the Data Dictionary, underline those words or phrases
to indicate that they have a specialized, reserved meaning.
7. Make careful use of "and" and "or" as well as "greater than" and "greater than or equal to" and other
logical comparisons.
Example 6
Consider a bank which grants loan under the following conditions;
If a customer has an account with the bank and had no loan outstanding, loan will be granted.
If a customer has an account with the bank but some amount is outstanding from previous
loans then loan will be granted if special approval is obtained.
Reject all loan applications in all other cases
IF customer has a Bank Account THEN
IF Customer has no dues from previous account THEN
Allow loan facility
ELSE
IF Management Approval is obtained THEN
Allow loan facility
ELSE
Reject
ENDIF
ENDIF
ELSE
Reject
ENDIF
CODES
Digital computer is based on discrete system, and uses digital circuit elements that have two distinct states
ON or OFF. These two states are represented by two distinct values. The number system that has two
distinct values is called base two systems (binary number system). The binary digits are '0' and '1', and
each digit is called bit. Any discrete system can be represented using a combination of 1's and 0's. For
example 4,5,6 are three discrete elements in a group of decimal digits, A is a distinct letter of the alphabet.
Digital computer understands the binary code only, digital circuits operate on two state systems, and
registers store binary bits. So everything that we enter into the computer or process within computer must
be represented in binary form. For example decimal 5 can be represented by 101 using three bits binary
code. Three bits are required to represent decimal values 0 to 7. Similarly, at least four bits code is required
to represent decimal digits 0 to 15 in binary form. Therefore, n bits can be used to represent 2n distinct
elements. The n bit code can be used to count from 0 to 2n – 1 distinct binary state. Decimal digits (0-9) can
be represented in binary form using four bits. But, four bits can count up to 16 distinct states; the
remaining bit combinations are unassigned and unused.
There are different types of codes to represent the discrete systems in binary form, and each of them may
use different numbers of bits or different bit combinations. They may also be used for different purposes.
Here, we will discuss about BCD, ASCII, EBCDIC, Unicode, and absolute binary codes.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 299.
Binary Coded Decimal (BCD) Code
BCD is sometimes also called decimal code, because it is a simplest code used to represent the decimal
digit in binary form. BCD is almost similar to the straight forward conversion of individual decimal digits
into binary form. But, each decimal digit must be converted into four bit binary to get the BCD code.
Therefore, there is a difference between the direct binary conversion and code form for the given decimal
number. The direct conversion of decimal digit gives binary digits, while the use of code produces a
combination of 1's and 0's according to the rule of the code. For example; binary equivalent of decimal
value 12 is 1100. But, in BCD code decimal number 12 has the code 0001 0010.
Weights can be assigned to each binary bit in BCD code according to their positions. The weights in BCD
code are 8, 4, 2, 1. Therefore, BCD code is sometimes also known as 8421 code. The bit combination 1001
can be interpreted by the weights, which gives decimal digit 9 as shown below.
1x8+0x4+0x2+1x1=9
The BCD code for the decimal digits is shown in the table 5.4.
Gray Code (Absolute Binary Code)
Many system give analog data. The analog data must be represented in digital format in order to use in
digital computers. A code that is used to represent the digital data converted from analog data is called
gray code. It is also known as reflected code or absolute binary code. The bits are arranged in such a way
that number in gray code changes by only one bit (0 to 1 or 1 to 0) from one number to the next. It is used
in shaft encoder to represent the continuous angular change in position of a shaft in digital form. The BCD
and gray code of some decimal equivalent are shown in table 5.4.
Decimal Digit BCD (8421) Code Gray Code
Table 5.4 0 0000 0000
BCD and Gray code 1 0001 0001
2 0010 0011
3 0011 0010
4 0100 0110
5 0101 0111
6 0110 0101
7 0111 0100
8 1000 1100
9 1001 1101
10 0001 0000 1111
11 0001 0001 1110
12 0001 0010 1010
Alphanumeric Code
Computer can be used to process or store varieties of data. The data can be alphabets, numeric, textual or
combination of both or some special characters or symbols. The combination of numeric and textual
elements is called alphanumeric. Therefore, not only the numbers, alphabets, punctuation marks, and
special control characters should also have some binary code. That means, all the ten decimal digits, 26
letters of alphabet, and some special characters should have some form of binary code; and this binary
code is called alphanumeric code. Here, the total numbers of alphanumeric characters is greater than 36.
Therefore, to represent at least 36 distinct elements, we need at least 6 bits (25=32 is not enough, and 26= 64
Approved by Curriculum Development Centre (CDC), Nepal
.300 … Computer Science–I
is greater than 36). But, if we consider both the lowercase and upper case letters of alphabets and some
special control characters for the transmission of information, the number of characters can be more than
64. Hence, the six bit code will be insufficient, and we need more than 6-bit code. Under the alphanumeric
code, we will discuss two codes; ASCII and EBCDIC codes.
ASCII Code
ASCII stands for American Standard Code for Information Interchange. ASCII is a alphanumeric binary
code for representing English characters which includes upper and lower case letters of alphabet, decimal
digits 0 to 9, and some special characters and symbols. 128 characters can be coded using ASCII code, and
each character is assigned a number from 0 to 127. Therefore, ASCII is a 7-bits code (27=128 elements). The
characters that can be typed are defined by ASCII code. ASCII code contains 94 characters (26 uppercase
letters A to Z, 26 lowercase letters a to z, 10 numerals 0 to 9, and 32 special printable characters such as %,
*, $, #, & etc) that can be printed and 34 non printing characters used for control functions. The seven bits
of the code are represented as x6x5x4x3x2x1x0. The first 3-bits are called zone bits and last 4-bits are used for
digit values.
There are some larger character sets that use 8 bits, and the code capacity is extended to 256 characters
(28=256). The extra 1-bit is used to represent non-English characters such as Greek alphabet or italic type
font, parity, graphics symbols, and mathematical symbols. ASCII code is used to represent text files, but
numeric data files are generally not stored in ASCII format. ASCII format is never used for Executable
programs.
EBCDIC
EBCDIC (eb-sih-dik) stands for Extended Binary Coded Decimal (BCD) Interchange Code. It is an IBM
code widely used in IBM equipment for representing characters as numbers. EBCDIC uses nine bits in
total. The ninth bit is used for parity, and eight bits for each character. 8-bits can be used to code 256
characters. It uses the same character symbols as ASCII but the bits are different for same characters. The
first4-bits are called zone bits and last 4-bits are used for digit values.
ASCII code and EBCDIC code for some of the characters are shown in the table 5.8.
Table 5.5 Characters 7-bit ASCII code 8-bit EBCDIC code
ASCII and EBCDIC code
0 011 0000 1111 0000
1 011 0001 1111 0001
2 011 0010 1111 0010
3 011 0011 1111 0011
9 011 1001 1111 1001
A 100 0001 1100 0001
B 100 0010 1100 0010
C 100 0011 1100 0011
X 101 1000 1110 0111
Y 101 1001 1110 1000
Z 101 1010 1110 1001
Blank 010 0000 0100 0000
+ 010 1011 0100 1110
$ 010 0100 0101 1011
* 010 1010 0101 1100
= 011 1101 0111 1110
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 301.
Unicode
ASCII code can only encode the Latin alphabets. Some other codes are required to encode alphabets of
other languages or some special symbols. Unlike ASCII, Unicode is a universal code used for character
encoding of any written language of the world. Single software in Unicode can be used across multiple
platforms, languages and countries. The data in Unicode can be transported across different systems
without significant error.
To keep character coding simple and efficient, the Unicode Standard assigns each character a unique
numeric value and name, independent of platform program or language. The Unicode standard supports
three encoding forms UTF-8 (8 bit code unit), UTF-16 (16 bit code) and UTF-32 (32 bit code) that use a
common repertoire of characters. These encoding forms can be used to encode millions of characters. It can
be used to define code for all the written languages of the world, punctuation marks, diacritics,
mathematical symbols, technical symbols, arrows, dingbats etc.
A single number, called code point, is assigned to each code element. It is in hexadecimal form following
the prefix "U". For example; code point U + 0041 (equal to decimal 65 for character "A"), U + 0042 (equal to
decimal 66 for "B"). Each character is also assigned a unique name, and the name can't be duplicated. For
example; U + 0041 is given the name "LATIN CAPITAL LETTER A", U + 0A1B has name "GURMUKHI
LETTER CHA" etc. A system of related characters is called scripts in Unicode, and the characters are
grouped together by scripts in blocks. The Unicode arranges the characters in code space according to
their original order.
Unicode 5.2 can code 1,07,361 characters from the worlds alphabets, ideograph sets, and symbol
collections. Like memory, code points are grouped logically through the range of code points, called code
space for encoding. The coding starts at U + 0000 with the ASCII characters first and then Greek, Cyrillic,
Hebrew, Arabic, Indic, and other scripts followed by symbols and punctuations etc.
All the commonly used characters fit in the first 64K code point, called Basic Multilingual Plane (BMP).
More than 8,60,000 unused code points are available for other characters in other 16 supplementary planes.
Unicode also has provision of 6,400 reserved code points for private use
PROGRAMMING IN C
Introduction
C is a programming language. It is most popular computer language today because it is a structured high
level, machine independent language. Programmers need not worry about the hardware platform where
they will be implemented.
Dennis Ritchie invented C language. Ken Thompson created a language which was based upon a language
known as BCPL and it was called as B. B language was created in 1970, basically for UNIX operating
system. Dennis Ritchie used ALGOL, BCPL and B as the basic reference language from which he created C
language.
It is a basic language better to start with this so that it will make strong foundation on programming field.
C has many qualities which any programmer may desire. It contains the capability of assembly language
with the features of high level language which can be used for creating software packages, system
software etc. It is more strong in system level programming.
It supports the programmer with a rich set of built-in functions and operators. C is highly portable. C
programs written on one computer can run on other computer without making any changes in the
program. Structured programming concept is well supported in C, this helps in dividing the programs
into function (modules) or code blocks.
Approved by Curriculum Development Centre (CDC), Nepal
.302 … Computer Science–I
Sample program-1
Printing a message
#include<stdio.h>
#include<conio.h>
void main()
{
...../* Printing begins here */
printf (“C is a very good programming language.”);
...../* Printing ends here */
getch();
}
The first line is a preprocessor command which adds the stdio.h header file into our program. Actually
stdio.h stands for standard input output, this header file supports the input-output functions in a
program. In a program, we need to provide input data and display processed data on standard output –
Screen. The stdio.h header file supports these two activities. There are many header files which will be
discussed in later.
The second line main () tell the compiler that it is the starting point of the program, every program should
essentially have the main function only once in the program. The opening and closing braces indicates the
beginning and ending of the program. All the statements between these two braces form the function
body. These statements are actually the C code which tells the computer to do something with the given
instruction. Each statement (word or character) is an instruction for the computer to perform specific task.
The /* …. */ is a comment and within this symbol instructions will not be executed, the compiler simply
ignores this statement. These are essential since it enhances the readability and understandability of the
program. It is a very good practice to include comments in all the programs to make the users understand
what is being done in the program.
The next statement printf (), this statement is the only executable line in the above sample program. The
printf () function is a standard inbuilt function for printing a given line which appears inside the double
quotes. Therefore in the standard output device we can see the following line
C is a very good programming language.
The next line is again a comment statement as explained earlier. The closing brace indicates the end of the
program.
Executing a C Program
The following basic steps are carried out in executing a C Program.
1. Type the C language program (source code).
2. Store (save) the program by giving a suitable name and following it with an extension .c.
3. Compile the program.
4. Debug the errors if any, that is displayed during compile.
5. Run the program. It will provide the output of the program.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 303.
Brief History
C is a general-purpose language. C is a programming language which introduce at “AT & T’s Bell
Laboratories” of USA in 1972. It was written by Dennis Ritchie. This language was created for a specific
purpose to design the UNIX operating system (which is used on many
computers). From the beginning, C was intended to be useful to allow
busy programmers to get things done.
Because C is such a powerful, dominant and flexible language, its use
quickly spread beyond Bell Labs. In the late 70’s C began to replace
widespread well-known languages of that time like PL/I, ALGOL etc.
Programmers everywhere began using it to write all sorts of programs.
Soon, however, different organizations began applying their own
versions of C with a slight difference. This posed a serious problem for
system developers. To solve this problem, the ANSI formed a
committee in 1983 to establish a standard definition of C. This
committee approved a version of C in 1989 which is known as ANSI C.
With few exceptions, every modern C compiler has the ability to hold
on to this standard. ANSI C was then approved by the International
Standards Organization (ISO) in 1990.
Many of the important ideas of C adopt from the language BCPL,
developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B,
which was written by Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-7.
BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of “The C Programming
Language” by Kernighan & Ritchie made a revolution in the computing world of programming language.
Characteristics (Features)
Some of C's characteristics that define the language and also have lead to its popularity as a programming
language. Naturally we will be studying many of these aspects throughout the course.
• Small size (size of C language program).
• Extensive use of function calls (Modularization).
• Loose typing (Can start from any place).
• Structured language.
• Low level (Bitwise) programming readily available.
o Pointer implementation - extensive use of pointers for memory, array, structures and functions.
• Low Level Feature: - a) It is closely related to lower level language such as “Assembly Language”. b)
It is easy to write assembly codes in C.
• Portability: - a) C-programs are portable i.e. they can be run on any compiler with little or no
modification. b) Compiler and preprocessor make it possible for C-program to run it on different PC.
• Powerful: - a) Provides wide variety of Data types. b) Provides wide variety of Functions. c) Provides
useful control and loop control statements.
• Bit Manipulation: - a) C- programs can be manipulated using bits. b) Provides wide variety of bit
manipulation operators.
• High Level Features: - It is more user friendly as compare to previous languages.
• Modular Programming
• Efficient use of pointers: - Helps to direct access to memory.
• More Efficient.
Approved by Curriculum Development Centre (CDC), Nepal
.304 … Computer Science–I
C has now become a widely used professional language for various reasons.
• It has high-level constructs.
• It can handle low-level activities.
• It produces efficient programs.
• It can be compiled on a variety of computers.
Some of the specific features of C are:
• An extremely simple core language, with non-essential functionality provided by a standardized set
of library routines.
• Focus on the procedural programming paradigm, with facilities for programming in a structured
style.
• Use of a preprocessor language, the C preprocessor, for tasks such as defining macros and including
multiple source code files.
• O (1) performance for all operators.
• Low-level access to computer memory via the use of pointers.
• Parameters are always passed to functions by value, sometime by reference.
• Lexical variable scoping (but no support for closures or functions defined within functions).
• C is portable – it provides standard set of libraries that work on the same way with all machines
• C is efficient on most machines, because certain constructs are machine dependant.
Advantages and Disadvantages of C-language
Advantages of C Language
• First of all C language is the basic (fundamental) programming language which is the mother of all
modern language.
• C is a building block for many other currently known languages. Take a look at Python for example a
fully Object-Oriented High-Level programming language. It is also written in C
• C is a compiled language versus an interpreted language. Simply, this means that the code is
compacted into executable instruction. This feature also lends heavily to the speed of C programs.
• A lot of libraries are written in C as compared to previous programming language.
• The main advantage of C language is that there is not much vocabulary to learn, and that the
programmer can arrange for the program is very fast. C programming language is very easier to
learn. C programming language is still a practical and compact language. It comprises a good
semantic. Syntax is of C is clear. C language is very near to assembly programming, so it can be easily
program system related instruction.
• C has features that allow the programmer to organize programs in a clear, easy, logical way. For
example, C allows meaningful names for variables without any loss of efficiency, yet it gives a
complete freedom of programming style, including flexible ways of making decisions, and a set of
flexible commands for performing tasks repetitively (for, while, do-while).
• It easily gets complied without much memory.
• C is a portable language.
• It is free form language so, program can be start from any line and column.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 305.
Disadvantages of C Language
• There is no runtime checking in C language, as the program extends it is very difficult to fix the bugs.
• There is no strict type checking (for ex: we can pass an integer value for the floating data type).
• C doesn't have the concept of namespace.
• C doesn't have the concept of constructors and destructors.
• It does not support the object oriented concepts such as polymorphism, data hiding and the others.
• There is no enough library function for handling today’s programming environment.
• It is case sensitive so, mixing case makes difficult while programming.
• Hard to run in latest operating system (i.e. 64 bit system).
• It is not design oriented. It is not easy to write C codes.
Basic Structure of C Programs
1. Documentation Section.
2. Link Section.
3. Definition Section
4. Global declaration Section.
5. main () function section.
{
Declaration Section
Executable Section
}
6. Sub-program Section
a) function1
{
Statements
}
b) function2
{
Statements
}
c) function3
{
Statements
}
The documentation section consists of a set of comment lines giving the name of the program, the
author and other details such as a short description of the purpose of the program. This portion
makes the program readable for all level of person. This is not mandatory but better to mention. It
makes the readability of program.
The link section provides instructions to the compiler to link functions from the system library. This
is the important part of programming, without this your code cannot work properly. With this we
can directly write the programs.
The definition section defines all the symbolic constants. The variables can be declared inside the
main function or before the main function.
Declaring the variables before the main function makes the variables accessible to all the functions in
a C language program, such variables are called Global Variables.
Approved by Curriculum Development Centre (CDC), Nepal
.306 … Computer Science–I
Declaring the variables within main function makes the usage of the variables confined to the main
function only and it is not accessible outside the main function.
Every C program must have one main function. Enclosed in the main function are the declaration
and executable parts.
In the declaration part we have all the variables.
There is at least one statement in the executable part.
The two parts must appear between the opening and closing braces
The sub-program section contains all the user-defined functions that are called in the main function.
User-defined functions are generally placed immediately after the main function although they may
appear in any order.
The Compiling Process
Developing a program in a compiled language such as C requires at least four steps:
1. editing (or writing) the program (source code)
2. compiling it
3. linking it
4. executing it
We will now cover each step separately.
1. Editing: You write a computer program with words and symbols that are understandable to human
beings. This is the editing part of the development cycle. You type the program directly into a
window on the screen and save the resulting text as a separate file. This is often referred to as the
source file. The custom is that the text of a C program is stored in a file with the extension .c for C
programming language.
2. Compiling: You cannot directly execute the source file. To run on any computer system, the source
file must be translated into binary numbers understandable to the computer's Central Processing
Unit. This process produces an intermediate object file - with the extension .obj, the .obj stands for
Object. To compile needs the compiler and it is various by company or system.
3. Linking: The first question that comes to most peoples’ minds is Why is linking necessary? The main
reason is that many compiled languages come with library routines which can be added to your
program. Theses routines are written by the manufacturer of the compiler to perform a variety of
tasks, from input/output to complicated mathematical functions. In the case of C the standard input
and output functions are contained in a library (stdio.h) so even the most basic program will require
a library function. After linking the file extension is .exe formed which is an executable file.
4. Executable files: Thus the text editor produces .c source files, which go to the compiler, which
produces .obj object files, which go to the linker, which produces .exe executable file. You can then
run .exe files as you can other applications, simply by clicking. After that input- process- output
cycles will occur as per the requirement.
C Preprocessor and Header Files
The Preprocessor
A unique feature of c language is the preprocessor. A program can use the tools provided by preprocessor
to make the program easy to read, modify, portable and more efficient.
Preprocessor is a program that processes the code before it passes through the compiler. It operates under
the control of preprocessor command lines and directives. Preprocessor directives are placed in the source
program before the main line before the source code passes through the compiler it is examined by the
preprocessor for any preprocessor directives. If there is any appropriate actions are taken then the source
program is handed over to the compiler.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 307.
Preprocessor directives follow the special syntax rules and begin with the symbol # in column1 (starting of
program) and do not require any semicolon at the end. A set of commonly used preprocessor directives
Directive Function
#define Defines a macro substitution
#undef Undefined a macro
#include Specifies a file to be included
#ifdef Tests for macro definition
#endif Specifies the end of #if
#ifndef Tests whether the macro is not def
#if Tests a compile time condition
#else Specifies alternatives when # if test fails
The preprocessor directives can be divided into three categories
1. Macro substitution division.
2. File inclusion division.
3. Compiler control division.
1. Macros: Macro substitution is a process where an identifier in a program is replaced by a pre defined
string composed of one or more tokens we can use the #define statement for the task.
It has the following form
#define identifier string
The preprocessor replaces every occurrence of the identifier int the source code by a string. The
definition should start with the keyword #define and should follow on identifier and a string with at
least one blank space between them. The string may be any text and identifier must be a valid C
name (variable). There are different forms of macro substitution. The most common form is
a. Simple macro substitution.
b. Argument macro substitution.
c. Nested macro substitution.
a. Simple macro substitution: Simple string replacement is commonly used to define constants
example:
#define pi 3.1415926
Writing macro definition in capitals is a convention not a rule a macro definition can include
more than a simple constant value it can include expressions as well. Following are valid
examples:
#define AREA 12.36
b. Macros as arguments: The preprocessor permits we to define more complex and more useful
form of replacements it takes the following form.
# define identifier (f1, f2, f3…..fn) string.
Notice that there is no space between identifier and left parentheses and the identifier f1, f2, f3,
…., Fn is analogous to formal arguments in a function definition.
There is a basic difference between simple replacement discussed above and replacement of
macro arguments is known as a macro call
A simple example of a macro with arguments is
Approved by Curriculum Development Centre (CDC), Nepal
.308 … Computer Science–I
# define CUBE (x) (x*x*x)
If the following statements appears later in the program,
volume=CUBE (side);
The preprocessor would expand the statement to
volume = (side*side*side);
c. Nesting of macros: We can also use one macro in the definition of another macro. That is macro
definitions may be nested. Consider the following macro definitions
# define SQUARE(x)((x)*(x))
Undefining a macro: A defined macro can be undefined using the statement
# undef identifier.
This is useful when we want to restrict the definition only to a particular part of the program.
2. File inclusion: The preprocessor directive #include <filename.h> can be used to include any file in to
the program if the functions or macro definitions are present in an external file they can be included
in file. In the directive the filename is the name of the file containing the required definitions or
functions alternatively this directive can take the form
#include< filename.h >
Having without double quotation marks. In this format the file will be searched in only standard
directories.
The C preprocessor also supports a more general form of test condition #if directive. This takes the
following form
#if constant expression
{
statement-1;
statemet-2;
….
….
}
#endif
the constant expression can be a logical expression such as test < = 3 etc.
C Header Files
In this C header file, we explore the use of header files in C, ways in which they can be used, and the
philosophy for breaking up code into separate source files.
Introduction
C header files are used to provide a way of telling the compiler what interface specific functions require in
order to be used. The compiler has no interest in what the source code actually does, but it does need to
know how to interface to that code, and the header file gives it that information.
Every external function will be mentioned in a header file, including libraries that are pre-compiled into
object code, and source files required to build the C program. We will look at the standard header files,
user defined header files, and how they fit into the compiling and linking sequence.
Including a header file produces the same results as copying the header file into each source file that needs
it. Such copying would be time-consuming and error-prone. With a header file, the related declarations
appear in only one place. If they need to be changed, they can be changed in one place, and programs that
include the header file will automatically use the new version when next recompiled. The header file
eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy
will result in inconsistencies within a program.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 309.
In C, the usual convention is to give header files names that end with `.h'. It is most portable to use only
letters, digits, dashes, and underscores in header file names, and at most one dot.
Standard Header Files
By now, the reader should be aware that there are many operations that are not catered for in the C
programming language, string manipulation, for example. However, the creators of all compiler sets will
make available a set of libraries to provide this 'missing' functionality.
These are collectively known as the standard libraries and include:
string.h : for string handling
stdlib.h : for some miscellaneous functions
stdio.h : standardized input and output
math.h : mathematical functions
We place references to these at the start of the source code file that uses one or more functions from that
library. So, a simple hello world application might require the formatted output offered in the stdio.h
header file:
#include<stdio.h> // Formatted I/O
#include<conio.h> // Entry point function
void main (void) // Output
{
printf ("Hello World");
getch ();
}
This program simply writes Hello World to the screen. What is important to note is that the code for the
function printf () is not defined in the program itself, but in a library that comes pre-compiled. The
compiler can compile the source code above, thanks to the #include line, which tells it where the definition
of printf () can be found.
Character Set used in C
It is symbols which are used in C. The symbols can be letter, digits or any special symbols. Characters are
the basic most needed units, which is used to form different words, numbers, operators, constants,
expression that means the part of (component of) programming language depending upon the computer
on which the program is run. The characters available in C are grouped into the following categories:
1. Letters
2. Digits
3. White Spaces
4. Special Characters
1. Letters: Letters are alphabet of a language and C is case sensitive so that letter may be upper or lower
or both for making words, sentence (statement) etc.
Example, A…….Z and a…….z
2. Digits: Digits are decimal numbers, they are 0 ….9.
3. White Space: Some white space characters like Blank space, Horizontal tab, carriage return, new line,
Form feed etc.
4. Special Characters: Some special characters are used while making the program in C-programming
language and these characters are differing from one to another programming language. List of
special characters in C.
Approved by Curriculum Development Centre (CDC), Nepal
.310 … Computer Science–I
,comma ‘apostrophe \ backslash & ampersand
“ quotation mark ~ tilde / slash ; semicolon
! exclamation mark _ underscore : colon | vertical bar
. period * asterisk - minus sign + plus sign
? question mark % percentage sign $ dollar sign ^ caret
< opening angle > closing angle } right brace ( left parenthesis
[ left bracket ] right bracket { left brace ) right
parenthesis
# number
Use of Comments
The /* …. */ and // both are comment specifier and will not be executed, the compiler simply ignores this
statement. These are essential since it enhances the readability and understandability of the program. It is
a very good practice to include comments in all the programs to make it understandable the users and to
the programmer him/herself what is being done in the program. This /*….*/ provides multi-line
comments and // provides single line comments.
C comments can be written like this:
/* This is a comment */
/* It will be ignored by the compiler */
/* This is also a comment
Note: you don't necessarily need an ending comment
statement at the end of every line. You only
need it at the end of each comment! */
// This is only for readability.
Remember that everything between the beginning comment statement '/*' and the ending one '*/' and
before statement ‘//’ will be ignored by C complier.
Identifiers and Keywords and Token
Identifiers
Identifiers are the any words which are used while making the program. Simply identifier means which
identify the existence of used word in different form (meaning). The words or statements which are used
that must be formed under the rule of C-programming language. Identifiers may be name of variable,
constant, expression, function, array, pointer, structure etc. Identifiers are formed with the combination of
characters set.
Rules for naming identifiers
1. First character must be a alphabet (or underscore).
2. Only letters, digits, and underscore are used.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white space.
6. Better to use meaningful name of identifier.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 311.
Keywords
It is also called reserve words. The program is constructing with the combination of keywords and
identifiers. The keywords are those words which are already used by the programming language and have
fixed meanings and these meanings cannot be changed. These keywords cannot be used as a identifier
while making programs. Keywords must be written in lowercase. There are 32 keywords in C-
programming language. They are as follows:
Term Description Term Description
Auto Optional local declaration Int Integer type declaration
Break Used to exit from loop and switch Long Adjective to data type
Case Choice in a switch statement register Variable in register
Char Character type declaration return Return to calling
Const Variable cannot be changed short Adjective to data type
continue Go to bottom of loop signed Adjective to data type
Default Last case of switch sizeof Size of data type
Do Body of do while loop static Make local variable static
Double Double precision floating point type declaration struct Structure type declaration
Else False part of “if” structure switch Conditional statement for
cases
Enum User define enumeration type declaration typedef User define data type
declaration
Extern Declaration of variable externally union Union type declaration
Float Floating point type declaration unsigned Adjective to data type
For Looping statement Void Less type declaration
Goto Jump to a label volatile Variable can be change any
time
If Conditional statement while Looping statement
C Tokens
C tokens are the component of C-programming language. With the help of these tokens C-program is
formed. In any valid C-statement is not other than C-tokens. So, C-programs are written using these
tokens and the syntax of the programming language. List of tokens are:
• Keywords • Constants • Operators • Identifiers • Special Symbols
Data Types in C
C is a very powerful programming language because of its various data types. In computer data and
information are stored and manipulated. Storage representation and machine instructions to handle
constants differ from machine to machine. Data types are used to define the kind of data being stored or
manipulated. Means what type of value that variable or constant hold and it also specifies the range of
values that a variable or constant can hold into the computer memory. The variety of data types available
in C to allow the programmer to select the type appropriate to the needs of the application as well as the
machine.
Approved by Curriculum Development Centre (CDC), Nepal
.312 … Computer Science–I
ANSI C supports three classes of data types.
1. Primary (Fundamental) data types.
2. Derived data types.
3. User-define data types.
Primary Data Types
These are the basic data types and support by all the C compilers. They are mention below.
Data Types Size (Bytes) Range
Char 1 -128 to 127
Int 2 -32,768 to 32,767
Float 4 3.4e-38 to 3.4e+38
Double 8 1.7e-308 to 1.7e+308
Long double 10 3.4e-4932 to 1.1e+4932
Qualifiers
Qualifiers modify the behavior of the variable type and their size to which they are applied. There are four
different types of qualifiers.
1. Size qualifiers: - Size qualifiers alter the size of the basic data type. The keyword long and short
qualifiers are used. Both short and long can be applied to int but only long can be applied to double.
2. Sign qualifiers: - Sign qualifiers alter the size of data type dividing from negative to positive. The
keyword signed and unsigned qualifiers are used. Both signed and unsigned can be applied to the
data types int and char only.
3. Const: - This is new qualifier defined by ANSI standard. A variable declared to be const cannot be
modified by a program. Using const variable can be declared as:
const int a=10;
But the following segment of code is invalid.
a=15; //illegal
4. Volatile: - This is also new qualifier defined by ANSI standard. A variable should be declared
volatile whenever its value can be changed by same external sources from outside the program.
Using volatile variables can be declared as:
volatile int a=10;
Integer types
Integers are whole numbers with a range of values which differ from machine to machine architecture.
Generally, integer occupies one word of storage, the word size may be the 16 or 32 bits depends upon the
machine to machine. C has three classes of integer storage, they are short int, int, and long int having both
signed and unsigned forms. By default integer is always signed. Unsigned integer use all the bits for the
magnitude of the number and always positive.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 313.
Figure: 5.15 Use of integer Differently
int
signed or unsigned Short or long
shined or unshined
Floating point type
Floating point is also called real number which is decimal point value having 6 digits of precision. The
word size is 32 bits in the entire 16 and 32 bits machine. For more accuracy double is used instead of float
which uses 64 bits giving a precision of 14 digits. It is further extended to long double which uses 80 bits.
Real number can be expressed in exponent form also.
Character type
A single character can be defined as a character type data. The character data type consists of ASCII
character. Characters are usually stored in 8 bits. The qualifier signed or unsigned may used. By default is
signed.
Void type
The void type has no values, means empty. Generally void is not used to declare the variable. This is
usually used to specify the type of functions. The type of function is said to be void when it does not
return any value to the calling function. Eg. void add ();.
Derived Data Types
Fundamental data types are extensively used to express the identifiers as a derived data types such as
functions, structures, pointers, arrays etc are discussed as and when they are encountered.
User Defined Data Types
C language has given the features for defining user defined data types. On the basis of fundamental data
types, users (programmers) can defined their own data types as a new name not new data type. By two
different ways, programmer can defined user defined data types, they are type definition and
enumeration.
Type definition
C allows the definition of our own types based on existing fundamental data types. We can define using
the keyword typedef.
Syntax:
typedef fundamental data type identifier;
Where identifiers to the “new” name given to the data type.
Eg.
typedef int marks;//marks is used as a new data type.
marks English, computer, maths;
Approved by Curriculum Development Centre (CDC), Nepal
.314 … Computer Science–I
Enumeration type
Enumeration is the user defines technique which defines by default integer type constants. Enumeration is
useful to define a set of constants instead of using multiple # define (symbolic constant). Enumeration is
used to create user define data type. Keyword enum is used to create enumerated data type. It is defined
as follows:
Syntax:
enum identifier {value1, value2, …….,valuen};
The “identifier” is a user defined enumerated data type which can be used to declare variables that can
have one of the values enclosed within the braces (known as enumerated constants). We can declare
variable to be of this “new” type.
Syntax:
enum identifier var1, var2, …..,varn;
Then, we can assign the value to the variable by this way given below.
var1=value2;
var3=value5;
Eg.
enum day {sun, mon, …..,sat};
enum day st_week, end_week;
st_week=sun;
end_week=Friday;
The compiler automatically assigns integer digits beginning with 0 and increment by 1 to all the
enumeration constants up to the last value successively. However, programmer can assign values
explicitly to the enumeration constants.
For eg. enum day {sun=2, mon, ……, sat};
Both definition and declaration can be combined in one statement.
enum day {sun, mon, …….., sat} st_week, end_week;
Figure: 5.16 C Data Types
C Data Types
Fundamental (Basic) type Derived type User define type
Character (char) Array Type definition
integer (int) Function (typedef)
Floating point Pointer Enumeration
(float, double) Structure (enum)
Void
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 315.
Constants and Variables
Constants
Constants mean fixed values that do not change during the execution of a program. Such values remain as
it is until the written code is changed. Suppose the expression (2+3) is a constant, its value is always 5
whenever you execute. C programming language supports several types of constants. They are as follows:
Figure: 5.17 Types of C Constants
Constants
Numeric constants Character constants
Integer Single character constants
Real
String constants
Integer Constants
An integer constant is a sequence of digits. It also called whole number constants. Integer constants may
be decimal, octal, or hexadecimal. Mostly useable numbering system is decimal so, decimal constants are
discussed here.
Decimal integers consist of a set of digits, 0 through 9. The number may be preceded by signed
(- or +) and appending qualifiers.
For example,
5892, -56, +60, 50601u, 52230592ul etc.
Embedded spaces, commas, and non-digit characters are not permitted between digits.
For example,
10 25, 11,00, &20 etc.
Real Constants
Only integer numbers are not enough to represent quantities that vary continuously. In C real constants is
called floating point constants means having decimal precision (fractional part) which attempts to provide
the actual value of that thing.
For example,
560., .50, -.42, +0.91 etc.
A real number also can be expressed in exponential (scientific) notation.
For example,
The value 4523.45 can be written as 45.2345e2 in exponential notation, e2 means multiply by 102
(100). The general form is:
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an
integer number with an optional plus or minus sign. The letter e is separating the mantissa and the
exponent of an expression.
Approved by Curriculum Development Centre (CDC), Nepal
.316 … Computer Science–I
For example,
30e-5, 2.3e+4, -2.5e-3 etc.
Exponential notation is useful for representing numbers that are either very large or very small in
magnitude.
For example,
43000000000 can be written as 4.3e10 or 43e9. Similarly, 0.00000592 can be written as -5.92e6.
Single Character constants
The single character which is enclosed within a pair of single quotation marks either alphabet, digit or any
other special character (symbol) is considered as a character constant and has a constant fixed value.
Character constants have integer values known as ASCII values. Since each character constant represents
an integer value, it is also possible to calculate arithmetic calculation on character constants.
For example,
printf (“%d”,’A’); //The statement would print the number 65, similarly, the statement
printf (“%c”,’65’); //would give output capital ‘A’.
Escape sequence
Escape sequences are used in the programming languages. An escape sequence is a sequence of characters
that does not represent itself when used inside a character or string, but is translated into another
character or a sequence of characters that may be difficult or impossible to represent directly.
In C, all escape sequences consist of two or more characters, the first of which is the backslash, \ (called
the “Escape character”); the remaining characters determine the interpretation of the escape sequence. It
helps to escape the usual meaning of the character that follows it. For example, \n is an escape sequence
that denotes a newline character.
Character Escape Sequence ASCII Value
Null character \0 0
Alert (bell) \a 7
Backspace \b 8
Horizontal tab \t 9
New line \n 10
Vertical line \v 11
Form feed \f 12
Carriage return \r 13
Double quote \” 34
Single quote \’ 39
Question mark \? 63
Backslash \\ 92
String Constants
A string constant is a sequence of characters enclosed in double quotes. It may contain letters, numbers,
special characters or blank spaces. However, it does not have an equivalent ASCII value. That means, the
character constant ‘A’ is differ from string constant “A”.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 317.
Variables
A variable is an identifier which is used to store data item in the program. Variables mean whose value is
varied. Unlike a constant, the value of variable can change during the execution of a program. The same
variable can store different value at different portion of a program. Variable is the means of allocation of
memory space in the computer for processing whenever it required.
Variable name consist with the combination of letters, digits, or underscore characters. The rules for
naming variables are similar to the identifiers. Some examples of valid variable names are:- kathmandu,
palpa, first_name, n2 etc.
Declaration of Variable:-
The variables should be declared before using it in a program. The variables are defined or declared using
following syntax:-
data type varname, varname1, varname2,………….varnameN;
data type varname = value or variable;
For example,
int marks, score, weight;
float cost = 2.5;
char name[10], ch;
Rules for variable declaration
1. The variable name should be started with letters or underscore.
2. The variable name should not be keyword.
3. White space and other special characters are not allowed in between the name of variable.
4. Up to 31 characters are allowed but first 8 characters are significant.
5. Uppercase and lowercase are different (case sensitive).
6. Different variables of the same name are not allowed to be declared in the same scope.
Scope of variable
Scope of variable determines over what parts of a program a variable is actually available for use. On the
basis of place of declaration, variables are categorized as local (internal, automatic, static) and global
(external). The variable declare within the function is known as local variable and declare outside the
function is known as global variable. These concepts details will be studied in grade 12 while in the
concepts functions.
Type of Specifier
Type specifier is a data type format which represents the particular type of data. It is need of type specifier
in input output operation. This specifies what type of data is needed for I/O operation. The type specifier
of different data types are as follows:
Format Specifier Type Specifier Keyword Data type
%d d int Integer (signed)
%ld ld long int Long integer (signed)
%hd hd short int Short integer (signed)
%c c char Character
%s s char Character (string)
Approved by Curriculum Development Centre (CDC), Nepal
.318 … Computer Science–I
%f f float Floating point value
%lf
%Lf lf double Double floating point value
%e
%g Lf long double Long double floating point value
%i
%o e float Floating point value in exponent form
%x
%u g float Floating point value either e or f type
%[..]
%lu i int Decimal, hexadecimal or octal integer
o int Octal integer
x int Hexadecimal integer
u unsigned int Unsigned integer
[..] char String of words
lu long unsigned int Long unsigned integer
Statements
Every program consists of a set of statements. A statement is a single command given to the computer
which is formed according to the rule of programming language. The way of forming valid statement is
differ from one programming language to another programming language. Generally, in speaking
statements are called sentences. So, sentence is called statement in programming language. A statement is
a smallest standalone instruction (element) of a program. The statements may be simple or compound.
The syntax and semantics of statements depend on the programming language.
Simple statement
The statements consist of a single line of instruction called simple statement. Simple statement can be
declaration, assigning the value or expression.
For example,
int a,b,s;
a=5;
b=6;
s=a+b;
a++; etc.
Compound Statement
A series of statements in a block called compound statement. Compound statement can be combination of
declaration, assigning, expression and other control statements. It means, compound statement embeds
statements within other statements. It contains several individual statements.
For example,
x=(a<b)?a:b;
while(a<b)
{
sum=a+b;
printf(“%d”,sum);
a++;
}
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 319.
Operators and Expressions
To form a statement in C-programming language needs operators, variables, constants etc.
Operators
An operator is a symbol that operates on a certain data and variables. Operators are used in programs to
perform certain mathematical, logical, relational manipulation. C supports a rich set of operators for
making statements while programming. There are different types of operators in C-programming
language. They are categorized as follows:
1. According to the number of operands required
2. According to the utility and action (operation)
1. According to the number of operands required
The operators are classified into three different types. They are Unary, Binary, and Ternary operator.
Unary operators:
The operator which operates only one operand is known as unary operator. The unary operators are
++ (increment), -- (decrement), + (unary plus), - (unary minus) etc.
For Example,
++a, - -a, -a, +a;
Binary operators
The operator which operates two operands is known as binary operator. Most of the operators are
binary in C-language. The binary operators are arithmetic, relational, logical etc.
For Example,
a+b, a-b, a*b, a/b etc.
Ternary operators:
The operator which operates three operands is known as ternary operator. Ternary operator is also
called conditional operator. The paired operator ? (Question mark) and : (colon) is a ternary operator.
For Example,
s = (a<b) ? a : b;
2. According to the utility and action (operation)
The operators are classified into various types. They are as follows:
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment / Decrement operators.
6. Conditional operators.
7. Bitwise operators.
8. Other special operators.
1. Arithmetic operators: The operators which are used for basic arithmetic operation is called
arithmetic operators. These operators are binary operator. These can operate on any built in data type
allowed in C. The arithmetic operator can be used in integer, real or mixed mode data type. The
result of operation will be always real in the case of mixed operation having real type. But modulo is
always used in integer type. There are different five arithmetic operators in C. They are as follows:
Approved by Curriculum Development Centre (CDC), Nepal
.320 … Computer Science–I
Operator Meaning Example
+ Addition A+B
- Subtraction A-B
* Multiplication A*B
/ Division A/B
% Modulo division A%B
2. Relational operators: Relational operators are used to compare two similar operands, and depending
on their relation, take some actions. Relational operators are also called comparison operators.
Relational operators are binary operator. There are different types of relational operators. They are as
follows:
Operator Meaning Example
< Less than A<B
> Greater than A>B
<= Less than or equal to A<=B
>= Greater than or equal to A>=B
= = Equal to A= =B
!= Not equal to A!=B
3. Logical operators: Logical operators are used to compare or evaluate logical and relational
expression. The result of logical operator produce either 1 (true) or 0 (false). Logical operators are
binary operators except NOT. The logical operators are as follows:
Operator Meaning Example
&& Logical AND A= =B && C>D
|| Logical OR A= =B || C>D
! Logical NOT !(A= =B || C>D)
In logical AND manipulation, any or both expression is false, the result is false otherwise result is
true.
In logical OR manipulation, any or both expression is true, the result is true otherwise, the result is
false.
In logical NOT manipulation (evaluation) if the expression is true the result is false and vice versa.
This can be elaborated from the following table:
A B !A !B A && B A || B
00 1 1 0 0
01 1 0 0 1
10 0 1 0 1
11 0 0 1 1
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 321.
0 (zero) -> False
1 (one) -> True
4. Assignment operators: Assignment operators are used to assign the result of an expression to a
variable. The left expression should be variable. Assign means, right value or variable or expression
is kept on the left variable. The single equal (=) sign is used for assignment operator.
For example,
x=c;
x=a+b;
y=5;
5. Increment and Decrement operator: The increment and decrement operators are used to increase or
decrease the value of an operand by 1. Both operators are unary operator. Increment and decrement
operators can be pre or post operators. Pre means first increment or decrement then value is assign to
the variable. Post means first value is assign and the increment or decrement the value by 1. The ++
operator is used for increment and - - operator is used for decrement. The pre and post value is differ
while assigning to other variable.
++ variable or variable = variable + 1;
variable ++ or variable = variable + 1;
- - variable or variable = variable -1;
variable - - or variable = variable - 1;
6. Conditional operators: This operator is used for making two way decision like if – else statement.
The operator paired ? (question mark) and : (colon) is known as conditional operator. It takes three
operands. So, it is also called ternary operator. The syntax is:
expr1? expr2: expr3;
Here, expr1 is evaluated first. If expr1 is true, the value of expr2 is the value of conditional
expression. If expr1 is false, the value of expr3 is the value of conditional expression.
For Example,
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b, smaller;
clrscr();
printf(“Enter the two numbers:\n”);
scanf(“%d%d”,&a,&b);
smaller=(a<b) ? a : b;
printf(“The smaller number is %d”, smaller);
getch();
}
Output Screen
Enter the two numbers
25
Output
The smaller number is 20.
Approved by Curriculum Development Centre (CDC), Nepal
.322 … Computer Science–I
7. Bitwise operators: Bitwise operators are used for manipulating data at bit level. These operators are
used for testing, complementing or shifting bits to the left or right. Bitwise operators are applied only
to integer type operand. There are three types of bitwise operators. They are:-
1. Bitwise logical operators.
2. Bitwise shift operators.
3. One’s complement operators.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ Complement (negation)
8. Special operators: C supports some special operators such as comma operator (,), sizeof () operator,
pointer (& and *) operator, member selection (. and ->) operator etc.
Comma operator:
Comma operator is a link operator which separates the one expression to another expression and
evaluate from left to right.
For examples,
sum=(a=5,b=6,a+b); First five is assign to a, then 6 is to b, and lastly sum of a and b 11 is assign to
sum.
sizeof operator:
This is a unary operator. It takes arguments as a constant, a variable, a data type or a more complex
expression and returns the size of that operand on the current compiler and processor in bytes.
For example,
sizeof(int);
printf(“The size of integer is %d”,sizeof(int));
Output
The size of integer is 2.
Precedence & Associability
Each operator in C has precedence (priority) related with it. This precedence is used to evaluate how a
mixed expression involving more than one operator is evaluated. There are distinct levels of precedence
and an operator may belong to one of these levels. The operators at the higher level of precedence are
evaluated first. This priority of operators to evaluate in an expression having different level of operators is
called operator precedence.
The operators of the same precedence are evaluated either from left to right or from right to left depending
on the level. This is known as the associativity property of an operator. The complete list of operators
according to their precedence level, and their rules of associativity are shown below. The groups are listed
in the order of decreasing precedence. Precedence level 1 indicates highest precedence level and 15th the
lowest.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 323.
Precedence Level Operator Description Associativity
() Function call
1 [] Array elements reference Left to right
-> Indirect member selection
2 . Direct member selection Right to left
! Logical negation (complement)
3 ~ Bitwise one’s complement Left to right
4 + Unary plus Left to right
5 - Unary minus Left to right
++ Increment
6 -- Decrement Left to right
& Address
7 * Pointer reference (indirection) Left to right
8 Return size in bytes Left to right
9 sizeof() Type cast (conversion) Left to right
10 (type) Multiply Left to right
11 Divide Left to right
12 * Remainder(modulus) Left to right
13 / Addition Left to right
14 % Subtraction Right to left
+ Left shift
- Right shift
<< Less than
>> Less than or equal
< Greater than
<= Greater than or equal
> Equal to
>= Not equal
== Bitwise AND
!= Bitwise XOR
& Bitwise OR
^ Logical AND
| Logical OR
&& Conditional expression
|| Simple assignment
?:
=
Approved by Curriculum Development Centre (CDC), Nepal
.324 … Computer Science–I
*= Assign product Left to right
/= Assign quotient
%= Assign remainder
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
15 , Comma operator
Expressions
An expression is a combination of variables, constants, and operators arranged according to the syntax
(rule) of the language. It is a valid statement. C can handle simple as well as complex mathematical
expressions. Expressions are evaluated using an assignment of the form:
variable = expression;
Some examples of expression are:-
x = a*b+c;
y = c+d/b-a;
x1 = (a-b)*d;
y1 = (a/(b-d)+c)*d;
In the case of evaluating expression y1 = (a/(b-d)+c)*d. First the expression (b-d) is evaluated then this
difference will divide ‘a’ and the result is added to ‘c’. Finally, the total result is multiplied by ‘d’.
Rules for evaluation of expression
1. First, parenthesized sub expressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub expression.
3. The precedence rule is applied in determining the order of application of operators in evaluating sub
expression.
4. The associativity rule is applied when two or more operators of the same precedence level appear in
a sub expression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence.
6. When parentheses are used, the expressions within parentheses highest priority.
Type Casting and Conversions
C allows mixing of constants and variables of different types in an expression. In these situations, one type
must be converted to another before evaluation can be done is known as type conversion. This conversion
can be take place either implicitly (automatic) or explicitly (by force).
Implicitly (Automatic) type conversion
C allows mixing of different data types in a single expression. When there are constants and variables of
different data types in a single expression, C automatically converts any intermediate values to the proper
type. This conversion assures that the expression can be evaluated without losing any significance. This
automatic conversion is called as implicit type conversion.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 325.
During evaluation if operands are of different types, the lower type is automatically converted into the
higher type before the operation proceeds. The result will be the higher type. The conversion takes place
according to a rule called the conversion hierarchy. The final result of an expression is converted to the
type of the variable on the left of the assignment before assigning the value to it. However, the following
changes are introduced before the final assignment:-
1. Float to int causes truncation of the functional part.
2. Double to float causes rounding of digits.
3. Long int to int causes dropping of the excess lower order bits.
Conversion Hierarchy
Figure: 5.18 Automatic Types Conversion
short int char
int
unsigned int
long int
unsigned long int
float
double
long double
For Example
short int x;
int a;
float b;
double c;
long int y
x = a + y / c * (b – a);
Result
float = b - a;
double = y / c;
double = y / c * (b - a)
Approved by Curriculum Development Centre (CDC), Nepal
.326 … Computer Science–I
double = a + y / c * (b - a)
short int = a + y / c * (b – a)
Process of implicit type conversion
Explicit (type casting) type conversion
Sometime it is required to convert the type of an expression forcefully. This is known as type casting or
explicit type conversion.
Syntax,
(type name) expression;
Where type name is one of the standard C data type. The expression may be constant, variable or any
complex expression.
Example Action
X=(int) 7.5 7.5 is converted to integer by truncation
A=(int)21.3/(int)4.5 Evaluated as 21/4 and the result would be 5
B=(double)sum/n Division is done in floating point mode
Y=(int)(a+b) The result of a+b is converted to integer
Z= (int)a+b is converted to integer and then added to b
P=cos(double)x Converts x to double before using it.
Introduction to Library Functions
C contains number of various type of library function that performs various tasks. These functions are
defined in C language can be used whenever needed while writing programs.
Some important types of functions
1. Character handling function
2. Standard I/O function
3. String handling function
4. Mathematical function
5. Time manipulation function
6. Process handling function
7. Utility function
8. Console I/O function etc.
Input/Output (I/O) Function
Program is a system that means input, process and output. In this part, we will discuss about how a C
program can take inputs from standard input devices (keyboard) and displays the output on the monitor
(standard output device). C has number of I/O library function contains in a stdio.h header file. Each
program that usages a standard I/O function must contain the statement #include<stdio.h> at the
beginning of the program. I/O functions are basically categorized into two different types, unformatted
and formatted.
1. Unformatted Functions: Unformatted functions do not allow the user to read or display data in his
customized (according to his need) format. These library functions basically deal with a single
character or a string of character. The functions like getchar(), putchar(), getch(), getche(), putch(),
gets(), puts() are considered as unformatted functions. They are also categorized into single character
I/O function and string I/O functions.
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 327.
a. Single character I/O functions: The function which reads single character from standard input
device, keyboard and display single character on standard output device, monitor is known as
character I/O functions. Single character I/O functions are:
getchar () and putchar()
The getchar() is a single character library function which reads a character from standard input
device.
Syntax,
charvarname = getchar ();
Charvarname is a valid character (char) type variable. It takes single character from keyboard
and assign to the charvarname. Likewise, the putchar () is a single character library function
which display a character into standard output device.
Syntax,
putchar (charvarname);
Where charvarname is a character (char) type variable containing a character.
For Example,
# include<stdio.h>
# include<conio.h>
void main ()
{
char gender;
clrscr();
printf("Enter gender M or F:\n");
gender = getchar();
printf("The entered gender is:\t");
putchar(gender);
getch();
}
getch(), getche(), and putch()
The function getch() and getche() reads a single character the instant it is typed without
waiting for the enter key to be hit (press). The difference between them is that getch ()
reads the character typed without echoing it on the screen while getche() reads the
character and echoes (display) it on to the screen.
Syntax,
charvarname = getch();
Likewise
charvarname = getche();
The function putch() prints a character onto the screen
Syntax,
putch(charvarname);
For Example,
# include<stdio.h>
# include<conio.h>
void main()
Approved by Curriculum Development Centre (CDC), Nepal
.328 … Computer Science–I
{
char ch1, ch2;
clrscr();
printf ("enter the character ch1 \n");
ch1 = getch();
printf ("enter the character ch2 \n");
ch2 = getche();
printf("character ch1 is:\t");
putch(ch1);
printf("character ch2 is:\t");
putch(ch2);
getch();
}
String I/O function
String is a collection of characters. The function which reads number of characters from
standard input device, keyboard and display number of character onto the standard
output device, monitor is known as string I/O function. String I/O functions are:-
gets() and puts()
The gets() is a string library input function which is used to read number of characters,
containing spaces until the newline character is encountered from the standard input
device.
Syntax,
gets (stringvar);
Here, it takes string from the user and stores in a stringvar.
Likewise,
The puts() is a string library output function which is used to display string onto the
standard output device.
Syntax,
puts(stringvar);
For Example,
# include<stdio.h>
# include<conio.h>
void main()
{
char str[10];
clrscr();
printf("enter the string\n");
gets(str);
printf("enter string is:\t");
puts(str);
getch();
}
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 329.
2. Formatted input/Output function: Formatted input/output function is also library function. With
the help of these function programmer can customized input/output according to his requirements.
It means, the features of function can be used on the basis of need of the program not by default.
a. Formatted input: Formatted input refers to an input data that has been arranged in a particular
format. The data may be any type and must be read according to its format.
The built in function scanf () can be used to enter input data into the computer from the
standard input device. The input can be any combination of numerical, character or strings. Its
general form is as follows:
scanf ("control string", arg1, ary2, ……..argn);
The control string refers to the field format in which the data is to be entered. It may include:
• Format specification, consisting of a percentage sign (%) field width (optional) and a
conversion character. Format specification is the compulsory part of the control string.
• Blank (white space), tab(\t) and newline (\n) characters. These are optional in control string.
If these are used in the control string to separate the different format specification, they must
be entered consecutively while inputting the data but they will not be stored in memory.
The arguments arg1, arg2, …………..,argn specify the address of location where the data is
stored. It represents pointer that indicates the address of the data items within computer
memory. Thus, it is preceded by ampersand (&). The number of format specification must equal
the number of arguments and type of argument must match the corresponding format
specification.
Format specifications for data input (for scanf())
Basic format specification Data type Type of argument
%c Character Address of character variable
%s String Name of the string variable
%d Integer Address of integer variable
%i Integer (decimal, octal Address of integer variable
or hexadecimal)
%u Unsigned integer Address of unsigned variable
%f Floating point Address of floating point variable
%e Floating point with Address of floating point variable
exponent
%g Floating point Address of floating point variable
%ld, %li Long integer Address of signed long integer variable
%lu Unsigned long integer Address of unsigned long integer variable
%hd, %hi Short integer Address of short integer variable
%hu
Unsigned short integer Address of unsigned integer variable
%le, %lf, %lg
Double Address of double precision floating point
%Le %Lf, %Lg variable.
%O
%X Long double Address of long double variable.
%[ ]
Octal integer Address of integer variable.
Hexadecimal integer Address of integer variable.
String of words Name of string
Approved by Curriculum Development Centre (CDC), Nepal
.330 … Computer Science–I
i. Inputting integer numbers
The format specification for reading an integer looks like %wd. It means, reads an integer
number of field width w.
For Example,
# include<stdio.h>
# include<conio.h>
void main()
{
printf("enter an integer number \n");
scanf("%d", &x);
printf("The entered value x is%d",x);
printf("entered the number y \n");
scanf("%3d", &y);
printf("The entered value of y is %d", y);
getch();
}
S.N. Output Discussion
i. Enter the integer number x No field width specified the given value is within the range
23456. of integer. Therefore, it is read and assigned to memory
The entered value x is 23456. location specified by &x.
ii. Enter the number y 23456. Field with of 3 columns so value in the first three field is
The entered value of y is 234. read and stored in memory location specified by &y.
ii. Inputting real numbers
Reading real number is easier than the integer number because it is not required to specify
the field width.
# include<stdio.h>
# include<conio.h>
void main()
{
float x, y;
double x1, y1;
printf ("enter the value of x and y \n”);
scanf("%f %e", &x, &y);
printf("value of x = %f and value of y = %e", x, y);
printf("enter the value of x1 and y1,\n");
scanf("%lf %le", &x1, &y1);
printf("in value of x1 = %lf and value of y1 = %le", x1, y1);
getch();
}
Approved by Curriculum Development Centre (CDC), Nepal
Programming Concepts and Logics Unit 5 … 331.
Output
Enter the value of x and y
321.123 21.34e – 13
value of x = 321.123000 and value of y = 2.134000e – 12
enter the value of x1 and y1
123456789.12345678 1234.765e + 123
value of x1 = 123456789.123456 and
value of y1 = 1.234765000000000000000000000000000000000e + 126
iii. Inputting a character
The single character can be read using the scanf() function also. In addition, a scanf()
function can input strings containing more than one characters.
# include<stdio.h>
# include<conio.h>
void main()
{
char ch;
printf("enter a character \n");
scanf("%c", &ch);
printf("The entered character is %c", ch);
getch();
}
iv. Input strings
As we know a string is a sequence of characters. There are three ways of reading strings
using scanf() functions. The first way is to use %ws format specification.
# include<stdio.h>
# include<conio.h>
void main()
{
char str[15];
printf("enter a string\n");
scanf("%10s", str);
printf("Read string is %s", str);
printf("enter a string\n");
scanf("%s”, str);
printf("Read string is %s", str);
getch();
}
Output
Enter a string
aaaaaaaaaaaa
Read string is aaaaaaaaaa (Only first 10 character)
Enter a string
Riway is a very good boy.
Approved by Curriculum Development Centre (CDC), Nepal
.332 … Computer Science–I
Read string is Riwaj (Reading terminated at the encounter of any white space)
The second way to read string is to specify the field width in %c format. Whose format
specification is %wc. It means reading characters in the field with w. When this format is
used for reading a string, the system will wait until the wth character also including white
space.
Example 7
# include<stdio.h>
# include<conio.h>
void main()
{
char str[30];
printf("enter the string\n");
scanf("%10c", str);
printf("Entered string is %s", str);
getch();
}
Output
Enter the string Riwaj is a good boy.
Entered string is: Riwaj is a (Reading first ten characters with white spaces)
The another, the third way of reading string are % [characters] and %[^character]. The specification
%[characters] means that only the characters specified within the brackets are permissible in the
input string. The reading of the string will be terminated at the encounter of any other character in
the input-string. The specification %[^characters] means exactly reverse of %[characters]. This
means the characters specified after the circumflex(^) are not permitted in the input string. The
reading of the string will be terminated at the encounter of one of these characters.
For Example,
# include<stdio.h>
# include<conio.h>
void main()
{
char str[30], str1[30];
printf("what is your name \n");
scanf("%[a – zA – Z]", str);
printf("where do you live\n");
scanf("%[^M]", str);
printf("The name is %s", str);
printf("He live in: %s", str1);
getch();
}
Approved by Curriculum Development Centre (CDC), Nepal