Anda di halaman 1dari 110

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD

I Year B.Tech-SYLLABUS
COMPUTER PROGRAMMING

UNIT - I
Introduction to Computers – Computer Systems, Computing Environments, Computer Languages,
Creating and running programs, Program Development.
Introduction to the C Language – Background, C Programs, Identifiers, Types, Variables,
Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions,
Precedence and Associativity, Expression Evaluation, Type conversions, Statements-
Selection Statements(making decisions) – if and switch statements, Repetition statements ( loops)-
while, for, do-while statements, Loop examples, other statements related to looping –break, continue,
goto, Simple C Program examples.
UNIT - II
Functions-Designing Structured Programs Functions, user defined functions, inter function
communication, Standard functions, Scope, Storage classes-auto, register, static, extern, scope rules,
type qualifiers, recursion- recursive functions, Limitations of recursion, example C programs,
Preprocessor commands.
Arrays – Concepts, using arrays in C, inter function communication, array applications, two –
dimensional arrays, Multidimensional arrays, C program examples.
UNIT - III
Pointers – Introduction (Basic Concepts), Pointers for inter function communication, pointers to
pointers, compatibility, Pointer Applications-Arrays and Pointers, Pointer Arithmetic and arrays,
Passing an array to a function, memory allocation functions, array of pointers, programming
applications, pointers to void, pointers to functions.
Strings – Concepts, C Strings, String Input / Output functions, arrays of strings, string manipulation
functions, string /
data conversion, C program examples.
UNIT - IV
Enumerated, Structure ,and Union Types– The Type Definition(typedef), Enumerated types,
Structures –Declaration, initialization, accessing structures, operations on structures, Complex
structures, structures and functions, Passing structures through pointers, self referential structures,
unions, bit fields, C programming examples, command –line arguments,
Input and Output – Concept of a file, streams, text files and binary files, Differences between text
and binary files, State of a file, Opening and Closing files, file input / output functions (standard
library input / output functions for files), file status functions (error handling),Positioning functions, C
program examples.
UNIT – V
Searching and Sorting – Sorting- selection sort, bubble sort, Searching-linear and binary search
methods. Lists- Linear list – singly linked list implementation, insertion, deletion and searching
operations on linear list, Stacks- Push and Pop Operations, Queues- Enqueue and Dequeue operations.
TEXT BOOKS:
1. Computer Science: A Structured Programming Approach Using C, B.A.Forouzan and R.F. Gilberg,
ThirdEdition, Cengage Learning.
2. Programming in C. P. Dey and M Ghosh , Oxford University Press.
Computer Programming 2

Unit-1
Introduction to Computers – Computer Systems, Computing Environments, Computer Languages,
Creating and running programs, Program Development.
Introduction to the C Language – Background, C Programs, Identifiers, Types, Variables,
Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions,
Precedence and Associativity, Expression Evaluation, Type conversions, Statements-Selection
Statements(making decisions) – if and switch statements, Repetition statements ( loops)-while, for,
do-while statements, Loop examples, other statements related to looping –break, continue, goto,
Simple C Program examples.

Introduction to Computer Systems:

A Computer is an electronic device that takes data and instructions as an input from the user,
processes data, and provides useful information known as output.

A computer is a system made of two major components Hardware and Software. The
computer hardware is the physical equipment. The software is the collection of programs
(instructions) that allow the hardware to do its job. Following figure represents a Computer System.

 The computers can perform complex and repetitive calculations rapidly and accurately
 Store large amount of data and information for subsequent manipulations
 Provide information to the user in many different forms.
 Compare items and make decisions.
These capabilities of computers have enabled us to use them for a variety of tasks.
Applications areas where the computers are used :
 Data Processing(commercial use)
 Numerical Computing(Scientific use)
 Message Communication(E-mail)
 Image Processing(animation and industrial use) etc.

Dept of Computer Science & Engineering


Computer Programming 3

Computer Hardware:
The Hardware components of the computer system consists of five parts :
 Input Devices
 Central Processing Unit(CPU)
 Primary Storage
 Output Devices
 Auxiliary Storage Devices

The computer will be of no use unless it is able to communicate with the outside world. Input/Output
devices are required for users to communicate with the computer.

Input Devices:

The input devices are used to enter information to the computer system. Some of the
examples of input devices are keyboard, Mouse, Scanner, Touch Screen, Joystick, Light Pen etc.

An input device is used to provide data and control signals form the user to an computer.

Output Device:

Output devices are the devices through which the user gets information from the computer.
Some of the examples of output devices are Monitor, LCD, Printer, Plotter, Speakers etc.

If the output is shown on the monitor, we call it as a soft copy. If it is produced on a paper by the
printer, we call it as a hard copy.

Central Processing Unit (CPU):

The central processing unit (CPU) is the main part of a computer system which is responsible
for all arithmetic calculations, movement of data, and comparison among the data. It can be called as
the brain of the computer.

The central processing unit in micro computer is also called as microprocessor.

Dept of Computer Science & Engineering


Computer Programming 4

The CPU consists of three functional units

 Control unit (CU)

 Arithmetic Logic Unit (ALU)

 Registers

 The Control Unit stores the instruction set which specifies the operation to be performed by
the computer. Control unit transfers the data and the instructions to the Arithmetic Logic unit.
Simply, it is responsible for supervising the operation of the entire computer system.

 The Arithmetic Logic Unit performs arithmetical or Logical operation on the received data.

 The Register, is a high speed storage area within the CPU that stores the data to be processed
by the CPU and also stores the processed data. The power and speed of the CPU depends on
the number of registers and the size of each register.

Primary Memory:

The Primary storage, also known as Main Memory, is a place where the programs and data
are stored temporarily during processing i.e., the main memory holds instructions and data when a
program is executing. The data in primary storage are erased when we turn off a personal computer.
There are two types of Main Memory devices namely,

1. Random Access Memory and

2. Read Only Memory.

Random Access Memory:

 RAM is also called as Read-Write memory, i.e., both read and write operations can be done in
RAM.

 It is a type of computer memory that can be accessed randomly, i.e. any byte of memory can
be accessed without touching the preceding bytes.

 RAM is volatile in nature i.e., the information present in these types of memory devices is lost
as soon as the power is turned off.

Read Only Memory:

 ROM is a type of memory that normally can only be read, as opposed to RAM which can be
both read and written. The contents of ROM cannot be changed.

 It is non-volatile in nature i.e., the information present in these types of memory devices is not
lost as soon as the power is turned off.

Dept of Computer Science & Engineering


Computer Programming 5

 ROM is most commonly used to store system-level programs that we want to have available to
the PC all the times. For Example, BIOS (Basic Input Output System) programs are stored in
ROM which are need at the time of system booting process.

Cache Memory is a memory placed between CPU and main Memory. It is faster compared
to the primary memory. Parts of the program or data that need to be accessed repeatedly are stored in
Cache Memory.

Auxiliary Storage:

The Auxiliary storage, also known as secondary storage (or external storage), it is the place
where the programs and data are stored permanently. When we turn off the computer, our programs
and data remain in the secondary storage ready for next time we need them. Secondary memory
devices include

 Magnetic disks (like hard drives and floppy disks)

 Optical disks (CDs and CDROMs)

 Magnetic tapes

Computer Software
Software is a set of programs or collection of programs that are necessary for the functioning
of a computer to perform certain tasks.
A Program is a set of instructions written to carry out a particular task, so that the computer
can follow them.

Dept of Computer Science & Engineering


Computer Programming 6

Computer Software is divided into two broad categories : System Software and Application
software.
System Software
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
operating system, system support software and system development software.

 The operating system provides services such as a user interface, file and database access.

The primary purpose of this software is to keep the system operating in an efficient manner
while allowing the users access to the system.

In simple words Operating system is as software which interacts with the hardware resources
of the computer directly.

It also provides the interface between user and computer.

 System support software provides system utilities and other operating services.

Examples of system utilities are sort programs and disk format programs.

Operating services consists of programs that provide performance statistics and security
monitors to protect the system and data.

 The last system software category, System development software, includes the language
translators that convert programs into machine language for execution ,debugging tools etc.

Application software

Application software is directly responsible for helping user in solving their problems. It is
broken in to two classes: general-purpose software and application-specific software.

 General purpose software is purchased from a software developer and can be used for more
than one application.

Dept of Computer Science & Engineering


Computer Programming 7

Examples of general purpose software include word processors, database management


systems, and computer aided design systems.

They are labeled general purpose because they can solve a variety of user computing
problems.

 Application-specific software can be used only for its intended purpose.

A general ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software.

They can be used only for the task for which they were designed they cannot be used for other
generalized tasks.

Each layer represents the connection point user interacts with application software to do some work.
The application software interacts with operating system, which is a part of system software directly
interacts with the hardware. The user can directly interact with operating system whenever needed.

Computing Environment:
Computing Environment is the entire set of conditions under which one operates a computer.
Simply it refers to a hardware platform and the operating system that is used in it.

There are four different computing environments

1. Personal Computing Environment


2. Time-Sharing Environment
3. Client/Server Environment
4. Distributed Environment

Dept of Computer Science & Engineering


Computer Programming 8

Personal Computing Environment :

In this environment, all of the computer hardware components are tied together in our
personal computer (PC). In this situation, we have the whole computer for our self; we can do
whatever we want.

Time-Sharing Environment:
Employees in large companies often work in what is known as a time-sharing environment.

In the time-sharing environment, many users are connected to one or more computers. Also, in
the time-sharing environment, the output devices and auxiliary storage devices are shared by all of the
users.

In the time-sharing environment, all computing must be done by the central computer.

In other words, the central computer has many duties :

 It must control the shared resources


 It must manage the shared data and printing
 It must do the computing.
 All of this work tends to keep the computer busy.

In fact, it is some times so busy that the user becomes frustrated by the computer’s slow
responses. Example for time-sharing environments is a college lab in which a minicomputer is shared
by many students.

Dept of Computer Science & Engineering


Computer Programming 9

Client / Server Environment :

A Client/Server computing Environment splits the computing function between a central


computer and user’s computers. The users are given personal computers or work stations so that
some of the computation responsibility can be moved from the central computer and assigned to
workstations. The user’s personal computer called “clients” , which will communicate with the
powerful central computer called “server”.

Because the work is shared between user’s computers (clients) and central computer (server),
response time and monitor display are faster and the users are more productive.

Distributed Computing Environment:

A distributed computing environment , the computing complexity will be distributed among


multiple servers and clients. The internet provides connectivity to different servers throughout the
world. This environment is reliable and scalable.

Dept of Computer Science & Engineering


Computer Programming 10

Computer Language:
The operations of a computer are controlled by a set of instructions called computer program.
Instructions are written to tell the computer:

 What operation to be performed


 Where to locate the data
 How to present the data
 When to make decisions

The communication between two parties, whether they are machines or human beings, always
needs a common languages or terminology. The language used in the communication of computer
instructions known as the programming language. The computer has its own language and any
communication with computer must be in its language or translated into this language.

To write a program for a computer, we must use a computer a language. Over years computer
languages have evolved from machine languages to natural languages.

Machine languages Symbolic languages High Level Languages

1940s 1950s 1960s

Machine Language (Low Level Languages):

 As computers are made of two-state electronic devices they can understand only pulse and no-
pulse i.e., 1 or 0 conditions. Therefore all instructions and data should be written using binary
codes 1 and 0. The binary code is called machine code or machine language.

 Machine language is usually referred to as the First Generation Language.

Advantages of machine language:

 Computers do not understand English, Hindi or any other language. They respond only to
machine language hence no need of any translator.

 The computer directly starts executing the machine language instructions and it takes less
execution time.

Disadvantages of machine language:

 Machine dependent: The computers are not identical in design; therefore, each computer has
its own machine language.

Dept of Computer Science & Engineering


Computer Programming 11

 Difficult to use and Error prone: It is difficult to understand and remember various
combinations of 1’s and 0’s representing numerous data and instructions. This makes it
difficult for a programmer to write error-free instructions.

 Difficult to debug and modify: checking error locations in machine instructions is as tedious
as writing the instructions. Further, modifying such a program is highly problematic.

 Time consuming: Writing error-free instructions in machine language is a slow process.

Assembly Language (Symbolic languages):

 The Assembly Language, introduced in 1950s, reduced program complexity and provided
some standardization to build an application. It is considered as a Second-Generation
Programming Language.
 Unlike machine level language here we use some codes known as mnemonic codes can be
called as operation code or opcode.
mov al,061h
 In the above instruction, the opcode “move” is used to move the hexadecimal value 61 into
processor register al.
 In case of assembly language a translator is required to translate assembly language to
machine langue. The translator program used in assembly language called as “Assembler”.

Advantages of assembly language:

 Writing a program in assembly language is more convenient when compared to machine


language.

 Instead of binary sequence, as in machine language, a program in assembly language is


written in the form of symbolic instructions. This gives the assembly language program
improved readability.

Disadvantages of assembly language:

 Machine-dependent: Although symbolic languages greatly improved programming


efficiency, they still require programmers to concentrate on the hardware that they are using.

 Programming is difficult and time consuming.

High – Level Language:

Although symbolic languages greatly improved programming efficiency, they still require
programmers to concentrate on the hardware that they are using. The desire to improve programmer
efficiency and to change the focus from the computer to the problem being solved led to the
development of high- level language, i.e., High- level languages are designed to relieve the
programmer from the details of the assembly language.

Dept of Computer Science & Engineering


Computer Programming 12

High- level languages are to be converted into machine language. The process of converting
them is known as Compilation and the tool used to convert is “compiler”.

In this language, instructions are written using normal English language and mathematical
symbols like +, -, %, / etc.

Advantages of high – level languages:

 Readability: Programs written in these languages are more readable than those written
in assembly and machine languages.

 Ease in the development of programs: Since the instructions of these programming


languages are closer to English language, it is easy to develop programs in high-level
languages.

 Portability: High – level programming languages can be run on different machines


with little or no change.

 Easy debugging: Errors can be easily detected and removed.

The following figure shows the simple English statement in high level language(C) and machine level
language.

High-level languages can be classified into 3 categories

 Procedure oriented languages (Third Generation Languages)


 Problem oriented language (Fourth Generation Languages)
 Natural language(Fifth Generation Languages)

Dept of Computer Science & Engineering


Computer Programming 13

Procedure oriented languages (Third Generation Languages) :


 High level languages designed to solve general-purpose problems are called Procedural
Languages or third generation languages.
 These include BASIC, COBOL, FORTRAN, C, C++ and JAVA which are designed to
express the logic and procedure of a problem.
 The syntax of these programming languages is different and easy to follow.
 Another advantage of third generation languages is that they are portable i.e., we can
put the compiler on any computer and create the object code.
Problem oriented language (Fourth Generation Languages) :
 The problem - oriented languages are used to solve specific problems known as fourth-
generation languages. These include Query Languages. Report generators, and
application generators which have simple English like syntax rules.
 Fourth-generation languages have reduced programming efforts and overall cost of
software development.
 A single statement in a fourth generation language can perform the same task as
multiple lines of a third generation language.
Natural language (Fifth Generation Languages) :
 Natural languages are designed to make a computer to behave like an expert and solve
problems; the programmer just needs to specify the problem.
 Natural languages such as LISP and PROLOG are mainly used to develop artificial
intelligence and expert systems.
Language Translators:
A computer can understand only
Each and every high-level language needs a translator to translate instructions written in the
high-level programming language into a machine language that a computer can understand and
execute. Different machines may need different compilers or interpreters for the same programming
language.

 Assembler
 Compiler
 Interpreter

Assembler:

An Assembler is a computer program that takes


each of the assembly language statement from the source
code and translates them into machine language codes i.e.,
in the form of 0’s and 1’s. This output obtained in the
binary format is called object or machine code. This code
is finally executed to obtain the results.

Dept of Computer Science & Engineering


Computer Programming 14

Compiler:

Compiler is a program that translates the source


code written in a high level language into corresponding
object code (i.e., executable machine code). This
translation process is called “compilation”. A program that
translates low –level languages to high level language is
called “de-compiler”.

Interpreter:
 Interpreter is a type of program translator used for translating higher level language into
machine language. It takes one statement of higher level languages, translate it into machine
language and immediately execute it.
 Translation and execution are carried out for each statement. It differs from compiler, which
translate the entire source program into machine code and does involve in its execution.
 The advantage of interpreter compared to compiler is its fast response to changes in source
program.
 Interpreters are easy to write and do not require large memory in computer.
 The disadvantage of interpreter is that it is time consuming.
Thus compiled machine language program runs much faster than an interpreted program.

Creating and Running Programs:


It is the job of a programmer to write and run the program. This process involves four steps.

 Writing and editing programs


 Compiling the program
 Linking the program with required library modules
 Executing the program
Writing and editing programs:
 The software used to write programs is known as a text editor. A text editor helps us enter,
change, and store character data.
 Depending on the editor on our system, we could use it to write letters, create reports, or write
programs.
 Text editor is a generalized word processor, but it is more often a special editor included with
the compiler. Some of the features of the editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements from one part of a program
to another etc.
 After completing a program, we save our file to disk (with extension programName.c). This
file will be input to the compiler; it is known as a source file.

Dept of Computer Science & Engineering


Computer Programming 15

Compiling the program:

The source code file must be translated into machine language, which is the job of a compiler. The
c compiler has actually two separate programs: 1. Preprocessor 2. Translator.
 The preprocessor reads the source code and prepares it for the translator. While preparing
the code, it scans for special instructions known as preprocessor commands. These
commands tell the preprocessor to look for special code libraries, make substitutions in the
code, and in other ways prepare the code for translation into machine language. The result
of the preprocessing is called the Translation Unit.
 After the preprocessor has prepared the code for compilation, the translator does the actual
work of converting the program into machine language while converting translator checks
correctness of each statement. If there are any syntactical errors the process of compilation
ends here and those errors will be listed out by the Compiler. (In this step object code is
created with the extension “.obj”.)
An object module is the code in machine language called “Object File” (ProgramName.obj
file)
Even though the output of the compiler is machine language code, it is not yet ready to run;
that is, it is not yet executable because it does not have the required C and other functions
included.
Linking the program
 Linking the program is essential process. It puts together all other program files and functions
that are required by the program.
 For example, If the programmer is using sqrt() function, then the object code of this function
should be brought from math.h library of the system and linked to the main() program.
 After linking, the file obtained is called "Executable File" (ProgramName.exe file).

Executing the program

 The Executable file is loaded into memory for execution by a tool is called “loader”.
 Address at which program loaded is informed to CPU. Now CPU runs the program from the
address given by loader.

Dept of Computer Science & Engineering


Computer Programming 16

Software or System Development Method:


Today’s large-scale, modern programming projects are built using a series of interrelates
phases commonly referred to as the system development cycle. Although the exact number and
names of the phases differ depending on the environment, there is general agreement as to the steps
that must be followed.

One very popular development life cycle is the Waterfall model. Depending on the company
and the type of software being developed, this model consists of between five and seven phases.

Dept of Computer Science & Engineering


Computer Programming 17

 The water fall model starts with system requirements. In this phase , all the requirements of a
project will be gathered, the system analyst define the requirements.
 In the analysis phase, different alternatives will be analyzed from system's point of view.
 The design phase determines how the system will be built, the functions of individual
programs and the design of files/database is completed.
 In the coding phase, the programs will be written.
 In the testing phase, all the programs will be tested together, to make sure that the system
works as a whole.
 In the maintenance phase, the project will be put in work into production.

Program Development:
When we are given the assignment to develop a program, we will be given a program
requirements statement and the design of any program interfaces. Also we should receive an overview
of the complete project. Our job is to determine how to take the inputs we are given and convert them
into the outputs that have been specified. This is known as program design.
Program development is a multistep process which consists o the following steps:
 Understand the problem
 Develop a solution
 Write a program
 Test the program

Understand the problem:


The first step in solving a problem is to understand it carefully i.e., we need to have a clear idea about
the problem. This can be done by asking the questing about the problem to the user.

Develop a solution:
Once we finally understand the problem, we use three tools in developing a solution.
 Structured Chart
 Algorithm/Pseudo Code
 Flow Chart
A Structured Chart also known as a “Hierarchy Chart” is used to design the whole program,
which shows the relationship of various units. (i.e., the functional flow the program).
Algorithm is the Step by step procedure to solve a problem.
Pseudocode is English- like statements that follow a loosely defined syntax and are used to
convey the design of an algorithm. Pseudo code is part English, part program logic. Its purpose is to
describe, in precise algorithmic detail, what the program being designed is to do. This requires
defining the steps to accomplish the task in sufficient detail so that they can be converted into a
computer program. Most of the statements in the pseudocode are easy to understand.
Flowchart: Graphical representation of an algorithm is called as flowchart. A flowchart is a
program design tool in which standard graphical symbols are used to represent the logical flow of
data through function.

Dept of Computer Science & Engineering


Computer Programming 18

Writing a Program:

After developing a solution the program has to be written in any programming language.

Test the Program:

After writing the program, it has to be tested to check if there are any errors or not. There are
basically two kinds of testing techniques.
a. Black Box Testing
b. White Box Testing.

 Black Box Testing is done by the testing Engineer and the user.
These people don’t know what is there inside the program. They will just test the program
using the given requirements set.

 White Box Testing done by the programmer who knows what is there inside the program and
he can test each line of instruction in a program.

Algorithm (Pseudo code):

An Algorithm is the step-by-step process of solving a particular problem or algorithm is the


step-by-step method of performing any task. Each step can be called as an instruction. Therefore, an
algorithm is a finite set of well-defined instructions for accomplishing a specified task.

There is a time and space complexity associated with each algorithm. Time complexity
specifies the amount of time required by an algorithm and space complexity specifies the amount of
space required. The algorithm that ensures best time and space trade off should be chosen for
obtaining the desired solution.

Features of an algorithm:

 Finiteness: An algorithm should terminate in a finite number of steps.


 Definiteness : Each of the algorithm must be precisely defined
 Effectiveness: All the operations used in the algorithm can be performed exactly in a
fixed duration of time.
 Input: An algorithm has zero or more inputs
 Output: An algorithm has one or more outputs.

Categories of an algorithm:

Algorithms are divided into three categories:


1. Sequence
2. Selection
3. Iteration

Dept of Computer Science & Engineering


Computer Programming 19

Sequence: In this category all the instructions are performed one after the other.

Selection: In the selection, instructions will be executed based on the condition, i.e., if the condition
is true, some block of statements are executed; else if is false, another block of statements gets
executed

The selection form can be written as

if(condition)
then statement;

if(condition)
then statement1;
else statement2;

Iteration: In this category some of the instructions will be performed repeatedly for some specific
number of times. Iteration statements are written using the following format.

Repeat
Statements;
Until(Condition)
The statements will be executed continuously if the condition is true.
If the condition becomes false the next step will be executed.

Pseudo Code:

 Pseudo code is a problem solving tool.


 It is quite similar to an algorithm but follows a loosely defined syntax.
 The goal of writing pseudo code is to provide high level description of an algorithm, which
helps us to translate from an English language description of a problem to a program written
in programming language like C.

Ex : Write an algorithm for adding two numbers.


Algorithm Pseudo code:
Step 1: start Step 1: start
Step 2: read 2 numbers Step 2: read 2 numbers a,b
Step 3: add the 2 numbers Step 3: sum <- a+b (or) sum = a+b
Step 4: print sum Step 4: Display sum
Step 5: stop Step 5: stop

We can write an Algorithm or Pseudo code for a given problem.


In the above example the algorithm explains the process of solving the problem in simple
English language where as the Pseudo code gives the programmatic representation of thsse problem.
We can use any one of them or both.

Dept of Computer Science & Engineering


Computer Programming 20

Sequence, selection, iteration; all are same for Pseudo code and algorithm.

Example Algorithms:

Algorithm 1: To find the average of three numbers.


Step 1: Start
Step 2: Read the values a,b,c
Step 3: average = (a+b+c)/3.0
Step 4: print average
Step 5: stop
Algorithm 2: To find the area and circumference of the circle.
Step 1: start
Step 2: read radius ( r ) of the circle
Step 3: area  3.14*r*r
Circumference  2.3.14*r
Step 4: print the area, circumference
Step 5: stop.
Algorithm 3: To find the area of the triangle.
Step 1: start
Step 2: Read the value of a,b,c
Step 3: Calculate three sides of the triangle using formula
S  (a+b+c)/2
Step 4: Find the area of a triangle apply formula
area  sqrt(s*s(s-a)*(s-b)*(s-c))
Step 5: print area
Step 6: stop
Algorithm 4: To swap given two numbers 10,20.
Step 1: start
Step 2: read a  10,b  20
Step 3: c  a
ab
bc
Step 4: print a, b
Step 5: stop.

Algorithm 5: To swap two variables without using another variable.


Step 1: Start
Step 2: read the values of a, b
Step 3: 3.1 : a  a + b
3.2 : b  a – b
3.3 : a  a – b
Step 4: print a , b
Step 5: stop.

Dept of Computer Science & Engineering


Computer Programming 21

Algorithm 6: To find the number is negative or positive.


Step 1: start
Step 2: Read n
Step 3: if n>0 then
Step 3.1 : print number is negative
Step 3.2 : else print number is positive
Step 3.3 : endif
Step 4: stop

Algorithm 7: To find greatest of two numbers.


Step 1: start
Step 2: Read a,b
Step 3: if a>b then
Step 3.1: print a is greater
Step 3.2: else print b is greater
Step 3.3: endif
Step 4: stop.
Algorithm 8: To find the roots of the quadratic equation.
Step 1: start
Step 2: Enter the value of a,b,c
Step 3: discriminate (d)  b*b-4*a*c
Step 4: if d>=0 then
Step 4.1: Root1 (-b+sqrt(d))/(2*a)
Root2  (-b-sqrt(d))/(2*a)
Step 4.2: print root1 , root2
Step 5: if d <0 then
Step 5.1: print roots are imaginary
Step 6: stop.

Algorithm 9: To find the largest of three numbers.


Step 1: start
Step 2: read a,b,c
Step 3: if (a>b) and (a>c) then
Step 3.1: print A is greater
Step 3.2: else
Step 3.2.1: if ( b > c ) then print B is greater
Step 3.2.2: Else print C is greater
Step 4: stop
Algorithm 10: To find whether the given number is odd or even
Step 1: Start
Step 2: Read the number (n)
Step 3: if(n%2===0) then
Step 3.1: print even
Step 3.2: Else print odd
Step 4: stop

Dept of Computer Science & Engineering


Computer Programming 22

Flow chart:
A Flow chart is a Graphical representation of an Algorithm or a portion of an Algorithm.
Flow charts are drawn using certain special purpose symbols such as Rectangles, Diamonds, Ovals
and small circles. These symbols are connected by arrows called flow lines.

(or)

The diagrammatic representation of way to solve the given problem is called a flow chart.

The following are the most common symbols used in Drawing flowcharts:

By using the basic flow chart symbols, we can design any program. Then we will combine them to
design solutions to more complicated problems. There are three design structures, such as Sequence
Selection and loop.

Dept of Computer Science & Engineering


Computer Programming 23

Sequence Structure: It is the simplest, because it is nothing more than a series of statements
performed one after another. It is a sequence because the flow always continues in same direction
every time the structure is executed. A sequence may include number of instructions, but each would
be done in turn in the same order.

Selection Structure: selection structure uses a decision to ask some question. This structure includes
the decision and the operation to be performed in response to the decision. There will be two exists
from the decision, but both of these branches are still a part of the selection structure, then both
branches must rejoin a single flow line to exit the structure. Using these selection structure different
steps may be executed depending on the result of the decision test.

Sequence Structure Selection Structure

Loop Structure : The loop structure are used to execute a sequence of steps in a number of times or
until a particular condition is true. This structure will have a decision, one or more additonal symbols
indicating the steps to be done within the loop, and a flow line that sends control back to the
beginning of the loop.

There are two loops are available Top Tested loop and Bottom Tested Loop

Top Tested Loop:

The top tested loops are leading decision loops means the decision is evaluated always at the
first statement of the of the loop. If it is true, the control follows the flow lines that goes into the loop.
If it is false , control follows the first statement after the loop.

Bottom Tested Loop:

The bottom tested loop is a trailing decision loop , means the decision is always evaluated at
the last statement of the loop. The body of the loop will be executed once before control even gets to
the loop test. If the condition is true then the control follows the flow lines that goes into the loop. If it
is false , control follows the first statement after the loop.

Dept of Computer Science & Engineering


Computer Programming 24

Top – Tested Loop Bottom– Tested Loop

Example Flowcharts:

1. Draw a flow chart for average of three numbers.

Dept of Computer Science & Engineering


Computer Programming 25

2. Draw a flow chart to find the roots of the quadratic equation.

3. Draw a flow chart to find the factorial of a given number.

Dept of Computer Science & Engineering


Computer Programming 26

Introduction to C Language:
C is one of the most popular programming language, it was developed by Dennis Ritche at
AT & T ( American Telephone & Telegraph) Bell Laboratories at USA in 1972.
It is an upgraded version of two earlier languages, called BCPL and B, which were also developed at
Bell Laboratories.

The root map for all modern computer languages are started through the ALGOL language in
early 1960’s after then COBOL( Common Business Oriented Language) was used for Commercial
Application, FORTRAN was being developed for Scientific Application. At this stage, people started
thinking about the single language which can program all possible applications.

In 1967, Matrin Richards developed a language called BCPL (Basic Combined


Programming Language) primarily for writing System Software. In 1970 Ken Thompson created a
language using many features of BCPL and called it simply B. B was used to create early versions of
UNIX at Bell Laboratories.

C was evolved from ALGOL, BCPL and B by Dennis Ritche at Bell


Laboratories in 1972. C used many concepts from these languages and added the
concept of data types and other powerful features. The UNIX Operating System,
which was developed at Bell Laboratories, was coded almost entirely in C. UNIX
is one of the most popular operating system. Major parts of popular operating
systems like Windows, UNIX, Linux is still written in C.

Many other high-level languages have been developed based on C. For instance, Perl is a
popular programming language in World Wide Web (WWW) design across the Internet. Perl actually
borrows a lot of features from C. If you understand C, learning Perl is becomes easy. Another
example is the C++ language, which is simply an expanded version of C, although C++ makes object-
oriented programming easier. Also, learning Java becomes much easier if you already know C.

During 1970s, C had evolved into what is now known as “Traditional C”. The language
became more popular after publication of the book “The C Programming Language” by Brian
Kernighan and Dennis Ritche in 1978. The book so popular that the language came to be known as
“K & R C” among the programming community.

The rapid growth of C led to the development of different versions of the language. To assure
that the C language remains standard, in 1983, American National Standards Institute (ANSI) formed
a technical committee to define a standard for C. the committee approved a version of C in 1989
which is now known as ANSI C. It was then approved by the international standard Organization in
1990. This version of C is also referred to as C89.

During 1990’s, C++ a language entirely based on C, underwent a number of improvements


and changes and became an ANSI/ISO approved language in November 1977. All popular computer
languages are dynamic in nature. They continue to improve their power and scope by incorporating

Dept of Computer Science & Engineering


Computer Programming 27

new features and C is no exception. The Standardization Committee of C felt that a few features of
that a new features of C++ / java , if added to c , would enhance usefulness of the language. The
result was the 1999 standard for c. this version is usually referred as C99.

The history and development of C is illustrated in figure.

ALGOL ----- International Group ------ 1960

BCPL ----- Martin Richards ------ 1967

B ----- Ken Thompson ------ 1970

Traditional C ----- Dennis Ritche ------ 1972

K&RC ----- Kernighan & Ritche ------ 1978

ANSI C ----- ANSI Committee ------ 1989

ANSI/ISO ----- ISO Committee ------ 1990

C99 ----- Standardization Committee ------ 1999

Although C99 is an improved version, still many commonly available compilers do not support new
features incorporated in C99.

Features of C Language:
 C is general purpose , structured programming language.
 C is highly portable (i.e., it can be run in different operating systems environments).
 C is robust language whose rich set of built in functions and operators can be used to write any
complex programs.
 C is well suited for writing system software as well as application software.
 C is a middle level language . it performs the task of low level language as well as high level
language. We can write the codes for operating system , Application programs , Assembly
language programs in C language.
 C has ability to extend itself. We can continuously add our own functions to the existing
library functions.
 C programs are fast and efficient. This is due to its variety of data types and powerful
operations.
 C language allows manipulation of data at the lowest level i.e., bit level manipulation. This
features is extensively useful in writing system software program.
 C can be applied in systems programming areas like Compiler , Interpreters and Assemblers
etc.

Dept of Computer Science & Engineering


Computer Programming 28

Structure of A ‘C’ Program


The program written in C language follows this basic structure. The sequence of sections
should be as they are in the basic structure. A C program should have one or more sections but the
sequence of sections is to be followed.

1. Documentation section

2. Linking section

3. Definition section

4. Global declaration section

5. Main function section

Declaration section

Executable section

6. Sub program or function section

1. Documentation Section :

Documentation section comes first , it consist of set of comment lines giving name of the
program , the name of the author and other details like flow of the program , describing or description
about the functions , variables tec.
The comment lines are nothing but same of kind of statements which are to be placed between
the delimiters like /* & */. The complier ignores or doesn’t compiles the comments. Thus we can say
that comments are not a part of executable program
The programmer can use frequently any number of comments that can be placed any where
in the program.
// this is a single comment line
/* -------------------------------------
--------------------------------*/ this is an example of multi comment lines
2. Link Section :
The Link Section provides instruction to the compiler to link functions from the system
library. In general the link section contains preprocessor directive statements. These statement starts
with a pound sign(#). The preprocessor statements are used to include the header files to the current
program. Each header file by default has an extension of .h. the header file should be included by
using #include directive as given below.
e.g. #include <stdio.h>

Dept of Computer Science & Engineering


Computer Programming 29

3. Definition Section :
The Definition Section used to define all symbolic constants and assign them some value.
e.g. #define MAX 25

Here #define is a compiler directive which tells the compiler whenever MAX is found in the
program replace it with 25.

4. Global Declaration Section :


This section declares some variables that are used through out the program (including main
and other functions). These variables are known as Global variables. This section must be declared
outside of all functions.
Ex. int i; (before main())

5. Main Function Section :


Every program written in C language must contain the main() function. Empty parentheses
after main are necessary. The main() function is the starting point of every C program.
main()
{
point from execution starts
}

The execution of the program always begins with the main(). Except the main() section other
sections may or may not necessary. The program execution starts from the opening brace { and ends
with closing brace }. Between two braces the programmer should declare declaration and executable
parts.
Declaration part : The Declaration part declares all variables that are used in executable part.
Initialization of variables can be done in this section.
Executable part : The Executable part contains the statements followed the declaration of variables.
This part contains set of statements or a single statement. These statements are enclosed between the
braces.

6. Subprogram Section :
The Sub Program section consist of all user defined functions that are called in the main
function. User defined functions are generally placed immediately after the main function, although
they appear in any order.

SIMPLE ‘C’ PROGRAM:

Dept of Computer Science & Engineering


Computer Programming 30

/* simple program in c */
#include<stdio.h>
main() // starting point of the program
{
printf(“welcome to c programming”);
/*printf() is a predefined function or built-in-function which is defined in stdio.h (standard
input/output header file). It is used to print the data that is passed within double quotes on the console
or output screen*/
} /* End of main */

Explanation about Sample program:

1. The first line: /* sample C program */ is a comment.


The comments in c used to describe about the program name, author other details etc.
2. The second line: #include<stdio.h>
Any statement that starts with # symbol is known as preprocessor directives.
The #include<stdio.h> informs or instructs the preprocessor to include the <stdio.h> header
file to the current program. The header file consist of predefined or built-in functions.
3. The third line main()
The main() is the starting point of the program. The program execution starts from main()
function.
The opening brace { marks the beginning of the program closing brace } indicates the end of
the program. All the statements between the two braces form function body. The function
body contains set of instructions to perform the given task.
In the above program the function body contains only one state i.e., printf statements it is a
predefined function for printing the output on the console or screen.

Program Development steps:


 Editing phase
 Compiling phase
 Link phase
 Executing phase

In case of Turboc IDE the following are shortcuts to invoke Compiler, linker

ALT+F9 ------------------- FOR COMPILING THE PROGRAM


F9---------------------------FOR LINKING PROGRAM
CTRL+F9----------------FOR EXECUTING THE PROGRAM
ALT+F5-----------------TO SEE THE OUTPUT
Running C programs

Dept of Computer Science & Engineering


Computer Programming 31

The process of executing a C program is slightly different under Dos and UNIX.

 Running C programs in DOS :

A C program must be converted into an executable file(i.e., a file with an .exe) to run it
in DOS. First the c program has to be typed in a file using an editor. This file is called source
file often, c compilers in many companies supplying C compilers for DOS. Some of the
popular companies are Borland International , Microsoft Corp etc.

Borland International itself has produced many C compilers such as TurboC ,


TurboC++ and Borland C++.(it must be mentioned at this part that c++ is superset of c and
has the same syntax. A c program can be compiled by a c++ compiler.)
In all these cases the actual compiler program into two forms :
1. As an IDE(Integrated Development Environment ) :
2. As a Command Line Compiler.
As an IDE (Integrated Development Environment ) :
The IDE includes all facilities to develop and run programs such as the editor,
compiler, debugger and so on. In case of TurboC & TurboC++ the IDE is a program called tc.exe. In
case of Borland C++ the IDE is invoked by typing a command bc or tc at the dos prompt. After
installing TurboC or TurboC++ the following steps is to followed.

Start ----- my computer ------ c drive ------ tc or TURBOC3 ----- click on Tc.exe

Dept of Computer Science & Engineering


Computer Programming 32

After typing the program , save the program with extension .c

Now press ALT+F9 to compile the program. If the program contains any errors those errors are
displayed to the programmer, no errors then object file is created with extension of .obj.

Now we need press f9 then linker software is invoked. The linker combines different object files to
produce the actual executable file.

Now press ctrl+f9 to run the program , observe that screen will flicker for a moment, in reality the
program has been executed by the IDE , it took a very short time to run , during which is printed on
the screen and came back to the IDE. So how can we sure that the program has printed exactly what
we wanted? For this we must view the output screen. By pressing ALT+F5 key we can see the
message that has been printed on the screen after seeing the result of the program press any key to get
back to the main IDE.

As a Command Line Compiler

This comes a program called tcc.exe in turboc & turboc++. The program is called bcc.exe in
Borland C++. These are the programs that have to be invoked from the command line, and their
purpose is to convert the c program into executable fle.\

For example, assuming that the file hello.c has been created using an editor, the command

tcc hello.c

type at the DOS prompt will convert the c programs hello.c to an executable program called
hello.exe.

In both of these case (IDE or Command line ) an executable file called hello.exe would have been
generated. This program is standalone executable i.e. , it can run independently without the help of
any other file, the IDE or the compiler.

Running a C program in UNIX

Virtually every UNIX system has a C compiler called cc. on same UNIX systems a C compiler
called gcc exits. Both are command line compilers. Their purpose is to convert the c program into
executable code.

The program has to be typed into a file separately using an editor such as vi etc. thereafter the
command

cc hello.c

will create an executable file called a.out by default. This file can be executed by typing a.out at the
prompt.

C – Basics

Dept of Computer Science & Engineering


Computer Programming 33

A programming language should be designed to support certain kind of data, such as numbers,
characters, strings etc. to get useful output known as information. A program is a set of statements for
a specific task, which will be executed in a sequential form. These statements/instructions are formed
using certain words and symbols according to the rules known as syntax rules. Every program must
follow accurately the syntax rules by the language.

C Character Set
The Characters used to form words, numbers and expressions depend upon the computer on
which the program runs. The characters in C are classified in the following categories.

1. Letters
2. Digits
3. White spaces
4. Special characters

Letters
A ……………………......Z
a…………………………z

Digits
0……………………9

White Spaces

Blank Space
Horizontal tab
Vertical tab
New Line
Form feed

Special characters

+ plus , comma < lesser than

- minus . full stop > greater than

* asterisk ; semicolon = equal to

/ slash : colon ( open parenthesis

Dept of Computer Science & Engineering


Computer Programming 34

\ back slash ‘ apostrophe ) close parenthesis

% percent “ double quote [ open bracket

| vertical bar & ampersand ] close bracket

~ tile # hash { open set bracket

? question mark $ dollar } close set bracket

! exclamation mark ^ caret _ underscore

C-TOKENS:
Tokens are individual words and punctuations marks in English language sentence. The smallest
individual units are known as C tokens.

Keywords:

The C keywords are reserved words. All keywords have fixed meanings and these meaning cannot
be changed. Keywords serves as basic building blocks for programs. All keywords must be written in
lower case. The following are list of keywords.

auto double int struct

break else long switch

case enum register Typedef

char extern return union

const float short unsigned

Dept of Computer Science & Engineering


Computer Programming 35

continue for signed void

default goto sizeof volatile

do if static while

All keywords must written in lower case.

Identifiers:
Identifiers are names given to variables, functions and arrays etc. these are user
defined names and consist of sequence of letters and digits with a letter as a first character.
Both uppercase and lower case letters are permitted although lower case letters are commonly used.
Rules for identifiers :
1. The First character of an identifier must be alphabetic character or under score.
2. The identifiers must contain only of alphabetic characters, digits or underscore
3. The identifiers cannot be a keyword
4. No space and special symbols are allowed.
The underscore is used to link the two words in long identifiers or it is used to separate two different
words.

We can also define identifiers in definition section as follows.

#define N 10

#define a 15

Here N & a are user defined identifiers.

DATA TYPES :
To represent different types of data in C program we need different data types. A data type is
essential to identify the storage representation and the type of operations that can be performed on
that data. C supports four different
classes of data types namely

Dept of Computer Science & Engineering


Computer Programming 36

1. Basic Data types(primary or fundamental data types)


2. Derives data types
3. User defined data types
4. Empty data types

Basic Data types(primary or fundamental data types) :


All C compilers supports the five fundamental data types called int , char, float , double.
A Data is represented using numbers or characters. The numbers may be integers or real numbers. A
Datatype is used to indicate the type of value stored in a variable. The data type of a variable is
specified at the time of declaration and is attached till the end of a program.
Various data types and its terminology used to describe them are given following figure.

Size and range


of Basic data
types

INTEGER
TYPE:

The integer
data type is
used to store the
whole numbers.
The integers
does n ’t
contain the

Dept of Computer Science & Engineering


Computer Programming 37

decimal point. They take the binary form for storage. On a 16-bit machine the range of integer values
is -32768 to +32767.

Signed integers

Signed integers are those integers which uses 15 bits for storing the magnitude of a number
and 1 bit to store the sign. The left most bit i.e., 16th bit is used for storing the sign, it is ‘1’ for a
negative number and ‘0’ for the positive number.

Unsigned integers

Unsigned integer use all 16 i.e., (15+1) bits to store the magnitude i.e.,these are the whole
numbers that always hold positive values and the sign bit(left most bit) also contains the value.
(signed integers include sign whereas unsigned integers doesn’t include sign).

Size and range of Data types on a 16 bit machine

Dept of Computer Science & Engineering


Computer Programming 38

CHARACTER TYPE

Characters are generally stored in 8 bits of the internal storage and a single character can be defined as
char data type. Each character has an equivalent ASCII value i.e., these characters are internally
stored as integers.

Data Type Size (bytes) Range Control string or


format specifier

char or signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

FLOATING POINT TYPES

Floating point (or real ) numbers are stored in 32 bits with the 6 digits of precision. These
numbers are defined by using the keywords float and double, whereas the double data type uses the
64bits with the 14 digits of precision.

Data Type Size (bytes) Range Control string or


format specifier

float 4 3.4E-38 to 3.4E+38 %f or %g

double 8 1.7E-308 to 1.7E+308 %lf

long double 10 3.4E-4932 to %lf


1.1E+4932

2 . DERIVED DATA TYPES:

Derived datatypes are used in ‘C’ to store a set of data values. Arrays and Structures are
examples for derived data types.

Dept of Computer Science & Engineering


Computer Programming 39

Ex: int a[10];


Char name[20];

3 . USER DEFINED DATATYPES:

C Provides a facility called typedef for creating new data type names defined by the user. For
Example ,the declaration ,
typedef int Integer;
makes the name Integer a synonym of int.Now the type Integer can be used in declarations
,casts,etc,like,
Integer num1,num2;
Which will be treated by the C compiler as the declaration of num1,num2as int variables.
“typedef” ia more useful with structures and pointers.

Variable:
A variable is an identifier that is used to store some specified type of value. The variable may
take different values at different times during the execution. i.e. , it is the named memory location.

Rules for naming the variables :

 The first character of a variable must be an alphabet or an underscore(_)


 The length of the variable cannot exceed upto 8 characters long , and some of the C compilers
can be recognized upto 31 character long.
 No commas or blank spaces are allowed within a variable name.
 The name of the must be chosen by the programmer in such a way that it should reflect the
functionality of the variable.

Variable Declaration: After designing suitable variable names, we must declare the variables in
declaration part and this declaration tells the compiler what the variable name and type of the data that
the variable will hold.

Syntax

Data_type v1,v2,v3……vn;

Data_type is the type of the data

v1,v2,v3,…..vn are the list of variables

Dept of Computer Science & Engineering


Computer Programming 40

Ex : int n1, n2;


Here the variables , code is integer type
int code; variables holds only integer values and price is
float type variable holds fractional values
float price;

Initializing Variables: Initialization of variables can be done using assignment operator ( = ). The
variables can be initialized while declaration itself.

Syntax :

Variable_name = constant;

Or

Data_type variable_name = constant;

Example 1: int i;

float b;

char c;

//i , b are integer and float type of variables

i=10;

b=32.22;

c=’s’;

Example 2 int i1=100;

float b1=12.22;

char a=’k’;

int a=b=122; a, b are initialized with 122.

printf() : printf() is a predefined or built functions in C. which is used to print message and variables
on the output screen.

Syntax : printf(“message”);

printf(“control string” , var1,var2,var3…..varn);

printf(“\n wel come to C programming “); // prints the data on the screen.

printf(“%d”,a); // prints value of a

Dept of Computer Science & Engineering


Computer Programming 41

scanf() : scanf() is a predefined or built function in C, which is used to read information or values
from the keyboard.

Syntax : scanf(“control string”,&var1,&var2,……….&varn);

Ex : int a; scanf(“%d”,&a); // accepts the value of a from keyboard.

/* write a program to assign a values to the variables */


#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
float ff=32.7;
printf(“\n Enter any numbers “);
scanf(“%d%d”,&a,&b);
printf(“\n User Entered Values : %d %d “,a,b);
printf(“\n float value ff: %f “,f);
}

/* write a program to accept two numbers and add two numbers */


#include<stdio.h>
#include<conio.h>
main()
{
int num1,num2,sum;
printf(“\n Enter any two numbers “);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“\n sum of two numbers : %d “,sum);
}

Constants :
Constants are data values that cannot be changed during the execution of a program. In ‘C’
constants can be classified as follows.

Dept of Computer Science & Engineering


Computer Programming 42

Numeric Constants:

Integer Constants: These are the sequence of numbers from 0 to 9 without decimal points or
fractional part or any other symbols. There are three types of integer constants which forms different
number system.

 Decimal Number : Decimal integers consists of set of digits 0 through 9 , preceded by an


optional –ve or +ve sign. Valid example of decimal integer constants are

Ex : 123 -321 +98

 Octal Number: Octal integer consists of any combination of digits from the set 0 through
7 , with leading 0. Some of the examples of octal integer are

Ex : 037 0 0435

 Hexadecimal Number : Hexadecimal integers are sequence of digits preceded by 0x or 0X.


They may also include alphabets A through F.( A=10, B=11, C=12 , D=13 , E=14 , F=15).
Following are the examples of hex integers

Ex : 0X2 0x5F

The largest integer value that can be stored is machine – dependent. It is 32767 on 16-bit
machines and 2,1247,483,647 on 32-bit machines.

Real Constants : Integers numbers are inadequate to represent quantities that vary continuously, such
as distances , heights , temperatures , prices and so on. These quantities are represented by numbers
containing fractional parts like 17.548. such numbers are called real or floating point constants.

 A real number may also be expressed in exponential ( or scientific) notation. For example
the value 215.65 may written as 2.1565e2 in exponential notation. e2 means multiply by 10
^ 2. The general form is :

mantissa e exponent

Dept of Computer Science & Engineering


Computer Programming 43

 The Mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer number with an optional plus or minus sign.

Ex : 0.65e4 12e-2 3.18E3

Single Character Constants

 A single character constant contains a single character enclosed within a pair of single quote
marks.
 It may be an alphabet, digit , white space or special character.
 We can’t write more than one character in single quotes.
Ex: ‘a’ ‘A’ ‘ ‘ ‘9’ ‘^’
 Character are internally represented by integers ASCII.( American Standard Code for
Information Interchange)
Ex: ‘a’ – 97 ‘A’ – 65 ‘0’ – 48 etc.
 There are 256 ASCII values.

String Constant

 A String constant is a sequence of characters enclosed in double quotes. The characters may
be letters, numbers, special characters and blank space.
Ex : “hello!” , “123#7” , “skr27”
 Remember that a character contant (e.g., ’x’) is not equivalent to the single character string
constant(e.g., “x”). further a single character string constant does not have an equivalent
integer value while a character constant has an integer value.

BACKSLASH CONSTANTS
The backslash constants are predefined which are to be used in o/p functions.
\n new line
\t horizontal tab
\v vertical tab
\a audible alert ( bell )
\r carriage return
\b back space
\f form feed
\’ single quote
\” double quote
\? Question mark
\\ back slash
\0 null

Operators:

Dept of Computer Science & Engineering


Computer Programming 44

An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.

C operators can be classified as

1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment or Decrement op+erators

6. Conditional operator

7. Bit wise operators

8. Special operators

1. Arithmetic Operators : All basic arithmetic operators are present in C.

Operator Meaning Examples

+ Addition 2+9=11

- Subtraction 9-2=7

* Multiplication 2*9=18

/ Division 9/3=3

% Modulo division(remainder) 9%2=1

All the above operators are binary operators as they act upon two operands.

Dept of Computer Science & Engineering


Computer Programming 45

The modulo division gives the remainder of an integer division.

An arithmetic operation involving only real operands(or integer operands) is called real arithmetic(or
integer arithmetic). If a combination of arithmetic and real is called mixed mode arithmetic.

Operation Result Example

int / int int 2/5=0

real / int real 5.0/2=2.5

int / real real 5/2.0=2.5

real / real real 5.0/2.0=2.5

/*Ex 1: program to illustrate the usage of arithmetic operator.*/


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k; // integer variables
clrscr(); // used to clear the screen
i=10;
j=20;
k=i+j;
printf("\n value of k : %d",k);
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 46

/* program to find out all arithmetic operations on two given values */


#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,d;
int sum,sub,mul,rem;
float div;
clrscr();
printf("\n Enter the values of a,b :");
scanf("%d%d",&a,&b);
sum=a+b;
sub=a-b;
mul=a*b;
div=a/b;
rem=a%b;
printf("\n sum = %d , sub = %d , mul = %d , div = %f rem = %d",sum,sub,mul,div,rem);
getch();
}
Output:

2. Relational Operators : We often compare two quantities and depending on their

relation take certain decisions for that comparison we use relational operators. For example we my
compare the age or salaries of two persons or the price of two items and so on.

Operator Meaning Examples Result

< Is less than 2<9 1

> Is greater than 1>2 0

Dept of Computer Science & Engineering


Computer Programming 47

<= Is less than or equal to 2<=2 1

>= Is greater than or equal to 3<=7 1

!= Is not equal to 1!=1 0

== Is equal to 2==2 1

It is the form of

AE1 relational operator AE2

AE1 & AE2 are constants or an expressions.

When arithmetic expression are used on either side of a relation operator , the arithmetic expression
will be evaluated first and then the result compared.

/* program to use various relation operator*/


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\n Condition\t:\tResult ");
printf("\n 5>5 \t:\t%d",5>5);
printf("\n 10<100 \t:\t%d",10<100);
printf("\n 100!=100 \t:\t%d",100!=100);
printf("\n 100==100 \t:\t%d",100==100);
getch();
}
Output :

In above
program
the true condition returns 1 and false returns 0. In this example first and third conditions are false and
second and fourth conditions are true.

/* program to accept two numbers and find out which one is greater */
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2;
clrscr();
printf("\n Enter any two integer numbers ");

Dept of Computer Science & Engineering


Computer Programming 48

scanf("%d%d",&num1,&num2);
if(num1>num2)
printf("\n %d is greater ",num1);
else
printf("\n %d is greater ",num2);
getch();
}

Output:

3. Logical Operators : Logical operators are used to combine the results of two or more conditions
or expressions. ‘C’ has the following logical operators.

&& ------ logical AND

|| --------- logical OR

!----------logical NOT

The logical AND (&&) operator is usually used in situation , where a set of statements are to be
executed, if two or more expressions are true.

The logical OR (||) operator is used in situation , if either of them ( at least ) one condition must be
true form two or more conditions or expressions. Then the set of statements are executed.

The logical NOT (!) operator reverse the value of the expression it operates on. i.e., if makes a true
expression false and false expression true.

Op-1 Op-2 Op-1&&Op-2 Op-1||Op-2

Non-Zero Non-Zero 1 1

Non-Zero 0 0 1

0 Non-Zero 0 1

Dept of Computer Science & Engineering


Computer Programming 49

0 Non-Zero 0 0
Op-1 !Op-1

Non-Zero 0

0 1

Example : ‘ i ’ is an integer variable with value of 7

‘ f ’ is float variable with value of 5.5

‘c’ is a character variable which represents ‘w’ character.

The following expressions

(i>=6)&&(c==’w’) returns true i.e., 1

(f<11)&&(i>100) returns false i.e., 0

(c!=’p’)||(i<=100) returns true i.e., 1

// program to illustrate relational operator


#include<stdio.h>
#include<conio.h>
void main()
{
int c1,c2,c3;
clrscr();
printf("\n enter the values of c1, c2 and c3 ");
scanf("%d%d%d",&c1,&c2,&c3);
printf("\n condition : return values(1---true,0---false) ");
printf("\n c1>c2 : %d ", c1>c2);
printf("\n c2<=c3 : %d ", c2<=c3);
printf("\n c3!=c1 : %d ", c3!=c1);
getch();
}

Dept of Computer Science & Engineering


Computer Programming 50

Output :

/* program to print logic 1 if input character is capital otherwise 0 */


#include<stdio.h>
#include<conio.h>
main()
{
char x;
int y;
clrscr();
printf("\n enter a character ");
scanf("%c",&x);
y=(x>=65 && x<=90);
printf(" y : %d ",y);
getch();
}
/* In the above program a character is entered. using logical operator and entered characters ascii
value is checked. if it is in between 65 and 90 the result displayed will be 1 otherwise 0.the and
operator joins two conditions. if the condition is true 1 is assigned to y otherwise 0.*/
Output :

Dept of Computer Science & Engineering


Computer Programming 51

/* write a program to display 1 if inputed number is either 1 or 100 otherwise 0. Use logical or
operator*/
#include<stdio.h>
#include<conio.h>
main()
{
int num,res;
clrscr();
printf("\n enter any number ");
scanf("%d",&num);
res=(num==1 || num==100);
printf("\n res : %d ",res);
getch();
}
/*In the above program the or operator checks two conditions. if one of the conditions satisfies 1 is
assigned to res otherwise 0.*/
Output :

/* write a program to display 1 if inputted number is between 1 to 100 otherwise 0. Use logical &&
operator*/
#include<stdio.h>
#include<conio.h>
main()
{
int num,res;
clrscr();
printf("\n enter any number ");
scanf("%d",&num);
res=(num>=1 && num<=100);
printf("\n res : %d ",res);
getch();
}
/* In the above program the and operator checks two conditions. if both condtions are
conditions satisfies 1 is assigned to res otherwise 0.*/
output :

Dept of Computer Science & Engineering


Computer Programming 52

5. Assignment Operators : They are used to assign the result of an expression to a variable. The
assignment operator is '='.

Syntax : variable_name = expression or value;

X = 10; // x is variable

x=x+1; or x+=1;

C provides compound assignment or short hand assignment operators are used to assign a
new value to a variable after performing a specified operation.

Ex : x+=y; is same as x=x+y;

Operator Statement with simple Statement with shorthand


assignment operator operator

+= x+=y x=x+y

- = x-=y x=x–y

* = x*=y x = x*y

/= x/=y x = x/y

%= x%=y x=x%y

6. Increment and Decrement operators :

C has two vey useful operators , they are increment (++) and decrement (--) operators.

The operator ++ adds 1 to the variable or operand, while – subtracts 1 from the variable or operand.
Both are unary operators. Because they act upon only one variable.

++x ------------------ Pre Increment or prefix increment operator

x++ ----------------- Post Increment or postfix increment operator

--x ------------------ Pre decrement or prefix decrement operator

x-- ----------------- Post decrement or postfix decrement operator

A prefix increment operator first adds 1 to the operand or variable and then the result s assigned to the
variable on the left. On the other hand , a postfix increment operator first assigns the value to the
variable on left and then increments the operand.

Dept of Computer Science & Engineering


Computer Programming 53

Similar is the case when we use decrement (--) operator.

/* program to demonstrate increment and decrement operators */


#include<stdio.h>
#include<conio.h>
main()
{
int a=3,b=5;
clrscr();
printf("\n a = %d , b = %d ",a,b);
printf("\n--------------------------");
printf("\n post increment operation ");
printf("\n--------------------------");
printf("\n a++ = %d , b++ = %d",a++,b++);
printf("\n a = %d , b = %d ",a,b);
printf("\n--------------------------");
printf("\n pre increment operation ");
printf("\n--------------------------");
printf("\n ++a = %d , ++b = %d ",++a,++b);
printf("\n a = %d , b = %d ",a,b);
printf("\n--------------------------");
printf("\n post decrement operation ");
printf("\n -------------------------");
printf("\n a-- = %d , b-- = %d ",a--,b--);
printf("\n a = %d , b = %d ",a,b);
printf("\n--------------------------");
printf("\n pre decrement operation ");
printf("\n -------------------------");
printf("\n --a = %d , --b = %d ",--a,--b);
printf("\n a = %d , b = %d ",a,b);
getch();
}
/* where
a++ post increment , first do the operation and then increment
++a pre increment , first increment and then do the operation
a-- post decrement , first do the operation and then decrement
--a pre decrement , first do the operation and then decrement
*/

Dept of Computer Science & Engineering


Computer Programming 54

Output :

7. Conditional Operator : A ternary operator pair "? :" is available in C to construct conditional
expressions of the form
exp1 or condition? exp2 : exp3;

It work as

if exp1 or condition is true then exp2 else exp3

the ‘ ? : ’ operator acts as a ternary operator, it first evaluate the condition , if it is true (non- zero)
then exp1 is evaluated , if the condition is false (zero) then the exp2 is evaluated.

/* program to find greatest of two numbers by using ternary operator*/


#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2;
clrscr();
printf("\n Enter the values of n1 , n2 :");
scanf("%d%d",&n1,&n2);
printf(n1>n2?"\n n1 is greater ": "\n n2 is greater ");
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 55

8. Bit wise Operators : C supports special operators known as bit wise operators for manipulation of
data at bit level i.e., these operations on the bits of a binary format of an integer. They are not applied
to float or double.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

~ one's complement

9. Special Operators : These operators which do not fit in any of the above classification are
,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->).

The ‘comma’ (,) operator is used

 to link related expressions together.

The operations are performed from left to right and the result obtained at last operation is
assigned to a variable.

Ex: int i=0,j;

j=(i+=2,++i,i*3);

Here first i+=2 is performed (result is i=2) then ++i (result is i=3 and at last i*3 is performed
(result is i=9) and the resultant value is stored in j.

j=9

Dept of Computer Science & Engineering


Computer Programming 56

/* program to swap two integer variables using the commo operator

#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2,n3;
clrscr();
printf(“\nEnter two integers : “);
scanf(“%d%d”,&n1,&n2);
printf(“\n-----Before Swaping-----\n”);

printf(“n1 = %d\tn2 =%d”,n1,n2);

n3=n1,n1=n2,n2=n3;

printf(“\n-----After Swaping-----\n”);

printf(“n1 = %d\tn2 =%d”,n1,n2);

getch();

 in looping statements. (for,while)

Tthe ‘sizeof’ operator is used to know the size of an operand.

Syntax : sizeof(operand)

The ‘&’ operator prints address of the variable in the memory.

Syntax : &(variable)

/* program to use & and sizeof operator and determine the size of integer and float variables*/
#include<stdio.h>
#include<conio.h>
main()
{
int x=2;
char c='a';
float y=2;
clrscr();
printf("\n sizeof(x) = %d bytes",sizeof(x));
printf("\n sizeof(c) = %d bytes",sizeof(c));
printf("\n sizeof(y) = %d bytes",sizeof(y));
printf("\n address of x = %u bytes and y = %u",&x,&y);
getch();
}

Dept of Computer Science & Engineering


Computer Programming 57

Type Casting:
Type Casting or Type conversion refers to the process of conversion of one data type to
another data type.

There are two types of type conversions

i. Implicit type casting


ii. Explicit type casting.

Implicit type casting


It is an automatic type casting.
Ex: int a = 9.5; here system truncates the decimal part of 9.5 and assigns only integral part
to integer variable (TRUNCATION)

float x=10; here system promotes value 10 to 10.0 (PROMOTION).

char ch=65; here integer value 65 is converted into ‘A’.

Explicit type casting


It is process of converting one data type to another forcefully. It is to be done by the
programmer or user.
The general form of explicit type cast is

(type – name) expression

type – name is one of the standard C data types whereas expression may be a constant,
variable or an expression.
Ex: float a=9.6;

float b=3.2;

int c = (int)a%(int)b;

Now modulo division is performed in integer mode

Dept of Computer Science & Engineering


Computer Programming 58

Expression

An Expression is a sequence of operands and operators that reduces to a single value.


Expression can be simple or complex. A Simple Expression contains only one operator. (Ex : 2+3) A
Complex Expression contains more than one operator.
Ex : 2+5*2
To evaluate a complex expression, we reduce it to a series of simple expressions. In the
previous example we first evaluate the simple expression 5*7 and then the expression 2 + 35 giving
result of 37.

Precedence is used to determine the order in which the different operators in a complex
expression are evaluated. Associativity is used to determine the order in which operators with the
same precedence are evaluated in a complex expression. Precedence is applied before associativity
the order in which expressions are evaluated. Associativity is then applied , if necessary.

 Each operator in C has a precedence associated with it.


 This precedence is used to decide how to solve an expression involving more than one
operator.
 Generally operators at higher levels of precedence are evaluated first.
 The operators of the same precedence are evaluated either from left to right or from right to
left depending on the level. This is known as associativity rule
 The following table gives you a complete list of operators, their precedence levels, and their
rules of association.
 Rank 1 indicates highest rank and 15 the lowest.

Operator Description Associativity Precedence Level

() Parentheses

[] Brackets(array subscript)

. and -> Member selection operators

++ Post increment Left –to-right 1

-- Post decrement

Dept of Computer Science & Engineering


Computer Programming 59

+ Unary plus

- Unary minus

++ Pre increment

-- Pre decrement

! Logical Not Right-to-left 2

~ One’s complement

(type) Type cast conversion

& and * Pointer operators

Sizeof Determine size in bytes

* Multiplication

/ Division Left-to-right 3

% Modules

+ Addition

- Subtraction Left-to-right 4

<< Bitwise left shift

>> Bitwise right shift Left-to-right 5

< Less than

<= Less than or equal to Left-to-right 6

> Greater than

>= Greater than or equal to

== Equal to Left-to-right 7

!= Not equal to

Dept of Computer Science & Engineering


Computer Programming 60

& Bitwise AND Left-to-right 8

^ Bitwise XOR Left-to-right 9

| Bitwise OR Left-to-right 10

&& Logical AND Left-to-right 11

|| Logical OR Left-to-right 12

?: Ternary Right-to-left 13

+=

-=

*=

/=

%= Assignment Operators Right-to-left 14

&=

^=

|=

<<=

>>=

, Comma Left-to-right 15

Associativity:

Associativity can be left-to-right or right-to-left. Left –to-right associativity evaluates the


expression by starting on the left and moving to the right. Conversely , right-to-left associativity
evaluates the expression by proceeding from the right to the left. Associativity is applied when we
have more than one operator of the same precedence level in an expression.

Dept of Computer Science & Engineering


Computer Programming 61

Left-to-right Associativity:

The following shows an example of left-to-right associativity. Here we have four operators of
the same precedence (* / % ).
3*8/4%4*5
Associativity determines how the subexpressions are grouped together. All of these operators have the
same precedence(3). Their associativity is form left to right. So they are grouped as follows:
(((3*8)/4)%4)*5)
The value of this expression is 10.

Right to left associativity :

Several operators have right-to-left associativity as shown in the precedence table. For
example , when more than one assignment operator occurs in an assignment expression , the
assignment operators must be interpreted form right-to-left. This means that rightmost expression will
be evaluated first then its value will be assigned to the operand on the left of the assignment operator
and the next expression will be evaluated.
a+=b*=c-=5
is evaluated as
(a + = (b*=(c-=5)))
Which is expanded as
(a=a+(b=b*(c=c-5)))
If a has an initial value of 3 , b has an initial value of 5 , and c has an initial value of 8 ,these
expressions become
(a=3+(b=(5*(c=8-5)))
Which results in c being assigned a value of 3 , b being assigned a value of 15 , and a being assigned a
value of 18. The value of the complete expression is also 18.

Evaluation of Expression:

Dept of Computer Science & Engineering


Computer Programming 62

While evaluating an expression the operator with highest precedence will be evaluated first,
then the second highest precedence operator and the operator with least precedence will be evaluated
last.
* / % have higher priority level (3)
+ - have lower priority level(4)
Let us consider the following expression a%3-b/2+(c*d-5)/e
Where a=30,b=10,c=11,d=5,e=10
Replacing the values of a, b, c ,d, e in the expression we get
Step 1 30%3-10/2+(55-5)/10

Step 2 30%3-10/2 + 50/10 (operation with in parentheses)

Step 3 0-10/2+50/10 ( here we are following left to right associativity ,% operation )

Step 4 0-5+50/10 ( / operation )

Step 5 0-5+5 ( - operation )

Step 6 0 (+ operation )
/* program to demonstrate operator precedence */
#include<stdio.h>
#include<conio.h>
main()
{
int a=30,b=20,c=10;
clrscr();
printf(" \n a*b+c : %d", a*b+c); // 610
printf(" \n a*(b+c) : %d", a*(b+c)); // 900
printf(" \n a+b*c : %d", a+b*c); //230
printf(" \n a-b/c : %d", a-b/c); //28
printf(" \n --a+b*c : %d", --a+b*c); //29+200=229
printf(" \n a-b++/(c-3) : %d",a-b++/(c-3)); //27
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 63

Input / Output

We know that input , process, output are the three essential features of computer program. The
program takes some input data, processes it and gives the output. we have two methods for
providing data to the program.
 Assigning the data to the variables in a program
 By using the input/output statements.
In ‘C’ language two types of Input/Output statements are available , and all input and output
operations are carried out through function calls. Several functions are available for input/output
operations in C. These functions are collectively known as the standard I/O library.

i. Unformatted Input / Output Statements


ii. Formatted Input/ Output Statements

Dept of Computer Science & Engineering


Computer Programming 64

Unformatted Input / Output Statements

These statements are used to Input or Output a single/group of characters. Or these statements
or functions are used to accept/display the single or group of characters from/to the user.

getchar() : getchar() is used to read a single character from the input device(keyboard).

varname=getchar();

the getchar() function is defined in standard I/O library.

Syntax : char variable_name = getchar();


Char : datatype
Variable_name any valid c variable.

Ex : char x;
X=getchar();

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch;
printf("\n Enter any character ...");
ch=getchar();
if(isalpha(ch)>0)
printf("\n It is a alphabet ");
else if(isdigit(ch)>0)
printf("\n It is a digit ");
else
printf("\n It is alphanumeric ");
getch();
}
/* isalpha() is predefined function from ctype.h file. It is used to check whether the character variable
consists of alphabet or not. If it consist of alphabet it returns 1 otherwise 0. */
Output :

Dept of Computer Science & Engineering


Computer Programming 65

putchar() : The putchar() function is used to display one character at a time on the standard output
device.

Syntax : putchar(character_variable);
Ex : char ch=’a’;
putchar(ch);

/* program to convert a character from lower to uppercase */

#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter any Alphabet in lower case \n....");
ch=getchar();
ch=ch-32;
putchar(ch);
getch();
}
/* a to z is 97 to 122
A to Z is 65 to 90
0 to 9 is 48 to 57
back space is 8
enter key is 13
space bar is 32 */

output :

getc() : the getc() is used to accept a single character from the standard input to a character variable.

Syntax : char ch=getc();

putc() : the putc() is used to display a single character on the standard output device.

char ch=’y’;

putc(ch);

Dept of Computer Science & Engineering


Computer Programming 66

gets() : the gets() function is used to read the string from the standard input device(keyboard).

Syntax : gets(character type of array variable name);

puts() : the puts() function is used to display the string to the standard output devive(monitor).

puts(character type of array variable name);

getch() and getche() functions :

The getch() read a single character directly from the keyboard , without echoing to the screen.

The getche() reads a single character form the keyboard and echoes it to the screen.

/* program to demonstrate the getch() and getche() functions */

#include<stdio.h>

#include<conio.h>

main()

char c,ch;

clrscr();

printf("\n Enter any character ");

c=getch();

printf("\n Enter another character ");

ch=getche();

printf("\n first entered character : %c ",c);

printf("\n second entered character : %c",ch);

getch();

Output :

Dept of Computer Science & Engineering


Computer Programming 67

Formatted Input/Output Statements :

Formatted input/output refers to input and output, that has been arranged in a particular
format. The following are the input and output functions

scanf() and printf()

we have already used this input function in number of examples. the scanf() functions is used to read
data from the standard input device i.e, keyboard.

Scanf() : The scanf() statement or function reads all types of data values. It is used for runtime
assignment of variables. The scanf() statement also requires conversion symbol to identify the data to
be read during the execution of a program.

Syntax : scanf(“control string”,&var1,&var2,………&varn);

The scanf() function requires ‘&’ operator called address operator. The role of address
operator in scanf() function is to indicate the memory location of the variable , so that the value read
would be placed at that location. The scanf() function also returns values. The return value is exactly
equal to the number of values correctly read.

The below table illustrates control string in Input / output statements :

Format specifier Meaning

%c Single character

%d Decimal integer upto -


32,768 ti 32,767

%s String

%f Float values

%ld Long integer upto -65,536


to 65,535

%u Unsigned decimal

%o Octal number

%x Hexa decimal number

Dept of Computer Science & Engineering


Computer Programming 68

%e Floating point value

/* program to find the average of three numbers */

#include<stdio.h>

#include<conio.h>

main()

int n1,n2,n3,sum;

float avg;

clrscr();

printf("\n Enter any Three integers : ");

scanf("%d%d%d",&n1,&n2,&n3);

sum=(n1+n2+n3);

avg=(float)sum/(float)3;

printf("\n sum of three numbers : %d ",sum);

printf("\n average of three numbers : %.3f ", avg);

getch();

Output :

printf() : The printf() function prints all types of data values to the console. It requires conversion
symbol and variable names to print the data. The conversion symbol or control string and variable
names should be same in number.

Syntax : printf(“control strings”,var1, var2,…..varn);

Dept of Computer Science & Engineering


Computer Programming 69

Let us consider the following program

main()

int x=2;

float y=2.2;

char z=’c’;

printf(“\n %d %f %c”,x,y,z);

In the above program %d corresponds to ‘x’ variable , %f to y and %c to ‘z’.

main()

int y=65;

clrscr();

printf(“ %c %d “,y,y);

Output :

A 65

In the above example the integer variable ‘y’ contains value 65 , the variable ‘y’ is printed using
conversion symbols integer and character. As shown in the output , the %c converts numberic 65
value to its corresponding character A. The %d prints the value of 65, as it is , because the variable is
of an integer type. Some times if no conversion is possible between two data types ; some garbage
value is printed.

1. Write a program to find the average of three real numbers.


2. Write a program to swap the values of two variables using temporary variable or third variable
3. Write a program to swap the values of two variables without using third variable or temporary
variable.
4. Write a program to accept the alphabet in lower case and display it in upper case.
5. Write a program to accept a number and calculate square of it.
6. Write a program to accept the radius of circle and calculates its area.( area of circle is PI*R*R,
PI=3.14159).

Dept of Computer Science & Engineering


Computer Programming 70

7. Write a program to find the size of integer variable , character variable , float variable.
8. Write a program to accept the length and breadth of a rectangle and calculate the area of
rectangle.
9. The total distance travelled by vehicle in ‘t’ seconds is given by distance = ut+1/2at*t where
‘u’ is the initial velocity(m/sec).
‘a’ is the accerleration(m/sec*sec).
Write a C program to find the distance travelled at regular intervals of time given the values of
‘u’ and ‘a’.
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
double a,u,t,d;
clrscr();
printf("\n Enter the values of initial velocity(u), acceleration(a) and time(t) :");
scanf("%lf%lf%lf",&u,&a,&t);
d=u*t+0.5*a*t*t;
printf("\n Distance travelled by vehicle = %lf meters",d);
getch();
}
10. Write a program to calculate slope and midpoint of a line (by giving input as two points).

Program : /* program to find the slope and midpoint */

#include<stdio.h>

#include<conio.h>

main()

float x,y,x1,x2,y1,y2,slope;

clrscr();

printf("\n Enter first point x1,y1 : ");

scanf("%f%f",&x1,&y1);

printf("\n Enter second point x2,y2 : ");

scanf("%f%f",&x2,&y2);

slope=(y2-y1)/(x2-x1);

Dept of Computer Science & Engineering


Computer Programming 71

x=(x1+x2)/2.0;

y=(y1+y2)/2.0;

printf("\n slope : %f" , slope);

printf("\n mid point(x,y) :(%f , %f )",x,y);

getch();

11. Write a program to read the values of x,y and z and print the results of the following
expressions
a=(x+y+z)/(x-y-z) , b = (x+y+z)/3 , c=(x+y)(x-y)(y-z)
12. Write a program to display the system current date and time.
13. Write a program to accept the values of a,b,c and calculate b*b-4*a*c
14. Write a program to print the numbers from 1 to 10.

*********************************************************************************
***************************************************************************

Dept of Computer Science & Engineering


Computer Programming 72

Statements :
A statement causes an action to be performed by the program. It translates directly in to one or more
executable computer instructions.

C defines eleven types of statements. They are :

1. Null Statements
2. Expression Statements
3. Return Statements
4. Compound Statements
5. Conditional Statements
6. Labeled Statements
7. Switch Statements
8. Iterative Statements
9. Break Statements
10. Continue Statements
11. Goto Statements

Null Statements

The null statement is just a semicolon (the terminator).

Eg //null statement

Although they do not arise often, there are syntactical situations where we must have a statement but
no action is required .In these situations we use the null statement.

Expression Statements

An Expression is turned in to a statement by placing a semicolon(;)after it.

expression; //expression statement

Eg : a=2;

Return Statement

A Return Statement terminates a function. All functions ,including main, must have a return
statement. Where there is no return statement at the end of the function ,the system inserts one with a
void return value.

return expression; //return statement

Dept of Computer Science & Engineering


Computer Programming 73

The return statement can return a value to the calling function. In case of main ,it returns a value to
the operating system rather than to another function. A return value of zero tells the operating system
that the program executed successfully.

Compound Statement

A Compound Statement is a unit of code consisting of zero or more statements .It is also known as a
block. The compound statement allows a group of statements to become one single entity.

A Compound Statement consists of an opening brace ,an optional declaration and definition
section ,and an optional statement section ,followed by a closing brace.

Eg: {

int x; //Local Declarations

int y;

int z;

x=1; //Statements

y=2;

} //End Block

The compound statement does not need a semicolon.

Selection Statements :

A Program is nothing but the execution of sequence of one or more statements. This is known as
sequential flow of control. In practical applications there are a number of situations where one has to
change the order of the execution of statements based on the conditions. This involves a decision
making condition to see whether a particular condition is satisfied or not. If the condition is true then
a set of statements are executed otherwise another set of statements are executed.

The C language provides a numbers of program control statements or selection statements that can
be used to control the way of execution of the program. These include

The decision statements :

If and switch statements

The looping constructs :

For , while ,do..while

Dept of Computer Science & Engineering


Computer Programming 74

Decision Making Statements or Conditional Statements


C Language possesses Decision Making capabilities by supporting the following statements

1. IF statements
2. Switch
3. Goto

The if statements is a powerful decision making statement and is used to control the flow of execution
of statements. It is basically a two-way selection or decision statement. It takes the following form :

Different forms of If Statements

1. Simple if
2. if…..else statement
3. Nested if….else statement
4. else if ladder

Simple if :

The general form of simple if statement is

Syntax :

if ( Test Expression )

Statement-block;

Statement-x;

Dept of Computer Science & Engineering


Computer Programming 75

The statement block may be a single or group of statements. if the test expression or condition is true
then the statement block will be executed otherwise the statement block will be skipped and the
execution will jump to the statement-x.

Remember , when the condition is true both the statement-block and the statement-x are executed in
sequence.

/* program to check wether the given number is less than 10 */


#include<stdio.h>
#include<conio.h>
main()
{
int num;
clrscr();
printf("\n Enter any number < 10 ");
scanf("%d",&num);
if(num<10)
printf("\n Entered number %d < 10",num);
getch();
}
Output :

In the above program the values of the variable num is entered through the keybord. The value
of num is checked with if statement num<10. If the num value is less than 10 then print the message
“Entered number 8 < 10”.
Note: If we want to execute multiple statements in the if statement, that statements must be blocked
with in braces.

Dept of Computer Science & Engineering


Computer Programming 76

/*program to calculate the sum and multiplication using if statement. */


#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2,i;
clrscr();
printf("\n Enter any two number ");
i=scanf("%d%d",&n1,&n2);
if(i==2)
{
printf("\n Adddition of two numbers : %d ",(n1+n2));
printf("\n Multiplication of two numbers : %d ",(n1*n2));
}
getch();
}
Output :

The program reads the value of n1,n2 through scanf() function and assigned to variable m. if
statement checks the condition and executes the block of statements.

if…..else statement

It is observed that if statement in the previous programs executes only when the condition is true. It
does nothing when the condition is false.

The if….else statement takes care of true as well as false conditions. it has two blocks. One
block is for if and it is executed when the condition is true. The other block is of else and it is
executed when the condition is false.

Dept of Computer Science & Engineering


Computer Programming 77

 The else statement cannot be used without if.


 No multiple else statements are allowed with one if.
 No semicolon (;) is needed for an if…else statement .

/* program to find the greatest of two numbers */


#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2;
clrscr();
printf("\n Enter any two numbers ");
scanf("%d%d",&n1,&n2);
if(n1>n2)
printf("\n %d is greater ",n1);
else
printf("\n %d is greater ",n2);
getch();
}

Dept of Computer Science & Engineering


Computer Programming 78

/* program to convert a character from lower case to upper case by using predefined functions */
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch;
clrscr();
printf("\n Enter any alphebet in lower case or upper case ");
ch=getchar();
if(islower(ch))
putchar(toupper(ch));
else
putchar(tolower(ch));
getch();
}
/* toupper and tolower are predefined functions from ctype.h file.
islower is used to check whether the character is in lowercase or not
if it is lower case character then it returns 1 otherwise 0.
toupper is used to convert the given character into uppercase.
tolower is used to convert the given character into lowercase.*/
output :

/* write a program to read the values of a,b,c through the keyboard. add them
and after addition check if it is in the range of 100 & 200 or not.*/
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,d;
clrscr();
printf("\n Enter three numbers :");
scanf("%d%d%d",&a,&b,&c);
d=a+b+c;
if(d<=200 && d>=100)
printf("\n sum is %d which is in between 100 & 200 " ,d);
else
printf("\n sum is %d which is out of range ",d);
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 79

Nested If :

When a series of if..else statements are occurred in a program. We can write one if..else statement in
another if…else statement called nested if. (simple if…else within another if…else is referred as
nested if.

/* program to illustrate Nested If*/


#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
clrscr();
printf("\n Please Enter two integers : ");
scanf("%d%d",&a,&b);
if(a<=b)
{
if(a<b)
printf(" \n %d < %d ",a,b);
else
printf("\n %d == %d ",a,b);
}
else
printf("\n %d > %d ",a,b);
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 80

/* program to find greatest of three numbers */


#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
clrscr();
printf("\n Enter any three numbers ");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("\n %d is greater ",a);
else
printf("\n %d is greater ",c);
}
else if(b>c)
printf("\n %d is greater ",b);
getch();
}
Output :

--------------------------------------------------------------------------------------------------------------------

Write a program to find whether the given number is even or odd.

Write a program to find the roots of an quadratic equation.

If…else ladder

There is another way of putting ifs together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if.

Dept of Computer Science & Engineering


Computer Programming 81

The conditions are evaluated from the top, downwards. As soon as condition is found to be true,
statement associated with it is executed. When all the n conditions become false, then the final else
containing the default statement will be executed.
/* write a program to accept a character and check whether it is vowel or consonant or digit or
special symbol*/
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf("\n Enter any character ");
scanf("%c",&ch);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
printf("\n ***********v o w E L **************");
else if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
printf("\n***********v o w E L ************** ");
else
printf("\n ***********C O N S O N A N T**************");
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 82

Switch Statement :

Switch is a multi-way decision statement in C. In general switch statement can be used as an


alternative to if – else statement. Switch can be used when we know the exact value of a variable.
Whereas if – else can be used when we know either exact value or range of values for a variable.

 Switch statement tests the value of a given variable or result of the expression against a list of
case values and when a match is found a block of statements associated with that case is
executed.
 The expression or variable must be an integer or character type.

 Value1, Value2 …. are constants or expressions are known as case labels.


 case labels must end with a colon.
 block – I block – II are the statement blocks and may contain zero or more statements.
 When the switch is executed the value of expression is successively compared against the
values. 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 signals the end of a particular case.
 When the break statement is executed program control immediately exits from the switch
statement.
 The default is an optional case.
 If no match is found in that case default block will be executed if it present, if doesn’t present
no action takes place.

/* write a program to check whether the entered character is consonant or vowel */

Dept of Computer Science & Engineering


Computer Programming 83

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("\n Enter any character ");
scanf("%c",&ch);
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : printf("\n Vowel ");
break;
default : printf("\n Consonant ");
break;
}
getch();
}
Output :

/*write a program to perform arithmetic operation using switch statement*/


#include<stdio.h>
#include<conio.h>
main()
{
int a,b,res,choice;
clrscr();
printf("\n O P E R A T I O N S ");
printf("\n 1.Addition(+) : ");
printf("\n 2.Subtraction(-) : ");
printf("\n 3.Multiplication(*) : ");
printf("\n 4.Division(/) : ");
printf("\n Enter U R Choice ");
scanf("%d",&choice);

Dept of Computer Science & Engineering


Computer Programming 84

switch(choice)
{
case 1 : printf("\n Enter any two numbers ");
scanf("%d%d",&a,&b);
res=a+b;
printf("\n Sum of two numbers : %d ",res);
break;

case 2 : printf("\n Enter any two numbers ");


scanf("%d%d",&a,&b);
res=a-b;
printf("\n Difference of two numbers : %d ",res);
break;

case 3 : printf("\n Enter any two numbers ");


scanf("%d%d",&a,&b);
res=a*b;
printf("\n Product of two numbers : %d ",res);
break;
case 4 : printf("\n Enter any two numbers ");
scanf("%d%d",&a,&b);
res=a/b;
printf("\n Division of two numbers : %d ",res);
break;
default : printf("\n U Selected an invalid choice ");
}
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 85

Repetitive Statements or Looping Statements:


 Looping is a process of repeated execution of block of statements until the condition for its
termination is satisfied.
 A loop therefore consists of two segments, one is body of the loop and other one is condition
known as control statement.
 A looping generally contains the following 4 steps
o Setting and initialization of a counter variable
o Test for a specified a condition for execution of the loop
o Execution of the statements in the loop
o Incrementing the counter variable
 Depending the position of control statement (condition) in the loop a control structure may be
classified as either entry controlled loop or exit controlled loop.
 In the entry controlled loop condition is tested before body of loop get executed.
 In exit controlled loop condition is tested at the end of the body of the loop and therefore the body
is executed unconditionally for the first time.
The C language provides the following three loop constructs for performing loop operations
1. The while statement
2. The do statement
3. The for statement

While Loop :

while is an entry controlled loop. First condition is evaluated if it is true then body of the loop
is executed. After executing the body, condition is once again evaluated ,if it is true body is executed
once again. This process continues as long as condition is true. The body of the loop may have one or
more statements.
Note: The braces are not required if body contains only one statement.

Dept of Computer Science & Engineering


Computer Programming 86

Programs

1. write a program to print the numbers from 1 to 100


2. write a program to print first ten numbers and their squares.
3. write a program to find the sum of numbers from 1 to n( the value of n is accepted from the
keyboard)
4. write a program to find the factorial of a given number
5. write a program to find the sum of all digits in a given number
6. write a program to Reverse of a given number
7. write a program to check whether the given number is palindrome or not
8. write program to print Fibonacci series
9. Write a program to find GCD/HCD and LCM of two numbers

Dept of Computer Science & Engineering


Computer Programming 87

/* write a program to print the numbers from 1 to 100*/


Explanation : 1
2…..up to 100.
#include<stdio.h>
#include<conio.h> Output:
main()
{
int i=1;
clrscr();
printf("\n Numbers from 1 to 100 ");
while(i<=100)
{
printf("\n %d",i);
i++;
}
getch();
}

/* write a program to print first ten numbers and their squares*/


Explanation : 1 1
2 4
3 9…up to 10 100 .
#include<stdio.h> Output:
#include<conio.h>
main()
{
int i=1;
clrscr();
printf("\n Number \t Square");
while(i<=10)
{
printf("\n %d \t\t %d",i,(i*i));
i++;
}
getch();
}

/*write a program to find the sum of numbers from 1 to n( the value of n is accepted from the
keyboard)*/
Output : suppose the value of n is 10 then the output must be 1+2+3+4+5+6+7+8+9+10=55

#include<stdio.h>
#include<conio.h>
main()
{
int i=1,n,sum=0;
clrscr();

Dept of Computer Science & Engineering


Computer Programming 88

printf("\n Enter any number ");


scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("\n sum of all numbers from 1 to %d is : %d ",n,sum);
getch();
Output :
}

/*write a program to find the factorial of a given number*/


Explanation : 5! = 5*4*3*2*1 = 120
#include<stdio.h>
#include<conio.h>
main()
{
int i=1,n,sum=0;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf("\n sum of all numbers from 1 to %d is : %d ",n,sum);
getch();
}
Output :

/* write a program to display the multiplication table*/


#include<stdio.h>
Output :
#include<conio.h>
main()
{
int i=1,n,mul=1;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
printf("\n Multiplication Table for %d ",n);
while(i<=12)
{

Dept of Computer Science & Engineering


Computer Programming 89

printf("\n %d * %d = %d ",n,i,n*i);
i++;
}
getch();
}
/* write a program to find the sum of all digits in a given number*/
Explanation : let us consider n=123 then we need find sum of all digits in it i.e, 1+2+3=6
#include<stdio.h>
#include<conio.h>
main()
{
int n,sum=0,rem=0,n1;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
n1=n;
while(n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("\n Sum of digits in %d numbers is %i ",n1,sum);
getch();
}
Output :

/* write a program to Reverse of a given number */


Explanation : suppose the number is 256 then display it in reverse order 652
#include<stdio.h>
#include<conio.h>
main()
{
int n,rev=0,rem=0,n1;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
n1=n;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf("\n Reverse of %d is %d ",n1,rev);
getch();

Dept of Computer Science & Engineering


Computer Programming 90

}
Output :

/* write a program to check whether the given number is palindrome or not*/


Explanation : the number is said to be palindrome if and only if the reverse of that number must
equal to that number. Let us consider n=121 reverse of n is 121, Hence the reverse of n is same as
n then n is called palindrome number.
#include<stdio.h>
#include<conio.h>
main()
{
int n,rev=0,rem=0,n1;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
n1=n;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(rev==n1)
printf("\n %i is palindrome ",n1);
else
printf("\n %d is not a palindrome ",n1);
getch();
}
Output :

/* write program to print Fibonacci series*/


#include<stdio.h>
#include<conio.h>
main()
{
int n,f1=0,f2=1,f3,i=2;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
printf("\n Fibonacii Series :");
printf("\n %d\t%d",f1,f2);
while(i<n)

Dept of Computer Science & Engineering


Computer Programming 91

{
f3=f1+f2;
f1=f2;
f2=f3;
printf("\t%d",f3);
i++;
}
getch();
}
Output :

/*write a program to find GCD/HCF and LCM of given two numbers */


#include<stdio.h>
#include<conio.h>
main()
{
long int n1,n2,a,b;
clrscr();
printf("\n GCD/HCF & LCM OF TWO NUMBERS");
printf("\n\n\tENTER TWO NUMBERS: ");
scanf("%ld %ld",&n1,&n2);
a=n1;b=n2;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
printf("\n GCD/HCF Of Two Numbers is: %ld",n1);
printf("\n LCM Of Two Numbers is : %ld",(a*b)/n1);
getch();
}

Dept of Computer Science & Engineering


Computer Programming 92

do while:
 do-while is exit controlled loop. In some cases it might be compulsory to execute the body of
the loop before the test is performed. Such situations can be handled with the help of the do
statement.
 It is also repetitive statement and executes the body of the loop once irrespective of the
condition , then checks the condition and continues the execution until the condition becomes
false.

Write a program to find average of N numbers


Write a program to two numbers using do…while

For Statement :
For is an another entry controlled loop. The general form of the for loop is

Syntax :

for ( initialization ; testcondition ; incr/decr )


{

body of the loop

The execution of the for statement is as follows:


 Initialization of control variables is done first.
 Now the value of the variable is tested using test condition. If the test condition is true body of
the loop is executed otherwise loop is terminated.
 After executing the body of the loop, control is transferred to increment/decrement block.
 Test condition is once again evaluated, and if it is true body is executed once again.

Dept of Computer Science & Engineering


Computer Programming 93

 This process continues till value of the control variable fails to satisfy the condition.

Program based on For Loops :


1. Write a program to check whether the given numbers is prime or not.
2. Write a program to find sum of even numbers , count of even numbers ,sum of odd numbers,
count of odd numbers from 1 to 100.
3. Write a program to check whether the given number is Armstrong or not.
4. Write a program to check whether a number is perfect square or not
5. Write a program to find X to power of N
6. Write a program to display numbers from 9 to1 and their square roots
7. Write a program to find sum of the following series
1^2+2^2+3^2+4^2+……n^2
8. Write a C program to read in two numbers, x and n, and then compute the sum of this
geometric progression:
1+x+x2+x3+………….+xn
For example: if n is 3 and x is 5, then the program computes 1+5+25+125.
9. write a c program to calculate the following sum:
Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!*/

/*write a program to check whether the given number is prime or not*/


#include<stdio.h>
#include<conio.h>
main()
{
int count=0,i=1,n;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
printf("\n %d is prime number ",n);
else
printf("\n %d is not prime number ",n);
getch();
}
Output :

/*write a program to print all even numbers from 1 to 100 and also print sum and count of all even
number */
#include<stdio.h>
#include<conio.h>

Dept of Computer Science & Engineering


Computer Programming 94

main()
{
int i,count=0,sum=0;
clrscr();
printf("\n All Even Numbers from 1 to 100 ");
for(i=1;i<=100;i++)
{
if(i%2==0)
{
printf("\t %d" ,i);
sum=sum+i;
count++;
}

}
printf("\n Sum of all Even Numbers from 1 to 100 is %d ",sum);
printf("\n Count of all Even Numbers from 1 to 100 is %d ",count);
getch();
}
Output:

/* write a program to check whether the given number is Armstrong or not*/


#include<stdio.h>
#include<conio.h>
main()
{
int rem=0,sum=0,n,n1;
clrscr();
printf("\n Enter any number ");
scanf("%d",&n);
n1=n;
for(;n>0;n=n/10)
{
rem=n%10;
sum=sum+rem*rem*rem;
}

Dept of Computer Science & Engineering


Computer Programming 95

if(sum==n1)
printf("\n %d is Armstrong ",n1);
else
printf("\n %d is not Armstrong ",n1);
getch();
}
Output :

/* write a program to check whether the number is perfect or not */


#include<stdio.h>
#include<conio.h>
void main()
{
long int n,i=1,perfect=0;
clrscr();
printf("\nEnter a number: ");
scanf("%ld",&n);
while(i<n)
{
if(n%i==0)
{
perfect+=i;
}
i++;
}
if(perfect==n)
printf("\n%ld is perfect",n);
else
printf("\n%ld is not perfect",n);
getch();
}
Output :

/* write a program to find x to the power of N*/


#include<stdio.h>
#include<conio.h>
main()
{
long int x,n,i,res=1;
clrscr();
printf("\n Enter X & N ");
scanf("%ld%ld",&x,&n);

Dept of Computer Science & Engineering


Computer Programming 96

for(i=0;i<n;i++)
res=res*x;
printf("\n %ld^%ld is %ld ",x,n,res);
getch();
}
Output :

/* write a program to print numbers from 9 to 1 and display their square root*/
#include<stdio.h> Output :
#include<conio.h>
#include<math.h>
main()
{
int i;
clrscr();
printf("\n=====================================");
printf("\n\tNumber\tSquare Root");
printf("\n=====================================");
for(i=9;i>0;i--)
printf("\n\t%d\t%.2f",i,sqrt(i));
getch();
}

Unconditional Statements :

Break and continue Statements :

There are two statement built in C, break; and continue; to interrupt the normal flow of control of a program.

Loops performs a set of operation repeately until certain condition becomes false but, it is sometimes desirable
to skip some statements inside loop and terminate the loop immediately without checking the test expression.

In such cases, break and continue statements are used.

In C programming, break is used in terminating the loop immediately after it is encountered. The break
statement is used with conditional if statement.

Synatx of Break statement :

break;

The break statement can be used in terminating all three loops for, while and do...while loops.

Dept of Computer Science & Engineering


Computer Programming 97

The figure below explains the working of break statement in all three type of loops.

Example of Break Statement :

Write a C program to find average of maximum of n positive numbers entered by user. But, if the input
is negative, display the average(excluding the average of negative input) and end the program.

/* C program to demonstrate the working of break statement by terminating a loop, if user inputs negative
number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}

Dept of Computer Science & Engineering


Computer Programming 98

Output :

Maximum no. of inputs


4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using break statement with
executing the statement below it i.e., without executing sum=sum+num.

In C, break statements are also used in switch...case statement.

It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are used.

Continue Statement :

Syntax of continue statement :

Continue;

Just like break, continue is also used with conditional if statement.

For better understanding of how continue statements works in C programming. Analyze the figure below
which bypasses some code/s inside loops using continue statement.

Dept of Computer Science & Engineering


Computer Programming 99

Example of continue statement :

Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it.

//program to demonstrate the working of continue statement in C programming


# include <stdio.h>
int main(){
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement product*=num and
continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}

Output :

Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30

goto statement :

C supports the go to statement to branch unconditionally from one point to another in the
program. Although it may not be essential to use the go to statement in a highly structured language
like C, there may be occasions when the use of go to might be desirable.

 The goto requires a label in order to identify the place where the branch is to be made.
 A label is any valid variable name, and must be followed by a colon.
 The label is placed immediately before the statement where the control is to be transferred.
 The general forms of goto and label statements are shown below :

goto label; label : statements;

----------- statements;

----------- -------------;

lable : statements; goto label;

Dept of Computer Science & Engineering


Computer Programming 100

Example of goto statement :


/* write a program to check whether the given number is even or odd */
#include<stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()
{
int x;
clrscr();
printf("\n Enter any Number ");
scanf("%d",&x);
if(x%2==0)
goto even;
else
{
printf("\n %d is Odd Number ");
exit(0);
}
even : printf("\n %d is Even Number ",x);
return;
}
Output :

/* write a program to check whether entered year is a leap year or not */


#include<stdio.h>
#include<conio.h>
void main()
{
int year;
clrscr();
printf("\n Enter any year : ");
scanf("%d",&year);
if(year%4==0)
goto leap;
else
goto nonleap;
leap : printf("\n %d is a leap year ",year);
return;
nonleap : printf("\n %d is not a leap year ",year);
return;
getch();
}
Output :

Dept of Computer Science & Engineering


Computer Programming 101

Previous Year Question Papers


1. (a) Explain in detail about different data types available in C.
(b) Write the structure of a `C' program and explain. {R07 Supply December 2011}
2. (a) Discuss the History of `C' language.
(b) Write the structure of `C' program and explain. {R07 Supply December 2011}
3. (a) Explain the types of operators available in C?
(b) Write a C program with Exclusive OR operation between the two integers and display the
result? {R09 Supply December 2011}
4. (a) Explain different categories of an algorithm with an example?
(b) What are the differences between signed and unsigned data types, list out them? {R09 JAN
2012}
5. (a)What is meant by compilation ? Explain in detail?
(b) What are the C keywords? Elaborate them? {R09 JAN 2012}
6. (a) What are unary operators and their uses? Describe logical operators with their return values?
(b) Write a C program to shift inputted data by 2 bits left? {R09 JAN 2012}

7.(a) Define Algorithm and Flow Chart?


(b) A utility company charges its customers based on their monthly utilization in terms of units as
follows:
Description charge:
First 100 units Rs.10 per unit
Next 200 units Rs. 9 per unit
Next 200 units Rs.8 per unit
Next units Rs.7 per unit
Write an Algorithm and flowchart that reads monthly units of a customer and output the charge
amount. {R09 JAN 2012}
8.(a) What are various conditional and bitwise operations in ‘C’, explain them with an example?
(b) Explain various looping statements in ‘C’ language with example? {R09 JAN 2012}
9. What are various arithmetic and assignment operators in ‘C’, explain them with an example. {R09
JAN 2012}
10.( a) Define the flow chart? Draw a flow chart for finding roots of a quadratic equation with all
cases?
(b) What are various conditional and relational operators in ‘C’, explain them with an example.
{R09 JAN 2012}
11.( a) Explain the control statements in ‘C’ language with an example?
(b) Explain various looping statements in ‘C’ language with example {R09 JAN 2012}
12.(a) Explain and specify the interactions between various components that support the basic
functionality of a computer?
(b) Discuss in detail the program execution steps? [7+8] {R09 DEC 2010}
13.(a) List the basic data types, their sizes and range of values supported by ‘C’ language?
(b) Describe the purpose of commonly used conversion characters in scanf() function?
(c) Explain the only ternary operator available in ‘C’ with illustrative example? {R09 DEC 2010}
14.(a)Define Algorithm? What are the characteristics that any algorithm should satisfy?
(b) Draw a flowchart for finding maximum of given three integers?
(c) Differentiate between compiler and interpreter? [7+4+4]
15.( a) Differentiate between if-else-if ladder and switch statement?

Dept of Computer Science & Engineering


Computer Programming 102

(b) What is the implicit type conversion hierarchy that is applied while evaluating expressions?
(c) List and give examples for different bitwise operators available in ‘C’?{R09 DEC 2010 set 2}
16. (a) Differentiate between application software and system software?
(b) Draw a flowchart for finding the sum of ‘n’ numbers starting from 1?
(c) Briefly discuss various computing environments with neat diagrams? {R09 DEC 2010 set 3}
17.(a) What do you mean by operator precedence and associativity? How one can
override the precedence defined by C language? Give illustrative examples?
(b) Explain the structure of a C program? {R09 DEC 2010 set 3}
18.(a) List the activities involved in each phase of waterfall system development life cycle model?
(b) What are the different types of errors one can encounter during the program execution? [10+5]
{R09 DEC 2010 set 4}
19.( a) What is an identifier? What are the naming rules for identifiers in C?
(b) List different categories of C operators based on their functionality? Give examples?
(c) Explain different types of coding constants in a C? {R09 DEC 2010 set 4}
20. (a) Explain the functions of the following:
(i) Preprocessor
(ii) Compiler
(iii) Linker.
b) Draw a flowchart to find maximum and minimum of the given three input numbers.{R09 June
2010 set-1}
21.(a) Write minimal C-expressions for the following:
i)3x4+5x3-4x2+7x+20
ii) abcbccaab−−
iii) Digit at 100’s place of the given integer x. (Ex. Digit at 100’s place in 2578 is 5).
iv) If a > b then the value of expression is a-b, otherwise b-a
v) True if 5 <, otherwise false x < 10
vi) Divide the integer variable x by 16 using bit-wise operators
(b) What is the difference between the following c-words?
(i) amount and “amount”
(ii) 200 and 200.0
(c) A number is said to be prime, if it is not exactly divisible by any other numbers other than 1 and
the number it self. For example 7 and 11 are primes. Write C- language program that reads a number
from input and determine whether it is a prime or not. [6+2+7] {R09 June 2010, set-1}
22.(a)List out the various steps in software development.
(b) Given the 3 sides of triangle a, b and c as input, Draw a flowchart to test whether it is
isosceles, equilateral or not. It should also validate whether the input forms a triangle or not. (Ex. 10,
3, 3 is not a triangle) [6+9] {R09 June 2010, set-2}
23.(a) Write minimal C-expressions for the following:
4 3 2
i) 5a +3a -4a +6a+12
ii) abcbccaab−−
iii) If the given integer value of x is treated as binary, the fifth bit from the right.
iv) Absolute value of variable x.
v) True if x is exactly divisible by 5 but not divisible by 3, otherwise false.
vi) Subtract x from y and then increment x.
(b) What is the difference between the following C-words?
i) 253 and 0253

Dept of Computer Science & Engineering


Computer Programming 103

ii) ‘r’ and ‘\r’


(c) Write C-program for determining whether the given integer at input is perfect number or not.
A number is said to be perfect number if the sum of factors is equal to number itself. For example, the
factors of 6 are 1, 2, 3 whose sum 1+2+3=6. {R09 June 2010, set-2}

24(a) What is an algorithm? List and explain the properties of algorithm.


(b) A utility company charges its customers based on their monthly utilization in terms of units as
follows:
Description charge
First 100 units Rs.10 per unit
Next 200 units Rs. 9 per unit
Next 200 units Rs.8 per unit
Next units Rs.7 per unit
Write flowchart that reads monthly units of a customer and output the charge amount. [7+8] {R09
June 2010, set-3}
25.(a) Write minimal C- expressions for the following:
4 3 2
i) 6b +3b -5b +6b+15
ii) 2234abccab−−
iii) Increment x and then add to z
iv) Maximum of the values of 3 variables a, b and c
v) True if the value of character variable c is in uppercase, otherwise false
vi) Rightmost octal digit in the value of integer variable x
(b) What is the difference between the following C-words?
(i) 5 and ‘5’ (ii) if and ++
(c) Write C-program for generation of multiplication table for the given integer input x. For
example, if
input is 5, the program need to output
5X1=5
5 X 2 =10
…..
5 X10 =50 {R09 June 2010, set-3}
26. (a) List and explain the functions of various parts of computer hardware.

(b) A university gives grades based on the percentage of marks obtained in the examinations as
follows:
Percentage of marks Grade
70 and above Distinction
60 and above but below 70 First
50 and above but below 60 Second
40 and above but below 50 Third
below 40 Fail
Write a flowchart that inputs the percentage marks and output the division. [6+9]{ R09 june2010 set-
4}
27.a) Write minimal C- expressions for the following:
4 3 2
i) 6a +3a -5a -6a+22
ii) 1235abbc+

Dept of Computer Science & Engineering


Computer Programming 104

iii) Equivalent to C-statement while (a > = b)a = a-b where a and b are unsigned integers.
iv) True if x/y >3 without zero divide, false otherwise
v) If x<y then -1 else if x = = y then 0 else 1(use ternary operator)
vi) Fourth bit from the right if the number x is treated in binary representation.
(b) What is the difference between the following C-words?
i) count and int ii) 526 and “526”
(c) Write C-program that reverses the decimal digits of integer value at input. For example, for input
5379, the program need to output 9735. { R09 june2010 set-4}
28.(a) What is an algorithm? Write an algorithm to read five integers and find out if the values are in
ascending order.b) Draw a flow chart to read ten integer values and print the sum of squares of the
values.{R09 June-11 s1}
29.(a) Write minimal C expressions for the following:
4 3 2
(i) 2x + 3x - 4x + 7x -10
(ii) Digit at the 10's place of the given positive integer x (for example, digit at the 10's place in
3458 is 5)
(iii) True if the given positive integer x is odd, false otherwise
(iv) Add x to y, and then decrement x
(v) True if 5 <= a <= 10, false otherwise
(vi) Fourth bit from the right if the number x is treated in binary representation.
(b) Write a complete C Program to print all the prime numbers between 1 and n. Where ‘n’ is the
value supplied by the user. {R09 June-11 s1}

30.(a) What is an algorithm? Write an algorithm to find out if a given number is a prime.
(b) Draw a flow chart to read ten positive integers and print how many are multiples of 7. {R09
June-11 s2}
31(.a) Write minimal C expressions for the following:
4 3 2
(i) 3x + x - 4x + 7x
(ii) Maximum of the values of three variables a, b and c
(iii) Digit at the 100's place of the given positive integer x (for example, digit at the 100's
place in 3458 is 4)
(iv) True if the given positive integer x is even, false otherwise
(v) Increment x, and then add to z
(vi) True if the given positive integer x is a multiple of 3 and 7, false otherwise.
(b) What are the bitwise operators in C? Explain the same with examples. {R09 June-11 s2}

32.(a) Write an algorithm to find out all the factors of a given positive integer.
(b) What is a flow chart? Draw a flow chart to read ten integers and print the sum of squares of all
ten values. [8+7] {R09 June-11 s3}
33.(a) Write minimal C expressions for the following:
3 2
(i) x - 4x + 7x -12
(ii) Absolute value of (a-b)
(iii) Remainder when unsigned integer variable x is divided by 8, using bitwise operators.
(iv) True if the given positive integer x is even and is also a multiple of 7, false otherwise.
(v) Minimum of the values of three variables a, b and c.
(vi) True if the given character variable c represents a numeral (that is '0'...'9'), false otherwise.
{R09 June-11 s3}

Dept of Computer Science & Engineering


Computer Programming 105

34.(a) Write an algorithm to read ten positive integers and find out how many are perfect squares
(such as
49, 81). You may assume that the input values read are in the range 1 to 10000.
(b) List the various steps in software development. [8+7] {R09 June-11 s4}
2.(a) Write minimal C expressions for the following:
3 2
(i) x -3x + 3x -1
(ii) Digit at the 10's place of the given positive integer x (for example, digit at the 10’s place in
3458 is 5)
(iii) True if the given positive integer x is a multiple of both 17 and 11, false otherwise.
(iv) Remainder when unsigned integer variable x is divided by 8, using bitwise operators.
(v) True if 25 > a ≥ 10, false otherwise
(vi) Second bit from the right if the number x is treated in binary representation.
b) Write a complete C Program to read ten integers and find:
(i) The number of even integers and their sum, and
(ii) The number of odd integers and their sum. {R09 June-11 s4}

(R09 DEC 2012)

(R09 JUNE 2012)

OBJECTIVE QUESTIONS:

Dept of Computer Science & Engineering


Computer Programming 106

Choose the correct alternative:


1. Which of the following is a component of a computer system?
a) Hardware b) Software
c) Bothe hardware and software d) Pseudo code
2. Which of the following is an example of application software?
a) Database management system b) Security monitor
c) Operating system d) Sort
3. The _________is a program design tool that is a visual representation of the logic in a
function within a program.
a) Flowchart b) Program map c) Structure chart d) Waterfall model
4. Which of the following is used to perform computations on the entered data?
a) Memory b) Processor c) Input device d) Output device
5. Which of the following is not an input device?
a) Plotter b) Scanner c) Keyboard d) Mouse
6. Which of the following is used as a primary memory of the compter?
a) Magnetic storage device b) RAM
c) Optical storage device d) Magneto-optical storage device
7. Which of the following is used as a secondary memory of the computer?
a) Magnetic storage device b) RAM
c) Cache memory d) ROM
8. In which of the following languages, the instructions are written in the form of 0s and 1s.
a) Assembly languages b) Programming languages
c) High level languages d) Machine languages
9. Which of the following is not a translator
a) Linker b) Assembler c) Compiler d) Interpreter
10. Which of the following is not a loop
a) for b) if c) while d) none
11. BIOS is stored in _____________
a) RAM b) ROM c) Hard Disk d) Magnetic tape
12. ______________is a program that copies programs from a storage device to main memory
a) Compiler b) interpreter c) loader d) linker
13. Which of the following is not a feature of C language?
a) Portability b) extensibility c) structured d) case insensitive
14. Which of the following is not a translator program
a) Linker b) Assembler c) Compiler d) Interpreter
15. Which of the following is the correct order of operators for the evaluation of the expression
z=x+y*z/4%2-1
a) */%+-= b) -%?*+= c) /*%-+= d) */%-+=
16. Which of the following is not a data type in C?
a) int b) float c) char d) string
17. The statement violates the rules of structured programming.
a) goto b) break c) continue d) switch

Dept of Computer Science & Engineering


Computer Programming 107

18. The ______ statement is used to terminate the execution of the nearest enclosing loop in
which it appears.
a) break b) goto c) loop d) continue
19. The series of interrelated phases that is used to develop computer software is known as
a) Program development b) Software engineering
c) System design d) Software Development Life Cycle
20. Which of the following statements about the do-while loop is false?
a) a do-while loop executed one or more iterations
b) any statement may be used as the action in a do-while
c) The do-while is best suited for use as an event-controlled loop
d) the do-while is the only loop that requires a semicolon
21. The ___________ function reads data from the standard input file keyboard.
a) write b) printf c) read d) scanf
22. What will be sum of the binary numbers 1111 and 11001
a) 111100 b) 100010 c) 11110 d) 101000
23. Which one of the following is known as the language of the computer
a) Programming language b) Machine language
c) High level language d) Assembly level language
24. Find the output
Void main()
{char a[]=”12345\0”;
int i=strlen(a);
printf(“here in 3 %d\n”,++i);}
a) here in 3 b) here in 3 6 c) 6 d) 3
25. Which of the following is syntactically correct
a) for(;); b) for(); c) for(,); d) for(;;);
26. Find out the output for the following
#include<stdio.h>
main() {
int c=--2;
printf(“c=%d”,c);}
a) -2 b) 0 c) 2 d) None
27. Identify the result
Void main()
{ int i=5;
Printf(“%d”,i+++++i);}
a) 5 b) 6 c) 10 d) compiler error
28. What will be the ASCII Octal value of A
a) 100 b) 101 c) 110 d) 111
29. a<<1 is equal to
a) multiplying by 2 b) dividing by 2 c) added 2 d) None
30. Consider the following and find the output

Dept of Computer Science & Engineering


Computer Programming 108

Main()
{ int a=0;int b=30;char x=1;
If (a,b,x)
Printf(“Hello”);
}
a) compiler error b) abxHello c) Hello d) None
31. What type of errors are checked during compilation
a) logical errors b) divide by zero error
c) run - time errors d) syntax errors
32. Which one of the following numeric value is used to represent base of the binary number
a) 8 b) 10 c) 2 d) 16
33. What will be the binary value of B
a) 1001 b) 1011 c) 1100 d) 1101
34. The program fragment
int a=5, b=2;
printf(“%d”,a+++++b);
a) prints 7 b) prints 8 c) prints 9 d) none of the above
35. Consider the following program segment. i=6720; j=4;
while((i%j)==0)
{ i=i/j; j=j+1;
}
On termination j will have the value
a) 4 b) 8 c) 9 d) 6720
36. #include<stdio.h>
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
a) GOOD b) BAD c) GOOD BAD d) Compiler Error
37. How many times the body of the following loop executed? x=5; y=50; while(y! = 0) {y/=x;}
a) 4 b) 1 c) 4 d) 2

Fill in the blanks:


1. The ___________ contains programmer’s original program code
2. C language was developed by _____________.

Dept of Computer Science & Engineering


Computer Programming 109

3. Ternary operators symbols are______________


4. In #include<conio.h>, conio stands for___________
5. Multi way selector statement is________________
6. In C language_________________ is input function.
7. In binary expression _______ numbers of operands are existed.
8. _______________ converts assembly language into machine language.
9. 10101 binary number is equal to ____________ decimal number.
10. 32 decimal number is equal to ________________ binary number
11. ________________is a system software program that helps in coordinating system resources
and allows other programs to execute. (ans: Operating System)
12. English like statements that follow a loosely defined syntax and are used to convey the design
of an algorithm is called__________________(ans: Pseudo Code)
13. The file created from compiler is known as ______________file (object file)
14. ANSI stands for__________________ (ans: American National Standard Institute)
15. The # symbols is know _______________(ans: preprocessor commands)
16. __________ finds syntax error in the source program.
17. A variable can be made constant by declaring it with the qualifier _________ at the time of
initialization.
18. ______________ problem occurs when there is no matching else.
19. In a pre-test loop, if the body is executed n times, the limit test is executed _____ times.
20. The multi-way selection is coded using switch statement which is similar to _______
construct.
21. The _____________ operator is used to turn on mask bits in an operand.
22. The process of repeating a group of statements in an algorithm is known as___________
23. Extend the term CPU ________________________________
24. ALU stands for ____________
25. Monitor, keyboard, mouse and printers are _________devices
26. _________is used to compile your c program
27. Short Integer size is ____ bytes
28. The while loop repeats a statement until the test at the top proves _______
29. The __________statement transfers control to a statement within its body
30. The _______is a unconditional branching statement used to transfer control of the program
from one statement to another
31. ________ translates the high level language source code into low-level language
32. The size of long double variable is _________
33. The ___________of an operator gives the order in which expressions involving operators of
the same precedence are evaluated.
34. The output of the assembler in the form of sequence of 0’s and 1’s is called _________
35. The process of repeating a group of statements in an algorithm is known as _______
36. ______________ are identifiers reserved by the C language for special use
37. The _________of an operator gives the order in which operators are applied in expressions

Dept of Computer Science & Engineering


Computer Programming 110

38. _____________ is very similar to the while loop except that the test occurs at the end of the
loop body
39. _______ is the largest value that an unsigned short int type varible can store
40. The hardware along with the read-only software that resides on this hardware is combinely
called as _________
41. _______ logical operator is true only when both operands are true
42. The order of evaluation can be changed by using _____ in an expression
43. A for loop with no test condition is called as _______ loop
44. Execution of a C program begins at _______
45. ______ loop in C is both counter controlled and pretest loop
46. In menu driven programs _______ loop statement is used
47. In flowcharts, decisions are represented by using ______ symbol
48. ______ acts as an interface between the computer hardware and user of the computer

Dept of Computer Science & Engineering

Anda mungkin juga menyukai