Cpbook1 Updated 24.09.2018
Cpbook1 Updated 24.09.2018
1 R.SATHISH KUMAR/MVIT/CSE
SYLLABUS
OBJECTIVES
To introduce the basics of computers and information technology.
To educate problem solving techniques.
To impart programming skills in C language.
To practice structured programming to solve real life problems.
Unit – I
History of Computers – Block diagram of a Computer – Components of a Computer
system –Classification of computers - Hardware – Software – Categories of Software –
Operating System – Applications of Computers – Network structure – Internet and its
services – Intranet – Study of word processor – Preparation of worksheets.
Unit – II
Problem solving techniques – Program – Program development cycle – Algorithm
design – Flowchart - Pseudo code.
Introduction to C – History of C – Importance of C - C tokens – data types – Operators
and expressions – I/O functions.
Unit – III
Decision making statements – branching and looping – arrays – multidimensional arrays
– Functions – Recursion – Passing array to functions.
Storage classes – Strings – String library functions.
Unit – IV
Structures – Arrays and Structures – nested structures – passing structures to functions
– user defined data types – Union.
Pointers – pointers and arrays – pointers and functions - pointers and strings - pointers
and Structures.
Unit – V
Files – operations on a file – Random access to files – command line arguments.
Introduction to preprocessor – Macro substitution directives – File inclusion directives –
conditional compilation directives – Miscellaneous directives.
Text Books
1. Balagurusamy. E, “Programming in ANSI C”, Tata McGraw Hill, Sixth edition, 2012.
Reference Book
1. Vikas Verma, “A Workbook on C “, Cengage Learning, Second Edition,2012
2. Ashok N Kamthane, “Computer Programming”, Pearson education, Second
Impression, 2008.
Website:
1. http://www.cse.unt.edu
2. nptel.iitm.ac.in
2 R.SATHISH KUMAR/MVIT/CSE
DEPARTMENT VISION MISSION
Vision
To impart knowledge with latest technological advancement in the field of Computer Science
and Engineering and transform the learners into global contributors as Innovators,
Entrepreneurs and Researchers.
Mission
Department of Computer Science and Engineering is committed.
Higher Order Thinking: To impart strong fundamental concepts, analytical and problem
solving ability to hone their professional skills.
Continuous learning: To create an excellent conducive atmosphere for student learning and
continuous updation of their knowledge on technology.
Entrepreneurship: To imbibe the spirit of leadership skills to be an active entrepreneur in
society with moral values.
Competency: To enhance the creativity in research and to develop the competency of the
students in Technological field.
3 R.SATHISH KUMAR/MVIT/CSE
PROGRAM OUTCOME
PO1: Engineering knowledge: Apply knowledge of mathematics and science, with fundamentals of
Engineering and Technology to be able to solve complex engineering problems related to Computer
Science and Engineering.
PO2: Problem analysis: Identify, Formulate, review research literature and analyze complex engineering
problems related to CSE and reaching substantiated conclusions using first principles of mathematics,
natural sciences and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems related to
CSE and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety and the cultural societal and environmental considerations
PO4: Conduct investigations of complex problems:Use research–based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern tool usage: Create, Select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to computer science related complex
engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply Reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and sustainability: Understand the impact of professional engineering solutions in
societal and environmental contexts and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply Ethical Principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and team work: Function effectively as an individual and as a member or leader in
diverse teams and in multidisciplinary Settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large such as able to comprehend and with write effective reports and
design documentation, make effective presentations and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multi-disciplinary environments.
PO12: Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PROGRAMME SPECIFIC OUTCOME
PSO1: Foundation of mathematical concepts: Ability to apply the fundamental principles of
mathematics in the field of computer science and engineering to provide optimal solutions.
PSO2: Foundation of Software and Business technology: To design, test and evaluate software in order
to meet the requirements of end users and provide cutting-edge technologies for devising cost-effective
solutions.
4 R.SATHISH KUMAR/MVIT/CSE
Expected Outcome
The students will be able to
Blooms Taxonomy
CO No Descriptions
Level
Have a deeper knowledge on the evolution of computers,
CO1 components and its applications, have an awareness of internet R, U & A
, network structures, word processing and worksheets.
Know about various problem solving techniques, basics tokens
CO2 R, U & A
of C program and its structure
Learn about various control statements, declaration and
CO3 initialization of arrays, functions, storage classes and string R, U & A
functions.
CO4 Became familiar on structure, pointers and its manipulation. R, U & A
Know about Preprocessors, command line arguments and
CO5 R, U & A
various file operations.
CO6 How programming can be applied to real math problems. R, U & A
5 R.SATHISH KUMAR/MVIT/CSE
P101 COMPUTER PROGRAMMING LAB
OBJECTIVES
List of Exercises:
1. Study of OS Commands
2. Write a simple C program to find the Area of the triangle.
3. Write a simple C program to find the total and average percentage obtained by a
student for 6 subjects.
4. Write a simple C program to read a three digit number and produce output like
1 hundreds 7 tens 2 units for an input of 172.
5. Write a simple C program to check whether a given character is vowel or not using
Switch – Case statement.
6. Write a simple C program to print the numbers from 1 to 10 along with their squares.
7. Write a simple C program to find the sum of ‘n’ numbers using for, do – while
statements.
8. Write a simple C program to find the factorial of a given number using Functions.
9. Write a simple C program to swap two numbers using call by value and call by
reference.
10. Write a simple C program to find the smallest and largest element in an array.
11. Write a simple C program to perform matrix multiplication.
12. Write a simple C program to demonstrate the usage of Local and Global variables.
13. Write a simple C program to perform various string handling functions: strlen, strcpy,
strcat, strcmp.
14. Write a simple C program to remove all characters in a string except alphabets.
15. Write a simple C program to find the sum of an integer array using pointers.
16. Write a simple C program to find the Maximum element in an integer array using
pointers.
17. Write a simple C program to create student details using Structures.
18. Write a simple C program to display the contents of the file on the monitor screen.
19. Create a File by getting the input from the keyboard and retrieve the contents of the
file using file operation commands.
20. Write a simple C program to pass the parameter using command line arguments.
6
Course Name:C106 Year of Study:2018-19
COMPUTER PROGRAMMING
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
C106.1 3 - 1 - 2 - 2 2 1 1 1 1
C106.2 3 3 3 1 2 3 - 1 - 1 3 2
C106.3 3 3 1 - 1 3 - - - 1 1 2
C106.4 3 3 1 - - 3 - - - 1 1 2
C106.5 3 3 1 - - 3 - - - 1 1 2
C106.6 3 3 1 - 1 3 - - - 1 1 1
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
C 107.1 1 - 1 - 1 2 1 2 3 3 3 3
C 107.2 3 3 2 3 2 3 1 2 3 2 3 3
7
UNIT - I
Basics of Computer: Input and output Devices- Characteristics- Operations-Application-Hardware-
Categories of software-compiler & Interpreter.
Components & Classification: History of Computers – Block diagram of a Computer – Components of a
Computer system –Classification of computers
Network & Worksheets: Network Structure– Internet and its services – Intranet– Study of word processor
– Preparation of worksheets .
Basics of Computer
1. Explain briefly about Input and output devices of Computer?
INTRODUCTION TO COMPUTER
Computer has emerged as the most useful machine in recent times. It can perform wide variety of
tasks like receiving data, processing it, and producing useful results. However, being a machine, the
computer cannot perform on its own. A computer needs to be instructed to perform even a simple task like
adding two numbers. Computers work on a set of instructions called computer program, which clearly
specify the ways to carry out a task. A computer takes instructions, in the form of computer programs, and
carries out the requested task.
The human beings use natural languages such as English, Spanish, or French to communicate.
Similarly, a user communicates with the computer in a language understood by it. The instructions, provided
in the form of computer programs, are developed using computer or programming languages.
Overview:
A Computer is an electronic machine that takes input from the user process the given input and generates
output in the form of useful information.
A computer accepts input in different forms such as data, programs and user reply.
Data: It refers to the raw details that need to be processed to generate some useful information.
Programs: It refers to the set of instructions that can be executed by the computer in a sequential or
non sequential manner.
User reply: User reply is the input provided by the user in response to a question asked by the
computer.
The main task of a computer system is to process the given input of any type in an efficient manner.
Therefore the computer is also known as data processing unit, data processor and data processing system.
Figure 1.1
2) OUTPUT DEVICES:
Just as humans communicate with computers through input devices, the computer can communicate with
human beings using output devices. Output devices take the machine-coded output results from the CPU
and convert them into a form that is easily readable (such as characters, graphical) by human beings.
Output unit processes data into useful information.
The outputs, which can be easily understood and used by human beings, are in the form of hard copy and
soft copy. The physical form of output is known as hard copy.
The electronic version of an output, which usually resides in computer memory and/or on disk, is known
as soft copy: Some of the commonly used output devices are monitors, printers, plotters, and audio
response. Figure 2.2 shows various Output devices
2 R. SATHISHKUMAR/MVIT/CSE
2. What are the Characteristics of Computers?
Some of the characteristics of computers, which make them an essential part of every emerging
technology and a desirable tool in human development.
Speed: Computers process data at extremely fast rate-millions of instructions per second. In few
seconds, a computer can perform a huge task that a normal human being may take days or even
years to complete. The speed of a computer is calculated in MHz (Megahertz).
Accuracy: Besides efficiency, computers are accurate as well. The level of accuracy depends on the
instructions and the type of machine being used.
Diligence: Computer, being a machine, does not suffer from the human traits of tiredness and lack
of concentration. If four million calculations have to be performed, then the computer will perform
the last four-millionth calculation with the same accuracy and speed as the first calculation.
Reliability: Reliability is the measurement of performance of a computer, which is measured against
some predetermined standard for operation without any failure.
Storage Capability: Computers can store large amounts of data and can recall the required
information almost instantaneously. The main memory of the computer is relatively small and it can
hold only a certain amount of information, therefore, the data is stored on secondary storage devices
such as magnetic tape or disks.
Versatility: Computers are quite versatile in nature. They can perform multiple tasks simultaneously
with great ease.
Resource Sharing: With the tremendous growth in computer technologies, computers today have
the capability to connect with each other. This has made the sharing of costly resources like printers
possible. Apart from device sharing, data and information can also be shared among groups of
computers, thus creating a large information and knowledge base.
APPLICATIONS OF COMPUTER
In the last few decades, computer technology has revolutionized the businesses and other aspects of human
life all over the world. Some of the areas where computers are being used are listed below:
Science: Scientists have been using computers to develop theories, to analyse, and test the data. The fast
speed and accuracy of the computer allow different scientific analyses to be carried out. They can be
3 R. SATHISHKUMAR/MVIT/CSE
used to generate detailed studies of how earthquakes affect buildings or pollution affects weather
pattern. Satellite-based applications could not have been possible without the use of computers. It would
also not be possible to get the information of our solar system and the cosmos without computers.
Education: Computers have also revolutionised the whole process of education. Currently, the
classrooms, libraries, and museums are utilising computers to make education much more interesting.
Unlike recorded television shows, Computer Aided Education (CAE) and Computer Based Training
(CBT) packages are making learning much more interactive.
Medicine and Health Care: There has been an increasing use of computers in the field of medicine.
Now doctors are using computers right from diagnosing the illness to monitoring a patient's status
during a complex surgery. By using automated imaging techniques, doctors are able to look inside a
person's body and can study each organ in detail (such as CAT scans or MRI scans), which was not
possible a few years ago.
Engineering Architecture/Manufacturing: The architects and engineers are extensively using
computers in designing and drawings. Computers can create objects that can be viewed from all the
three dimensions. By using techniques like virtual reality, architects can explore houses that have been
designed but not built. The manufacturing factories are using computerised robotic arms in order to
perform hazardous jobs.
Entertainment: Computers are finding greater use in entertainment industry. They are used to control
the images and sounds. Special effects, which mesmerize the audience, would not have been possible
without computers. In addition, computerised animation and colourful graphics have modernised the
film industry.
Communication: E-mail is one of the communication media in which computer is used. Through e-
mail, messages and reports are passed from one person to one or more persons. The benefit of e-mail
service is that while transferring the messages it saves time, saves paper, and so on. Moreover, the
person who is receiving the messages can read the messages whenever he is free and can save it, reply
it, forward it or delete it from the computer.
Publishing: Computers have created a field known as DTP (Desktop Publishing). In DTP with the help
of a computer and a laser printer one can perform the publishing job all but oneself.
Banking: In the field of banking and finance, computers are extensively used. People can use the ATM
(Automated Teller Machine) services 24 hours of the day in order to deposit and withdraw cash. When
the different branches of the bank are connected through computer networks, then the inter branch
transactions such as cheque and draft can be done by the computers without any delay.
4 R. SATHISHKUMAR/MVIT/CSE
These include various input devices, central processing unit, output devices, and memory.
The hardware is the name given to any piece of equipment that is used along side a computer (including
the main computer itself).
These hardware devices can split into three categories.
1. Input
2. Process
3. Output
Figure3.2 Motherboard
SOFTWARE
Definition:
Software is a collection of programs.
Software is a generic term for organized collection of computer data and instructions.
It responsible for controlling, integrating and managing the hardware components of a
5 R. SATHISHKUMAR/MVIT/CSE
computer and to accomplish specific tasks. In other words, software tells the computer what to
do and how to do it.
A computer needs to be instructed to perform any task. These instructions are given in the form of computer
programs, which are written in computer programming the hardware or languages.
6 R. SATHISHKUMAR/MVIT/CSE
provide basic functionality like file management, visual display, and keyboard input, and are used by
application software to accomplish these functions. Some examples of system software are operating
systems, device drivers, language translators, and system utilities.
4.1.1 Operating System:
Definition
Operating system is the first layer of software loaded into computer memory when it starts up. It acts as
an interface between user and computer system (hardware).
The operating system ensures that different programs executing at the same time do not interfere with each
other. In simple words, the operating system organizes and controls the hardware. Examples: Windows XP,
UNIX, and Linux.
a) Functions of OS
Memory management
Process management
I/O management & User interface
Security & Multi tasking
The following is the figure 4.2 shows list of Operating Systems.
8 R. SATHISHKUMAR/MVIT/CSE
Figure4.3. Utility Software
Application Software
Definition: It is used to accomplish specific tasks rather than just managing a computer system.
Application software is dependent on system software.
The most often used software by a user is the application software. Application software may consist of a
single program, such as Microsoft's Notepad (for writing and editing simple text). It may also consist of a
collection of programs, often called a software package, which work together to accomplish a task, such as
database management software.
Application software is dependent on system software. A system software (like operating system)
acts as an interface between the user and the computer hardware, while application software performs
specific tasks. Applications are software that perform tasks for the use besides helping the computer operate,
which is the task of system software. Application software are controlled by system software, which
manages hardware devices and performs back ground tasks for them. Some of the most commonly used
application software are discussed below.
1) WORD PROCESSORS:
A word processor is software used to compose, format, edit, and print electronic documents.
Word processing is one of the earliest applications for office productivity and the personal
computer.
It involves not only typing, but also checking the spelling and grammar of the text and
arranging it correctly on a page.
A variety of different type faces is available for a variety of effects. It is possible to include pictures,
graphs, charts and many other things within the text of the document. It also allows for changes in
margins, fonts, and color. Examples of some well-known word processors are Microsoft Word and
WordPerfect.
2) SPREADSHEETS:
A spreadsheet application is a rectangular grid, which allows text, numbers, and complex
functions to be entered into a matrix of thousands of individual cells.
One of the first commercial uses of computers was in processing payroll and other financial records. So
the programs were designed to generate reports in the standard spreadsheet format used by bookkeepers
and accountants.
10 R. SATHISHKUMAR/MVIT/CSE
5. Explain the Various compiler and interpreter?
Along with every programming language developed, a language translator was also developed, while
accepts the programs written in a programming language and executes them by transforming them into a
form suitable for execution. Depending on the programming language used, language translators are divided
into three major categories: compilers, interpreter, and assembler.
• A program written in high level language is called source code. We need to convert the source
code into machine code and this is accomplished by Compiler and interpreter.
• Hence a compiler or an interpreter is a program that converts program written in high level
language into machine code understand by the computer.
Language Description
Translators
Compiler The programs written in any high-level programming language (C or Pascal)
are converted into machine language using a compiler. As a system program,
the compiler translates source code (user written program) into object code
(binary form).
Interpreter An interpreter analyses and executes the source code in line-by-line manner,
without looking at the entire program. However, programs produced by
compilers run much faster than the same programs executed by an interpreter
Assembler Assembly language is fundamentally a symbolic representation of machine
code. The assembly language program must be translated into machine code
by a separate program called an assembler. An assembler converts the
assembly codes into machine codes, making the assembly program ready for
execution
7. Program need not be compiled Every time high level program is converted
every time. into low level program.
6. Errors are displayed after entire Errors are displayed for every instructions
program is checked interpreted (if any)
7. Example: C Compiler Example: BASIC
11 R. SATHISHKUMAR/MVIT/CSE
6. Explain the Storage Units?
The following Figure shows the various storage units.
INTRODUCTION
The term “computer” is derived from the word compute, which means to calculate. A computer is
an electronic machine, devised for performing calculations and controlling operations that can be expressed
either in logical or numerical terms. In simple words, a computer is an electronic device that performs
diverse operations with the help of instructions to process the information in order to achieve desired results.
12 R. SATHISHKUMAR/MVIT/CSE
GENERATIONS OF COMPUTERS
The history of computer development is often discussed with reference to the different generations
of computing devices. According to the technology used, there are five generations of computers which are
discussed in the following sections.
13 R. SATHISHKUMAR/MVIT/CSE
conditioning was essential.
These were non-portable and very slow equipments.
They lacked in versatility and speed.
They were very expensive to operate and used a large amount of electricity.
These machines were unreliable and prone to frequent hardware failures. Hence, constant
maintenance was required.
Since machine language was used, these computers were difficult to program and use.
In second generation computers, magnetic cores were used as primary memory and magnetic disks as secondary
storage devices. However, they still relied on punched cards for input and printouts for output.
One of the major developments of this generation includes the progress from machine "language to assembly
language. Assembly language used mnemonics (abbreviations) for instructions rather than numbers, for example,
ADD for addition and MULT for multiplication.
Instead of punched cards and printouts, users interacted with third generation computers through
15
SATHISHKUMAR/MVIT/CSE
keyboards and monitors and interfaced with operating system.
For example: NCR 395 and B6500.
For example; PDP-8, IBM 1401 and IBM 7090.
Fig 4: IC’s
Fig 5: 3rd Generation Computers
16
SATHISHKUMAR/MVIT/CSE
memories such as hard disks became economical, smaller, and bigger in capacity. For Example: Apple II, Altair
8800, CRAY-1
17
SATHISHKUMAR/MVIT/CSE
2. Explain Briefly about Block diagram of a Computer? Or
Explain the Components of Computer system
COMPONENTS OF A COMPUTER SYSTEM
A computer is an information processing machine. It can be viewed as a system, which consists of a number of
interrelated components that work together with the aim of converting data into information. To attain
information, data is entered through input devices. This data is processed using the central processing unit and
then the processed data known as information is displayed to the users using various output devices. All these
parts (input devices, central processing unit, and output devices) are referred to as hardware of the computer. In
the following sections, we discuss both these (hardware and software) parts in detail.
HARDWARE
Definition:
Hardware refers to all visible devices that are assembled together to build a computer system. These include
various input devices, central processing unit, output devices, and memory.
Memory Unit
Control Arithmetic/
Unit Logic unit
18
SATHISHKUMAR/MVIT/CSE
stored program instructions.
A CPU controls all internal and external devices, performs arithmetic and logic operations, and operates only on
binary data, that is, data composed of 1’s and 0’s.
In addition, it also controls the usage of main memory to store data and instructions, and controls the sequence of
operations.
The central processing unit consists of three main subsystems, the Arithmetic/Logic Unit (ALU), the Control Unit
(CD), and the Registers.
Memory
Computers require memory to process data and store output. Memory refers to the electronic holding place for
instructions and data. Some data will be required instantaneously, while others may not be needed for extended
periods. Likewise, CPU requires memory to handle the intermediate results and to store the final output. Hence,
we can classify memory into two broad categories: primary memory (to handle the data) and secondary memory
19
SATHISHKUMAR/MVIT/CSE
(to store the output).
Primary Memory
Primary memory, also known as main memory, stores data and instructions for processing. Primary memory can
be further classified into random access memory (RAM) and read only memory (ROM).
Secondary Memory
Secondary memory, also known as auxiliary memory or external memory is used for storing instructions (software
programs) and data, since main memory temporary and limited in size. This memory is least expensive and has
much larger storage capacity than primary memory.
MICRO COMPUTERS
A micro computer is a small, low cost digital computer, which usually consists of a microprocessor, a storage
unit, an input channel, and an output channel, all of which may be on one chip inserted into one or several PC
boards.
The addition of a power supply and connecting cables, appropriate peripherals (keyboard, monitor, printer,
disk drives, and others), an operating system and other software programs can provide a complete micro
computer system.
IBM-PC, Pentium 100, IBM-PC Pentium 200 and Apple Macintosh are some of the examples of micro
computers.
Micro computers include desktop, laptop, and hand-held models such as PDAs (Personal Digital Assistants).
Desktop Computer Desktop computer, also known as Personal Computer (PC), is principally intended for
standalone use by an individual. These are the most common type of micro computers. These micro computers
20
SATHISHKUMAR/MVIT/CSE
typically consist of a system unit, a display monitor, a keyboard, internal hard disk storage, and other peripheral
devices. Some of the major personal computer manufacturers are APPLE, IBM, Dell and Hewlett-Packard.
Laptop A laptop is a portable computer, that is, a user can carry it around. Since the laptop computer resembles a
notebook, it is also known as "notebook". Laptops are small computers enclosing all the basic features of a normal
desktop computer. The biggest advantage of this computer is that one can use this computer anywhere and at
anytime, especially when one is travelling.
Hand-held Computers A hand-held, also called Personal Digital Assistant (PDA), is a computer that can
conveniently be stored in a pocket (of sufficient size) and used while the user is holding it. PDAs are essentially
small portable computers and are slightly bigger than the common calculators. A PDA user generally uses a pen
or electronic stylus, instead of a keyboard for input. The monitor is very small and is the only apparent form of
output. Since these computers can be easily fitted on the palm, they are also known as palmtop computers. Some
examples of PDAs are Apple Newton, Casio Cassiopeia and Franklin eBookMan.
MINI COMPUTERS
In the early 1960s, Digital Equipment Corporation (DEC) started shipping its PDP series computer referred as
mini computers.
The mini computer is a small digital computer whose process and storage capacity is lesser than that of a
mainframe, but more than that of micro computer.
Its speed of processing data is in between that of a mainframe and a micro computer.
It is about the size of a two drawer filing cabinet.
It is capable of supporting from 4 to about 200 simultaneous users.
It serves as a centralised storehouse for a cluster of workstations or as a network stations in server.
Mini computers are usually multi-user systems, so these are used in interactive applications in industries,
research organisations, colleges and universities.
Some of the widely used mini computers are PDP 11, IBM (8000 series) and VAX 7500.
MAINFRAME COMPUTER
A mainframe is an ultra-high performance computer made for high-volume, processor-intensive computing.
It consists of a high-end computer processor, with related peripheral devices, capable of supporting large
volumes of data processing, high performance online transaction processing systems, and extensive data
storage and retrieval.
It is able to process and store more data than a mini computer and far more than a micro computer.
It is designed to perform at a faster rate than a mini computer and at even more faster rate than a micro
computer.
Mainframes are the second largest (in capability and size) of the computer family, the largest being super
computers.
21
SATHISHKUMAR/MVIT/CSE
It is typically used by large businesses and for scientific purposes.
Examples of mainframe computers are IBM's ESOOO, VAX 8000 and CDC 6600.
SUPER COMPUTERS
Super computers are the special purpose machines, which are specially designed to maximise the numbers of
FLOP (Floating Point Operation Per Second).
A super computer has the highest processing speed at a given time for solving scientific and engineering
problems.
It contains a number of CPUs that operate in parallel to make it faster.
Its processing speed lies in the range of 400-10,000 MFLOPS (Millions of Floating Point Operation Per
Second).
It can resolve complex mathematical equations in a few hours, which would have taken a scientist with paper
and pencil a lifetime, or years, using a hand calculator.
It is the fastest, costliest and the most powerful computer available today.
CRAY-3, Cyber 205 and PARAM are some well known super computers.
22
SATHISHKUMAR/MVIT/CSE
• Business and government entities utilize WANs to relay data among employees, clients, buyers, and
suppliers from various geographical locations.
• In essence, this mode of telecommunication allows a business to effectively carry out its daily function
regardless of location.
A Metropolitan Area Network (MAN), connects across the cities, which are accessed only by certain group of
users. It is more secured.
Network topologies (structure)
Bus topology
Star topology
Mesh topology
Ring topology
Bus topology
A bus topology uses one cable to connect multiple computers. The cable is also called a trunk, a backbone,
and a segment. Most of the time, as seen in figure, T-connectors are used to connect to the cabled segment. They
are called T-connectors because they are shaped like the letter T. You will commonly see coaxial cable used in
bus topologies
Star Topology
In a star topology, all computers are connected through one central hub or switch, as illustrated in below
Figure. This is a very common network scenario. Computer in a star topology are all connected to a central hub.
23
SATHISHKUMAR/MVIT/CSE
A star topology actually comes from the days of the mainframe system. The mainframe system had a
centralized point where the terminals connected.
Advantages
• The biggest advantage of a mesh topology is fault tolerance.
• If there is a break in a cable segment, traffic can be rerouted.
• This fault tolerance means that the network going down due to a cable fault is almost impossible.
Disadvantages
24
SATHISHKUMAR/MVIT/CSE
• A mesh topology is very hard to administer and manage because of the numerous connections.
• Another disadvantage is cost. With a large network, the amount of cable needed to connect and the
interfaces on the workstations would be very expensive.
Ring Topology
In a ring topology, all computers are connected with a cable that loops around. As shown in the below figure.
The ring topology is a circle that has no start and no end. Terminators are not necessary in a ring topology.
Signals travel in one direction on a ring while they are passed from one computer to the next. Each computer
checks the packet for its destination and passes it on as a repeater would.
Advantages
• The nice thing about a ring topology is that each computer has equal access to communicate on the
network. (With bus and star topologies, only one workstation can communicate on the network at a time.)
Disadvantages
• The biggest problem with a ring topology is that if one computer fails or the cable link is broken the
entire network could go down.
• With newer technology this isn’t always the case.
• The concept of a ring topology is that the ring isn’t broken and the signal hops from workstation to
workstation, connection to connection.
25
SATHISHKUMAR/MVIT/CSE
core of Internet.
In 1980’s Usenet news groups and Electronic Mail (e-mail) came into picture.
University of Minnesto created GOPHER, a web browser for easy to use interface to work with internet.
In 1990’s CERN released to World Wide Web(WWW). The CERN team developed a protocol based on
hypertext that makes it possible to connect content on the web with hyperlinks.
Today, websites provide users with a range of experiences such as pictures, multimedia and interactivity.
BASIC INTERNET TERMS
Web Page: The World Wide Web consists of files, called pages or web pages, which contain information and
links to resources throughout the Internet. A web page is an electronic document written in a computer
language called HTML.
Website: A Website is a set of related web pages published by an organization or individual.
Browser: A web browser, often times shortened in name to browser, allows you to view web pages like this
one. The most popular web browsers are Netscape Navigator and Internet Explorer.
Uniform Resource Locator: The "Uniform Resource Locator" is the unique address of any web document. It
is also called domain name or internet address. You enter it in the address bar in your browser
Domain Name: A domain name is the initial part of an URL, down to the first /. In case of this website
internet-starter-guide.com is the domain name. Every domain name has a suffix that indicates for what
purpose this domain is used. The most widespread domain suffix is .com and even though it stands for
commercial it is used by many non commercial websites as well. Every country has also a specific suffix.
.com identifies a business (commercial)
.us is intended for use by U.S. websites
.de is intended for use by German websites
.info is an informational Web site
.name is a personal name site for individuals
.org identifies an organization
.edu identifies an educational organization
.gov identifies a government agency
HyperText: Hypertext refers to the text or image that connects to other documents.
Internet Service Provider (ISP): An ISP is a company that provides access to the internet to individuals or
companies.
Web Server: A Server is a computer equipped with server software, which provides a specific kind of service
to client software running on other computers. A web server is a computer that answers requests from user’s
computers.
COMPONENTS / REQUIREMENTS FOR INTERNET
The basic requirements for getting connected to internet are:
A TCP/IP enabled computer with a web browser
An account with an ISP
26
SATHISHKUMAR/MVIT/CSE
A telephone line plugged to a suitable socket
A modem to connect the computer to the telephone line.
TYPES OF INTERNET CONNECTION
The modem must be connected to a telephone line to access the web. Some of the common types of Internet
access are:
Dial-up
ISDN (Integrated Services Digital Network)
Cable Modem
Leased Line
DSL (Digital Subscriber Line) Service
Broadband
INTERNET SERVICES
The Internet has grown from a small project to today's biggest network-of computers. Due to this colossal
growth, the Internet has become the biggest domain of information. Some of the important services provided by
the Internet are briefed in the following few sections.
IRC, Chatting
Telnet E-Mail
FTP Newsgroups
Commerce
World Wide Web (WWW) The World Wide Web (abbreviated as the Web or WWW) is one of the most popular
services available on Internet. It is a subset of the Internet and it presents text, images, animation, video, sound,
and other multimedia in a single interface. Although the world wide web is often referred to as the Internet, they
are actually two different concepts. The Internet is the decentralised global network of computers that transfer
information and the wiring that makes all this possible whereas the web is a collection of documents or websites,
that users can access using the Internet and a web browser. The web is a part of the Internet and it refers to a
system of Internet servers that supports hypertext using a specific Internet protocol called HTTP on a single
interface (web browsers). This includes e-mail, FTP, Telnet, and Usenet News.
The operation of the web relies primarily on hypertext, as it is a means of information retrieval. Hypertext
is a document containing words that connect to other documents. These words are called links, which the user can
select.
Electronic Mail (E-mail) : Electronic mail, or e-mail, is a fast, easy, and inexpensive way to communicate
with other Internet users around the world. It is one of the basic and earliest services of the Internet and the most
27
SATHISHKUMAR/MVIT/CSE
used application on the Internet too.
Each user of e-mail has a mailbox address to which messages are sent and the mailbox can be accessed
from anywhere and at anytime. Not only this, e-mail can also be used to send documents, images, audio, video,
and so on, as an attachment along with the mail.
File Transfer Protocol (FTP): FTP or File Transfer Protocol is a set of rules that enables a user to log on to
another computer and transfer information between it and his/her computer. It was the first service developed for
the Internet so that government and educational institution could easily exchange files.
Telnet The word "telnet" is derived from telecommunications and network and is a protocol that allows a user to
log on to a remote computer. Telnet is also known as remote login, which means connecting one machine to
another in such a way that a person may interact with another machine as if being used locally.
The user's computer, which initiates the connection, is referred to as the local computer or telnet client,
and the machine being connected to, which accepts the connection, is referred to as the remote computer or telnet
server.
Internet Relay Chat (IRC) IRC or Internet Relay Chat is a service on the Internet that allows the people to
communicate in real-time and carryon conversations via the computer with one or more people. It provides the
user with the facility to engage in simultaneous (synchronous) online "conversations" with other users from
anywhere in the world.
Chatting and Instant Messaging Chat programs allow users on the internet to communicate with each other by
typing in real-time. Note that even though chatting is based on standardised IRC system, unlike the user does not
need to have any special software to connect to any chat rooms.
A variation of chat is instant messaging where a user on the web can contact another currently logged in
and type a conversation. To avail this Internet service, the user must have software called instant messenger
installed on the system.
Internet Telephony Internet telephony is the use of Internet rather than traditional telephone company
infrastructure, to exchange spoken or other telephonic information. It consists of hardware and software that
enable people to use the Internet as a transmission medium phone calls. There are many Internet telephony
applications available. Some, such CoolTalk and NetMeeting come bundled with popular web browsers.
Video Conferencing Video conferencing uses the same technology as IRC, but also provides sound and video
pictures. It enables direct face-to-face communication across network.
Commerce through Internet Today business is taking place through electronic telecommunication media.
Nowadays, various organisations offer the facility of shopping online. This type of business model is known as
Electronic Commerce or E-commerce. E-commerce refers to buying and selling goods and online.
28
SATHISHKUMAR/MVIT/CSE
When discussing about e-commerce, we normally talk about virtual shopping malls, up stores where the
user virtually visits and selects the product(s) of his/her choice. After selecting the desired product(s), the
payment for the purchase is done. Online payment can be through credit card. Some of the well-known e-
commerce sites are www.amazon.com and www.ebay.com.
Mobile commerce or M-commerce refers to transactions through mobile phone network and data
connection that result in the transfer of value in exchange for goods and services.
Newsgroups (Usenet) Newsgroups are international discussion groups that focus on a particular topic and help in
gathering information about that topic. The topics discussed here cover all the fields such as politics, computers,
technology, and many more.
Newsgroups provide a source of information and a medium through which users can ask questions from
the Internet community. They provide a forum for users to discuss topics of mutual interest.
Benefits of intranets
Workforce productivity: Intranets can also help users to locate and view information faster and use
applications relevant to their roles and responsibilities. With the help of a web browser interface, users can
access data held in any database the organization wants to make available, anytime and - subject to security
provisions - from anywhere within the company workstations, increasing employees' ability to perform their
jobs faster, more accurately, and with confidence that they have the right information. It also helps to improve
the services provided to the users.
Time: With intranets, organizations can make more information available to employees on a "pull" basis (i.e.,
employees can link to relevant information at a time which suits them) rather than being deluged
indiscriminately by emails.
Communication: Intranets can serve as powerful tools for communication within an organization, vertically
and horizontally. From a communications standpoint, intranets are useful to communicate strategic initiatives
that have a global reach throughout the organization.
29
SATHISHKUMAR/MVIT/CSE
Cost-effective: Users can view information and data via web-browser rather than maintaining physical
documents such as procedure manuals, internal phone list and requisition forms. This can potentially save the
business money on printing, duplicating documents, and the environment as well as document maintenance
overhead.
Promote common corporate culture: Every user is viewing the same information within the Intranet.
Enhance Collaboration: With information easily accessible by all authorized users, teamwork is enabled.
Cross-platform Capability: Standards-compliant web browsers are available for Windows, Mac, and UNIX.
Immediate Updates: When dealing with the public in any capacity, laws/specifications/parameters can
change. With an Intranet and providing your audience with "live" changes, they are never out of date, which
can limit a company's liability.
Enter the fields Rollno, Name, Maths, Physics, Chemistry, Total, Average.
Enter the rollno, name of 5 students and enter their maths, physics and chemistry marks.
Find the total of the first student by =SUM(maths, physics, chemistry marks) and click enter.
Move the mouse cursor at the bottom most corner of cell and click and drag the cell to calculate the total for
other students. (OR) Below the cell total, type = and chose
FormulasAutosumsum and click enter to find the total. Click and drag to find the total of all students.
Find the average of the first student by =AVERAGE(total marks/3) and click enter.
Move the mouse cursor at the bottom most corner of cell and click and drag the cell to calculate the average of
other students. (OR) Below the cell avearge, type = and chose
FormulasAutosumaverage and type total/3 .Click and drag to find the average of all students.
To create a chart, select the required columns and click Insert column or pie or bar to insert a chart.
Enter the fields eno, name, Basic Pay(BP), DA, HRA, Netpay. Consider DA=10% of BP, HRA=5% of BP.
30
SATHISHKUMAR/MVIT/CSE
Enter the eno, name of 5 employees and enter their Basic Pay.
To find the DA of 1st employee type =(10/100)*BP and press enter. Move the mouse cursor at the bottom most
corner of cell and click and drag the cell to calculate the DA of other employees.
To find the HRA of 1st employee type =(5/100)*BP and press enter. Move the mouse cursor at the bottom most
corner of cell and click and drag the cell to calculate the DA of other employees.
Net pay of the employee is calculated by adding BP,DA and HRA, which can be done by the function SUM
To create a chart, select the required columns and click Insert column or pie or bar to insert a chart.
2. To open a new word document: Goto file -> new -> blank document -> create
3. You can start typing the text. After typing if you want to highlight key points, it can be done by highlighting the
necessary text first and then to make
4. To insert a TABLE, goto insert -> table -> and select number of rows and columns.
5. To add HEADER, goto insert -> header-> edit header and add the text you need as header
6. To add FOOTER, goto insert -> footer -> edit footer and add the text you need as footer
7. To add PAGE NUMBERS, goto insert -> page number -> choose top or bottom
8. To add PAGE BORDER, choose page layout -> and select suitable page border.
9. To SEARCH a particular word from the document and to used replace a particular word, ctrl+f can be used.
10. To go to a particular PAGE NUMBER, ctrl+g can be used and desired page number can be given.
11. After typing the text, it can be SAVED using ctrl+s and select the destination drive and folder to save the
document by giving a suitable name.
12. For PRINTING, ctrl+p can be used. Specify number of copies and click print.
To open a Microsoft office word, click startall programsMicrosoft officeMicrosoft office word.
Enter the body of the mail. Above the body of the mail, left the To address blank.
31
SATHISHKUMAR/MVIT/CSE
Click start mail mergeLetters.
New Address List window will be opened. In that, add the Title, First Name, Last Name, Company Name,
Address, City, Pincode, State.
Similarly add any number of recipient addresses and click ok and save the address list in any location.
Click the cursor below the To address and then Click Insert Merge Field and then
Now the E-mail message is merged with all the recipients which are added
32
SATHISHKUMAR/MVIT/CSE
Unit II
Problem solving Techniques- Program – program development cycle – Algorithm design – Flowchart –
Pseudocode.
Introduction to C – History of C – Importance of C – C Tokens – Data Types – Operators and expressions –
I/O Functions.
----------------------------------------------------------------------------------------------------------------------------
Program:
Definition: A set of coded instructions that a computer can understand to solve a problem or produce a
desired result.
Two basic types of computer programs are
a) Operating system: The most fundamental instructions a computer uses in its operations.
b) Application program: Which runs on the operating system and does a specific job such as word
processing.
Programs are written either in one of high level programming languages such as (Basic, C, Java) which
are easier but execute relativel slow. Low level language such as assembly level language are very
complex but execute fast.
DEVELOPING A PROGRAM
A program consists of a series of instructions that a computer processes to perform, the required
operation. In addition, it also contains some fixed data, required to perform the instructions, and the process of
defining those instructions and data. Thus, in order to design a program, a programmer must determine three
basic rudiments:
1. The instructions to be performed.
2. The order in which those instructions are to be performed.
3. The data required to perform those instructions.
To perform a task using a program, a programmer has to consider various inputs of the program along
with the process, which is required to convert input into desired output. Suppose we want to calculate the sum of
two numbers, A and B, and store the sum in C, here A and B are the inputs, addition is the process, and C is the
output of the program.
A, B C=A+B C
33
SATHISHKUMAR/MVIT/CSE
into a series of smaller steps, independent of the programming language. One common technique is to use the
program development cycle, with the number of steps that may vary according to the person who has formalized
the development. Development cycle of a program includes the following phases.
Algorithm Testing
1. Analyse/Define the Problem: The problem is analyzed precisely and completely. Based on understanding,
the developer knows about the scope within which the problem needs to be analysed.
2. Task Analysis: After analyzing the problem, the developer needs to develop various solutions to solve the
given problem. From these solutions, the optimum solution is chosen, which can solve the problem comfortably
and economically.
3. Designing Phase: After selecting the appropriate solution, algorithm is developed to depict the basic logic of
the selected solution. An algorithm depicts the solution in logical steps. Further, algorithm is represented by
flowcharts and pseudo codes. These tools make program logic clear and they eventually help for coding. This
phase is also known as design phase.
4. Testing the Algorithm for Accuracy: Before converting the algorithms into actual code, it should be
checked for accuracy. The main purpose of checking algorithm is to identify major logical errors at an early
stage, because logical errors are often difficult to detect and correct at later stages.
5. Coding: After meeting all the design considerations, the actual coding of the program takes place in the
chosen programming language. Depending upon application domain and available resources, a program can be
written by using computer languages of different levels such as machine, assembly or high-level languages.
6. Test and Debug the Program: It is common for the initial program code to contain errors, a program
compiler and programmer-designed test data machine tests the code for syntax errors. The results obtained are
compared with results calculated manually from this test data. Depending upon the complexity of the program,
several rounds of testing may be required.
7. Documentation and Implementation: Once the program is free from all the errors, it is the duty of the
program developers to ensure that the program is supported by suitable documentation. After documentation, the
program is installed on the end user's machine.
The phases starting from the feasibility study to the integration and system testing phase are
known as the development phases.
Software is developed during the development phases, and at the completion of the
development phases, the software is delivere d to the customer.
As the customers start to use the software, changes to it become necessary on account of bug
fixes and feature extensions, causing maintenance works to be undertaken. Therefore, the last
phase is also known as the maintenance phase of the life cycle
Corrective maintenance: This type of maintenance is carried out to correct errors that were not
discovered during the product development phase. Page | 16
Perfective maintenance: This type of maintenance is carried out to improve the performance of the
system, or to enhance the functionalities of the system based on customer’s requests.
Adaptive maintenance: Adaptive maintenance is usually required for porting the software to work in a
new environment. For example, porting may be required to get the software to work on a new computer
platform or with a new operating system.
2. Explain the various problem solving Techniques (Algorithm Flowchart and
Pseudo Code)?
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques and graphical tools that helps in providing in logic for
solving a problem. In other words, these tools are used to express the logic of the problem by specifying the
correct sequence of all instructions to be carried out.
The various problem solving Tools are
Algorithms
Flowcharts
Pseudo codes
36
SATHISHKUMAR/MVIT/CSE
2.1 ALGORITHM: Algorithm is a sequence of instructions used to solve a problem which is written
in easy English so that even a non programmer can understand it.
Input: READ
Process: ADD, SUB, MULTIPLY, DIVIDE,COMPUTE
Output: PRINT, DISPLAY
Algorithms are one of the most basic tools that are used to develop the problem solving logic.
An algorithm is defined as a finite sequence of explicit instructions that, when provided with a set of input
values produces an output and then terminates.
In algorithm, after a finite number of steps, solution of the problem is achieved. Algorithms can have steps
that repeat (iterate) or require decisions (logic and comparison) until the task is completed.
Properties of an algorithm:
Finiteness- An algorithm must terminate after finite number of steps.
Definiteness- Each step of an algorithm must be precisely defined.
Input – The data must be present before any operations can be performed on it.
The variable can be given initial value using SET instruction.
Example: READ A,B
SET N=0
Output – After Executing all the steps of the algorithm at least one output must be obtained.
Effectiveness- The operations to be performed in the algorithm can be carried out manually in
finite interval of time.
Advantages of Algorithm:
It is simple to understand and gave step by step solution for the problem.
It is easy to debug errors.
An algorithm is independent of programming language.
It uses the most efficient logic to solve the given problem statement(Time complexity)
It uses minimal system memory for its execution(space complexity)
Example1: Finding the Sum of two numbers
Step 1: Start
Step 2: Read two numbers say A, B.
Step 3: ADD two numbers and store the Result in to SUM
Step 4: Display SUM
Step 6: Stop
Example2: Finding the Average of Three numbers
Step 1: Start
Step 2: Read three numbers say A, B,C
Step 3: ADD three numbers and store the Result in to SUM
Step 4: Find the Average by DIVIDE SUM by 3 and store the result in AVERAGE
Step 4: Display AVERAGE
Step 6: Stop
Example3: Finding the Biggest of Three numbers
37
SATHISHKUMAR/MVIT/CSE
Step 1: Start
Step 2: Read three numbers say A, B, C
Step 3: Find the larger number between A and B and store it in MAX_AB
Step 4: Find the larger number between MAX_AB and C and store it in MAX
Step 5: Display MAX
Step 6: Stop
Example: 4 Finding the sum of Even numbers
Step 1: Start
Step 2: Read N
Step 3: SET I=2, SUM=0
Step 4: IF I<n then calculate SUM=SUM+I and increment I value.
Step 5: REPEAT step 4 until the IF condition false
Step 6: Display SUM
Step 7: Stop
Example: 5 Area of Traiangle
Step 1: Start
Step 2: Read three sides of triangle say A, B, C
Step 3: Compute value of s=(a+b+c)/2
Advantages of Flowcharts:
A flowchart helps to clarify how things are currently working and how they could-be improved. The reasons for
using flowcharts as a problem-solving tool are given below.
Makes Logic Clear: The 'main advantage of using a flowchart to plan a task is that it provides a pictorial
representation of the task, which makes the logic easier to follow. Even less experienced personnel can trace the
actions represented by a flowchart, that is, flowcharts are ideal for visualizing fundamental control structures
employed in computer programming.
Communication: Being a graphical representation of a problem-solving logic, flowcharts are better way of
communicating the logic of a system to all concerned.
Effective Analysis: With the help of a flowchart, the problem can be analysed in an effective way. This is
because the analysing duties of the programmers can be delegated to other persons, who may or may not know
the programming techniques, but they have a broad idea about the logic.
Useful in Coding: The flowcharts act as a guide or blueprint during the analysis and program development
phase. Once the flowcharts are ready, the programmers can plan the coding process effectively as they know
where to begin and where to end, making sure that no steps are omitted.
Proper Testing and Debugging: By nature, a flowchart helps in detecting the errors in a program, as the
developers know exactly what the logic should do.
Appropriate Documentation: Flowcharts serve as a good program documentation tool. Since normally the
programs are developed for novice users; they can take the help of the program documentation to know what the
program actually does and how to, use the program.
Limitations of Flowcharts Flowchart can be used for designing the basic concept of the program in pictorial
form but cannot be used for programming purposes. Some of the limitations of the flowchart are given as
follows:
Complex: The major disadvantage in using flowcharts is that when a program is very large, the flowcharts
may continue for many pages, making them hard to follow.
Costly: Drawing flowcharts are viable only if the problem-solving logic is straightforward and not very
lengthy. However, if flowcharts are to be drawn for a huge application, the time and cost factor of program
development may get out of proportion, making it a costly affair.
Difficult to Modify: Due to its symbolic nature, any changes or modification to a flowchart usually requires
redrawing the entire logic again, and redrawing a complex flowchart is not a simple task. It is not easy to draw
thousands of flow lines and symbols along with proper spacing, especially for a large complex program.
No Update: Usually programs are updated regularly. However, the corresponding update of flowcharts may
not take place, especially in the case of large programs. As a result, the logic used in the flowchart may not
40
SATHISHKUMAR/MVIT/CSE
match with the actual program's logic.
41
SATHISHKUMAR/MVIT/CSE
EXAMPLE FLOWCHART:
DO IT NOW EXERCISE:
42
SATHISHKUMAR/MVIT/CSE
2.3 PSEUDOCODE
Pseudocode (pronounced soo-doh-kohd) is made up of two words: pseudo and code. Pseudo means
imitation and code refers to instructions, written in a programming language.
As the name suggests, pseudocode is not a real programming code, but it models and may even
look like programming code. Pseudocode uses plain English statements rather than symbols, to
represent the processes of a computer program.
It is also known as PDL (Program Design Language), as it emphasises more on the design aspect of
a computer program or structured English, because usually pseudocode instructions are written in
normal English, but in a structured way.
If an algorithm is written in English, the description may be at such a high level that it may prove
difficult to analyse the algorithm and then to transform it into actual code.
If instead, the algorithm is written in code, the programmer has to invest a lot of time in
determining the details of an algorithm, which he may choose not to implement (since, typically,
algorithms are analysed before deciding which one to implement).
Therefore, the goal of writing pseudocode is to provide a high-level description of an algorithm,
which facilitates analysis and eventual coding, but at the same time suppresses many of the details
that are insignificant.
Pseudocode uses some keywords to denote programming processes. Some of them are:
Input: READ, OBTAIN, GET, and PROMPT
Output: PRINT, DISPLAY, and SHOW
Compute: COMPUTE, CALCULATE, and DETERMINE
Initialise: SET and INITIALISE
Add One: INCREMENT
2.3.1 Pseudocode Guidelines Writing pseudocode is not a difficult task. Even if you do not know
anything about the computers or computer languages, you can still develop effective and efficient
pseudo codes, if you are writing in an organized manner.
Here are a few general guidelines for developing pseudocodes:
Statements should be written in simple English and should be programming language independent.
Remember that pseudocodes only describe the logic plan to develop a program, it is not
programming.
Steps must be understandable, and when the steps are followed, they must produce a solution to the
specified problem.
Pseudocodes should be concise.
Each instruction should be written in a separate line and each statement in pseudocode should
express just one action for the computer.
43
SATHISHKUMAR/MVIT/CSE
Capitalise keywords such as READ, PRINT, and so on.
Each set of instructions is written from top to bottom, with only one entry and one exit.
It should allow for easy transition from design to coding in programming language.
Benefits of Pseudocode Pseudocode provides a simple method of developing the program logic as it
uses everyday language to prepare a brief set of instructions in the order in which they appear in the
completed program. It allows the programmer to focus on the steps required to solve a program rather
than on how to use the computer language. Some of the most significant benefits of pseudocode are:
Since it is language independent, it can be used by most programmers.
It is easier to develop a program from a pseudocode than with a flowchart.
Often, it is easy to translate pseudocode into a programming language, a step which can be
accomplished by less experienced programmers.
Unlike flowcharts, pseudocode is compact and does not tend to run over many pages. Its simple
structure and readability makes it easier to modify.
Figure HISTORY OF C
IMPORTANCE OF “C” LANGUAGE
C is a Structured Programming Language and powerful language.
C is a versatile Language (i.e.,) it has features of both Low Level Languages and High Level
Languages.
It is used in system programming. Compilers, packages, Operating System are written using C.
C is a highly portable language. Source Program written in one computer can be compiled,
executed and run on another computer with less modification.
Users can develop program quickly with few mistakes.
45
SATHISHKUMAR/MVIT/CSE
It increases the readability of Program. Program can be modified without affecting the other
parts of a program.
C is a Case Sensitive Language. It differentiates both Upper Case and Lower Case separately.
Every statement in C ends with semicolon.
Programmers can write additional functions of their own. C language has a C Compiler.
C language has the ability to extend itself. C is also a free form language, because each group of
statements can be placed together on one line.
C language is used for developing software packages, system software, database systems,
graphics packages, spread sheets, CAD/CAM applications, word processors, office automation,
scientific and engineering applications.
STRUCTURE OF C PROGRAM
Documentation Section
Header File Section / Link Section
Definition Section
Global (Variable) Declaration Section
main()
{
Declaration(local variable) part
Executable part
}
sub program section
function 1
function 2
‘
‘
Function n
46
SATHISHKUMAR/MVIT/CSE
Global declaration section
Used to declare functions, variables or symbolic constants globally. Two types of declaration are allowed in
C Language.
main( ) section
The execution of C program starts from the main function. Every C program must have a main
function. It contains two parts. They are declaration part and executable part. Declaration part and
executable part must appear between opening ‘ { ‘ and closing braces ‘ }’. Opening brace specifies the
beginning of C program and close brace specifies the logical end of C program.
Declaration part
Declaration part is used to declare variables. Every variable must be declared before using it in C
program. Every variable are specified with their data type followed by a name. If there are more
variables of same data type then they must be separated by commas.
Execution part
Execution part contains program statements. There may or may not be a declaration part but there
must be an execution part. It includes input and output statements.
Sub program section
Sub program section consists of all user-defined functions. It is called from the main function. It is
placed before or after the main function. But generally placed after the main function.
The character set in C Language can be grouped into the following categories.
1. Letters 2. Digits 3. Special Characters 4. White Spaces
Alphabets
Letters Letters Digits
Upper Case A to Z Lower Case a to z 0 to 9
47
SATHISHKUMAR/MVIT/CSE
Special Characters
& .Ampersand # .Number Sign
' .Apostrophe < .Opening Angle (Less than sign)
* .Asterisk . .Period ( Dot )
@ At symbol % .Percentage Sign
\ .Backslash + .Plus Sign
^ .Caret ? .Question Mark
> .Closing Angle (Greater than sign) " .Quotation Marks
: .Colon } .Right Flower Brace
, .Comma ) .Right Parenthesis
$ .Dollar Sign ] .Right Bracket
.= Equal to ; .Semicolon
! .Exclamation Mark / .Slash
( .Left Parenthesis ~ .Tilde
[ .Left Bracket _ .Underscore
{ .Left Flower Brace | .Vertical Bar
Data Type is used to define the type of value to be used in a Program. Based on the type of value specified
in the program specified amount of required Bytes will be allocated to the variables used in the program.
Data types are broadly classified into four main types. They are as follows.
Data types
48
SATHISHKUMAR/MVIT/CSE
A) Integer Data Type
Integer data type can store only the whole numbers.
Name C Representation Size Range Format
(bytes) specifier
Integer int 2 -32768 to 32767 %d(%i)
Short Integer short int / short 2 -32768 to 32767 %d(%i)
Long Integer long int / long 4 -2147483648 to 2147483647 %ld
Signed Integer signed int 2 -32768 to 32767 %d(%i)
Unsigned Integer unsigned int 2 0 to 65535 %u
Signed Short Integer unsigned short int / short 2 -32768 to 32767 %d
Unsigned Short Integer unsigned short int / short 2 0 to 65535 %u
Signed Long Integer signed long int / long 4 -2147483648 to 2147483647 %ld
Unsigned Long Integer unsigned long int / long 4 0 to 4294967295 %lu
49
SATHISHKUMAR/MVIT/CSE
C) Character Data Type
Normally a single character is defined as char data type. It is specified by the keyword char. Char data type
uses 8 bits for storage. Char may be signed char or unsigned char.
Name C Representation Size Range Format
(bytes) Delimiter
Character Char 1 -128 to 127 %c
Signed Character signed char 1 -128 to 127 %c
Unsigned Character unsigned char 1 0 to 255 %c
a) Type definition(typedef)
It define a variable of existing data type. This variable can be used to declare variables of existing data type.
Syntax
typedef type identifier ;
where type refers to existing data type and identifier refers to the new name given to the existing data type.
Example:
typedef int marks;
marks s1,s2,s3;
b) Enumerated data type: It is a user defined data type, used to declare variables
Syntax:
enum identifier{variable 1 , variable 2 , ......... , variable n};
Here, identifier is the user-defined data type which can be used to declare variables
By default, the value of variable 1 is zero, value of variable 2 is one, value of variable 3 is two,etc.
The value of variables can also be changed by the user.
Example:
enum day{Monday=1,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday};
void is the empty data type. This data type is used before main function in a C Language. The word void
refers no return data type. It is used before the main function to specify the type of function. If a function is
of type void it does not return any value to the calling function.
50
SATHISHKUMAR/MVIT/CSE
6. EXPLAIN BRIEFLY ABOUT C TOKENS?
TOKENS
Among the group of text individual word, punctuation marks are called Tokens. It is a smallest individual unit in a C program. C has 6 types
of Tokens. They are
A. Keyword
B. Identifier TOKENS
C. Special symbols
D. Constant
Keyword Identifier Constant String Special Operators
E. String Symbol
F. Operators.
A. KEYWORDS
Every word in C language is a keyword or an identifier. Keywords in C language cannot be used as a
variable name. The compiler specifically uses them for its own purpose and they serve as building blocks of a c
program. There are 32 keywords in C language. The following are the Keyword set of C language.
auto double int Struct
break else long Switch
case enum register Typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof Volatile
do if static while
B. IDENTIFIERS
Identifier is a name given to program elements such as variables, functions, procedure, arrays and
soon. First character must be an Alphabet or Underscore. Identifier consists of sequence of letters, digits or
combination of both.
C. CONSTANT
Constant is a fixed value that doesn’t or does not change during the execution of a program. It
51
SATHISHKUMAR/MVIT/CSE
remains same throughout the program. Its value cannot be altered or modified in a program. A variable
is declared by the Keyword const.
Eg: const int a,b,c;
Constant is classified into three main types. They are described as follows.
1. Numeric Constant
2. Character Constant and
a. NUMERIC CONSTANT
Numeric Constant is further classified into two main types. They are
(i) Integer Constants and (ii) Real Constants
a) Integer Constants
Integer constant consist of sequence of digit without decimal point. It is normally a whole number.
Eg: 90, -46, 2000993, etc.
b) Real Constants
Real Constants are otherwise known as Floating Point Constants. Real Constant consists of decimal
number, exponent or combination of both. Real constant consist of two forms. They are Fractional form and
Exponential form.
eg: 9.0, 3.14, 8.005 e23 , etc
2) CHARACTER CONSTANT
Character Constant is categorized into
(i) Single character constant (ii) String constant
i. Single character constant
Any single letter inside a single codes (‘’) is a single character constant. The letter may be a alphabet or may be a
number or any symbols.
Eg: ‘y’,‘6’,’*’ etc.
ii. String constant
Anything inside the double codes (“”) is known as a string. It may be a group of character, single character, may
be a number or any symbols.
Eg: “hi how are you”, “amount:90.00”, “1”, etc
D. RESERVED WORD
Reserved words are inbuilt and have specific meaning. It is same as keywords. The reserved words used
in C language are as follows.
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while
E. VARIABLE
Variable is a name given to Memory location in which data is stored. Variable acts as value, which
52
SATHISHKUMAR/MVIT/CSE
changes during the execution of program. Variable may take different value at different times during execution.
Rules for Naming Variable:
1. Characters Allowed :
A. Underscore(_)
B. Capital Letters ( A – Z )
C. Small Letters ( a – z )
D. Digits ( 0 – 9 )
2. Blanks & Commas are not allowed
3. No Special Symbols other than underscore(_) are allowed
4. First Character should be alphabet or Underscore
5. Variable name Should not be Reserved Word
The general format of any declaration
datatype v1, v2, v3, ............. vn
where v1, v2, v3 are variable names. Variables are separated by commas. A declaration statement must end with
a semicolon.
Eg: int sum;
double average, mean;
F. VARIABLE ASSIGNMENT
It is another format of variable declaration. The general form is
data-type variable name [=value];
Here data type refers to the type of value used in the C program. Variable name is a valid name.
Square brackets [ ] denotes that the value may or may not be used or specified within the program.
Eg: int a; (or) int a=10;
Here if the value of a is assigned 10 the value remains the same throughout the program. If no value is
specified then the value keeps on changing.
53
SATHISHKUMAR/MVIT/CSE
o Variable is declared as constant by using the keyword or qualifier ‘const’ before the variable
name. This can be done at the time of initialization.
Eg: Const int class_size = 40;
Volatile Variable
A variable is volatile if the value gets changed at any time by some of the external sources.
Eg: volatile int num;
when we declare a variable as volatile the compiler will examine the value of the variable each time it is
encountered to see if an external factor has changed the value.
OPERATORS
Operator is a Symbol that tells or instructs the Compiler to perform certain Mathematical or
Logical manipulations (Calculations). Operators are used in a program to work on data and variables.
Operators in general form a part of Mathematical or Logical expression.
Operators are generally classified into different types. They are described one below another as
follows.
1. Arithmetic Operators (+,-,*,/,%)
2. Relational Operators (>,>=,<,<=,= =,!=)
3. Logical Operators (&&, ||, !)
4. Assignment Operators (=,+=,-=,*=,/=,%=,~=,<<=,>>=,&=,|=,^=)
5. Conditional Operator (?:)
6. Bitwise operators(~,&,|,^,<<,>>)
7. Increment and decrement operators (++,- -)
8. Unary operators(&,-,sizeof(),++,--)
1. ARITHMETIC OPERATORS
Arithmetic operators are used to perform Arithmetic operations. They form a part of program.
Programs can be written with or without operators. But calculations are performed only using
operators. Operators act along Operand to produce result.
Operator Meaning Details example
+ Addition Performs addition on integer numbers, floating point numbers. x+y
- Subtraction Subtracts one number from another. x-y
* Multiplication Used to perform multiplication x*y
/ Division It produces the Quotient value as output. x /y
% Modulo It returns the remainder value as output. x%y
Here x, y are known as operands. The modulus operator is a special operator in C language that
evaluates the remainder of the operands after division.
54
SATHISHKUMAR/MVIT/CSE
2. RELATIONAL OPERATOR
Relational Operators are used to compare two same quantities. There are six relational
operators. They are mentioned one below another as follows.
Operator Meaning Operator Meaning
< is less than >= is greater than or equal to
<= is less than or equal to == is equal to
> is greater than != is not equal to
The general form is
(exp1 relational operator exp2)
where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them.
Given below is a list of examples of relational expressions and evaluated values.
6.5 <= 25 TRUE -65 > 0 FALSE 10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C language such as if, while and
for statements to decide the course of action of a running program.
3. LOGICAL OPERATORS
Logical Operators are used when we need to check more than one condition. It is used to
combine two or more relational expressions. Logical Operators are used in decision making. Logical
expression yields value 0 or 1 i.e.,( Zero or One) . 1 indicates that the result of logical expression is
TRUE and 0 indicates that the result of logical expression is FALSE.
b) Logical OR ( || )
If any of the expression is true the result is true else false otherwise. The result is similar to basic Binary
55
SATHISHKUMAR/MVIT/CSE
addition.
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2
expressions is true.
Eg: a < m || a < n
It evaluates to true if a is less than either m or n and when a is less than both m and n.
c) Logical NOT ( ! )
It acts upon single value. If the value is true result will be false and if the condition is false the
result will be true. The logical not operator takes single expression and evaluates to true if the
expression is false and evaluates to false if the expression is true.
Eg: (!a)
4. ASSIGNMENT OPERATORS
The Assignment Operator evaluates an expression on the right of the expression and substitutes
it to the value or variable on the left of the expression. The general form is
identifier = expression Eg: x = a + b;
Here the value of a + b is evaluated and substituted to the variable x. ‘=’ equal to is used in Assignment
operators. It is of two types. They are
(i) Simple assignment operator
In Simple assignment operator only one ‘=’ equal to operator is used. It is used to assign a value to
variable or expression. The general form is
identifier = expression Eg: y=35; x=ax+b-c;
(ii) Shorthand assignment operator
Shorthand assignment operator must be an arithmetic operator or bitwise operator.
The general form is identifier <operator> = expression
The operator must be an arithmetic operator or bitwise operator.
Operator Meaning Example Example
Simp. Assign Shorthand
+= Assign sum x=x+1 x+ =1
-= Assign difference y=y-1 y-=1
*= Assign product z=z*(x+y) z*=(x+y)
/= Assign quotient y=y/(x+y) y/=(x+y)
%= Assign remainder x=x%z x%=z
~= Assignone’s
complement
<<= Assign left shift x = x << z x << = z
>>= Assign right shift
&= Assign bitwise AND y = y&x y&=x
|= Assign bitwise OR
^= Assign bitwise X - OR z = z^y z^=y
56
SATHISHKUMAR/MVIT/CSE
5. CONDITIONAL OPERATOR
Conditional Operator is also known as “Ternary operator”. The general form of Conditional Operator
is (exp1)?(exp2):(exp3);
where exp1 is the condition which is to be checked and exp2 is the true value and exp3 is the false
value. If the condition in exp1 is false then statement in exp3 will be automatically executed.
Eg:
#include<stdio.h> Output:
void main() Enter the value of a and b: 125 100
{ The biggest value is 125
int x,y,z;
clrscr(); Enter the value of a and b: 25 100
printf(“Enter the value of a and b :”); The biggest value is 100
scanf(“%d %d”,&x,&y);
z=((x>y)?x:y);
printf(“The biggest value is %d”,z);
getch(); }
6. BITWISE OPERATORS
Bit wise operator is used to manipulate with bits within a word of memory. Bit wise operator operates
only on integer and character but not on float and double.
Operator Meaning Operator Meaning
~ One’s Complement & Bitwise AND
<< Left shift | Bit wise OR
>> Right shift ^ Bit wise XOR
Truth table for AND, OR and XOR is
AND OR XOR
Input Output Input Output Input output
A B C A B C A B C
0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0
Bitwise AND (&)
Output of AND will be 1 if both inputs are at logic is 1.
For example :
A=4 and B=6 then A&B will be
A= 0000 0000 0000 0100
B= 0000 0000 0000 0110
A&B= 0000 0000 0000 0100 = 4
Bitwise OR (|)
Output of OR will be 1 if at least one of the input is 1.
For example:
A=7 and B=2 then A&B will be
A= 0000 0000 0000 0111
57
SATHISHKUMAR/MVIT/CSE
B= 0000 0000 0000 0010
A|B= 0000 0000 0000 0111 = 7
Bitwise XOR (^)
Output of XOR will be 1 if only if any one of the input is 1.
For example:
A=7 and B=2 then A&B will be
A= 0000 0000 0000 0111
B= 0000 0000 0000 0010
A|B= 0000 0000 0000 0111 = 5
58
SATHISHKUMAR/MVIT/CSE
Operator Meaning
- Unary minus (indicates negative numbers)
++ Increment by 1
-- Decrement by 1
sizeof() Return the size of the identifier (no. of bytes allocated)
& Address of operator
Eg:
-786 -0.64 -5e-8 -(a+b) -6*(f+b) -45.878
When operator is used before variable then it is prefix notation. When operator is used after variable
then it is postfix notation.
EXAMPLE: when X=3 Expression Result
++x 4
x++ 3
--x 2
x-- 3
9. SIZEOF OPERATOR
This operator is used to return the size of string or character. It cannot be used in together with Integers.
The syntax is
sizeof(variable-name);
Eg:
#include<stdio.h>
void main() Output:
{ The value of x is 2
int x;
clrscr();
printf(“The value of x is %d”,sizeof(x));
getch();
}
59
SATHISHKUMAR/MVIT/CSE
Finally Addition and Subtraction.
Precedence Operator Operation Associativity
level
1 () Function call Left to right
[] Array subscript Left to right
. Dot Left to right
→ Arrow Left to right
60
SATHISHKUMAR/MVIT/CSE
9. Describe the various input and output functions available in c?
61
SATHISHKUMAR/MVIT/CSE
%[..] Reads a string of word(s).
%X Reads a hexadecimal integer (Unsigned) using upper case A – F
%u Reads a unsigned integer.
%U Reads a unsigned long integer.
%p Reads a pointer value
%hx Reads hex short
%lo Reads octal long
%ld Reads long
Control String is followed by a prefix percentage (%) together with specific character.
Control string is also known as format string (or) format specifier.
Example:
For integer with d as value to be input %d. scanf (“%d %d”, &sum1, &sum2);
For character with c as value to be input %c. scanf (“%c %c”, &ch, &name):
b) printf()
This function is used to print Numerical values i.e.,(integer, float, double), single characters, strings or
combination of both. printf() function is used to redirect data from Computer’s memory to standard output
device. For float data type, number can be rounded to nearest decimal places.
The syntax of printf() is
printf(“control strings”, arg1, arg2, ....... , argn);
Control string consists of characters that will be printed on the screen. Escape sequences and Format
specification can be used together with the control string. Format specification is used to define the output
format for each item, which is being displayed. The format specifier and variable names should be in same
number.
Example Program :
#include < stdio.h >
main ( )
{
printf(“Hello!”);
printf(“Welcome to the world of Engineering!”);
}
Output:
Hello! Welcome to world of Engineering.
62
SATHISHKUMAR/MVIT/CSE
operator (&) is separated by commas. their name and separated by commas.
2. Unformatted Functions
These work only with the character data types. It does not require format specifier.
getchar()
The getchar function can be used to read a character from the standard input device. It reads
only alphabets from the user. It stores the value to the variable when user hits the enter key. The syntax
of getchar() is
variable_name = getchar();
Here variable name is a valid name of type char.
Example program
# include < stdio.h > // assigns stdio.h header file to your program
void main ( ) // Indicates the starting point of the program.
{
char C; // variable declaration
printf (“Type one character:”) ; // message to user
C = getchar () ; // get a character from key board and Stores it in variable C.
printf (” The character you typed is = %c”, C) ; // output
}
Output:
Type one character: y
The character you typed is =y
getche()
This input function is used to read a alpha numeric character from the Input Unit i.e., Keyboard. The
syntax of getche() is
variable_name = getche();
Example program
# include < stdio.h > // assigns stdio.h header file to your program
void main ( ) // Indicates the starting point of the program.
{
char C; // variable declaration
printf (“Type one character:”) ; // message to user
C = getche () ; // get a character from key board and Stores it in variable C.
printf (” The character you typed is = %c”, C) ; // output
}
Output:
Type one character: y
The character you typed is =y
getch()
This input function is used to read a alpha numeric character from the Input Unit i.e., Keyboard. The
character is invisible in the output screen. The syntax of getch() is
variable_name = getch();
63
SATHISHKUMAR/MVIT/CSE
Example program
# include < stdio.h > // assigns stdio.h header file to your program
void main ( ) // Indicates the starting point of the program.
{
char C; // variable declaration
printf (“Type one character:”) ; // message to user
C = getch() ; // get a character from key board and Stores it in variable C.
printf (” The character you typed is = %c”, C) ; // output
}
Output:
Type one character:
The character you typed is =y
gets()
This input function is used to accept a string as Input from the user through the input device i.e.,
Keyboard. The function gets accepts the name of the string as a parameter, and fills the string with characters
that are input from the keyboard till new line character is encountered.
The gets function relieves the string from standard input device. The syntax of the gets function is
gets(str);
Here str is a string variable.
Example program (Involving both gets and puts)
# include < stdio.h >
void main ( )
{
char s[80];
printf (“Type a string less than 80 characters:”);
gets(s);
printf (“The string typed is:”);
puts(s);
}
Output:
Type a string less than 80 characters: India is my country
The string typed is: India is my country
putchar()
This function prints a single character on the standard output device called Monitor. This function has a
single character as argument. This character is specified within single quotes. The syntax of putchar() is
putchar(variable-name);
Here variable name is of type char and it contains of single character.
Eg:
#include < stdio.h > // Inserts stdio.h header file into the Pgm
void main ( ) // Beginning of main function.
{
char in; // character declaration of variable in.
printf(” please enter one character”); // message to user
64
SATHISHKUMAR/MVIT/CSE
in = getchar ( ) ; // assign the keyboard input value to in.
putchar(in); // out put ‘in’ value to standard screen.
}
putch()
This function is used to write a single character from the input unit. It displays single character in the
Monitor as output. Its syntax is
putch ( variable name);
puts()
This function is used to display a string as output to the Output unit. Its syntax is
puts (str);
clrscr()
This function is used together in a program. It is mentioned below variable declaration and above
program statements. It helps to clear or remove the previously loaded values on the screen. Due to this
whenever we run the program the previously run program results will not appear.
10. Discuss the various Escape Sequence characters in C.
C supports some special backslash character constants that are used in output functions. For example the
symbol ‘\n’ stands for newline character. Each one of them represents one character, although they consist of
two characters. These characters combinations are known as escape sequences.
QUESTION BANK
PART A UNIVERSITY QUESTIONS
1. Define data type? Give Example of different data types? (May 2016)
2. What is pseudo code? (May 2016) (Jan 2014) (May 2015)
3. What are the benefits of Pseudo code? (April 2016)
4. Write any four Escape sequence in C? (April 2016)
65
SATHISHKUMAR/MVIT/CSE
5. What are the characteristics of an algorithm? (Jan 2016)
6. Distinguish between logical and bitwise operators (Jan 2016)
7. What are the basic symbols used in flowchart? (Jan 2016)
8. Write pseudo code for swapping two numbers using Temporary variable. (Jan 2016)
9. What are bitwise operators? (May 2015)
10. How does pseudo code differs from algorithm? (May 2015)
11. Define flowchart and state the guidelines for preparing the flowchart. (May 2015)
12. Draw a simple flowchart to find the sum of 5 numbers (Jan 2015)
13. Explain about void type? (Jan 2014)
14. What are the logical operators available in C? (May 2013)
15. What are the process of compiling and running a C program? (May 2013)
16. Write the use of #define? (Jan 2013)
17. What is the conditional operator? (Jan 2013)
18. What is flowchart? (May 2012)
19. What is Expression? (May 2012)
20. What are the benefits of flowchart? (May 2011)
66
SATHISHKUMAR/MVIT/CSE
UNIT-3
BRANCHING STATEMENTS
This statement executes the given condition based on the logical test. It performs two
actions based on the result. The final result of the statement may be true or false. Some of
the conditional execution statements are given below:.
Simple IF statement
IF…ELSE statement
Nested IF…ELSE statement
IF ELSE IF LADDER statement
Switch statement
SIMPLE IF STATEMENT
If statement is used in decision making execution. The condition part should not end
with a semicolon.
The If structure has the following syntax
if(condition)
{
Statement(s);
}statement-x;
If statement executes if the given condition is true otherwise it does not produces
any output. If the condition is true statement will be executed otherwise the statement is
skipped to statement-x.
Example program:
67
SATHISHKUMAR/MVIT/CSE
Computer Programming MVIT, Puducherry
if(condition)
Condition
{ True False
true statements;
}
else
True Stmt
{ False Stmt
false statements;
Statement-x
}
statement-x;
68
SATHISHKUMAR/MVIT/CSE
Computer Programming MVIT, Puducherry
In these statement both if part and else part will not be executed at the same time.
Either anyone of the both will be executed during run time.
Cond1
SATHISHKUMAR/MVIT/CSE
Computer Programming MVIT, Puducherry
{ 45 69 78
if(a>c)
printf(“%d is biggest\n”,a);
else
printf(“%d is biggest\n”,c);
}
else
{
if(c>b)
printf(“%d is biggest\n”,c);
else
printf(“%d is biggest \n”,b);
}
getch();
}
70 | P a g e
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
IF ELSE IF LADDER
If multiple decisions are involved in if statement elseif ladder is used. Here condition1
is checked first. If it is true statement1 will be executed. Otherwise it checks for condition2.
If condition2 is true statement2 will be executed. Otherwise it checks for condition-n and
statement n will be executed. If all of the given condition becomes false then statement-x will
be executed. The General form of elseif statement is as follows.
if(condition1)
statement1;
Cond1
elseif (condition2)
statement2; Stmt1 Cond2
elseif (conditon3)
Stmt2
Cond3
statement3;
Condn
………………… Stmt3
Stmt-n Stmt-x
elseif (condition n)
statement-n;
Next stmt
else
statement-x;
Exit
Next stmt
Example Program:
#include<stdio.h>
void main()
{
int day;
clrscr();
printf(“enter a number between 1 to 7\n”);
scanf(“%d”,&day);
if(day= =1)
printf(“monday\n”);
else if(day= =2)
printf(“tuesday\n”);
else if(day= =3)
71 | P a g e
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
printf(“wednesday\n”);
else if(day= =4)
printf(“thursday\n”);
else if(day= =5)
printf(“friday\n”);
else if(day= =6)
printf(“saturday\n”);
else if(day= =7)
printf(“sunday\n”);
else
printf(“enter a correct number\n”);
getch();
}
72 | P a g e
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
switch(expression)
{
case 1:
statement;
break;
case 2:
statement;
break;
…………
default:
statement;
}
73
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
break;
case4:
printf(“Quotient is %d”,a/b);
break;
default:
printf(“Invalid choice”);
}
getch();
}
Output:
Enter two numbers :
9
5
Sum is 14
difference is 4
Product is 45
Quotient is 1
----------------------------------------------------------------------------------------------------------------
LOOPING STATEMENTS
The process of executing a statement (or) group of statement repeatedly until a
particular condition is satisfied is called Looping.
Loop is nothing but the part of a program code that execute repeatedly is called Loop. There
are three types of Looping statements. They are
Loop
75
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
WHILE LOOP
while(test condition)
{
statement(s);
}
while statement executes only if the given condition is true. While loop is also called
entry-controlled loop. Entry-controlled loop also known as pre-test.
76
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
}
getch();
}
DO WHILE LOOP
In do..while loop , statement is executed first then the condition is checked. If the
given condition is not true at-least one statement will be definitely executed. If the
condition is true then the while loop will be executed.
The syntax of the do while loop is:
do
{
statement;
}
while(expression);
do-While loop is also called exit-controlled loop. Entry-controlled loop also known as post-
test.
Example program for generating ‘N’ Natural numbers using do-while loop:
# include<stdio.h >
Output :
#include<conio.h>
Enter the upper limit number 5
void main()
1 2 3 4 5
{
int n, i=1;
clrscr();
printf(“Enter how many numbers you want”);
scanf(“%d”, &n);
77
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
do
{
printf(“%d\t”,i);
i++;
} while(i < = n);
getch();
}
FOR LOOP
The for loop is an Entry Controlled Loop. It is a pre test.
The syntax of FOR loop is shown below:
Flowchart
initialise
Test
condition Exit of the loop
increment/
decrement
Here initialization is done in the beginning of the for loop. Test condition is the place
where the given condition is being checked. If the condition is true it executes body of the
loop and then the value gets incremented/decremented, the body of the loop gets executed
repeatedly untill the condition became false. If the condition became false it exits the loop.
Condition is checked every time using the increment/decrement value.
For loop example program:
# include<stdio.h >
Output :
#include<conio.h>
Enter the upper limit number 5
void main()
1 2 3 4 5
78
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
{
int n, i;
clrscr();
printf(“Enter how many numbers you want”);
scanf(“%d”, &n);
for(i=1;i<=n;i++)
{
printf(“%d\t”,i);
}
getch();
}
//Pascaline Triangle
#include<stdio.h>
Output:
#include<conio.h> *
void main( ) **
***
{ ****
int i,j; *****
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“*”);
}
printf(“\n”);
}
79
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
getch();
}
----------------------------------------------------------------------------------------------------------------
GOTO Statement
GOTO statement is used to transfer the control from one part of the program to
other ,with the use of label.
The syntax is given below:
goto label;
where label is an identifier.
Example program
#include<stdio.h>
Output:
void main()
{ I/P and O/P
Enter the Age: 18
int age;
You are Eligible to vote
clrscr();
I/P and O/P
printf(“Enter the Age :”);
Enter the Age : 10
scanf(“%d”,&age); You are not Eligible to vote
if(age>=18)
{
goto m;
}
else
{
printf(“\n You are not Eligible to vote:”);
80
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
exit();
}
BREAK STATEMENT
Break statement is used to terminate the control from one place to another in a
program. Break statement exits only single loop. Hence it is used together with the statements
wherever necessary.
It is also used to exit from a loop. A break causes the innermost enclosing loop or
switch to be exited immediately. It is also used together with while, dowhile, for and switch
statement.
Note: you can write any program with switch case which also involves break as
example.
/* A program to find the average of the marks*/
#include < stdio.h >
#include<conio.h>
void main()
{
int i=1;
while(i<20)
{
printf(“\t %d”,i);
if(i= =10)
break;
i++;
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10
81
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
CONTINUE STATEMENT
It is used to continue the process. Here keyword continue is used together within a
statement. This statement is specified after the condition. The continue statement causes the
loop to be continued with the next iteration after skipping any statement in between.
/* A program to find the average of the marks*/
#include < stdio.h >
#include<conio.h>
void main()
{
int i=1;
while(i<11)
{
printf(“\t %d”,i);
if(i= =10)
continue;
i++;
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 11
----------------------------------------------------------------------------------------------------------------
12. Explain string library functions (or) string handling functions (or) string operations in
detail with examples
String is a sequence of characters enclosed within a double quotes.
1. strlen() – It is used to find the length of a string.
82
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
STRINGS:
A string is a sequence of character that is treated as a single data item. A string is
declared using an array and represented within “ “ (double quotation). The compiler can
automatically adds a null character (‘\0’) at the end of the string to indicate the end of the
string.
Eg: “Computer Science”
C O M P U T E R S C I E N C E \0
Initialization:
1. Compile time
2. Run time
Compile time:
Char city[10]=”chennai”;
Run time:
i) Strcat()
String concatenation is the process of joining two strings together.
Syntax: strcat (str1, str2);
Eg: str 1= good
str 2 = evening
strcat (str 1, str 2);
ii) Strcmp()
It is used to compare two strings and
83
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
v) String reverse():
Strrev() is used to reverse a string
Syntax: strrev (string)
Eg: str= abc
strrev (str)
84
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Now,
Str= cba
Output:
Enter 2 srtings
good
day
string 1 = good
string 2 = day
after concatenation, string 1 = good day
string 2 = day
string 3 = day
reversed string = yad
day & yad not a palindrome
string 1 length = 7
string 1 in upper case GOOD DAY
string 1 in lower case good day
----------------------------------------------------------------------------------------------------------------
STORAGE CLASS:
The storage class of an identifier is used to determine where the variable must be saved,
life time. The default storage class is auto.
Storage class Storage place Initial value Lifetime of Linkage
specifier variable
86
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
{
auto int a,b,c;
a=10;
b=20;
c=a+b;
printf(“\n sum=%d”,c);
getch();
}
2. register storage class
register variables are stored in registers instead of main memory. These variables
can be accessed faster as they are stored in registers. They have local life time.
Eg:
#include<stdio.h>
#include<conio.h> output:
void main() sum=30
{
register int a,b,c;
a=10;
b=20;
c=a+b;
87
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
printf(“\n sum=%d”,c);
getch();
}
3. Static
These variables have global lifetime. The value of static variable will not change
between the function calls. These variables will be stored in main memory. If a static
variable presents inside a local scope it will not be reinitialized even if the program
control reenters the block in which the variable is declared.
Example program:
#include<stdio.h>
#include<conio.h>
output:
void main()
at execution no 1 a=10
{
value after increment a=11
int i;
at execution no 2 a=11
fun(i);
value after increment a=12
fun(i);
}
void fun(int i)
{
static int a=10;
printf(“\n at execution no %d a=%d”,i,a);
printf((“\n value after increment %d”,++a);
}
In the above program the value of a does not change between the function calls.
4. Extern:
Variables declared in global scope are extern by default. The initialization is possible
only if the declaration is done in global scope. It cannot be initialized at local scope
and it uses external linkage.
Example program:
#include<stdio.h>
88
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
#include<conio.h>
output:
void main()
a=100
{
ectern int a;
porintf(“\n a=%d”,a);
}
----------------------------------------------------------------------------------------------------------------
Arrays
An array is collection of homogeneous and logically related data items stored in successive
memory locations.
Types: 1-D Array
Array
Multidimensional array
Properties:
Arrays are stored in continuous memory locations
All the elements of an array share the same variable name and identified with the help of
element number.
It can store only homogeneous data elements
89
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
90
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
for(i=0;i<n;i++) 12
{ 20
30
scanf(“%d”,&a[i])
40
sum=sum+a[i];
sum=102
}
printf(“\n sum=%d”,sum);
getch();
}
M[i][j]
The above table has 3 rows and 3 columns. So it can be represented as M[3][3].
For matrix addition and subtraction first matrix row, column and second matrix row,
column should be the same.
For matrix multiplication, first matrix column and second matrix row must be equal.
Example program:
PROGRAM
#include<stdio.h>
91
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
#include<conio.h>
void main()
{
int n,i,j,a[3][3],b[3][3],c[3][3],m,k;
clrscr();
printf("Enter the order square matrix");
scanf("%d ",&m);
printf("\n Enter the Matrix A");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\n Enter the Matrix B");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("Matrix Multiplication\n");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
c[i][j]=0;
for(k=0;k<m;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
92
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
}
printf("\t%d",c[i][j]);
}
printf("\n");
}
getch();
}
Output:
Enter the order of aquare matrix 2
Enter the Matrix A
2 2 2 2
Enter the Matrix B
3333
Matrix Multiplication
12 12
12 12
MULTI-DIMENSIONAL ARRAY
Multi-dimensional Array consists of (or) requires more than two square brackets and
it may contain any number of values specified within square brackets. It may be three, four,
five, six and so on. A Multi dimensional Array in general takes the following form.
93
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
num[0][2][1]=5;num[1][0][0]=6;num[1][0][1]=7;num[1][1][0]=8;num[1][1][1]=9;
num[1][2][0]=10;num[1][2][1]=11;
Example:
int table[2][3]={0,0,0,1,1,1}; ( or ) int table[2][3]={{0,0,0},{1,1,1}}
int survey[3][5][12]; float table[5][4][5][3];
#include <stdio.h>
void main()
int i, j, k, test[2][3][2];
scanf("%d", &test[i][j][k]);
printf("\nDisplaying values:\n");
94
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
printf("test[%d][%d][%d] = %d\n", i, j, k,
test[i][j][k]);
getch();
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
95
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
----------------------------------------------------------------------------------------------------------------
Recursion:
A function calling itself repeatedly again and again until some specified condition is satisfied is
called as recursion.
Advantages:
Reduces the complexity of the program
Increases reusability
96
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
{
if(k = = 0 | | k = =1)
{
return 1
}
else
{ Output:
} 5
97
SATHISHKUMAR/MVIT/CSE
SHORT NOTES
UNIT-1
1. Describe the classification of computers.
Types of computer
98
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
i) Super computer:
It has a tremendous processing speed, memory than all othercomputers.
Speed is measured in trillions of instructions per second.
Size of the computer is very large and also very expensive
Application=>used in scientific and research labs, government organizations, weather
forecasting, animation purpose in hollywood movies etc.
99
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Hardware refers to all visible devices that are assembled together to build a computer
system.
These include various Input devices, Central Processing Unit, Output devices
BASIC ORGANIZATION OF COMPUTER:
Control Unit
Arithmetic
and Logic
Unit
1. INPUT UNIT:
It consists of one or more input devices like keyboard,mouse,Light pen, Joysticketc.
Keyboard is the most commonly used input device
Functions:
Accepts data or instructions from the outside world
Convert it into a form that the machine can understand
Supply the converted data for further processing
2. CPU:
It is called brain of computer system(Since all operations are done here)
Functions:
It performs all calculations and all decisions
It controls and co-ordinates all units of computer
It interprets the instructions of a program
It stores data
CPU is subdivided into
a) Control Unit(CU):
Instructs how to carry out program instructions
100
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
3. OUTPUT UNIT
It provides the result of computation(or) calculation
It also converts the result in binary data to the form that the user can understand
Some of the output devices are Monitor/Visual Display Unit(VDU), Printer, Plotter
etc.
2. Software
101
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
102
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
FormulasAutosumaverage and type total/3 .Click and drag to find the average of
all students.
To create a chart, select the required columns and click Insert column or pie or bar to
insert a chart.
4. Write the steps involved in preparing a pay slip for employees using worksheet.
To open a worksheet, Click startall programsMicrosoft officeMicrosoft Excel
To create a employee payroll, click on any one of thecell.
Enter the fields eno, name, Basic Pay(BP), DA, HRA, Netpay. Consider DA=10% of
BP, HRA=5% of BP.
Enter the eno, name of 5 employees and enter their Basic Pay.
To find the DA of 1st employee type =(10/100)*BP and press enter. Move the mouse
cursor at the bottom most corner of cell and click and drag the cell to calculate the DA
of other employees.
To find the HRA of 1st employee type =(5/100)*BP and press enter. Move the mouse
cursor at the bottom most corner of cell and click and drag the cell to calculate the DA
of other employees.
Net pay of the employee is calculated by adding BP,DA and HRA, which can be done
by the function SUM
To create a chart, select the required columns and click Insert column or pie or bar to
insert a chart.
5. State and explain the applications of computers.
Application Uses of computer
1. Business organizations Computers are used in maintaining employee
information, payroll calculation, budgeting, maintenance
of stocks etc.
2. Banking Computers are used in banks for online enquiry of
customer’s balance, deposit, updating the balance.
It also helps to withdraw money from ATM
3. Education Computers are used in education purpose in school,
colleges. It is used by students in doing projects
,learning. It is used by teachers to prepare ppt, report
card,etc. It is also used in library to keep track of books
and customer details.
103
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
104
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
7. Explain internet and its services. (OR) Explain application of internet and intranet.
Internet:
Network of networks is called Internet.(OR) Interconnection of networks is called
internet
Internet Services (or) Internet applications:
world wide web(www)
Electronic mail(E-mail)
File Transfer Protocol(FTP)
Telnet
Ecommerce
Newsgroups(Usenet)
Instant messaging
INTRANET:
An intranet is a private network that uses Internet Protocol(IP) to securely share
organization's information within that organization.
105
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
COMPUTER PROGARMMING
2 MARKS
It is used to accomplish specific tasks rather than System software are directly responsible for
just managing a computer system. controlling, integrating, and managing the
individual hardware components of a computer
system.
Artificial intelligence: It refers to a series of related technologies that tries to simulate and
reproduce human behaviour, including thinking, speaking and reasoning
106
SATHISHKUMAR/MVIT/CSE
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
3. reliability
4. storage capacity
5. resource sharing
Applications Of Computers
1. Banking
2. Entertainment
3. Medicine and healthcare
4. Education
5. Science
6. Research
107
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Reading and writing data are usually done sequentially, but in some cases only a part
of the file should accessed. It is called as File Random Access. It is done using
ftell()- returns the current position of file pointer
fseek()- defines where the file pointer must move
rewind()- file pointer moves back to beginning of
the file
9. What are the different ways to open a file? ?(modes for opening a file used in
fopen()) The three ways used to open a file are
W- Write
R- read
A- Append
10. Define preprocessor directives with an example and its advantages?
Preprocessor directive is a program that processes the source code before it passes through
the compiler.
It usually starts with # and no semicolon will be used.
Eg: # define pi 3.14
Advantages:
o Preprocessors increases readibility o These statements includes the external
files needed to the program o It uses to define macro constrains whose values
cannot be changed through out the program
fseek() ftell()
defines where the file pointer must move returns the current position of file pointer
15. Define pointers and this pointer? Its uses and advantages?
Pointer: Pointer is variable which is used to store the address of another variable. It is of
derived datatype.
This Pointer: this is keyword used to represent an object that invokes the member function. It
points to the object for which this function was called. It is automatically passed to a member
function when it is called
Uses and Advantages:
1. It reduces complexity of the program
2. Pointers allow dynamic memory management
3. Pointers are used to return multiple value from a function
4. Pointers increase execution speed.
23. What are the rules for naming an identifier? (same forvariable)
1. First character must be an alphabet or underscore
2. It must consist of only alphabets or digits or underscore
3. Keywords cannot be used
4. It must not contain any white space
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
…
.
.
…..
}
User defined function
{
……
…….
}
Advantages:
• Reduces the complexity of the program
• Increases reusability
Break continue
Break statement is used to jump out of a loop instantly Continue statement is used to take the control to the
without checking condition beginning of the loop to continue next iteration by
skipping the remaining parts in the current iteration only
Page 111
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
28. Define array, types and its properties?An array is collection of homogeneous and
logically related data items stored in successive memory locations. Types: 1-D Array
2-D Array
Multidimensional array
Properties:
• Arrays are stored in continuous memory locations
• All the elements of an array share the same variable name and identified with the help
of element number.
• It can store only homogeneous data elements
Advantages:
• Function provides reusability
• User defined functions can be used in many other source programs when
necessary
• Easy to locate and debug error
• Complex programs can be divided into smaller programs
Types:
• with return value and with arguments
• with return value and without arguments
• without return value and with arguments
• without return value and without arguments
Command line arguments are parameters supplied to a main function from the
command line when the program is executed.
argc- argument count
argv- argument vector
eg: void main(int argc, char *argv[]);
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
PROGRAMS
1. SEARCHING
#include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
int x[100],i,no,search; enter how many nos you want
printf(“\n enter how many nos you 5
want“); enter the numbers
56
scanf(“%d”,&no); 98
printf(“\n enter the numbers”); 14
for(i=0;i<no;i++) 37
scanf(“%d”,&x[i]); 84
printf(“\n enter search number”); enter search number 37
scanf(“%d”,&search); 37 is found at 4 position
for(i=0;i<no;i++)
{
if(search==x[i])
break;
}
if (search==x[i])
printf(“%d is found at %d position”,search,++i);
else
printf(“\n searched number not found “);
getch();
}
------------------------------------------------------------------------------------------------- -------------
2. SORTING
include<stdio.h>
#include<conio.h>
void main()
{
int x[100],i,no,search;
printf(“\n enter how many nos you want“);
scanf(“%d”,&no);
printf(“\n enter the numbers”);
for(i=0;i<no;i++)
scanf(“%d”,&x[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
if(x[i]>x[j])
{
t=x[i]; OUTPUT:
x[i]=x[j]; enter how many nos you want
x[j]=t; 5
}}} enter the numbers
printf(“\n ascending order”); 56
for(i=0;i<n;i++) 98
printf(“\n %d”,x[i]); 14
printf(“\n descending order”); 37
for(i=n-1;i>=0;i--) 84
printf(“\n %d”,x[i]); ascending order
getch(); 14
} 37
56
84
98
descending order
98
84
56
37
14
------------------------------------------------------------------------------------------------- -------------
{
return k* fact(k-1);
}
}
--------------------------------------------------------------------------------------------------------------
4. FIBONACCI SERIES
#include<stdio.h>
#include<stdio.h>
void main()
{
int n, first = 0, second = 1, next, c;
printf("enter the number of terms\n");
scanf("%d",&n);
printf("first %d terms of fibonacci series are :-\n",n);
for ( c = 0 ; c < n ; c++ )
{ OUTPUT:
if ( c <= 1 ) enter the number of terms
next = c; 5
else first 5 terms of fibonacci series are
{ :-
next = first + second; 0
first = second; 1
second = next; 1
} 2
printf("%d\n",next); 3
}
getch();
}
--------------------------------------------------------------------------------------------------------------
{
int x,y;
x= x+y;
y= x-y;
x= x-y;
printf(“\n swap function x=%d \t y=%d”, x,y);
return 0;
}
o/p screen:
before swap a= 50 b= 20
swap function x= 20 y= 50
after swap a= 50 b= 20
CAL BY REFERENCE
#include<stdio.h>
#include<conio.h>
void swap (int *x, int* y);
void main()
{
int a= 100, b=200;
printf(“\n before swap, a=%d \t b=%d”, a,b)
swap(&a, &b);
printf(“\n after swap, a=%d \t b=%d”,a,b);
getch();
}
void swap (int*x, int*y)
{
*x = *x+*y;
*y = *x-*y;
*x = *x-*y;
printf(“\n in swap function a=%d \n b=%d”,*x,*y);
}
O/P SCREEN:
before swap a= 100 b= 200
in swap function a= 200 b=100
after swap a= 200 b=100
--------------------------------------------------------------------------------------------------------------
6. PALINDROME
#include<stdio.h>
#include<conio.h>
#include<string.h>
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
7. SUM OF N NOS
#include<stdio.h>
#include<conio.h>
void main()
{ OUTPUT:
int n,i,sum=0 ; enter n value:
printf("enter n value:"); 5
scanf("%d",&n); the sum of number upto 5 is 15
for(i=1;i<=n;i++)
{
sum =sum+i;
}
printf ("the sum of number upto %d is %d", n,sum);
getch();
}
--------------------------------------------------------------------------------------------------------------
void main()
{ struct student
{
int rollno;
char name[25];
int totalmark;
}stud[100];
int n,i;
clrscr();
printf("enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter details of no.%d student\n",i+1);
printf("name:\n");
scanf("%s",&stud[i].name);
printf("roll number:\n");
scanf("%d",&stud[i].rollno);
printf("total mark:\n");
scanf("%d",&stud[i].totalmark);
}
printf("students details:\n");
printf(“********************\n\n”);
for(i=0;i<n;i++)
{
printf("\nroll number:%d",stud[i].rollno);
printf("\nname:%s",stud[i].name);
printf("\ntotal mark:%d",stud[i].totalmark);
printf(“\n*********************”);
}
getch();
}
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
.OUTPUT:
enter total number of students
1
enter details of no 1 student
name: arun
roll number: 09
total mark: 890
students details:
name: arun
roll number: 09
total mark: 890
--------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,choice;
clrscr();
printf(“enter two numbers : ”);
scanf(“%d%d”,&a,&b);
printf(“\n enter 1 for addition :”);
printf(“\n enter 2 for subtraction :”);
printf(“\n enter3 for multiplication :”);
printf(“\n enter 4 for division :”);
printf (“\n enter your choice :”);
scanf(“%d”,&choice :”);
switch (choice)
{
case1:
printf(“sum is %d”,a+b );
break;
case2:
printf(“difference is %d”,a-b);
break;
case3:
printf(“product is %d”,a*b);
break;
case4:
printf(“quotient is %d”,a/b);
break;
default:
printf(“invalid choice”);
}
getch();
}
OUTPUT:
enter two numbers :
9
5
sum is 14
difference is 4
product is 45
quotient is 1
--------------------------------------------------------------------------------------------------------------
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
11. PRIME NO
11.a) to find whether entered number is prime
#include <stdio.h>
void main()
{
int n, i, flag = 0;
printf("enter any number: ");
scanf("%d",&n); OUTPUT:
for(i=2; i<=n/2;i++) enter any number:
{ 6
if(n%i==0) 6 is not a prime number
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
}
--------------------------------------------------------------------------------------------------------------
getch();
}
OUTPUT:
enter how many prime numbers you want to print: 5
the prime numbers are 2
3
5
7
11
--------------------------------------------------------------------------------------------------------------------------
--
12. MATRIX MULTIPLICATION
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,a[3][3],b[3][3],c[3][3],m,k;
clrscr();
printf("enter the order square matrix");
scanf("%d ",&m);
printf("\n enter the matrix a");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
printf("\n");
}
printf("\n enter the matrix b");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&b[i][j]);
}
printf("\n");
}
printf("matrix multiplication\n");
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
c[i][j]=0;
for(k=0;k<m;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
}
printf("\t%d",c[i][j]);
}
printf("\n");
}
getch();
}
OUTPUT:
enter the order of square matrix 2
enter the matrix a
2 2 22
enter the matrix b
3333
matrix multiplication
12 12
12 12
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
Computer Programming Manakula Vinayagar Institute of Technology, Puducherry
UNIVERSITY PART-A QUESTIONS
Unit- 1
1. Compare application software and system software.
2. Write the uses of word processing software.
3. Define operating system.
4. Define the characteristics of fourth generation computers.
5. What is Artificial intelligence?
6. Write any 5 applications of computers.
7. What are the different types of Internet connection?
8. Define System Software. +3
9. What is work sheet?
10. List the components of the computer.
11. Write the uses of Internet and its services.
12. What is word processor?
13. List some commonly used application software programs.
14. Distinguish between analog and digital computers.
15. What are different types of software?
Unit-2
1. What is a flowchart?
2. What is expression?
3. Give any two programming languages.
4. What is the purpose of type declaration?
5. Write the guidelines for preparing flowcharts.
6. What are the data types available in ‘C’ languages?
7. What are the benefits of flow chart?
8. What you mean by structural programming?
9. Write about increment and decrement operators.
10. What is the difference between = and ==?
11. Find the largest of two integers using ternary operator.
12. What is a pseudocode?
13. How does the pseudocode differs from the algorithm?
14. What are bitwise operators?
15. What is meant by operator precedence?
16. Draw a simple flowchart to find the sum of 5 numbers.
17. Write down the conditional operator equivalent for the following if statement
if(top==0)
return 1;
else
return 0;
18. What are input and output commands in C ? Give some examples.
19. What are the steps involved in running a C program?
20. What are the standard input and output devices in C? How can we use them?
21. What are the characteristics of an algorithm?
22. Difference between logical and bitwise operators.
23. What are the benefits of pseudocode?
24. Write any four escape sequences in C.
Unit-3
1. Define recursion.
2. Write a function to multiply two numbers.
3. How do you pass array to function?
4. Write the syntax of “for loop”.
5. What is the difference between call by value and call by reference?
6. Explain any two string functions in ‘C’ with example.
7. Define array and its characteristics.
8. What is meant by branching?
9. What is function prototype?
10. How is an array name interpreted when it is passed to a function?
11. What is the use of break statement?
12. State the advantages of the use of functions.
13. How does an array definition differ from an ordinary variable?
14. Explain the meaning of an auto variable.
15. What are the advantages of using function in C programs?
16. What is meant by looping?
17. What is a nested loop?
18. What is user defined data type?
19. Let A and B be two strings ”Rama” and “Ramu”. What will be the output of
strcmp(a,b)?
20. Distinguish between iterative and conditional statements in C.
21. What are local and global variables?
22. What is a null character? What is its use in a string?
23. Write any 4 features of arrays.
24. Define ternary operator. Give example.
25. How strings are represented in C language?
Unit-4
1. What is the use of pointer in C?
2. What is the use of structure in C?
3. What is union?
4. What do you mean by array of pointers?
5. How union is different from structures? +2
6. Write the syntax of declaration and initialization of structures.
7. Define a structure for storing a Date.
8. What is a “this” pointer?
9. What is pointer in C?
10. Explain parameter passing by reference?
11. Give an example where a structure data type may be required.
12. Consider a function:
Double add(float,float)
Write a simple C function pointer and statement to point to the above function.
13. Discuss the use of UNION declaration in C with an example.
14. Write a function called date_Update that takes a pointer to a date structure as its
argument and that update the structure to the following day.
Unit-5
1. Write the operations that can be performed on a file.
2. How will you test the end of file?
3. What are the file handling functions available in ‘C’?
4. Define fseek function. Give an example.
5. Define macro.
6. What are the different file mode operations available inC?
7. What is the primary advantage to use a data file?
8. What role does the fseek() plays?
9. Write the file type specifications used in fopen statement.
10. What are stream oriented data files?
11. Discuss the different ways of opening a file.
12. How can files be randomly accessed?
13. Difference between ftell() and fseek() functions.
14. When does a programmer use “#include” directive?
15. What is a preprocessor statement? Explain with an example.
16. List the commands for reading from and writing to file in C?
17. Give the advantages of the pre- processor.
18. List any four functions for File Operations.
19. Create a file myfile.txt in the directory /mydir and write the contents “Hello World ” in
the file.
20. Briefly discuss about the purpose of C pre processor.
21. Give the conditional preprocessing directives.
22. Write any 8 built-in functions for file manipulation.
11 mark
Unit-1
Unit-3
1. String library functions
2. Storage classes
3. Arrays
4. Functions( Function types and function prototype types)
5. Branching and looping
Unit-4
1. Structure (mostly structure program for student marks willcome)
2. Array of Structure
3. Structure within Structure (Nested Structure)
4. Structure to functions
5. Structure to pointers
Unit-5
Important Programs
1. Searching
2. Sorting
3. Factorial using recursion
4. Fibonacci series
5. Swapping 2 nos(using call by value and reference)
6. Palindrome
7. Sum of N nos
8. Create employee structure for calculating salary
9. Roots of quadratic equation
10. Simple calculator using switch and functions
11. Prime no
12. Matrix multiplication