0% found this document useful (0 votes)
4 views86 pages

Chapter V

The document covers programming concepts, including an introduction to programming languages, types of programming languages (1GL to 5GL), and their characteristics, advantages, and disadvantages. It also explains the roles of compilers, interpreters, and assemblers in translating code into machine language. Key topics include control structures, program design tools, and specific features of the C programming language.

Uploaded by

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

Chapter V

The document covers programming concepts, including an introduction to programming languages, types of programming languages (1GL to 5GL), and their characteristics, advantages, and disadvantages. It also explains the roles of compilers, interpreters, and assemblers in translating code into machine language. Key topics include control structures, program design tools, and specific features of the C programming language.

Uploaded by

netrakobhanja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming Concepts

Unit: V
& Logics

5.1 Programming Concept


5.1.1 Introduction to programming languages
5.1.2 Low level, High level, 4 GL programming languages
5.1.3 Compiler, Interpreter and Assembler
5.1.4 Syntax, Semantic and Runtime errors
5.1.5 Control Structures: Sequence, Selection and Iteration
5.1.6 Program Design tools – Algorithm, Flowchart and Pseudo code
5.1.7 Absolute binary, BCD, ASCII and Unicode
5.2 C Programming Languages
5.2.1 Introduction and features of C Language
5.2.2 Structure of C program
5.2.3 C Preprocessor and Header Files
5.2.4 Character Set used in C
5.2.5 Use of Comments
5.2.6 Identifiers, Keywords and Tokens
5.2.7 Basic Data Types in C
5.2.8 Constants and Variables
5.2.9 Type of Specifier
5.2.10 Simple and Compound Statements
5.2.11 Operators and Expressions: arithmetic, relational, logical, assignment,
unary and conditional operators
5.2.12 Input/output (I/O) Functions
5.2.13 Selection Control Statement: Decisions (if, if-else, if-else-if, nested and,
switch)
5.2.14 Iteration Control Statement: Looping (while, do while, forested)
5.2.15 Array: definition, types (1D and 2D), matrix addition and subtraction
5.2.16 String: definition and string function: strlen (), strcat (), strcmp (), strrev
(), strcpy (), strlwr (), strupr ()
Programming Language
Language is a medium of communication. There are several languages developed in separate
environment and geographical conditions. Nepali, Newari, Hindi, Maithili, Bhojpuri, Urdu, English,
French, Germany, Japani etc are examples of Natural languages where as BASIC, FORTRAN,
COBOL, LISP, C, C++, C#, JAVA etc are artificial or fabricated languages. We express our motion
– emotions, feelings, understandings, skill and affection through the languages. In this way, language
is the bold and bonafide medium of expressions.
Computer Language
Programming languages are set of instructions used to write a program. The main programming languages
are machine language, low level language and high level language.
It is a type of artificial language used to communicate with computer. We know that a computer is
an electronic device works on ON and OFF (1 and 0) technique to read and write data. The history of
computer language evolution is linked with Ada, disciple of Charles Babbage (Father of Computer)
and daughter of famous English poet Byron. Adais regarded as “First Programmer of a world ". We
use several languages to communicate with others, just like it, we use many computer languages to
communicate with computers e.g. BASIC, LOGO, COBOL, PASCAL, FORTRAN etc. Computer
understands only computer language written in binary or simple English followed by special syntax.
It has small vocabulary, called reserve words or keywords. Higher level language like BASIC,
FORTRAN, and PASCAL etc has no more than 200 reserve words when ever 7 or 8 years old child
use more than 2000 words to communicate with others. Finally, we can say that computer language
is a medium of communication between man (operator) and machine (computer). There are five
types of programming languages.
▪ Machine Language or First Generation Language (1GL)
▪ Assembly Language or Second Generation Language (2GL)
▪ Procedural Language or Third Generation Language (3GL)
▪ Problem Oriented Language or Fourth Generation Language (4GL)
▪ Natural Language or Fifth Generation Language (5GL)

Machine Language or First Generation Language (1GL)


Machine Language is the First Generation Language (1GL) in which instructions and commands are
written in binary form using 0s and 1s and directly correspond to the electrical states. Since it is
written in binary, it does not require translation and can be directly understood by the computer.
Each type or family of processor requires its own machine language. For this reason, machine
language is said to be Hardware dependent or Machine dependent. It is computer dependent
language written in binary is called Machine code or Machine Language. It has two parts: (i)
Function Part (Opcode) and (ii) Operand (Address part). Machine code requires a high level of

310 Computer Science - XI Approved by CDC, Nepal


programming skill along with sound knowledge of computer architecture and functions. Instructions
written in binary are immediately executable without help of any language translators because
computer understands only machine codes.
The advantage of machine language that is it faster to execute as no translation is required. The
disadvantage of machine language is that it is difficult to understand. Example: - if “01100001” is a
computer instruction for ADD, then to add 2 and 3, we have to write “01100001 (i.e. ADD)
00000010 (i.e. 2) 00000011 (i.e. 3)”
Advantages
▪ It is written on machine code so no need to translate it into machine code for further execution.
▪ It has faster execution than other languages.
▪ Other translator type subsidiary programs are not required.
Disadvantage
▪ It is difficult to understand and develop a program using machine language.
▪ It is a machine-oriented language.
▪ The knowledge of computer internal architectures is essential for program coding.
▪ Time consuming coding.
▪ Debugging is tough and difficult.
Assembly Language or Second Generation Language (2GL)
Assembly Language is the Second Generation Language (2GL) and is also known as Symbolic
Languages. It uses symbols, abbreviations or mnemonic code (codes more easily memorized) to
replace the 0s and 1s of machine language. The program written in assembly language must be
converted into machine code before execution. The assembly language program is referred to as a
“source program” whereas; the machine language program is an “object program”. Generally,
each machines have their own assembly language depending upon the internal architecture of the
processor so, it is also machine dependent language.
Assembly Object Code in
Language Program Assembler Machine Language

Assembly language require ASSEMBLER to translate assembly language code into computer
understandable code (Machine code) .So, it is not immediately executable. Machine oriented and
time consuming program coding .It requires the programmer to have enough knowledge of computer
architectures. Assembly language program is not as fast as machine code .It has to be first translated
into machine (binary) language code.
Advantages
▪ Coding is faster than machine code language because mnemonics are used for program coding.
▪ Less time consumed respect to Machine code languages.
▪ Debugging is easy.
Disadvantage
▪ Machine oriented language
▪ The good knowledge of machine architectures is required.
▪ Time consuming
▪ Translator is used to translate program into machine code.
▪ Not as fast as machine code language in case of execution

Approved by CDC, Nepal Programming Concepts & Logics 311


Mnemonic. It is a short form of words like as acronym used in assembly language or second-
generation computer language. It is a memory aid with a sound resembling its meaning.
Example
ADD for ADDition
SUB for SUBtraction
Procedural Language or Third Generation Language (3GL)
High Level Language is the Third Generation Language (3GL) whose instruction set is more
compatible with human languages and human thought processes. A high level language eliminates
the need for programmers to understand the intimate details of how the computer processes data.
They enable programmers to create programs at a high level of abstraction, compared to machine
and assembly language. For example, the programmer can write an instruction using English words
such as PRINT and DISPLAY.
The time and cost of creating machine and assembly languages were quite high and this is a first
motivation for development of high-level computer language. High level language contains a set of
instructions written in simple English. It is a set of some symbols, words and rules to instruct
machine. The language is oriented towards the problem and procedures. Program written in high
level language is called source program. A language translator is used to translate into object code
(Machine code).
In a high level language, a single instruction will be equivalent to several instructions/ lines
(sometimes hundreds of lines) in machine language. This greatly simplifies the task of writing
complete, correct programs. A program written in a high level language must be translated into
machine language before it can be executed and this is known as compilation or interpretation. Some
of the high level languages are C, Pascal, Fortran, BASIC, CSMP, SIMAN, LISP, C++, etc.
The general features of high level languages are:
▪ They have an extensive vocabulary of words, symbols and sentences.
▪ Programs are written in the language and whole statements are translated into machine level
instructions. This translation is done by a special program called a compiler.
▪ Libraries of macros and subroutines can be incorporated.
▪ As they are problem oriented, the programmer is able to work, at least to some extent,
independently of the machine.
▪ A set of rules must be obeyed when writing the source program.
▪ Instructions in high level languages are usually called statements.
▪ It offers significant advantage over machine language simplicity, uniformity and portability.
Advantages
▪ Simple English is used for program coding.
▪ Machine independent
▪ Problem and procedure oriented.
▪ The knowledge of computer architectures is not necessary.
▪ It requires less time for program coding.
▪ Program can be debugged easily and program maintenance is also easy.

312 Computer Science - XI Approved by CDC, Nepal


Disadvantages
▪ Since it is written in user’s language so it should be converted into machine code. So it requires
a translator.
▪ The execution of the program is slower than machine code.
▪ The conversion time is slower than assembly language because it is entirely written on human
language.
Problem Oriented Language or Fourth Generation Language (4GL)
It is a high level language in which fewer instruction codes are used to accomplish a particular task.
It is a non- procedural language. Major 4th generation languages are used to get information from
files and databases. Database oriented programming language. Handles user queries. Codes are easy
to write, read and understand. Machine independent language.
This is also known as 4G. This is one step ahead from high level languages. These are results
oriented and included database query languages. There are fewer options for programmers, but the
programs are much easier to write than in lower level languages. 4GL programs are also needed to
be translated either by compiler or interpreter.
In fact, 4GL cannot be used for all purpose. They are dedicated for some particular application
developments. Example of 4GL is SQL.
Example: COLINGO, CUPID, DBASE- IV, FLORAL, FOCUS, FOXPRO 2.5, PROLOG, RAMS,
SQL, SQUARE, and NOMAD
The general features of high level languages are:
▪ They have an extensive vocabulary of words, symbols and sentences.
▪ Programs are written in the language and whole statements are translated into machine level
instructions. This translation is done by a special program called a compiler.
▪ Libraries of macros and subroutines can be incorporated.
▪ As they are problem oriented, the programmer is able to work, at least to some extent,
independently of the machine.
▪ A set of rules must be obeyed when writing the source program.
▪ Instructions in high level languages are usually called statements.
▪ It offers significant advantage over machine language simplicity, uniformity and portability.
Advantages
▪ Software developed using 4GL are user friendly.
▪ It is very easy to develop a program because no need to remember the commands and
instructions for program development and we can use drag and drop type command button to
develop the program. These buttons are available on the system that helps to develop the
program.
Disadvantages
▪ Program runs slower because it is heavy in size and design.
▪ It is required to devote longer time to convert into machine code.
▪ Huge sized powerful translators are required to convert.

Approved by CDC, Nepal Programming Concepts & Logics 313


Natural Language or Fifth Generation Language (5GL)
5GL or fifth-generation language is programming that uses a visual or graphical development
interface to create source language that is usually compiled with a 3GL or 4GL language compiler.
Microsoft, Borland, IBM, and other companies make 5GL visual programming products for
developing applications in Java, for example. Visual programming allows you to easily envision
object-oriented programming class hierarchies and drag icons to assemble program components.
A fifth-generation programming language (abbreviated 5GL) is a programming language based on
solving problems using constraints given to the program, rather than using an algorithm written by a
programmer. Most constraint-based and logic programming languages and some declarative
languages are fifth-generation languages.
While fourth-generation programming languages are designed to build specific programs, fifth-
generation languages are designed to make the computer solve a given problem without the
programmer. This means that 5GL can be used to solve problems without a programmer. Because of
this reason, 5GL are used in AI (Artificial Intelligence) research. This way, the programmer only
needs to worry about what problems need to be solved and what conditions need to be met, without
worrying about how to implement a routine or algorithm to solve them. Fifth-generation languages
are used mainly in artificial intelligence research. Prolog, OPS5, and Mercury are examples of fifth-
generation languages.
In the 1980s, fifth-generation languages were considered the wave of the future, and some predicted
that they would replace all other languages for system development, with the exception of low-level
languages.
Fifth generation programming languages (which followed 4GL) are programming languages that
allow programmers to solve problems by defining certain constraints as opposed to writing an
algorithm. Many constraint-based languages, logic-programming languages and some of the
declarative languages are identified, as 5GL. Prolog and Lisp are the most widely used 5GL for AI
applications. In the early 90’s when the 5GL came out, it was believed they would become the future
of programming. However, after realizing that the most crucial step (defining constraints) still needs
human intervention, the initial high expectations were lowered.

Assignment 5.1
▪ What is programming language? Why it is important?
▪ Discuss the types of programming languages with their merits and demerits.
▪ Define the term Mnemonic Code and 5GL.

Compiler, Interpreter and Assembler


Compiler and Interpreter are system software used to compile source program (code) into object
code (Machine code). Computer is digital devices. It can work only on the digits which are 0 and 1.
All types of commands, data and instructions required to be converted into machine code which is
the combination of 0’s and 1’s. Different types of programming languages accept the data and
instructions on natural language like English. But computer can not process such data and
instructions on natural language. So they should be translated into machine code. To convert such
natural languages into machine code we need the system called the language translator.

314 Computer Science - XI Approved by CDC, Nepal


According to the nature and application processing we have three types of language translators.
▪ Compilers: Translator systems that compile whole program and translate it into machine code
at a time are compilers. This translator translate whole program at a time and creates a object
code then executive code. This is fats in translation.
E.g. C Program, Pascal etc.
▪ Interpreters: A translator that can convert the source code (Program code) in line by line
manners without looking at the entire program at a time. It translate each statements or lines at
a time and translate another line.
E.g. BASIC
▪ Assembler: A translator that can convert the mnemonic codes of assembly level language into
machine code is called assembler. Mnemonic codes are the high level phrases used on the
assembly level language. These high level codes should be translated into machine code for
further execution of program. So assembler is essential for assembly level language translation.
E.g. Microsoft Assembler
S.N. Compiler Interpreter
1. Scan the entire program first and then translates Translate program line by line
it into machine code
2. convert the entire program to machine code, Each time the program is executed, every line is
when all the syntax errors are removed , checked for syntax errors and the converted to
program is executed. equivalent machine code.
3. Slow for debugging Good for fast debugging.
4. Execution time is less Execution time is more.
5. Object program produced by compiler is saved Object program produced by interpreter is not
for future references. saved for future references.
6. It is 5 to 25 times faster than interpreter. It is 5 to 25 times slower than compilers.
7. There are two types of compiler:
a. Self-Compiler: If compiler produces object
codes on which it runs, is called self or resident
compiler.
b. Cross Compiler: It produces object codes for
other compiler, not for that on which it runs.
8. Compilers are large programs and complex to Interpreter is simple to write and require less
write. It requires more memory spaces. memory space than compilers.
9. Example: Example:
[Link] [Link]
[Link] [Link], LISP etc
Program Logic / Program Control Structure
One of the most important aspects of programming is controlling which statement will execute next.
Control structures / Control statements enable a programmer to determine the order in which
program statements are executed. These control structures allow you to do two things: 1) skip some
statements while executing others, and 2) repeat one or more statements while some condition is
true.
Sequential Program Control
All of the programs have used sequential program control. By sequential we mean "in sequence,"
one-after-the-other. Sequential logic is the easiest to construct and follow. Essentially you place each

Approved by CDC, Nepal Programming Concepts & Logics 315


statement in the order that you want them to be executed and the program executes them in sequence
from the Start statement to the End statement. As you can see by the example program to the right,
the arrows linking the statements depict the execution flow. If your program
included 20 basic commands then it would execute those 20 statements in order
and then quit.
When you are solving a problem as a programmer, you must determine what
statements are needed to create a solution to the problem and the order in which
those statements must be executed. Writing the correct statements is one task.
Determining where to place those statements in your program is equally
important. For example, when you want to get and process data from the user you
have to GET the data before you can use it. Switching the order of these
statements would produce an invalid program.
Sequential control is the "default" control in the sense that every statement
automatically points to the next statement in the flowchart diagram. You do not
need to do any extra work to make sequential control happen. However, using
sequential control alone will not allow the development of solutions for most
real-world problems. Most real world problems include "conditions" that
determine what should be done next. For example, "If it is after taps, then turn
your lights out," requires a decision to be made based on the time of day. The "condition" (i.e., the
current time of day) determines whether the action should be executed or not executed. This is called
"selection control" and is introduced next.
Selection Control
It is common that you will need to make a decision about some condition of your program's data to
determine whether certain statements should be executed.
A selection-control statement allows you to make "decisions" in your code about the current state of
your program's data and then to take one of two alternative paths to a
"next" statement. The program code on the right illustrates a selection-
control statement, which is always drawn as a diamond. All decisions are
stated as "yes/no" questions. When a program is executed, if the answer
to a decision is "yes" (or true), then the left branch of control is taken. If
the answer is "no" (or false), then the right branch of control is taken. In
the example to the right, either statement 2a or statement 2b will be
executed, but never both. Note that there are two possible executions of this example program:
Possibility 1 Possibility 2
Statement 1 Statement 1
Statement 2a Statement 2b
Statement 3 Statement 3
Also note that either of the two paths of a selection-control statement
could be empty or could contain several statements. It would be
inappropriate for both paths to be empty or for both paths to have the
exact same statements, because then your decision, Yes or No,
would have no effect during program execution.
Loop (Iteration) Control
A Loop (iteration) control statement allows you to repeat one or
more statements until some condition becomes true. This type of
control statement is what makes computers so valuable. A computer

316 Computer Science - XI Approved by CDC, Nepal


can repeatedly execute the same instructions over-and-over again without getting bored with the
repetition.
One ellipse and one diamond symbol is used to represent a loop. The number of times that the loop
is executed is controlled by the decision expression that is entered into the diamond symbol. During
execution, when the diamond symbol is executed, if the decision
expression evaluates to "no," then the "no" branch is taken, which
always leads back to the Loop statement and repetition. The statements
to be repeated can be placed above or below the decision diamond.
We can demonstrate the lopping structure according to the following Statement 1

Example:
▪ Statement 1 is executed exactly once before the loop
(repetition) begins.
▪ Statement 2 will always be executed at least once because it Statement 2
comes before the decision statement.
▪ If the decision expression evaluates to "yes," then the loop
terminates and control is passed to Statement 4.
▪ If the decision expression evaluates to "no," then control
passes to Statement 3 and Statement 3 is executed next. Then Statement 3
control is returned back up to the Loop statement which re-
starts the loop.
Programming designing Tools
We have to represent the general program structure with different tools: Statement 4
They are
▪ Flow chart
▪ Algorithm
▪ Pseudocode/Structure English
Flowchart
The pictorial presentation of program is called – Flowchart. It is a tool and technique to find out
solution of programming problems through some special symbols. It is a way to represent program
using geometrical patterns. Prior to 1964, every manufactures use different types of symbols, there
was no uniformity and standards of flowcharting. The Standard symbols were developed by
American Standard National Institute (ANSI).
Program Flow Chart
The John Von Neumann used flowchart to solve problem in 1945 and explained its importance in
program designing.
S.N. Symbol Comments
Start/Stop
1.
This symbol is used to represent START and STOP of program.
Input/Output
2. It is used to denote input and output of data. We take data through it and display result also
using this symbol.
Process
3.
It is used to denote process, formula, increment, and decrement and assigned value also.
The pre-defined process is denoted by this symbol. Example: Sort Name is a pre-defined
4.
process and represented as:

Approved by CDC, Nepal Programming Concepts & Logics 317


Decision
5.
It is a symbol of decision. All type of decisions is written in it.
Connector
6.
It is used to link to segment of flowchart to complete as one.
Data Flow
7. → It is used to show data flow from one component to other component, one process to other
and one symbol to other symbol.
Example:
In our every day life, there is a sequence of works. These sequences of works are called – routine.
We all are tied with it. Suppose, we arise early in the morning at 5 O' clock, go to toilet, after coming
from toilet, clean hands with soap and water, brush our teeth then take bath. Here, one sequence of
work is formed.
In computer world, programming language is used to solve certain problems.
The solution of problem is a sequence of processes. In one problem, there may START
be many processes, the flowchart help to arrange processes in definite order.
Suppose, we have to convert Fahrenheit temperature into Celsius, it has
following five steps: Enter F
Step 1 Start
Step 2 Enter Fahrenheit temperature (F)
C= (F–32)(5/9)
Step 3 Application of formula: C= (F-32)(5/9)
Step 4 Displaying the result (C )
Step 5 Stop Display C
These types of processes involved in solution of problem are called Algorithm.
It is a stepwise presentation of problem solution in simple English without
STOP
using confusing words and phrases. When we draw flowchart, it is only
conversion of steps or algorithm in special symbols.
Flowchart is like as city map. Travelers or tourists search places of historical
importance through city map. Buildings are built on the basis of building-design (map) drawn by
Architect engineers. Just like it, program is coded on the basis of flowchart. Flowchart is a language
free concept, if it is prepared, any language can be used for program coding. In software
development cycle, flowcharting is one essential phase.
Algorithm
Algorithm is a stepwise presentation of procedures of program in simple and phraseless English. It is
also a programming tools used by programmer to develop software. It is a logical representation of
program procedures in order to obtain result. So, sometimes, it is called Procedure also. An
algorithm, named after the ninth Centaury scholar Abu Jafar Muhammad Ibn Musa Al-Khowarizmi
of Bagdad (Iraq).
A program is an expression of an idea in any programming language. A programmer starts with a
general idea of a task for the computer to perform. The problem is flesh out the outline into a
complete, unambiguous, step-by-step procedure for carrying out the task. Such a procedure is called
an “Algorithm”. An algorithm is not same as program. An algorithm is more like the idea behind the
program.
▪ Language independent
▪ Simple, complete, unambiguous, step-by-step program flow
▪ no standard format or syntax for the algorithm
▪ helpful to understand problems and plan out solution

318 Computer Science - XI Approved by CDC, Nepal


Example:
Following algorithm is written to find out roots of quadratic equations:
▪ Step-1: Start
▪ Step-2: Read a, b and c
▪ Step-3: d = b*b-4*a*c
▪ Step-4: If d<0 , root is imaginary
▪ Step-5: x1= (-b+ sqrt (D))/(2*a)
▪ x2= (-b-sqrt(D))/(2*a)
▪ Step-6: Display x1 and x2
▪ Step-7: Stop
Example:
Write an algorithm to find out area of triangle when sides are given.
▪ Step-1: Start
▪ Step-2: Read a, b, and c
▪ Step-3: S = (a+b+c)/2
▪ Step-4: A= s√(s-a)(s-b)(s-c)
▪ Step-5: Display A
▪ Step-6: Stop
Example:
Write an algorithm to find out slope and mid point of coordinate.
▪ Step-1: Start
▪ Step-2: Read x1, x2, y1, and y2
▪ Step-3: slope = (y2 - y1)/(x2-x1)
▪ Step-4: x = (x1+ x2)/ 2
▪ Step-5: y = (y1+y2)/ 2
▪ Step-6: Stop
There are no standard rules for algorithm designing, but we can use some common rules which are
not ambiguous to other computer literates:
▪ Value to variable: variable ← value or expression
Example:
x  18
▪ Conditional statements: if - - - endif and if – else – endif are used for conditions.
Example
If age>=18 then print “Caste vote”
else print “Wait until not 18”
endif
▪ Looping statement
i. do while(condition)
statement(s)
endo
ii. for variable = value1 To final value Step step value
statements(s)
endfor

Approved by CDC, Nepal Programming Concepts & Logics 319


Example
Write an algorithm to display factorial of given number
fact1
print “Enter number:”
read number
for count=1 to count number step 1
factfact*count
endfor
print “Factorial:”, fact
end
Problem 1
Draw a flow chart to input two numbers and display sum.
START

Enter x, y

Sum= x+ y
Loop
Display sum

Yes
Is any more?
No

STOP

Problem 2
Draw a flowchart to enter principal, rate and Time and display simple interest.
START

Enter value
of P, R, T

I= (P* R* T)/10
Loop
Print I

Yes
Is any more?
No

STOP

320 Computer Science - XI Approved by CDC, Nepal


Problem 3
Draw a flowchart to find the sum of the given series.
SUM=1/x +3/x2 + 5/x3 + …

START

SUM= 0
a= 1, b= 1

How many
terms?

Sum= Sum+ a/x^ b

a+ 2, b= b+ 1

Yes
Is b< = n?

No

Display Sum

STOP

Problem 4
Draw a flowchart to display fibnocci numbers starting from 1 unto 10 terms.
A

START
Display F

A = 1, B = 1
counter = 1 Y
A = B, B = F

Display A, B
counter= counter+ 1
Y

F= A + B
ls
counter< = 8?
A

STOP

Approved by CDC, Nepal Programming Concepts & Logics 321


Problem 5
Draw a flowchart to enter three digits and display largest of all.
START
START

Enter A, B, C
Enter A, B, C

Yes No Big= A
Is A> B?

Is B> Big and Big= B


No No B> C?
Is A> C? Is B> C?

Yes Yes Is C> Big and Big= C


C> A?
Display A Display C Display B

Display Big

STOP STOP

Pseudocode or Structured English


A logical construction, which has no strict rules like as programming language, unambiguous
statements, phrase less statements, contains noun and simple verb of English, and no adjective and
adverbs structure is called Pseudocode or Structured English.
It is a Program Design Language (PDL) provides skeleton for program design and it can replace
flowchart used to describe system design. General rules used in writing Pseudocodes are as follow:
▪ Imperative Sentence: The imperative sentences are used to show actions.
Example:
Add x to sum, Display result, Sort list etc.
▪ Operators: Mostly arithmetic operators (+, -, *, / etc) and relational operators (=, =<, =>, <, >
etc.) are used.
▪ Decision: IF, THEN, ELSE, ENDIF, CASE, ENDCASE are used for decision-making.
Example:
CASE (choice)
(choice = 1):Display Employee, Department
(choice = 2):Display Employee, Basic Sal, Allowance, Gross
(choice = 3): Terminate Program
ENDCASE.
▪ Looping: The looping or repetition of statements is shown by FOR, FOR DO, ENDFOR, DO,
DO WHILE, DO UNTIL, ENDDO etc.
Example:
Display "Selected For National scholarship Examination"
FOR roll=1 TO roll=10 DO
Display roll, Name, Address
ENDFOR.

322 Computer Science - XI Approved by CDC, Nepal


Example:
IF age >=18
THEN CASTE vote
ELSE
WAIT until age is not 18
ENDIF
Example:
Mailing a letter
BEGIN
WRITE a letter
IF bicycle is available
THEN GO to Post Office by Bicycle
ELSE
GO to Post Office on foot
ENDIF
BUY a stamp
STICK a stamp on the letter
PUT into letterbox
END.
Programming Concepts
Program and Programmer
Program is the specific set of instructions, understandable to computer. It is used to produce desired
results. Person who codes instructions using syntax of any computer languages is called
programmer. In this way, programmer is a human ware dedicated for software development.
Features of good programming Languages
Some special features of good programming languages are given below:
1. Simplicity
Simple programming language is easy in learning and coding. All the programmers like this
type of language.
2. Naturalness
A language should be natural and problem oriented. Many languages have a key word English
words like e.g., READ – DATA, PRINT, print f, write ln, DISPLAY, etc.
3. Efficiency
Efficiency of programs coding, error handling, problem solving are major criteria of higher
languages. Efficient languages are widely accepted and used major problem area.
4. Compactness
Verbose languages have no compactness. In case of COBOL, lack of compactness is a major
drawback. In PASCAL, C, C ++, JAVA, these drawbacks are removed. So, indented operations
can be coded very concisely.
5. Extensibility
A good programming language should allow extension through simple, natural, and elegant
mechanism.
6. Suitability
A language should be suitable to working environment .For instance, the program designed for
data processing job should be operative in batch mode.
Syntax, Semantics, bugs, debugging and program errors are explained below:

Approved by CDC, Nepal Programming Concepts & Logics 323


Syntax
The syntax is a rule that indicates about validity of programs. The program is a set of instructions
that follow valid syntax rules. Generally, syntax is a valid program strings and it differs language to
languages.
Example:
data Type variable = value;
In this syntax, value is assigned to variable. The semi-colon (;), data Type ( int ) and operator (=) are
also part of syntax.
Semantics
The rules that give meaning to programs are called the semantics of the programming languages. We
can say syntax has specific output oriented meaning, which is called semantics.
Example:
(a) sum = x + y: the semantics tells that sum of x and y is assigned to variable sum.
(b) s = u*t+1/2*a*t*t: It is a syntax which has two set of variables. In right set has u, a and t
variables and left set has only one variable s. The semantics tells that right side has operators
+, / and * working over variables. In first step, variables are multiplied (one set u and t and
other set a, t and t), then 1 is divided by 2*a*t*t and added to u * t, and sum is assigned to s.
Syntax is the rule programming grammar. So programming statement may be correct on the basis of
Syntax, but it may be semantically wrong.
Bugs and Debugging
When we compile program, error messages are displayed due to syntax error, we debug (removing
the bug or error is called debugging) program and program is executed without any erroneous
message. It is a very common daily life event in software industries. When program is coded
carefully, bugs are also crept very stealthily in the program. Some compilers are equipped with
debugger to remove programming errors. These compilers diagnose errors and debug them carefully.
There are three types of errors in the program:
▪ Syntax Error,
▪ Run time Error or Execution Error, and
▪ Logical Errors
1. Syntax Error
Syntax errors are result of avoidness of rules of program coding. These errors are occurred due
to lack of concentration on language syntax. Some QBASIC experts learn C or C+ +, avoid
semicolon at the end of statements or use crater (^) sign for exponential. These types of syntax
errors are occurred due to transference of skill of one language into others and syntax errors are
occurred.
Sr. QBASIC C/C++
1. sum = x + y sum = x + y
It is a correct statement This statement is correct in QBSIC, but in correct in C/C++
in QBASIC. due to avoidness of data type and semicolon. Its correct form
is
int sum = x + y ;
2. if( age>=18) then if( age>=18) then
print " Caste vote" printf "Caste vote";
endif endif
It is a correct QBASIC In C/C++, then is not used and space is provided between end

324 Computer Science - XI Approved by CDC, Nepal


statement. and if. printf() is a function, so parenthesis is not avoidable. Its
correct form is
if( age>=18)
printf("Caste vote");
end if
Some General causes of Syntax errors:
▪ Missing parenthesis or extra parenthesis causes syntax errors.
▪ In some language (Pascal, C, C++, C#, JAVA), statements' terminators are used. Missing
terminators or extra terminators cause syntax errors.
▪ Misspelled key words.
▪ Extra blanks or missing blanks also cause syntax errors.
▪ All type of operators is very sensitive to produce syntax errors, when not used properly.
▪ The use of colon (:) instead of semi-colon (;) causes syntax errors.
The syntax errors are displayed at the time of program compilation because compilers and
interpreters are equipped with error-diagnostic features. These errors are easily debugged from
programs and some compilers check erroneous input and recover errors also. The 50 to 75% overall
programming times are to be spent on debugging.
2. Run-time Errors
The errors appeared at the time of program execution is called run-time errors. Compilers and
compilers do not detect these types of errors because these types of errors are not appeared due
to avoidness of syntax rules.
3. Logical Errors
The incomplete logic codes produce logical errors in program. These types of errors provide
incorrect output .The compiler and interpreter are unable to detect these types of errors.
Example:
x1 = -b + sqrt(d)/(2*a);
x2 = -b + sqrt(d)/(2*a);
Syntactically acceptable and would not cause any error message but produce wrong outputs.
Operation, Operand and Operator
1. Operation
The logical and mathematical process to perform certain expressions is called operation. For
example: Addition, multiplication, Comparison etc.
2. Operand
The variables used on the operations are called operand. Operand contains some value for
operation process. For example
R=A+B
Above process is addition operation. The notation/variables A and B are operand.
3. Operator
The mathematical or logical sign or notation that control and perform the operation are called
operators. For example,
Arithmetic: +, –, *, /
Logical: AND, OR,NOT
Relational: =, <=, >=, <, >, <>

Approved by CDC, Nepal Programming Concepts & Logics 325


Data Type
In programming, classification of a particular type of information. It is easy for humans to
distinguish between different types of data. We can usually tell at a glance whether a number is a
percentage, a time, or an amount of money. We do this though special symbols – –, %, : and $ – –
that indicates that data's type. Similarly, a computer uses special internal codes to keep track of the
different types of data it processes.
Most programming languages require the programmer to declare the data type of every data object,
and most database systems require the user to specify the type of each data field. The available data
types vary from one programming language to another and from one database application to another,
but the following usually exist in one form or another.
▪ Integer: In more common parlance, whole number; a number that has no fractional part.
▪ Floating point: A number with a decimal point. For example, 3 is an integer, but 3.5 is a
floating point number.
▪ Character (text): Readable text that may be digit, character or combination of them.
Codes
A computer accepts data and instructions in machine language (0's and 1's form). My data must be
represented internally by the bits 0 and 1. The binary coding schemes are used to represent data
internally in the computer memory. In binary coding, every symbol of text data is represented by a
group of bits. The group of bits used to represent a symbol is called a byte. Modern computers use 8
bits to represents a symbol.
The most popular text code systems are:
▪ BCD and EBCDIC
▪ ASCII
▪ UNICODE
BCD and EBCDIC
BCD: The BCD stands for Binary Coded Decimal. The BCD code system is one of the early code
systems. It was defined by IBM for its early computer. It was one of the first code systems to
represents data in binary form. This code system consisted of 6- bit code to represent a single
character and maximum 64 (26) characters can be represented inside the computer.
EBCDIC: In BCD, 6-bit code only 64 characters can be represented. Hence, the I3 CD code was
extended from a 6-bit code to 8-bit code and new code system is named as EBCDIC. EBCDIC
stands for Extended Binary Coded Decimal Interchange Code. In this code system, it is possible to
represent 256 (2) different characters. EBCDIC code system is still used in IBM mainframe and
midrange system, but it is rarely used in personal computers.
ASCII :ASCII stands for American Standard Code for Information and Interchange. ft is the
standard code to represent alphanumeric data. It is defined by ANSI (American Standards Institute)..
The first ASCII code was 7-bit code. Then ASCII 7-bit code system was extended to 8-bit code.
Today, ASCII 8-bit code system is mostly used in all types of computers. This code system is
popular in data communicating.
Unicode :Unicode is a worldwide character code standard. In this code system 16-bits (2 bytes) are
used to represent a single character or symbol. Using this code system, 65, 536 (216) different
characters can be represented inside the computer. The first 256 codes in Unicode are identical to the
256 codes used by ASCII system.
The Unicode standard was developed in 1991 by a joint engineering team from Apple Computer
Corporation and Xerox Corporation. Unicode system is supported by the popular operating systems
such as Windows 2000 and OS/2 and also supported by some applications.

326 Computer Science - XI Approved by CDC, Nepal


Workshop
Long Answer Questions
1. What is programming language? Explain the types of programming languages.
2. What is translator? Differentiate between different types of translators.
3. What are control structure? Explain with logical diagram and algorithm.
4. What are the program presentation tools? Explain its type with example.
5. Discuss the terms program errors, syntax and semantic with examples.
6. What is an algorithm? Write an algorithm and draw the flowchart to compute a sales
person’s commission based on a sale volume shown below:
Sales Amount Commission (% of sales)
a. Under Rs. 500/- 2%
b. Rs. 500 or more but under Rs. 5000 5%
c. Rs. 5000 and above 10%
Short Answer Questions
1. What do you understand by 4GL? Give examples.
2. Draw a diagram showing semantics of ‘case statement’ and syntax in structure English.
3. What is flowchart? Write the advantage of drawing flowcharts?
4. Logical errors are difficult to find than syntax errors. Justify.
5. Distinguish the term Operation, Operator and Operand with example.
6. Explain the difference between syntax and semantics.
7. Draw a flowchart to test condition “if-then-else” in program design process.
8. What is programming logic? What are symbols used to draw a flowchart?
9. What is the two types of programming errors? How are they detected?
10. What is flow chart? Differentiate between program flowchart and system flowchart.
11. What is program debugging? Differentiate between syntax error and logical error.
12. What are the characteristic necessary for programming to be considered as a high-level
language?
13. What do you meant by programming tools? Write name of some programming tools?
14. Write difference between Compiler and interpreter.
15. Define mnemonic.
16. Write name of some software developed using C/C++.
17. What is the bytecode?
18. What is the pesudocode? Write some rules used in pseudocodes presentation, with suitable
examples.
19. What are normal data types?
20. What are different types of codes?
21. Explain the components of computer system with block diagram.
22. What are the programming languages? Explain each of them in detail.
23. What is programming language? Explain the types of programming languages with merits and
demerits.

Approved by CDC, Nepal Programming Concepts & Logics 327


C Programming Languages
Introduction
Overview
The C Language is one of the most powerful languages. In the beginning due to the different
architectures available, the programmer had to learn different languages to create different types of
applications. The problem with Low Level Languages is that they are very difficult for the humans
to understand and developed. On the other hand, High Level Languages are easy for the humans to
understand.
The C Language is high speed and easy to understand, so it is also term as Middle Level Language
or intermediate language between high level language and low level language. It has the properties
of high level language and low level language. It is very powerful programming language because it
is used to prepare system software as well as application software. It is a kind of general purposed,
structured programming language. It has large numbers of vocabularies and syntax to write a
program.
History
C is a general purpose programming language. C language has been designed and developed by
Dennis Ritchie at Bell Laboratories in 1972. It is an offspring of the "Basic combined programming
language" called 'B ' developed in the year 1960 at Cambridge University. This language is
associated with UNIX operating system. The source code for the UNIX operating system is coded in
C. It runs under a number of operating systems including MSDOS. C programs are efficient, fast and
highly portable programming language. C programs written on one computer can be run on other
with little or no modification. C functions are the building blocks in which all programming
activities are incorporated.
What about name? The C language is so named because its predessor was called B. The B Language
was developed by Ken Thompson of Bell Labs. The development of UNIX in the C language made
it uniquely portable and improvable.
Features of C Language
C Language is very popular language because it has large numbers of features for programmer to
write medium types of program. Some basic features of C language are given below.
▪ It is highly portable Language
▪ It is procedural programming Language because the program is divided into number of
functions.
▪ It inherits or invisible functionality (memory management, CPU-register manipulation
etc.)
▪ It is general purpose structured programming Language.
▪ It is internationally standardized programming Language.
▪ It is a structured Language. It allows variety of programs by dividing into modules.
C Language is portable, procedural, general purpose, structured, standardized and compact programming
Language.

Advantages of C Language
▪ It is easy for debugging, testing and maintaining.
▪ It is Portable programming Language. This means a program written for one Computer

328 Computer Science - XI Approved by CDC, Nepal


may run successfully on other computer also.
▪ It is fast for executing. This means that the executable program obtained after compiling
and linking runs very fast.
▪ It is compact Programming Language. The statements in C Language are generally short
but very powerful.
▪ It is simple / easy. The C Language has both the simplicity of High Level Language and
speed of Low Level Language. So it is also known as Middle Level Language.
▪ It has only 32 Keywords so that easy to remember.
▪ Its Compiler is easily available.
▪ It has ability to extend itself. Users can add their own functions to the C Library
▪ It can use to design middle type of software.
Disadvantages of C Language
C programming Language has not strong disadvantages. But it has some negligible disadvantages
that are given below.
▪ There is no runtime checking.
▪ There is no strict type checking (for example we can pass an integer value for the floating
data type).
▪ As the program extends it is very difficult to fix the bugs.
▪ It may be compile time overhead due to the misplacing and excessive use of pointers.
▪ It does not use to develop complex type of software now a day.
Structure of C program
Every C program contains a number of several building blocks known as functions. Each function
performs task independently. The structure of C program is given below.
▪ Header files: C program depends upon some header files for
/* Comments*/
function definition that are used in program. Each header file by Header files
default is extended with .h. The file should be included using Function header.
#include directive. Example is given below. Global Declaration
#include<stdio.h> main( )
{
▪ Global Declaration: It declares some variables that are used in
Declaration part
more than one function. These variables are known as global Executable part
variables. These veriables must be declared outside of all the }
functions. User defined functions
▪ main( ): Every program of C language must contain main( ) {
}
function. The main ( ) is starting point of every C program.
▪ Declaration Part: It declares the variables that are used inside this particular function. The
initializations of variables are also done in this section.
▪ Executable Part: This part contains the statement blocks that may be input statement, process
statement and output statement.
▪ User defined functions: The functions defined by the user are called user defined functions.
These functions are defined before or after the main( ) function.
▪ Comments: It is not necessary in the program. However, to understand the flow of programs
the programmer can include comments in a program.
▪ Function header: It defines the heading or prototypes of the functions.

Approved by CDC, Nepal Programming Concepts & Logics 329


Example:
/*program to find sum of any two numbers*/ /* Comments*/
#include<stdio.h>
#include<conio.h> Header files
int sum(int ,int); Function header
int s; Global Declaration
void main( ) main( )
{
int a,b; Declaration part
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
s=sum(a,b); Executable part
printf("sum=%d",s);
getch( );
}
int sum(int x,int y) User defined function
{
int Z;
Z=x+y;
return(Z);
}

Compiling Process
Step 1 Use an editor to write your source code. By tradition, C source code files have the
extension .C (for example, test.C, DATA.C, and so on).
Step 2 Compile the program using a compiler. If the compiler doesn't find any errors in the
program, it produces an object file. The compiler produces object files with an .OBJ
extension and the same name as the source code file (for example, test. C compiles to
[Link]). If the compiler finds errors, it reports them. You must return to step 1 to
make corrections in your source code.
Step 3 Link the program using a linker. If no errors occur, the linker produces an executable
program located in a disk file with an .EXE extension and the same name as the
object file (for example, [Link] is linked to [Link]).
Step 4 Execute the program. You should test to determine whether it functions properly. If
not, start again with step 1 and make modifications and additions to your source code.
Editor

Source File Include Files

Preprocessor

Source File

Compiler

Other Object Library


Object File
Files Files

Linker

Executable File

330 Computer Science - XI Approved by CDC, Nepal


Your First C Program
You're probably eager to try your first program in C. To help you become familiar with your
compiler, here's a quick program for you to work through. You might not understand everything at
this point, but you should get a feel for the process of writing, compiling, and running a real C
program.
This demonstration uses a program named HELLO.C, which does nothing more than display the
words Hello, World! On-screen. This program, a traditional introduction to C programming, is a
good one for you to learn. The source code for HELLO.C is given below.
Listing 1.1. HELLO.C.
1: #include <stdio.h>
2:
3: main()
4: {
5: printf("Hello, World!\n");
6: return 0;
7: }
(Don’t use the line number and colon sign on the program. I have given it for explanation)
Entering and Compiling HELLO.C
To enter and compile the HELLO.C program, follow these steps:
1. Make active the directory your C programs are in and start your editor. As mentioned
previously, any text editor can be used, but most C compilers (such as Borland's Turbo C++ and
Microsoft's Visual C/C++) come with an integrated development environment (IDE) that lets
you enter, compile, and link your programs in one convenient setting.
2. Use the keyboard to type the HELLO.C source code exactly as shown in Listing 1.1. Press
Enter at the end of each line.
3. Save the source code. You should name the file HELLO.C.
4. Verify that HELLO.C is on disk by listing the files in the directory or folder. You should see
HELLO.C within this listing.
5. Compile and link HELLO.C. Execute the appropriate command specified by your compiler's
manuals. You should get a message stating that there were no errors or warnings.
6. Check the compiler messages. If you receive no errors or warnings, everything should be okay.
If you made an error typing the program, the compiler will catch it and display an error
message. For example, if you misspelled the word printf as prntf, you would see a message
similar to the following:
Error: undefined symbols:_prntf in hello.c ([Link])
7. Go back to step 2 if this or any other error message is displayed. Open the HELLO.C file in
your editor. Compare your file's contents carefully with Listing 1.1, make any necessary
corrections, and continue with step 3.
8. Your first C program should now be compiled and ready to run. If you display a directory
listing of all files named HELLO (with any extension), you should see the following:
HELLO.C, the source code file you created with your editor
[Link] or HELLO.O, which contains the object code for HELLO.C
[Link], the executable program created when you compiled and linked HELLO.C
9. To execute, or run, [Link], simply enter hello. The message Hello, World! is displayed
on-screen.

Approved by CDC, Nepal Programming Concepts & Logics 331


Header Files
Header files are standard file of C-programming Language. It contains the function definition of
library functions. They are written at the top of the program. Some header files are given below.

Header files are standard files that are compulsory in C program and contains the function definition of
library functions

#include<stdio.h>
It is standard input output header file. It contains the function definition of input output
functions such as scanf( ), printf( ) etc.
#include<conio.h>
It is a header file which is included in the program this is used to use, clrscr ( ), getch ( ),
[Link] do not need to include this file in C program. It is necessary for C++ programs. Conio
stands for CONsole Input Output header file.
#include<math .h>
This header file is used for mathematical functions such as pow( ), sqrt( ), sin( ), tan( ) cos( )
etc.
#include<graphics.h >
It is graphic header file. It contains the function definition of graphic processing functions such
as line( ), circle( ), rectangle( ) etc.
#include<string.h >
It is string header file. It contains the function definition of string processing functions such as
strlen( ), strcat( ), strcpy( ) etc.
C Preprocessor
A unique feature of c language is the preprocessor. A program can use the tools provided by
preprocessor to make his 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.

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 follow the special syntax rules and begin with the symbol # and do not
require any semicolon at the end. A set of commonly used preprocessor directives
Preprocessor directives:
Directive Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies a file to be included
#ifdef Tests for macro definition
#else Specifies alternatives when # if test fails

332 Computer Science - XI Approved by CDC, Nepal


The preprocessor directives can be divided into three categories
▪ Macro substitution division
▪ File inclusion division
▪ Compiler control division
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.
Simple macro substitution:
Simple string replacement is commonly used to define constants example:
#define pi 3.1415926
#define name "HSEB"
#define AREA 12.36
Defining this is also called symbolic constant
Workshop
1. Write down the history of C programming language.
2. What are the features of C programming Language?
3. Mention advantages and disadvantages of C Language.
4. Write the structure of C program and explain.
5. Draw compilation cycle of C program and explain.
6. Why header files are needed in every C program.
7. Write down the names of any four header files.
8. What is C pre-processor? Write down the names of pre-processor directive.
9. Why C is most popular language? Explain with suitable reasons.

Approved by CDC, Nepal Programming Concepts & Logics 333


Fundamentals of C
Character Set used in C
The characters are used to form words, numbers and expressions depending upon the computer on
which the program runs. The character set in C Language can be grouped into the following
categories.
▪ Letters
▪ Digits
▪ Special Characters
▪ White Space
C character sets are Letters, Digits, and Special characters and White spaces that form words, numbers
and expressions.

C Character-Set Table
Letters Digits
Upper Case A to Z 0 to 9
Lower Case a to z .
Special Characters
, Comma & Ampersand
. Period ^ Caret
; Semicolon * Asterisk
: Colon - Minus Sign
? Question Mark + Plus Sign
' Apostrophe < Opening Angle (Less than sign)
" Quotation Marks > Closing Angle (Greater than sign)
! Exclamation Mark ( Left Parenthesis
| Vertical Bar ) Right Parenthesis
/ Slash [ Left Bracket
\ Backslash ] Right Bracket
~ Tilde { Left Brace
- Underscore } Right Brace
$ .Dollar Sign # Number Sign
% Percentage Sign
White Space
▪ Blank Space
▪ Horizontal Tab
▪ Carriage Return
▪ New Line
▪ Form Feed
Comments
Comments in code can be useful for a variety of purposes. They provide the easiest way to set off
specific parts of code as well as providing a visual "split" between various parts of your code.
Having good comments throughout your code will make it much easier to remember what specific
parts of your code do.
It is not compulsory in C program but it makes easy to study the programs

334 Computer Science - XI Approved by CDC, Nepal


Comments can be written in two forms:
▪ //Single Line Comments
▪ /*Multi-Line Comments*/
Tokens
The smallest part of C programmming Language is called C tokens. C programs are written using
these tokens. There are six types of C tokens that are given below.
Takes are fundamental parts of C program from which other parts are formed

▪ Operators
▪ Keywords
▪ Identifiers
▪ Constants
▪ Strings
Special symbols
Keywords or Reserved Words
C keeps a small set of keywords for its own use. These keywords cannot be used as identifiers in the
program. It will be easy to spot, because it will provoke your compiler into telling you about invalid
names for things. Here is the list of keywords used in Standard C. you will notice that none of them
use upper-case letters.
Key words are special words that are per-defined in C programming Language

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Identifiers
Identifiers are the names given to program unit such as variable, structure, function etc. They are not
defined in programming language but are used to define by the programmer. Some basic rules to
define identifiers are given below.
The rules of identifiers are used to define program units such as variable, constant, function, structure etc

▪ First character must be an alphabet underscore then digits or alphabets


▪ It must consist of only letters, digits and underscore.
▪ Any standard C language keyword cannot be used as identifier name.
▪ It should not contain a space.
▪ It allows both upper case and lower case characters.
Valid identifies
A1 B34C _wer School int_float HSEB Ramesh Book B etc.
Invalid identifies
2ab int void sum-is ./pop
Data Types in C
Data types can be represented in variety of ways in any programming language, so that we can store

Approved by CDC, Nepal Programming Concepts & Logics 335


data in system. C language provides us the way to hold any type of data in it. It is called data type. In
C language data types are classified into two categories:-
▪ Primary data types
▪ Secondary data types
Data types are mainly used to define the type and nature of data such that compiler detects and proceed.

Primary Data Types


The fundamental data types are called primary data types. They are also used to build other data
types. The fundamental data types are given in following table.
Variable Type Keyword Bytes required Range
Character char 1 -128 to 127
Unsigned character unsigned char 1 0 to 255
Integer int 2 -32768 to 32767
Short integer short int 2 -32768 to 32767
Long integer long int 4 -2,147,483,648 to 2,147,483,647
Unsigned integer unsigned int 2 0 to 65535
Unsigned short integer unsigned short int 2 0 to 65535
Unsigned long integer unsigned long int 4 0 to 4,294,967,295
Float float 4 1.2E-38 to
Double double 8 2.2e-308 to
Long double long double 10 3.4E-4932 to 1.1E+49352
Secondary Data Types
▪ Arrays
▪ Pointers
▪ Structure
You will study later in chapter about secondary data types
User defined type declaration
C language supports a feature where user can define an identifier that characterizes an existing data
type. This user defined data type identifier can later be used to declare variables. In short its purpose
is to redefine the name of an existing data type.
Syntax: typedef <type><identifier>
Example: typedef int number;
We have just changed the default keyword “int” to declare integer variable to “number”.

336 Computer Science - XI Approved by CDC, Nepal


Another user defined data type is enumerated data type. It is defined as follows:
enum identifier{value1, value2, value3, ………,valuen};
examples
enum digits{0,1};
enum day{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday Saturday};
Type format Specifier
The format specifiers are used in C for input and output purposes. Using this concept the compiler
can understand that what type of data is in a variable during taking input using the scanf() function
and printing using printf() function. Here is a list of format specifiers.
Format Specifier Type
%c Character
%d Signed integer
%f Float values
%l or %ld or %li Long
%lf Double
%Lf Long double
%s String
These are the basic format specifiers. We can add some other parts with the format specifiers. These
are like below:
• A minus symbol (-) sign tells left alignment
• A number after % specifies the minimum field width. If string is less than the width, it will
be filled with spaces
• A period (.) is used to separate field width and precision
Variables
A variable is a value that can change any time. It is a memory location used to store a data value. A
variable name should be carefully chosen by the programmer so that its use is reflected in a useful
way in the entire program. Any variable declared in a program should confirm to the following
▪ They must always begin with a letter, although some systems permit underscore as the
first character.
▪ The length of a variable must not be more than 8 characters.
▪ White space is not allowed
▪ A variable should not be a Keyword
▪ It should not contain any special characters.
Examples of Invalid Variable names are
123 (area) 6th %abc
Examples of valid Variable names are
Sun number Salary Emp_name average1
Types of Variable
1. Numeric variable: The variables that store numeric data only are called numeric variable. The
numeric data may be whole number or fractional number. Examples 5,40,60,23.45 etc.
2 String variable: The variables that store character data only are called string variable. The
string data may be single character or string. Examples 'A', G', "Colllege", "234er" etc.
Variable can change the value while executing a program. It allocates memory space inside a memory of
computer

Approved by CDC, Nepal Programming Concepts & Logics 337


What is the purpose of variable declaration?
The purpose of variable declaration is to allocate memory space inside a memory of computer.
Declaration does two things
▪ It tells the compiler what the variable name is
▪ It specifies what type of data the variable will hold.
Syntax of variable declaration
Data-type v1, v2, v3, ……..,vn;
a b c d
Where v1, v2, v3, ……..,vn are the names of valid variables
Examples
int a, b;
float c; Memory

char d;
This diagram describes that when the variables are declared the spaces in memory are allocated
according to size. In this example a and b are integer, allocates 2 byte memory each, b is floating,
allocates 4 byte memory, c is character, allocates 1 byte memory.
Constant
A constant value is the one which does not change during the execution of a program. C supports
several types of constants. These constants are given below
▪ Integer Constants
▪ Real Constants
▪ Single Character Constants
▪ String Constants
Constant is a name whose value is always same while executing a program

Integer Constants
An integer constant is a sequence of digits. There are 3 types of integers namely decimal integer,
octal integers and hexadecimal integer. These constants are given below.
Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or - sign. Spaces,
commas and non digit characters are not permitted between digits. Examples for valid decimal
integer constants are given below.
123
-31
0
562321
+ 78
Some examples for invalid integer constants are
15 750
20,000
Rs.1000
Octal Integer: constant consists of any combination of digits from 0 through 7 with a O at the
beginning. Some examples of octal integers are
O26
O
O347
O676
Hexadecimal integer
Constant is preceded by OX or Ox, they may contain alphabets from A to F or a to f. The alphabets

338 Computer Science - XI Approved by CDC, Nepal


A to F refer to 10 to 15 in decimal digits. Examples of valid hexadecimal integers are
OX2
OX8C
OXbcd
Ox
Single Character Constants
A single character constant stores only single character. It is enclosed by single quotation mark.
Examples of single character constants are:
'A', 'B', 'h', '2', '6' etc
String Constants
A string constant is a set of characters enclosed in double quotation marks. The characters in a string
constant sequence may be a alphabet, number, special character and blank space. Example of string
constants are
"VISHAL"
"1234"
"God Bless"
"!.....?"
Difference between Variables and constants
Variables Constants
It is a name whose value can be changed during It is a name whose value cannot be changed during the
the execution of a program execution of a program
The purpose of variable declaration is to allocate The purpose of variable declaration is to allocate memory
memory space inside a memory of computer. space inside a memory of computer and assign value in it.
This concept is not provided. The symbolic constant process before compiling the
program.
Syntax: Syntax:
Datatype variablename; Datatype constantname = value;
e.g. e.g.
int a; int a = 5;
float b; float b = 10.9
Escape Sequences
The non printing characters started with slash(\) are called escape sequences. They are special
characters used in output functions. Although they contain two characters they represent only one
character. Given below is the table of escape sequence and their meanings.

Escape sequence always starts with \ and used in output function

Escape sequence Meaning


\a Audible Alert (Bell)
\b Backspace
\f Formfeed
\n New Line
\r Carriage Return
\t Horizontal tab
\v Vertical Tab

Approved by CDC, Nepal Programming Concepts & Logics 339


\' Single Quote
\" Double Quote
\? Question Mark
Statements
Statement causes the computer to carry out some action. It is terminated by semicolon. The types of
statements of C Language are given below.
▪ Expression statement
▪ Compound statement
▪ Control statement
Expression statement
An expression statement consists of an expression followed by a semicolon. The execution of an
expression statement causes the expression to be evaluated.
EXAMPLES
B=5;
c=d+e;
printf("Enter a number");
Compound statement
A compound statement consists of several individual statements enclosed with a pair of braces { }. It
provides capability for embedding statements with in other statements.
EXAMPLE
{
A=l*b;
Area=3.14*r*r;
}
Control statement
Control statements are used to create special program features such as logical tests, loops, branches
etc. Many control statements require other statements may be embedded within them.
EXAMPLE
for(i=1;i<=100;i++)
Workshop
1. What are character sets?
2. What are white spaces?
3. What is the purpose of comments in a program?
4. What are C-tokens?
5. Differentiate between key words and identifiers.
6. What are data types of C-language?
7. Differentiate between variable and constant.
8. What are scape sequence?
9. What are statements of C-language?

340 Computer Science - XI Approved by CDC, Nepal


Operators and Expressions
Operator
An operator is a symbol which helps to do a certain mathematical or logical manipulations.
Operators are used in C language operate on data and variables. C has a rich set of operators which
can be classified as:
Operators are symbols that can use for mathematical and logical operations such as +, *, <, + etc.

▪ Arithmetic operators (Binary operators)


▪ Relational Operators (Comparison operators)
▪ Logical Operators (Boolean operators)
▪ Assignment Operators
▪ Unary Operators (Increment/decrement operators)
▪ Conditional Operators (Ternary operators)
▪ Bitwise Operators
▪ Special Operators
Arithmetic Operators
All the basic arithmetic operations can be carried out in C. It can perform simple arithmetic
calculations such as addition, subtraction, multiplication etc. All the operators have almost the same
meaning as in other languages. Both unary and binary operations are available in C language. It uses
two operand so that it is called binary operator. The types of arithmetic operators are given below.

Operator Meaning Examples


+ Addition a+b
– Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus Operator a%b

Example
#include <stdio.h> //include header file stdio.h
#include<conio.h>
void main() //tell the compiler the start of the program
{
int numb1, num2, sum, sub, mul, div, mod; //declaration of variables
printf("Enter any two numbers");
scanf (“%d %d”, &num1, &num2); //inputs the operands
sum = num1+num2; //addition of numbers and storing in
sum.
printf(“sum = %d”, sum); //display the output
sub = num1-num2; //subtraction of numbers and storing in
sub.
printf(“ difference = %d”, sub); //display the output
mul = num1*num2; //multiplication of numbers and storing in
mul.
printf(“product is = %d”, mul); //display the output
div = num1/num2; //division of numbers and storing in
div.
printf(“ division = %d”, div); //display the output

Approved by CDC, Nepal Programming Concepts & Logics 341


mod = num1%num2; //modulus of numbers and storing in mod.
printf(“ modulus = %d”, mod); //display the output
getch( );
}
Relational Operators
It is required to compare the relationship between operands and bring out a decision and program
accordingly. This is when the relational operator comes into picture. It is also called comparison
operator because it is used to compare any two expressions. C supports the following relational
operators.
Operator Meaning Examples
< is less than a<b
<= is less than or equal to a<=b
> is greater than a>b
>= is greater than or equal to a>=b
== is equal to a= =b
!= is not equal to a!=b
A simple relational expression contains only one relational operator and takes the following form.
exp1 relational operator exp2
Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of
them. Given below is a list of examples of relational expressions and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C language such as if, while and
for statements to decide the course of action of a running program.
Logical Operators
Logical operators are used to give logical value either true or false. C has the following logical
operators; they compare or evaluate logical and relational expressions.
Operator Meaning Examples
&& Logical AND (a>b)&& (a>c)
|| Logical OR (a>b)|| (a>c)
! Logical NOT !(a= =b)
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is true then
the whole compound expression is true.
Example
a > b && x = = 10
The expression to the left is a > b and that on the right is x = = 10 the whole expression is true only if
both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2
expressions is true.
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to

342 Computer Science - XI Approved by CDC, Nepal


true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false and
evaluates to false if the expression is true. In other words it just reverses the value of the expression.
For example; ! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater
than or equal to y
Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes it to
the value or variable on the left of the expression. It is used to assign the value of expression into
varuable. It is written in the form:
Variable=expression
Example
x=a+b
Where x is a variable and a+b is an expression. Here the value of a + b is evaluated and substituted
to the variable x.
Shorthand operators
It is a combination of arithmetic operators and assignment operators so that it can perform the task of
arithmetic operation and assignment operation. First it performs arithmetic operation then
assignment [Link] is written in the form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator
oper = is known as shorthand assignment operator
The commonly used shorthand assignment operators are as follows

Operators Statement with Statement with simple


shorthand operator assignment operator
+= a += 1 a=a+1
-= a -= 1 a=a–1
*= a *= 1 a=a*1
/= a /= 2 a=a/2
%= a %= b a=a%b
Unary Operators
The increment and decrement operators are one of the unary operators which are very useful in C
language. They are extensively used in for and while loops. The syntax of the operators is given
below
1. ++ variable name (prefix)
2. variable name++ (postfix)
3. – –variable name (prefix)
4. variable name– – (postfix)
The increment operator ++ adds the value 1 to the current value of operand and the decrement
operator – – subtracts the value 1 from the current value of operand. ++variable name and variable
name++ mean the same thing when they form statements independently, they behave differently
when they are used in expression on the right hand side of an assignment statement.
Consider the following
m = 5;

Approved by CDC, Nepal Programming Concepts & Logics 343


y = ++m; (prefix)
In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand
and then the result is assigned to the variable on the left. On the other hand, a postfix operator first
assigns the value to the variable on the left and then increments the operand.
Conditional or Ternary Operator
The conditional operator consists of 2 symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows
exp1 ? exp2 : exp3
Where exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes
the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression. Note that only one of the expression is evaluated.
Example
a = 10;
b = 15;
x = (a > b) ? a : b
Here x will be assigned to the value of b. The condition follows that the expression is false therefore
b is assigned to x.
Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators for manipulation data
at bit level. A bitwise operator operates on each bit of data. Those operators are used for testing,
complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or
double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise
Exclusive
<< Shift left
>> Shift right
Special Operators
C supports some special operators of interest such as comma operator, size of operator, pointer
operators (& and *) and member selection operators (. and ->). The size of and the comma operators
are discussed here. The remaining operators are discussed in forth coming chapters.
The Comma Operator
The comma operator can be used to link related expressions together. Comma-linked lists of
expressions are evaluated left to right and value of right most expression is the value of the
combined expression.
For example the statement
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest

344 Computer Science - XI Approved by CDC, Nepal


precedence in operators the parenthesis is necessary. Some examples of comma operator are
The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in the
memory. The operand may be a variable, a constant or a data type qualifier. Example
m = size of (sum);
n = size of (long int);
The size of operator is normally used to determine the lengths of arrays and structures when their
sizes are not known to the programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.
Precedence & Associativity
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence
than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table; those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type) * & size of Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right
Expressions
An expression is a combination of variables constants and operators written according to the syntax
of C language. In C every expression evaluates to a value i.e., every expression results in some value
of a certain type that can be assigned to a variable. Some examples of C expressions are shown in the
table given below.
An expression is a combination of variables constants and operators written according to the syntax of C
language. In C every expression evaluates to a value

Algebraic Expression C Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)

Approved by CDC, Nepal Programming Concepts & Logics 345


(ab / c) a*b/c
2
3x +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c
The following program illustrates the effect of presence of parenthesis in expressions.

#include<stdio.h>
#include<conio.h>
void main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %f\n”,x);
printf (“y = %f\n”,y);
printf (“z = %f\n”,z);
getch( );
}
Output
x = 10.00
y = 7.00
z = 4.00
Type Casting and Conversions
Implicit type conversion
C permits mixing of constants and variables of different types in an expression. C automatically
converts any intermediate values to the proper type so that the expression can be evaluated without
loosing any significance. This automatic type conversion is known as implicit type conversion
The process of converting one type of data into another type is called data conversion

During evaluation it adheres to very strict rules and type conversion. If the operands are of different
types the lower type is automatically converted to the higher type before the operation proceeds. The
result is of higher type.
EXAMPLE
int a;
float b;
b=a;
Where integer a is automatically converted into float b
Explicit type Conversion
Many times there may arise a situation where we want to force a type conversion in a way that is
different from automatic conversion. Consider for example the calculation of number of female and
male students in a class
female_students
Ratio =
male_students
Since if female_students and male_students are declared as integers, the decimal part will be

346 Computer Science - XI Approved by CDC, Nepal


rounded off and its ratio will represent a wrong figure. This problem can be solved by converting
locally one of the variables to the floating point as shown below.
Ratio = (float) female_students / male_students
The operator float converts the female_students to floating point for the purpose of evaluation of the
expression. Then using the rule of automatic conversion, the division is performed by floating point
mode, thus retaining the fractional part of the result. The process of such a local conversion is known
as explicit conversion or casting a value. The general form is
(type_name) expression
Introduction to Library Functions
C Language is accompanied by a number of library functions that carry out various commonly used
operations or calculations. The functions that are pre-defined in programming language are called
library functions. Some library functions are used for input/output operations, some are for string
processing operations, some are for mathematical operation and so on. Each library function can
perform specific task and return specific value. Some library functions are given below in tabular form.
The special functions that are well defined in C programming languages are called library functions such
as printf( ), scanf( ), strlen( ), sqrt( ) etc.

Library functions Meanings


sqrt(d) Return the square root of d.
sbs(d) Return the absolute value of d
ceil(d) Round up to the next integer value of d
exp(d) Raise e to the power d
fabs(d) Return the absolute value of d
floor(d) Round down to the next integer value of d
fmod(d1,d2) Return the remainder when d1 is divided by d2
log(d) Return the logarithm of d
pow(d1,d2) Return d1 raised to the d2 power
tan(d) Return the tangent of d
printf(…) Display data from standard output device
scanf(…) Enter data items from the standard input device
getchar() Enter a character from the standard input device
putchar() Display a character to the standard output device
sin(d) Return the sine angle of d
toascii( ) Convert into ascii code
tolower( ) Convert letter to lowercase
toupper( ) Convert letter to uppercase
Workshop
1. What are operators?
2. Differentiate between operator and operand.
3. Differentiate between binary and ternary operator.
4. What is relational operator? List its type.
5. What are special operators of C language?
6. Write down the precedence and associtivity.
7. What are expressions of C language?
8. Write down the type casting process.
9. What is library function? List any 10 library functions.

Approved by CDC, Nepal Programming Concepts & Logics 347


Input/Output (I/O) Functions
Character Input / Output
If you will not press the return key then they’ll not start reading any input, and they’ll not print
characters on the terminal until there is a whole line to be printed. This is the lowest level of output
and input. It provides very precise control, but is usually too fiddly to be useful also. Most computers
perform buffering of inputs and outputs. These include :
1. getchar 2. putchar
getchar
It is used to input single character through input device. getchar always returns the next character of
keyboard input as an int. The EOF (end of file) is returned,if there is an error . It is usual to compare
this value against EOF before using it. So error conditions will not be handled correctly,if the return
value is stored in a char, it will never be equal to EOF.
getchar ( ) and putchar functios are used to input single character from input device and single characte
from output device

The following program is used to count the number of characters read until an EOF is encountered.
void main()
{ int ch, i = 0;
while((ch = getchar()) != EOF)
{
i ++;
printf(“%d\n”, i);
}
}
putchar
It is used to display single character. putchar puts its character argument on the standard output
(usually the screen). The following example program converts any typed input into capital [Link]
applies the function toupper from the character conversion library ctype.h to each character in turn to
do this.
void main()
{ int ch;
while((ch = getchar()) != EOF)
putchar(toupper(ch));
}
Formatted Input / Output
1. scanf ( ) function
2. printf ( ) function
scanf( ) function
It is a standard library function that can use to input any types of data from standard input device
such as key [Link] function can be used to input any combinatiobn of numeric values, single
characters and steings.
The scanf( ) function is written in the form:
scanf(control string, arg1, arg2, ..., argn)
Where control string refers to a string containing required formatting information. It consists of
individual groups of characters, with one character group for each input data item. Each character
group must begin with percent sign(%).
arg1, arg2,……, argn are arguments that represent the individual data items. Each argument starts
with ampersand (&) except string data.

348 Computer Science - XI Approved by CDC, Nepal


Conversion Character Meaning
c Reads a single character
d Reads a decimal integer
i Reads an integer. The integer may be in octal (with leading 0) or
hexadecimal (leading 0x or 0X)
u Reads an unsigned decimal integer
x Reads a hexadecimal integer
o Reads a octal integer
e, f, g Reads a floating-point number (float)
s Reads a string
[...] Scans for a sets of characters
p Reads an address
ld Reads long integer
Example
#include<stdio.h>
void main( )
{
int a;
float b;
char x[10];
……………………..
scanf("%d%f%s", &a,&b,x);
………………………
}
prinf() function
It is a standard library function that can use to display any types of data from standard output device
such as monitor. This function can be used to output any combination of numeric values, single
characters and strings. This function moves data from the computers memory to the standard outpud
device.
scanf( ) function is used to input any types of data through input device and printf( ) function is used to
display any types of data from output device.

The printf( ) function is written in the form:


printf(control string, arg1, arg2, ..., argn)
Where control string refers to a string containing required formatting information. It consists of
individual groups of characters, with one character group for each input data item. Each character
group must begin with percent sign(%).
arg1, arg2,……, argn are arguments that represent the individual output data items. Each argument
does not start with ampersand(&) except address.
Conversion character Meaning
c single character
d signed decimal integers
e floating-point value in scientific notation (lowercase e)
f floating-point value without an exponent
o unsigned octal
s string of characters
u unsigned decimal integers
x unsigned hexadecimal (lowercase letters)
X unsigned hexadecimal (uppercase letters)
ld Long integer

Approved by CDC, Nepal Programming Concepts & Logics 349


Example
#include<stdio.h>
void main( )
{
int a;
float b;
char x[10];
……………………..
printf("%d%f%s", a,b,x);
………………………
}
We may use some number just before the conversion specifiers to display in particular format from
the screen. The format is given below.
%wd and %[Link]
Where w is the width of integer number .In w.d ,d indiates space after decimal point.
Example
%5d
%4.3f
gets( )
It is a library function that can use to input string data from standard input device.
Syntax: gets(string expression);
Example: #include<stdio.h>
void main( )
{
char x[10];
……………….
gets(x);
…………………
}
puts( )
It is a library function that can use to display data from standard outputt device.
gets( ) function is used to input character data s through input device and puts( ) function is used to display
characters data from output device.

Syntax: putss(string expression);


Example: #include<stdio.h>
void main( )
{
char x[10];
……………….
puts(x);
…………………
}
Differentiate betweens gets() and puts()
gets( ) puts( )
It stands for get - string. It stands for put-string.
Conversion specifies are not used with it. The conversion specifies are not used with puts(
).
It reads a string from key-board(Standard Input It uses one argument, which can be either a data -
Device) item, or a variable. It displays data (string) on

350 Computer Science - XI Approved by CDC, Nepal


screen (Standard Output Device).
Format: gets(variable) ; Format: gets(data - item or variable);
Example : Example:
main( ) main( )
{ {
char name[20]; char name[20];
printf("Enter name:"); gets(name); printf("What is your name:");
puts(name); gets(name) ;
} puts(name);
puts("Thank You ");
}
Differentiate between scanf() and printf()
Sr. scanf( ) printf( )
(i) It stands for scan format. So, it is a formatted input It stands for print format. So, it is used for
function. formatted out put.
(ii) Format: scanf(control sequence,var-1,var-2 ..) ; Format: printf(control sequence ,var-
We use %d, %f,%s etc are control 1,var-2 ...); or
sequences. printf(strings) ;
We use ampersand (&) with numeric
variables.
(iii) Example: Example:
void main( ) void main( )
{ {
int x , y ; float x , y ;
printf("Enter two integers :") ; printf("Enter two floats :") ;
scanf("%d%d" , &x , &y) ; scanf(" %f %f " , &x , &y) ;
printf("x = %d , y = %d\n" , x ,y) ; printf(" x = %.2f , y = %.2f \n" ,x,y)
getch( ); ;
} getch( );
}
Some Programs
1. Write a program to find area of circle
/*program to find area of circle*/
#include<stdio.h>
#include<conio.h>
#define pi 3.14
void main( )
{
float r, area;
printf("Enter radius of circle");
scanf("%f",&r);
area=pi*r*r;
printf("\nArea of circle=%f", area);
getch( );
}

Approved by CDC, Nepal Programming Concepts & Logics 351


2. Write a program to find area and perimeter of rectangle
/*program to find area and perimeter of rectangle*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int l,b,a,p;
printf("Enter length and breadth of rectangle:");
scanf("%d%d",&l,&b);
a=l*b;
p=2*(l+b);
printf("\nArea of rectangle=%d",a);
printf("\nperimeter of rectangle=%d",p);
getch( );
}
3. Write a program to find area of triangle in which three sides are given
/*program to find area of triangle*/
#include<stdio.h>
#include<conio.h>
#include<math.h >
void main( )
{
float a,b,c,s,A;
printf("Enter three sides of a triangle:");
scanf("%f%f%f",&a,&b,&c);
s=(a+b+c)/2;
A=sqrt(s*(s-a)*(s-b)*(s-c));
printf("\nArea of triangle=%f",A);
getch( );
}
4. Write a program to read a 4 digit number then find the sum of first & last digit.
/* program to read a four digit number then find the sum of first and last digit
*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,s;
long int x;
printf("Enter four digit number :");
scanf("%ld",&x);;
a=x%10;
b=x/1000;
s=a+b;
printf("\sum of four digit number =%d",s);
getch( );
}

352 Computer Science - XI Approved by CDC, Nepal


Workshop
1. What are input/output functions of C-language.
2. Differentiate between printf() and scanf() functions.
3. Differentiate between gets() and puts() functions.
4. Write a program to ask no of quantities and price for per quantity then find total price.
5. Write a program to read mark price of radio and find discount which is 30% of mark price then
find actual selling price of radio.
6. Write a program to read basic salary then find tax and allowance, tax is 20% of basic salary and
allowance 40% of basic salary. Also find out net salary.
7. Input cost price and selling price of watch then find profit percentage.
8. Write a program to input roll no., your college name and your name then display
9 Write a program to read the age of three people then find average age.
10. Write a program to find area of circle.
11. Write a program to convert meter into centimetre.
12. Write a program to convert hour into minutes.
13. Write a program to convert rupees into dollars. (1$ = 70Rs)
14. Write a program to convert feet into inch. (1 feet = 12 inch)
15. Write a program to convert Fahrenheit temperature into centigrade temperature.
16. Write a program to find square, cube and square root of given number.
17. Write a program to solve two linear equation
18. Write a program to find the sum of X and Y; X = a²+2ab+b², Y = a² – 2ab + b²
19. Write a program to input radius of circle of circle then find circumference and area.
20. Write a program to input four digits number then find its reverse.
21. The distance between two places is input through keyboard in meter then converts into
centimetre and again converts into inch.

Approved by CDC, Nepal Programming Concepts & Logics 353


Control Structures
Decisions
The C language programs presented until now follows a sequential form of execution of statements.
Many times it is required to alter the flow of the sequence of instructions. C language provides
statements that can alter the flow of a sequence of instructions. These statements are called control
statements. These statements help to jump from one part of the program to another. The control
transfer may be conditional or unconditional.
Control statements are mainly used to select statements, to repeat the statements number of times and to
jump from one part to other parts inside a program

We have seen that a C program is a set of statements, which are normally executed sequentially in
the order in which they appear. This happens when no repetitions of certain calculations are
necessary. However, in practice, we have a number of situations here we may have to change the
order of execution of statements based on certain conditions are met. They are called control
structure. It is broadly divided into following type.
Control statement

Selection Loopin g Jum pin g


statem en t statem en t statem en t

-if statem en t -for statement -break statem en t


-switch statem en t -wh ile statement -con tinu e statem en t
-do…wh ile statemen t -goto statem en t

Selection Statement
It is a kind of control statement that can use to select the required statements among the numbers of
statements. The types of selection statements are given below.
▪ if statement
▪ switch statement
if statement
The if statement is a powerful decision making statement and is used to control the flow of execution
of statements. It is basically a two-way decision statement and is used in conjunction with an
expression. It takes the following form:
if (test expression)
It allows the computer to evaluate the expression first and then, depending on whether the value of
the expression (relation or condition) is ' true ' (non-zero) or ' false' (zero), it transfers the control to a
particular statement. This point of program has two paths to follow, one for the true condition and
the other for the false condition. The if statement may be implemented in different forms depending
on the complexity of the conditions to be tested.
▪ Simple if statement
▪ if...else statement
▪ Nested if...else statement
▪ else if statement

354 Computer Science - XI Approved by CDC, Nepal


Simple if statement
This is a conditional statement used in C to check condition or to control the flow of execution of
statements. This is also called as 'decision making statement or control statement.' The execution of a
whole program is done in one direction only.
This statement is only used if all conditions are known otherwise it does not execute any statements.

Syntax: if(condition)
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside
the braces and executes the block of statements associated with it. If it returns false, then program
skips the braces. If there are more than 1 (one) statements in if statement then use { } braces else it is
not necessary to use.
Examples
..........
if (x == 1)
{
y = y +10;
}
printf("%d", y);
.........
Write a program to check given number is greater than, equal to or laess then 4.
#include <stdio.h>
#include <conio.h>
void main()
{
int a;
clrscr( );
printf("Enter a number:");
scanf("%d", &a);
if(a>4)
printf("\nValue of A is greater than 4 ");
if(a>4)
printf("\nValue of A is less than 4 ");
if(a= =4)
printf("\n\n Value of A is 4 ");
getch();
}
/* Program to find the greatest number between any two number using simple
if statements */
#include <stdio.h>
void main()
{
int x,y;
printf("\nInput an integer value for x: ");
scanf("%d", &x);
printf("\nInput an integer value for y: ");
scanf("%d", &y);
/* Test values and print result */
if (x == y)
printf("%d is equal to %d\n",x,y);
if (x > y)
printf("%d is greater than %d\n",x,y);
if (x < y)
printf("%d is smaller than %d\n",x,y);
}

Approved by CDC, Nepal Programming Concepts & Logics 355


The if…else statement
It is a statement having only one expression, if it is satisfied then corresponding statements are
executed otherwise else statements are executed. The if statement can optionally include an else
clause. It is written in the following form.
if (expression)
statement1;
else
statement2;
If expression evaluates to true, statement1 is executed. If expression evaluates to false,
statement2 is executed. Both statement1 and statement2 can be compound statements or blocks.
Using if..else, you can specify an action to be performed both when the condition is true and when it
is false.
if …. else statement is used if we need to select from any two alternatives

False Test True


expression

statement2 statement1

The program statements using if …. else statements are given below.


if (age >= 18)
printf("You can vote\n");
else
printf("You can’t vote\n");
In the program statements, if age is greater or equal to 18 then you can vote other wise you can’t
vote.
if (status == 'S')
tax = 0.20 * pay;
else
tax = 0.14 * pay;
printf("Tax: %f\n", tax);
In the program statements, if status is ‘S’ then tax is 20% otherwise tax is i4%
Program to check given number is odd or even

Write a program to check given number is odd or even


#include<stdio.h>
#include<conio.h>
void main()
{
int num,r;
printf(“\nEnter a number:”);
scanf(“%d”,&num);

356 Computer Science - XI Approved by CDC, Nepal


r=num%2;
if(r==0)
{
printf(“%d is even number\n”,num);
}
else
printf(“%d is odd number\n”, num);
getch()
}
Nested If-Else Statement
It is a conditional statement which is used when we want to check more than 1 conditions at a time
in a same program. The conditions are executed from top to bottom checking each condition whether
it meets the conditional criteria or not. If it found the condition is true then it executes the block of
associated statements of true part else it goes to next condition to execute.
Nested if … else statement is appropriate if we need to check one condition inside another condition. In this
statement, one if statement is completely inside another if statement.

Syntax: if(condition1)
{
if(condition2)
{
statements1;
}
else
{
statements2;
}
}
else
{
statements3;
}
In above syntax, the condition1 is checked first. If it is true, then the program control flow goes
inside the braces and again checks the next condition. If it is true then it executes the block of
statements1 associated with it else executes else part.
Write a program to check given number is positive, negative or zero.
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter Number :");
scanf("%d",&no);
if(no>0)
{
printf("\n\n Number is greater than 0 !");
}
else
{
if(no==0)

Approved by CDC, Nepal Programming Concepts & Logics 357


{
printf("\n\n It is 0 !");
}
else
{
printf("Number is less than 0 !");
}
}
getch();
}

/*Program to find greatest number among any three numbers using nested if
statement*/
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
printf(“Enter any three numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
if(x > y)
{
if(x > z)
printf("x is greater");
else
printf("z is greater");
}
else
{
if (y > z)
printf("y is greater");
else
printf("z is greater");
}
getch();
}
Else if Statement (else if ladder)
There is another way of putting if together when multipath decisions are involved. A multipath
decision is a chain of if in which the statement associated with each else is an if. A common
programming construct is the else if ladder. It is simply the combination of multiple nested [Link]
statements which forms like a ladder therefore it is sometimes called ladders of [Link] statements.
The conditions are evaluated from the top downward. As soon as a true condition is found, the
statement associated with it is executed and the rest of the ladder is bypassed. If none of the
conditions are true, the final else is executed. If the final else is not present, no actions take place if
all other conditions are false. The syntax of this statement is given below.
if(expression1)
Statement1;
else if(expression2)
Statement2;
else if(expression3)
Statement3;
……..
……..
else
Statementn;
Statementx

else if statement is used if we need to check large numbers of condition and determine the appropriate
result.

358 Computer Science - XI Approved by CDC, Nepal


In this statement, expression1 is evaluated; if it is true then statement1 is executed, if it is false and
statement2 is evaluated and if it is true then statement2 is executed and so no. If any expression is
not true then statement1 is executed. The last statement is executed if any expression is true or false.
The representation of flowchart is given below.
Program to input percentage then find division according to given conditions:
Percentage Division Entry
p>=80 Distinction
80>p>=60 First Division
60>p>=50 Second Division Y
Expression1 Statement1
50>p>=40 Third Division
Otherwise Fail
N
#include<stdio.h>
Y
#include<conio.h> Expression2 Statement2
void main()
{
float p; N
printf(“\nEnter percentage:”);
scanf(“%f”, &p); Y
Expression3 Statement3
if(p>=80)
{
printf(“Distinction\n”); N
} Statementn
else if(p>=60)
{
printf(“First Division\n”); Statementx
}
else if(p>=50)
{
printf(“Second Division\n”);
}
else if(p>=40)
{
printf(“Third Division\n”);
}
else
{
printf(“Fail\n”);
}
getch();
}
Switch case Statement
When one of the many alternatives is to be selected, we can use if statement to control the selection.
However, the complexity of such a program increases dramatically when the number of alternatives
increases. The program becomes difficult to read and follow. At times, it may confuse even the
person who designed it. Fortunately, c has a built-in multiway decision statement known as a switch.
The switch statement tests the value of a given variable (or expression) against a list of case values
and when a match is found, a block of statements associated with that case is executed. If there are
large numbers of conditions then if statement may not handle, to remove such problem switch
statement is used. It can use to handle any numbers of cases. The general form of the switch
statement is as shown below:

Approved by CDC, Nepal Programming Concepts & Logics 359


switch (expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
…………
………….
default:
default-block
break;
}
Statement-x;
The expression is an integer expression or characters. Value-1, value-2…….are constants or constant
expressions are known as case labels. Each of these values should be unique within a switch
statement. block-1, block-2 ……. are statement lists and may contain zero or more statements. There
is no need to put braces around these blocks. Note that case labels end with a colon (:).
When the switch is executed, the value of the expression is successfully compared against the values
value-1, value-2…if a case is found whose value matches with the value of the expression, then the
block of statements that follows the case are executed. The break statement at the end of each case is
to exit from the switch statement. If any value is not matched then default statement is executed.
Statementx is executed if any cases match or not.
The flow chart to represent switch statement is given below:
Entry

N
Expression1

Y
Default

Case1 Case2 Case2

Block1 Block2 Block3 Blockn

Statementx

Rules for switch statements


▪ The switch expression must be an integral type.
▪ Case labels must be constants or constant expressions.
▪ Case labels must end with semicolon.
▪ Case labels must be unique. No two labels can have the same value.
▪ There may be at most one default label.
▪ The default may be placed anywhere but usually placed at the end.
▪ The break statement transfers the control out of the switch statement.
▪ The break statement is optional If present, it will be executed when the expression does not find
a matching case label.

360 Computer Science - XI Approved by CDC, Nepal


Advantages of switch case
▪ Easy to use.
▪ Easy to find out errors.
▪ Debugging is made easy in switch case.
▪ Complexity of a program is minimized.
Program to choose color by switch statement is given below:
#include<stdio.h>
#include<conio.h>
void main()
{
char choice;
printf(“Enter your choice\n”);
choice = getchar();
switch(choice)
{
case 'r':
printf("RED");
break;
case 'w':
printf("WHITE");
break;
case 'b':
printf("BLUE");
break;
default:
printf("Unknown");
}
Write a program to choose 1-3 to demonstrate it.
#include <stdio.h>
#include <conio.h>
void main()
{
int no;
clrscr();
printf("\n Enter any number from 1 to 3 :");
scanf("%d",&no);
switch(no)
{
case 1:
printf("\n\n It is 1 !");
break;
case 2:
printf("\n\n It is 2 !");
break;
case 3:
printf("\n\n It is 3 !");
break;
default:
printf("\n\n Invalid number !");
}
getch();
}
Demonstrate the switch case condition to input any two numbers the find the followings according to
choice.
Choice Calculations
1 Multiply
2 Divide
3 Subtract
4 Add

Approved by CDC, Nepal Programming Concepts & Logics 361


#include<stdio.h>
#include<conio.h>
void main()
{
int Choice;
float Value1, Value2;
printf("Enter value 1: ");
scanf("%f", &Value1);
printf("Enter value 2: ");
scanf("%f", &Value2);
printf("\n1. Multiply");
printf("\n2. Divide");
printf("\n3. Subtract");
printf("\n4. Add");
printf("Enter your choice [1-4]: ");
scanf("%d", &Choice);
switch(Choice)
{
case 1:
printf("\nThe result is: %g", Value1*Value2);
break;
case 2:
printf("\nThe result is: %g", Value1/Value2);
break;
case 3:
printf("\nThe result is: %g", Value1-Value2);
break;
case 4:
printf("\nThe result is: %g", Value1+Value2);
break;
default:
printf(“Invalid choice”);
}
}
Write a program to find followings:
1. Area of circle 2. Area of rectangle
3. simple interest
#include<stdio.h>
#include<conio.h>
#define pi 3.14
void main()
{
int Choice;
float r,a,l,b.p,t,r,si;
printf("\n1. Area of circle");
printf("\n2. Area of rectangle");
printf("\n3. Simple interest");
printf("Enter your choice [1-3]: ");
printf("Enter your choice");
scanf("%d", &Choice);
switch(Choice)
{
case 1:
printf("Enter radius of circle:");
scanf("%f",&r);
a=pi*r*r;
printf(""\nArea of circle:",a);

362 Computer Science - XI Approved by CDC, Nepal


break;
case 2:
printf("Enter length and breath of rectangle:");
scanf("%f%f",&l,&b);
a=l*b;
printf(""\nArea of rectangle is:",a);
break;
case 3:
printf("Enter principal, time and rate :");
scanf("%f%f%f",&p,&t,&r);
si=(p*t*r)/100;
printf(""\nSimple interest is:",si);
break;
default:
printf(“Invalid choice”);
}
}
Example of switch statement using single case and multiple case
#include<stdio.h>
#include<conio.h>
void main()
{
Int n;
printf("Enter ypur choice");
scanf("%d", &n);
switch (n)
{
case 1:
case 2:
printf("1 or 2");
break;
case 3:
case 4:
printf(“3 or 4”);
case 5:
case 6:
printf("5 or 6?");
printf("or may be 3 or 4");
default:
break;
}
In this program for value 1 and 2 printf("1 or 2") is executed, similarly for value 3 and 4 printf("3 or
4") is executed and so on.
Looping
During looping a set of statements are executed until some conditions for termination of the loop is
encountered. A program loop therefore consists of two segments one known as body of the loop and
other is the control statement. The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Looping is the statement that repeats same types of statements number of times until specific condition is
satisfied.

In looping process in general would include the following four steps


▪ Setting and initialization of a counter
▪ Execution of the statements in the loop
▪ Test for a specified conditions for the execution of the loop

Approved by CDC, Nepal Programming Concepts & Logics 363


▪ Incrementing the counter
The test may be either to determine whether the loop has repeated the specified number of times or
to determine whether the particular condition has been met.
Types of Looping Statement
▪ while statement
▪ do …….. while statement
▪ for statement
While Statement
The most basic loop in C is the while loop. A while statement is like a repeating if statement. Like an
If statement, if the test condition is true: the statements get executed. The difference is that after the
statements have been executed, the test condition is checked again. If it is still true the statements get
executed again. This cycle repeats until the test condition evaluates to false.
while is a looping statement in which condition is checked first then body is executed if condition is true.

Syntax
while(expression)
{
Body of loop;
}

First expression is evaluated. If expression is nonzero (true), then body of loop is executed and
control is passed back to the beginning of the while statement, otherwise control passes to next
statement following the while statement. The flow chart of this statement is given below:

is True Body
expression of loop

False

Next
statement

/* Prints hello world 10 times */


#include<stdio.h>
#include<conio.h>
void main()
{
int c
c= 1; /* initialization */
while (c <= 10) /* repetition condition */
{
printf("Hello World\n");
++c; /* increment */
}
getch()
}
In the above example, what will happen if ++c; statement is omitted? The answer is the while loop
gets always thereby Hello World will be printed on the screen infinitely.

364 Computer Science - XI Approved by CDC, Nepal


/* Reads a positive number and calculates the sum of its digits */
#include <stdio.h>
#include <conio.h>
void main()
{
int n,sum;
printf("Enter a positive number: ");
scanf("%d", &n);
sum = 0;
while (n != 0)
{
sum = sum+n%10;
n = n/10;
}
printf("The sum of the digits in %d is %d\n", n, sum);
getch();
}

Nested while loop


If one while loop is inside another while loop called nested while loop. Generally it is written in the
following form.
while(expression1)
{
while(expression2)
{
Body of loop;
}
}
In this looping, expression1 is evaluated, if it is true then expression2 is evaluated, if it is also true
then body of loop is executed. If expression2 is false, exit from inner loop and if expresson1 is false
exit from outer loop.
Program using nested while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,m;
i=1;
while(i<=5)
{
j=1;
while(j<=5)
{
m=i*j;
printf(“%d\t”,m);
j++;
}
i++;
printf(“\n”);
}
gerch();
}
Output
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Approved by CDC, Nepal Programming Concepts & Logics 365


do...while loop
do ... while is just like a while loop except that the test condition is checked at the end of the loop
rather than the start. This has the effect that the content of the loop are always executed at least once.
do … while is a looping statement in which body of loop is executed first then condition is checked.

Syntax
do
{
Block of statements;
} while(expression); Body of
The do while loop is also a kind of loop, which is similar to the while loop

loop in contrast to while loop, the do while loop tests at the bottom of
the loop after executing the body of the loop. Since the body of the loop
is executed first and then the loop condition is checked we can be
assured that the body of the loop is executed at least once. is True
Some program structures are given below: expression

/*To display Hellow Word 10 times*/


#include<stdio.h>
#include<conio.h> False
void main()
{ Next
int c; Statement
c = 1;
do
{ printf("Hello World\n");
c++;
} while (c <= 10);
getch( );
}
Nested do … while loop
If one do … while loop is inside another do …. while loop is called nested do … while loop.
Generally it is written in the following form.
do
{
do
{
Body of loop;
}
while(expression1);
}
while(expression2);
In this looping, the body of loop is executed once then check expression1, if it is true then again
body is executed. If expression2 is not true then exit from the loop. Example is given below.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,m;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
m=i*j;

366 Computer Science - XI Approved by CDC, Nepal


printf(“%d\t”,m);
}
printf(“\n”);
}
gerch();
}
Output
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
for Loop
for loop is similar to while, it's just written differently. for statements are often used to proccess lists
such a range of numbers. It is written in the form:
Syntax
for( expression1; expression2; expression3)
{
Block of statements;
}
In the above syntax:
▪ expression1 - Initializes variables.
▪ expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
▪ expression3 - expression3 is the modifier which may be simple increment of a variable.
for is a looping statement in which initialize, condition and increment/decrement are written in a for.

expr1

expr3

true
expr2? statement

false

/* Prints Hello World 10 times on the screen*/


#include<stdio.h>
#include<conio.h>
void main()
{
int c;
for (c = 1; c<= 10; c++)
{
printf("Hello World\n");
}
getch( ):
}

Approved by CDC, Nepal Programming Concepts & Logics 367


/* Prints 0 to 100 */
#include<stdio.h>
#include<conio.h>
void main()
{
int d;
for (d= 0; d<= 100; d++)
{
printf("%d\n", d);
}
getch( );
}

/* Sum of first n natural numbers */


#include<stdio.h>
#include<conio.h>
void main()
{
int n,c,sum;
printf("Enter a value of n");
scanf("%d", &n);
sum = 0;
for (c = 1; c <= n; c++)
{
sum += c;
}
printf("The sum of first %d numbers is %d", n, sum);
getch( );
}
Nested for loop
If one for loop is inside another for loop called nested for loop. Generally it is written in the
following form.
for(expression1; expression2; expression3)
{
for( expression4; expression5; expression6)
{
Block of statements;
}
}
Program to display multiplication table.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,m;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
m=i*j;
printf(“%d\t”,m);
}
printf(“\n”);
}
gerch();
}
Output
12345
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

368 Computer Science - XI Approved by CDC, Nepal


Difference between for loop and while loop
for Loop while Loop
It is definite loop. It may be definite and may not be definite.
The loop expression is written in a one The loop expression is not written in one
block. block
The keyword for is used. The keyword while is used
Syntax: Syntax:
for(expression1;expression2;expression3) while(expression)
{ {
Block of statements; Body of loop;
} }
e.g. void main() e.g. void main()
{ {
int n; int n=1;
for(n=1;n<10;n++) while(n<=10)
printf("HSEB"); {
} printf("HSEB");
n++;
}
}
Difference between while loop and do..while loop
while Loop do-while Loop
In the while loop test condition is In do-while loop the test condition is evaluated
evaluated before the loop is executed. after the loop is executed.
The keyword while is used. Two keywords do and while are used.
Loop is not terminated with semicolon. Loop is terminated with a semicolon.
It doesn't execute the body of loop until Body of the loop will always executed at least
and unless the condition is true. once since the test condition is not checked until
the end of the loop.
Syntax: Syntax:
while(expression) do
{ {
Body of loop; Block of statements;
} } while(expression);
Example Example
void main() void main()
{ {
int n=1; int n=1;
while(n<=10) do
{ {
printf("HSEB"); printf("HSEB");
n++; n++;
} }
} while(n<=10);
}

Approved by CDC, Nepal Programming Concepts & Logics 369


Jumping statement
Jumping statements are unconditional control statements. These are mainly used to jump from one
place to another place inside a program. These statements may execute same statements numbers of
times or neglect some statements. The types of jumping statements are given below.
▪ break statement
▪ continue statement
▪ goto statement
Jumping statements are the statements that are used to jump from one part to another part inside a
program

Break Statement
Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as
soon as certain condition occurs, for example consider searching a particular number in a set of 100
numbers as soon as the search number is found it is desirable to terminate the loop. C language
permits a jump from one statement to another within a loop as well as to jump out of the loop. The
break statement allows us to accomplish this task. A break statement provides an early exit from for,
while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited
immediately.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i= =j)
break;
printf("%d\t%d\n",i,j);
}
printf("\n");
}
getch( );
}
output
2 1

Continue statement
During loop operations it may be necessary to skip a part of the body of the loop under certain
conditions. Like the break statement C supports similar statement called continue statement. The
continue statement causes the loop to be continued with the next iteration after skipping any
statement in between. The continue with the next iteration is occured.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i= =j)

370 Computer Science - XI Approved by CDC, Nepal


continue;
printf("%d\t%d\n",i,j);
}
printf("\n");
}
getch( );
}
output
12
21
Differences between break and continue
Break statement Continue statement
It is a statement that is used to terminate the It is a statement that is used to continue
control from the switch...case structure and from the control inside a loop
loop.
The break statement terminates the entire loop The continue statement terminates single
execution pass of the loop.
It uses the key word break. It uses the key word continue
The loop does terminate when a break is The loop doesn't terminate when a
encountered continue is encountered
E.g.: E.x:
void main() void main()
{ {
int i; int i;
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if(i>=5) if(i>=5)
break; continue;
printf("%d\t",i); printf("%d\t",i);
} }
} }
Goto statement
It is a kind of jumping statement. When program execution reaches a goto statement, execution
immediately jumps to the location specified by the goto statement. This statement is unconditional
because execution always branches when a goto statement is encountered. It is written in the form:
goto label;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
if(a%2= =0)
goto even;
else
goto odd;
even:
printf("%d is even number",a);
return;
odd:
printf("%d is odd number",a);
getch( );
}

Approved by CDC, Nepal Programming Concepts & Logics 371


Programs examples
Write a program to find the factorial of a given number
#include<stdio.h>
#include<conio.h>
void main()
{
int a,f=1,i;
printf("Enter a number to find factorial");
scanf("%d",&a);
for(i=1;i<=a;i++)
{
f=f*i;
}
printf("\nFactorial =%d",f);
getch( );
}
Write a program to check given number is prime or composite
#include<stdio.h>
#include<conio.h>
void main()
{
int a,r,i;
printf("Enter a number to check prime or composite");
scanf("%d",&a);
for(i=2;i<a/2;i++)
{
r=a%2;
if(r= =0)
{
printf("%d is composite number", a);
break;
}
}
if(r!=0)
printf("%d is prime number",a);
getch( );
}
Write a program to find the reverse of a given number
#include<stdio.h>
#include<conio.h>
void main()
{
int a,r,rev=0;
printf("Enter a number");
scanf("%d",&a);
while(a!=0)
{
r=a%10;
rev=rev*10+r;
a=a/10;
}
printf("\nreverse no=%d",rev)
getch( );
}
Write a program to check given number is palindrome or not
#include<stdio.h>
#include<conio.h>
void main()

372 Computer Science - XI Approved by CDC, Nepal


{
int a,r,rev=0,x;
printf("Enter a number");
scanf("%d",&a);
x=a;
while(a!=0)
{
r=a%10;
rev=rev*10+r;
a=a/10;
}
if(x= = rev)
printf("%d is palindrome number",x);
else
printf("%d is not palindrome number",x);
getch( );
}
Write a program to display 'n' terms of fibonnanci series
#include<stdio.h>
#include<conio.h>
void main()
{
int a=0,b=1,n,c,i;
printf("Enter a value of n");
scanf("%d",&n);
printf("%d\t%d\t",a,b);
for(i=3;i<=n;i++)
{
c=a+b;
printf("%d\t",c);
a=b;
b=c;
}
getch( );
}
Write a program to display following
1
12
123
123
1234
12345
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
getch( );
}

Approved by CDC, Nepal Programming Concepts & Logics 373


Workshop
1. Write a program to input a number then find out it is less than 200 or not.
2. Write a program to find the greater number between any two numbers.
3. Write a program to input age then display the following.
Age Display
Age>20 ADULT
20 = > Age>12 TEEN AGE
Age < 12 Child
4. Write a program to find whether a year is leap year or not.
5. Write a program to input sales amount for a sales person then find commission according to
given condition.
Sales amount Commission
Below 10000 No commission
>= 10000and <20000 20%
>= 20000 30%
6. Write a program to input temperature then print the massage according to temperature
a. Ice, if value of temperature is less than 0
b. Water, if value of temperature is between 0 and 100
c. Steam, if value of temperature is more than 100
7. Write a program to find following by select case statement
a. Area of rectangle.
b. Simple interest.
c. Volume of cube.
8. Write a program to find following by switch case statement.
a. Greater number between two number.
b. Check a number is odd or even number.
c. Check number is positive or negative.
9. Write a program to read number of quantity and price for each quantity then find out total price.
Also catagories the item according to total price by following condition.
Total price Category
Tp> 300000 Photocopy machines
300000> tp > =200000 Computers
200000 > tp >= 100000 Mobiles
Otherwise Stationeries
10. Electricity authority center going to record the biling system in computer program that ask the
number of unit electricity consumed then calculate the total charge according to goven
condition.
Unit of electricity Charge rate
U ≤20 Minimum Rs 100
20 < U ≤ 40 RS 6 per unit for more than 20
40 < U ≤ 80 RS 6.5 per unit for more than 40
80 < U ≤ 100 RS 7 per unit for more than 80
Otherwise RS 7.5 per unit for more than 100

374 Computer Science - XI Approved by CDC, Nepal


11. Write a program of following
a. 1,2,3,……………..100
b. 1,3,5,……………..99
c. 2,4,8,……………..10th terms
d. 2,4,6,……………..n’th terms
e. 1,8,27,64,………...10th term
f. 5,125,…………….5th terms
g. 1,11,111,1111,11111
h. 5,55,555,5555,55555
i. 100,98.5,97,………..10th terms
j. 3,9,27,……………...10th terms
k. 0.1,0.11,0.111,0.111,0.1111,0.11111
l. 11111,1111,111,11,1
m. -25,-20,-15,…………20th terms
n. 3,12,27,……………..10th terms
o. 1,1/2,1/3,…………..1/n
p. 1²,2²,3²………………100²
q. 2³,4³,6³,………………..100³
r. 2/1²,2/2²,2/3²…………….10th terms
s. ½,2/3,3/4………………...20th terms
t. 2²/3²,3²/4²,4²/5²,………….100²/101²
u. 1,3,5,……………………..n terms
v. 1!,3!,5!,…………………..n!
w. 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
x. 5 5 5 5 5
5 5 5 5
5 5 5
5 5
5
y. 5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
z. 1
1 1
1 1 1
1 1 1 1
1 1 1 1 1

Approved by CDC, Nepal Programming Concepts & Logics 375


12 Write a program to find factorial of a given number.
13. Write a program to check given number is prime or not
14. Display a multiplication table of 1 to 10
15. Write a program to display multiplication table of 2
16. Write a program to display all odd numbers between 100 to 200
17. Write a program to display all prime numbers between 500 to 600.
18. Write a program to find sum of square of digits of a given number.
19. Write a program to find the sum of 23,43 and 12 of a given number 234312
20. Write a program to find the product of digits of a given number.
21. Write the program to find the average of ‘n’ natural number.
22. Write a program to find the HCF of given two numbers.
23. Write a program to convert decimal to binary number.
24. What do you mean by Fibonacci series? Explain with suitable example.
25. Write a program to draw multiplication table. The program should be use “for” looping
structure in calculating and displaying the table.
26. The marks obtained by student in 7 different subjects are entered through the keyboard. The
students get a division as per the following rules:
a. Percentage greater or equal to 60 . .first divisions
b. Percentage between 45 to 59. .second division
c. Percentage between 35 to 44 . .Third division
d. Percentage less than 35 - -fail
e. Marks less than 35 in any subject. .fail
27. Write a program in C to process result of all students based on the specification stated above.
28. Use the nested loop to calculate and display the multiplication table from 1 to 12.
29. A ball is dropped from a certain height. It bounces back 0.8th of its previous fall. Considering
that the ball comes to rest when the height is less or equal to 0.2 cm, write a program to input a
height and count the number of bounces it makes.
30. Write a program to display list of menu as:
a. Perimeter of Rectangle
b. Area of Rectangle
c. Exit
When you select the option, it should perform accordingly.
31. Write a program to solve quadratic equitation if value of a, b and c are given below:
a. a b c
b. 0 2 3
c. 2 10 3
d. 1 2 1
e. 2 4 4
32. Total call recorded in a telephone bill is 540, of which the first 100 calls costs of Rs.180 and
extra calls are charged at the rate of Rs. 3 per call. How would be the payment of the telephone
calls? Write program in C.

376 Computer Science - XI Approved by CDC, Nepal


33. The Delta Gas Company bills its customers according to the following rate schedule:
a. First 500 liters Rs. 50(flat)
b. Next 300 Liters Rs. 5.25 per 100 liter
c. Next 30,000 liters Rs. 2.50 per 100 liters
d. Above this Rs.2.00 per 100 liters.
34. The input record has customer identification, name and address, meter reading, past and
present. Write a program for billing system to display customer identification, name, current
meter reading, past meter reading and payable amount.
35. Write a menu driven program for ABC Talkies, which menu is given as:
Dress Circle Rs. 40.00
Balcony Rs. 30.00
First Class Rs.25.00
Second Class Rs. 20.00
Third Class Rs.15.00
Program asks the number of tickets, required for selected class and display the total amount that
should be paid.
36. A bank has the following policy on deposits: on deposits of Rs. 25000 and above and for three
years or above the interest is 10%. On the same deposit for a period less than three years it is
8%. On deposits below Rs. 25000 the interest is 6% regardless of the period of deposit. Write
the program for process above conditions.
37. ABC Co Ltd. Sells computers of three types with following cost price:
PC(intel-I) Rs. 15,000
PC(intel-II) Rs 18,000
PC(intel-III) Rs 20,000
PC(intel-IV) Rs. 25,000
Write program to accept the cost price of each variety and print the total amount collected.
38. Find the sum of following series up to 10 terms:
a. 5+52+53+
b. 1/2+1/3+1/4+….
c. 2+4+6+8+….
d. 1+3+5+…
e. 1+x+x2+x3+…
39. The city of Dhangadhi has a population of 100 000, but this is falling by 10% each year. The
town of Mahendranagar has a population of 30 000, but this is increasing by 5% each year.
Write a program to predict the number of years that will pass before Mahendranagar will have a
greater population than Dhangadhi, if these trends continue.
40. To obtain a certain qualification, a candidate takes three examinations. To pass, the candidate
must score over 30% in each examination and also have an average mark for the three
examination so per 45%. Write a program to display result as PASS or FAIL.
41. Write a program to find out the net pay if the health insurance premium is deducted from
employee's salary (Rs. 10,000) according to the following scheme.
Premium is 25.50% if single
Premium is 15.25% if married without children
Premium is 9.75% if married without children

Approved by CDC, Nepal Programming Concepts & Logics 377


42. A salesman is paid commission on the following scale:
0-500 2%
500- 5000 3%
5000-10000 4%
Over 10000 5%
Write a program to input the amount of scales and output of the salesman’s commission.
43. The ABC Electricity Company charges for electricity as follows:
Kilowatt-Hours Cost
10 - 200 Rs. 10.00
201 - 1000 Rs. 10 + 0.5 for each KWH above 200
1001 and more Rs. 50.00 + 0.03 for each KWH above 1000
Write a program to input a customer’s usage figure for a month from the terminal and then
calculate and print the customer’s charges for the month.
44. Write a program to find out the net pay if the health insurance premium is deducted from
employee's salary (Rs. 10,000) according to the following scheme.
Premium is 25.50% if single
Premium is 15.25% if married without children
Premium is 9.75% if married without children
45. Draw a sequence chart of if – else if statement.
46. What do you mean by branching and looping?
47. Differentiate between while and do-while loop.
48. Differentiate between while and do- - - while loop with suitable examples.
49. For any integer input through the keyboard, write a C Program for find out whether it is and
odd number or even number.
48. Write a C Program to read in a positive integer less than 20 and display its multiplication table.
49. Write an algorithm and C Program to read salaries of 200 employees and count the number of
employees getting salary between 5000-10,000.
50. Write a program to determine odd or even number.
51. What is control statement?
52. Differentiate between switch and if statement.

378 Computer Science - XI Approved by CDC, Nepal


Array and String
Definition of Array
An array in C language is a collection of similar data-type, means an array can hold value of a
particular data type for which it has been declared. Arrays can be created from any of the C data-
types int, float, and char. So an integer array can only hold integer values and cannot hold values
other than integer. When we declare array, it allocates contiguous memory location for storing
values whereas 2 or 3 variables of same data-type can have random locations. So this is the most
important difference between a variable and an array.

Array is a data type it can use to store same types of data in a common name. It allows continuous memory
location for storing values

Why do We Need Array?


If we have a collection of similar data elements, we have inconvenient to give each one a unique
variable name. So clearly, we have a convenient way to refer to such collections of similar data
elements. And this problem is solved by the use of array by providing a way to refer to individual
items in a collection by using a same variable name.
Types of Arrays
▪ One dimension array
▪ Two dimension array
▪ Multi-dimension array.
One Dimensional Array
A one dimensional array has only a single subscript. A subscript is a number in a bracket that
follows an arrays name. This number can identify the number of individual elements in an array. It
stores data only row wise or column wise.
Declaration of One Dimensional Arrays
data_type array_name[size of array];
Example: int roll[8];
In this example, int specifies the type of the variable, roll specifies the name of the variable and the
value in bracket [8] is size of array. The bracket ([ ]) tells compiler that it is an array and number
mention in the bracket specifies that how many elements it can store. This number is called
dimension of array. So, with respect to this example we have declared an array of integer type and
named it “roll” which can store roll numbers of 8 students. You can see memory arrangement of
above declared array in the following image:
Name roll[0] roll[1] roll[2] roll[3] roll[4] roll[5] roll[6] roll[7]

Values 12 45 32 23 17 49 5 11

Address 1000 1002 1004 1006 1008 1010 1012 1014

1-D Array Memory Arrangement

Approved by CDC, Nepal Programming Concepts & Logics 379


One Dimensional Array Memory Arrangement.
Some Examples
Program to store 10 numbers in an array then display
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, b[10];
printf(“\nEnter 10 numbers:”)
for(i=0;i<10;i++)
{
scanf(“%d”, &b[i]);
}
printf(“Numbers are:\n”);
for(i=0;i<10;i++)
{
printf(“%d\t”,b[i]);
}
getch();
}
Program to find the greatest number among ‘n’ numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100], i, g,n;
printf(“\nEnter a number not more then 100:”);
scanf(“%d”,&n);
printf(“Enter %d numbers:\n”, n);
for(i=0; i<n;i++)
{
scanf(“%d”, &a[i]);
}
g=a[0];
for(i=1;i<10;i++)
{
if(g<a[i])
{
g=a[i];
}
}
printf(“Greatest no =%d”, g);
getch();
}
Write a program to input the percentage of 100 students then count the number of students
whose percentage is greater than or equal to 80.
#include<stdio.h>
#include<conio.h>
void main()
{
int p[100], i, c=0;
printf(“Enter percentage of 100 students");
for(i=0; i<100;i++)
{
scanf(“%d”, &p[i]);
if(p[i]>=80)
c++;

380 Computer Science - XI Approved by CDC, Nepal


}
printf("\nNumber of students whose percentage >=80 is %d", c);
getch();
}
Program to sort ‘n’ numbers in ascending order
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100], i, j,t,n;
printf(“\nEnter a number not more then 100:”);
scanf(“%d”,&n);
printf(“Enter %d numbers:\n”, n);
for(i=0; i<n;i++)
{
scanf(“%d”, &a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1]])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
else
t=a[j];
}
}
printf("numbers in ascending order are:");
for(i=0;i<n;i++)
{
printf(“%d\t”, a[i]);
}
getch();
}
One dimensional Array Assignment and Initialization
We can initialize and assign values to the arrays in the same way as we do with variable. We can
assign value to an array at the time of declaration or during runtime. Let’s look at each approach.
data_type array_name[size]={list of values};
Example
int arr[5]={1,2,3,4,5};
int arr[]={1,2,3,4,5};
In this above array example we have declared an integer array and named it “arr” which can hold 5
elements, we are also initializing arrays in the same time.
Both statements in our example are valid method to declare and initialize single dimension array. In
our first example we mention the size (5) of an array and assigned it values in curly brace, separating
element’s value by comma (,). But in second example we left the size field blank but we provided its
element’s value. When we only give element values without providing size of an array then C
compiler automatically assumes its size from given element values.
There is one more method to initialize array C programming; in this method we can assign values to
individual element of an array. For this let’s look at example:

Approved by CDC, Nepal Programming Concepts & Logics 381


Array Initialization Example
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5],i;
clrscr();
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
printf("Value in array arr[0] : %d\n",arr[0]);
printf("Value in array arr[1] : %d\n",arr[1]);
printf("Value in array arr[2] : %d\n",arr[2]);
printf("Value in array arr[3] : %d\n",arr[3]);
printf("Value in array arr[4] : %d\n",arr[4]);
printf("\n");
for(i=0;i<5;i++)
{
printf("Value in array arr[%d] : %d\n",i,arr[i]);
}
getch();
}
In the above c arrays example we have assigned the value of integer array individually like we do
with an integer variable. We have called array element’s value individually and using for loop so
that it would be clear for beginner and semi-beginner C programmers. So, from the above example it
is evident that we can assign values to an array element individually and can call them individually
whenever we need them.
Two Dimensional Array
It is an array that can use to store similar types of data in a common name. It consists of two
subscript in which first gives number of row size and second gives number of column size. The
maximum capacity of array is defined as the product of row size and column size.
Declaration of 2D array
data_type array_name[row_size][column_size];
Example: int arr[3][3];
So the above example declares a 2D array of integer type. This integer array has been named arr and
it can hold up to 9 elements (3 rows x 3 columns).

arr c01[0] c01[1] c01[2]


row [0] 10 20 45
row [1] 42 79 81
row [2] 89 9 36
2D Array Arangement

arr[0][0] arr[0][1] arr[0][2] arr[1][0] arr[1][1] arr[1][2] arr[2][0] arr[2][1] arr[2][2]


12 45 63 89 34 73 19 76 49
1000 1002 1004 1006 1008 1010 1012 1014 1016
Memory Map of 2D Array
Program to store data in two dimensional array and display
#include<stdio.h>
#include<conio.h>
void main()

382 Computer Science - XI Approved by CDC, Nepal


{
int x[4][4], i, j;
printf(“Enter elements”);
for(i=0;i<4;i++)
{
printf(“Enter the elements in %d row”,i+1);
for(j=0;j<4;j++)
{
scanf(“%d”, &x [i][j]);
}
}
printf(“The numbers are:\n”);
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf(“%d\t”, x[i][j]);
}
printf(“\n”);
}
getch();
}
Write a program to add two NxM matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,j,a[10][10],b[10][10],s[10][10];
printf(“Enter number of rows and number of columns not more than 10:\n”);
scanf(“%d%d”,&n,&m);
printf(“Enter the numbers of first matrix:\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the numbers of second matrix:\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“The sum of matrix is:\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
s[i][j]=a[i][j]+b[i][j];
printf(“%d\t”,s[i][j]);
}
printf(“\n”);
}
}

Approved by CDC, Nepal Programming Concepts & Logics 383


Write a program to subtract two NxM matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int n,m,i,j,a[10][10],b[10][10],d[10][10];
printf(“Enter number of rows and number of columns not more than 10:\n”);
scanf(“%d%d”,&n,&m);
printf(“Enter the numbers of first matrix:\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the numbers of second matrix:\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“The Difference of matrix is:\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
d[i][j]=a[i][j]-b[i][j];
printf(“%d\t”,d[i][j]);
}
printf(“\n”);
}
}

Program to find the sum of diagonal elements of 4x4 matrix.


#include<stdio.h>
#include<conio.h>
void main()
{
int x[4][4], i, j,s=0;
printf(“Enter elements”);
for(i=0;i<4;i++)
{
printf(“Enter the elements in %d row”,i+1);
for(j=0;j<4;j++)
{
scanf(“%d”, &x [i][j]);
if(i= =j)
s=s+a[i][j];
}
}
printf(“sum of diagonal elements is %d”,s);
getch();
}

384 Computer Science - XI Approved by CDC, Nepal


Write a program to multiply two 3x3 matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int k,i,j,a[3][3],b[3][3],m[3][3];
printf(“Enter the numbers of first matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the numbers of second matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&b[i][j]);
}
}
printf(“The multiply of matrix is:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m[i][j]=0;
for(k=0;k <3;j++)
{
m[i][j]=m[i][j]+a[i][k]+b[k][j];
}
printf(“%d\t”,m[i][j]);
}
printf(“\n”);
}
getch( );
}
Two dimensional Array Assignment and Initialization
We can initialize and assign values to the arrays in the same way as we do with variable. We can
assign value to an array at the time of declaration or during runtime. Let’s look at each approach.
data_type array_name[row size][column size]={list of values};
Example
int arr[2][3]={1,2,3,4,5,6};
Program with explanation
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
int arr[3][3]={
{12, 45, 63},
{89, 34, 73},
{19, 76, 49}
};
clrscr();

Approved by CDC, Nepal Programming Concepts & Logics 385


printf(":::2D Array
Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
getch();
}
So in the above example we have declared a 2D array named arr which can hold 3x3 elements. We
have also initialized that array with values, because we told the compiler that this array will contain
3 rows (0 to 2) so we divided elements accordingly. Elements for column have been differentiated
by a comma (,). When compiler finds comma in array elements then it assumes comma as beginning
of next element value. We can also define the same array in other ways, like.
int arr[3][3]={12, 45, 63, 89, 34, 73, 19, 76, 49};
or, int arr[ ][3]={12, 45, 63, 89, 34, 73, 19, 76, 49};
But this kind of declaration is not acceptable in C language programming.
int arr[2][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49};
or, int arr[ ][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49};
To display 2D array elements we have to just point out which element value we want to display. In
our example we have a arr[3][3], so the array element reference will be from arr[0][0] to arr[2][2].
We can print display any element from this range.
Differentiate between one dimensional and two dimensional array
One dimensional array Two dimensional array
It consists of only one subscript. It consists of two subscripts.
It stores data either row wise or column wise It stores data in row wise and column wise(matrix
form)
Maximum size is the size of array Maximum size is the product of row size and
column size
Syntax: Syntax:
data_type array_name[size of array]; data_type array_name[row_size][column_size];
Initialization: Initialization:
int a[5]={10,20,30,40,50}; int a[2][2]={10,20,30,40}
String
A string is a sequence of characters. Any sequence or set of characters defined within double
quotation symbols is a constant string. In C it is required to do some meaningful operations on
strings they are:
▪ Reading string displaying strings
▪ Combining or concatenating strings
▪ Copying one string to another.
▪ Comparing string & checking whether they are equal
▪ Extraction of a portion of a string
String functions are mainly used to process string data such as strlen( ), strcat( ), strcpy( ) etc.

386 Computer Science - XI Approved by CDC, Nepal


Strings are stored in memory as ASCII codes of characters that make up the string appended with
‘\0’(ASCII value of null). Normally each character is stored in one byte, successive characters are
stored in successive bytes.
Initializing Strings
The character array is initialized, the initialization of a string must the following form which is
simpler to one dimension array.
char month1[ ]={‘J’,’a’,’n’,’u’,’a’,’r’,’y’};
Then the string month is initializing to January. This is perfectly valid but C offers a special way to
initialize strings. The above string can be initialized char month1[]=”January”; The characters of the
string are enclosed within a part of double quotes. The compiler takes care of string enclosed within
a pair of a double quote. The compiler takes care of storing the ASCII codes of characters of the
string in the memory and also stores the null terminator in the end.
The string input/output functions are already mentioned in previous chapter.
(gets( ), puts( ), getchar( ), putchar( ) )
Arithmetic Operations on Characters
We can also manipulate the characters as we manipulate numbers in C language. When ever the
system encounters the character data it is automatically converted into a integer value by the system.
We can represent a character as a interface by using the following method.
X=’a’;
printf(“%d\n”,X);
Will display 97 on the screen. Arithmetic operations can also be performed on characters for
example x=’z’-1; is a valid statement. The ASCII value of ‘z’ is 122 the statement the therefore will
assign 121 to variable x.
It is also possible to use character constants in relational expressions for example
ch>’a’ && ch < = ’z’ will check whether the character stored in variable ch is a lower case letter. A
character digit can also be converted into its equivalent integer value suppose un the expression
a=character-‘1’; where a is defined as an integer variable & character contains value 8 then a=
ASCII value of 8 ASCII value ‘1’=56-49=7.
We can also get the support of the c library function to converts a string of digits into their
equivalent integer values the general format of the function in x=atoi(string) here x is an integer
variable & string is a character array containing string of digits.
String Functions
strlen() Function
This function counts and returns the number of characters in a string. The length does not include a
null character.
Syntax n=strlen(string);
Where n is integer variable and string is the string expression
Example
l=strlen(“HSEB”);
The function will assign number of characters 9 in the string to a integer variable l.
/*writr a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
char name[100];
int length;
printf(“Enter the string”);
gets(name);

Approved by CDC, Nepal Programming Concepts & Logics 387


length=strlen(name);
printf(“\nNumber of characters in the string is=%d”,length);
}
strcat() Function
when you combine two strings, you add the characters of one string to the end of other string. This
process is called concatenation. The strcat() function joins 2 strings together.
Syntax: strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to
string1. the string at string2 remains unchanged.
Example
strcpy(string1,”sri”);
strcpy(string2,”Bhagavan”);
printf(“%s”,strcat(string1,string2);
From the above program segment the value of string1 becomes sribhagavan. The string at str2
remains unchanged as bhagawan.
/*writr a program to concatenate two string*/
#include < stdio.h >
include < string.h >
void main()
{
char str1[20],str2[20];
printf(“Enter first string”);
gets(str1);
printf(“Enter seond string”);
gets(str2);
strcat(str1,str2)
printf(“\n concatenated string =%s”,str1);
getch( );
}
strcmp() Function
In C you cannot directly compare the value of 2 strings in a condition like if(string1==string2) Most
libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non
zero number if the strings are not the same.
Syntax: strcmp(string1,string2)
string1 & string2 may be string variables or string constants some computers return a negative if the
string1 is alphabetically less than the second and a positive number if the string is greater than the
second and returns zero if they are equal.
Example
/*writr a program to compare two string*/
#include < stdio.h >
include < string.h >
void main()
{
char str1[20],str2[20];
int c;
printf(“Enter first string”);
gets(str1);
printf(“Enter seond string”);
gets(str2);
c=strcmp(str1,str2)
if(c= =0)
printf("String are equal");
else

388 Computer Science - XI Approved by CDC, Nepal


printf("String are not equal");
getch( );
}
strcpy() Function
C does not allow you to assign the characters to a string directly as in the statement name=”Robert”;
Instead, use the strcpy() function found in most compilers to copy one string into another string.
Syntax: strcpy(string1,string2);
strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or
a string constant.
strcpy(Name,”Dipak”);
In the above example Dipak is assigned to the string called name.
/*writr a program to copy string*/
#include < stdio.h >
include < string.h >
void main()
{
char str1[20],str2[20];
printf(“Enter first string”);
gets(str1);
strcpy(str2,str1)
printf("copied string =%s", str2);
getch( );
}
strlwr () Function
This function converts all characters in a string from uppercase to lowercase.
Syntax strlwr(string);
Example
strlwr(“SCHOOL”) converts to school
/*writr a program to convert uppercase to lowercase string*/
#include < stdio.h >
include < string.h >
void main()
{
char str1[20];
printf(“Enter a string”);
gets(str1);
strlwr (str1)
printf("lower case string =%s", str1);
getch( );
}
strupr () Function
This function converts all characters in a string from lowercase to upperrcase.
Syntax: strupr (string);
Example
strupr(“school”) converts to SCHOOL
/*writr a program to convert lowercase to uppercase string*/
#include < stdio.h >
include < string.h >
void main()
{
char str1[20];

Approved by CDC, Nepal Programming Concepts & Logics 389


printf(“Enter a string”);
gets(str1);
strupr (str1)
printf("upper case string =%s", str1);
getch( );
}
strrev() Function
This function reverses the characters in a string.
Syntax:strrev(string);
/*writr a program to find reverse of a given string*/
#include < stdio.h >
include < string.h >
void main()
{
char str1[20];
printf(“Enter a string”);
gets(str1);
strrev (str1)
printf("reverse string =%s", str1);
getch( );
}
Write a program to input a string then find the following by menu driven program system.
a. Find length of given string
b. Find reverse of a given string
c. Input another string then check whether equal or not
d. Convert the string into upper case letters.
#include < stdio.h >
#include<conio.h>
#include<process.h>
include < string.h >
void main()
{
char str1[20],str2[20]
int l,choice,c;
printf("\nEnter a string");
gets(str1);
printf("\n1-length \n2-reverse\n3- check equal or not\n4-convert into uppercase\n");
printf("Enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
l=strlen(str1);
printf("Length of string=%d",l);
break;
case 2:
strrev(str1)
printf("Reverse string=%s",str1);
break;
case 3:
printf("\nEnter another string");
gets(str2);
c=strcmp(str1,str2)
if(c= = 0)
printf("String are equal");
else
printf("String are not equal");

390 Computer Science - XI Approved by CDC, Nepal


case 4:
strupr(str1);
printf("Upper case string=%s",str1);
default:
exit(0);
}
getch( );
}
Write a program to input the names of 10 students then sort in alphabetical order.
#include < stdio.h >
#include<conio.h>
include < string.h >
void main()
{
char str[10][20],t[20];
int i, c,j;
printf("Enter the names of 10 students")
for(i=0;i<10;i++)
{
scanf("%s",str[i]);
}
for(i=0;i<10;i++)
{
for(j=0;j<9-i;j++);
{
c=strcmp(str[j],str[j+1]])
if(c>0)
{
strcpy(t, str[j];
strcpy (stra[j],str[j+1]);
strcpy (str[j+1], t);
}
else
strcpy(t,str[j]);
}
}
printf("numbers in ascending order are:");
for(i=0;i<10;i++)
{
printf(“%s\t”, str[i]);
}
getch();
}
Write a program to input a string then count number of digits, vowels, consonants, white space
and other characters.
#include < stdio.h >
#include<conio.h>
include < string.h >
void main()
{
char str[20];
int nd=0,nv=0,nc=0,ns=0,no=0,i;
printf("Enter a string");
gets(str);
strupr(str);
for(i=0;str[i]!='\0';i++)
{
if(str[i]>='0' && str[i]<='9')
nd++;
else if(str[i]= = 'A' || str[i]= = 'E' || str[i]= = 'I' || str[i]== 'O' || str[i]== 'U')
nv++;
else if(str[i]>'A' && str[i]<='Z')

Approved by CDC, Nepal Programming Concepts & Logics 391


nc++;
else if(str[i]= = ' ')
ns++;
else
no++;
}
printf("No of digits=%d", nd);
printf("No of vowels=%d", nv);
printf("No of consonants=%d", nc);
printf("No of spaces=%d", ns);
printf("No of other characters=%d", no);
getch( );
}
Write a program to check given string is palindrome or not
#include < stdio.h >
#include<conio.h>
include < string.h >
void main()
{
char str[20],str1[20];
int c;
printf("Enter a string");
gets(str);
strcpy(str1,str);
strrev(str1);
c=strcmp(str,str1);
if(c= = 0)
printf("string is palindrome");
else
printf("String is not palindrome");
getch( );
}
Write a program to find reverse of given string without string string function
#include < stdio.h >
#include<conio.h>
include < string.h >
void main()
{
char str[20],str1[20];
int i, l=0,j;
printf("Enter a string");
gets(str);
for(i=0;str[i]!='\0';i++)
{
l++;
}
j=0;
for(i=l-1;i>=0;i--)
{
str1[j]=str[i];
j++;
}
printf("Reverse string =%s",str1);
getch( );
}

392 Computer Science - XI Approved by CDC, Nepal


Workshop
1. Write a program to input 10 float numbers and display these numbers and also find out (i)
largest and (ii) smallest numbers from list.
2. Write a program to sort following numbers: 9.9, 6.50, 66.75, 35.15, 60.50 and 13.85.
3. Write a program to count total number of vowels and consonants of given string.
4. Write a program to store Kathmandu valley’s 7 days maximum and minimum temperature and
calculate average, maximum, and minimum temperatures using function.
5. Write a program using C language to read the age of 100 persons and count the number of
persons in the age group between 50 to 60 years. Use “for’ and “continue” statements.
6. Write a program to declare a 3×4 matrix and print the matrix and display the following menu:
a. Sum of elements of any row
b. Sum of elements of any columns
c. Sum of diagonal elements
d. Sum of all elements
e. Exit from program
And to perform tasks as per users choice repeatedly until his /her choice is to exit.
7. A cricket team has the following table:
Player Runs Innings Times not out
Paras Khadka 899 7 3
Sandip Lamichhane 950 3 1
Suyash Adhikari 777 4 4
Rohit Gauchan 650 6 7
Write a program to read the data to calculate the batting average and to print the result as the
above tabular form including average.
8. Write a program to count particular words of given sentences. Example: Suppose your input
sentence is: “money is sweeter than honey, and money is greater than Victoria”
Count word: money
Count word: is
Count word: and
9. Write a program to count total vowels present is given strings and display in the following
form:
Vowels Numbers
A 3
E 1
I 3
O 2
U Nil
10. Write a program that inputs 10 unsorted centigrade temperatures. The program should then sort
the temperature into descending order and print them with their Fahrenheit equivalents.
11. Write a program that accept an input of up to 35 students’ names, each followed by a test mark.
Sort them according to name in ascending order.
12. For any set of numbers, if N is the number of numbers, S is the sum of all the numbers and SSQ
is the sum of the squares of all the numbers, the following formulae can be applied:
mean = S/N
range = largest number-smallest number
standard deviation=√SSQ/N-(S/N)2
median = the middle number, when the numbers are arranged in order
Write a program that allows a user to enter up to 50 examination results, which may ranges

Approved by CDC, Nepal Programming Concepts & Logics 393


from 0% to 100%. The program should then offer the user a range of options:
a. Calculate the mean of the results.
b. Calculate the standard deviation of the results.
c. Calculate the range of the results.
d. Calculate the median of the results.
e. Tabulate the results.
f. Quit
If option 5 is selected, tabulation should be printed in the following form:
Marks (%) 0-10 11-20 21-30 31-40 41-50
Marks (%) 51-60 61-70 71-80 81-90 91-100
13. A*(B+C) = A*B+A*C represents distributive laws and it can be proved. Write a program to
read in 3x3 matrices A, B, and C. Then find A*(B+C) and A*B+A*C. Print both values and
compare the results for several sets of matrices.
14. The rule A*B=B*A is called the commutative law. It does not necessarily hold for matrix
calculations. Write a program to read in 3×3 matrices A and B. Then find A*B and B*A and
print each product matrix and addition matrix.
15. The following table represents sale made by salespersons:
Salesperson Mon Tue Wed Thu Fri
Tank 45 65 23 67 78
Monika 65 81 45 34 22
Prabesh 34 22 45 67 89
Suyasha 55 87 21 77 23
Write a program that will store the above data in a matrix and then calculate and print:
a. Total daily Sales
b. Total weekly sales for each salesperson
c. Total weekly sales.
16. Write a program to input a message from the keyboard and display a menu driven program to
perform the following tasks:
a. Print the message in reverse order.
b. Print the message length in term of character.
c. Print the message in capital letters
d. Copy the message from one location of the screen to another location
17. Write a C Program to input ‘N’ numbers and find out greatest and smallest number.
18. What is array? Write down its type.
19. Differentiate between one dimensional and two dimensional array.
20. What is string? Write down the names of any five string functions and explain.

394 Computer Science - XI Approved by CDC, Nepal

You might also like