0% found this document useful (0 votes)
49 views51 pages

Pop - Module 1

Uploaded by

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

Pop - Module 1

Uploaded by

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

I Semester

PRINCIPLES OF PROGRAMMING USING C


BPOPS103
Credits: 03
Scheme: 2022

Module - I

Course Instructor
Ms. Vishnupriya G M
Assistant Professor,
Dept. of CSE, EPCET
MODULE 1
1.1 Computer
 A computer can be defined as an electronic device that is designed to accept data, perform the
required mathematical and logical operations at high speed, and output the result.
 Computer is an electronic device, which takes input from the user in the form of data and instructions
 Once the computer receives the data, it waits for the user’s instructions to process the data.
 On receiving the instructions from the user, the computer processes the data and generates the output and
displays it to the user.
 The data that is given as an input to the computer can be text, numerals, audio, video and image etc
Tasks of the Computer:
• Input: Sending the data and command to the computer is known as input.
• Processing: Work done by the computer with the help of processing hardware and software to produce results is known
as processing.
• Output: The result displayed by the computer is called as output. • Storage: A place to save results inside or outside
the computer is known as storage.

Characteristics of Computers

Figure 1.1. Characteristics of computers

1. Speed
 Computers can perform millions of operations per second.
 The speed of computers is usually given in nanoseconds and picoseconds, where 1 nanosecond
= 1 × 10 −9 seconds and 1 picosecond = 1 × 10 −12 seconds.

2. Accuracy
 A computer is a very fast, reliable, and robust electronic device.
 It always gives accurate results, provided the correct data and set of instructions are input to it.
 This clearly means that the output generated by a computer depends on the given
instructionsand input data.
 If the input data is wrong, then the output will also be erroneous. In computer
terminology, this is known as garbage-in, garbage-out (GIGO).
3. Automation
 Besides being very fast and accurate, computers are automatable devices that can
perform a taskwithout any user intervention.
 The user just needs to assign the task to the computer, after which it automatically
controlsdifferent devices attached to it and executes the program instructions.

4. Diligence
 Computers never get tired of a repetitive task. It can continually work for hours without
creatingerrors.
 Even if a large number of executions need to be executed, each and every execution
requires thesame duration, and is executed with the same accuracy.
5. Versatile
 Versatility is the quality of being flexible. Today, computers are used in our daily life in
different fields.
 For example, they are used as personal computers (PCs) for home use, for business-
oriented tasks, weather forecasting, space exploration, teaching, railways, banking,
medicine, and so on, indicating that computers can perform different tasks simultaneous.

6. Memory
 Computers have internal or primary memory (storage space) as well as external or
secondarymemory.
 The computer stores a large amount of data and programs in the secondary storage space.
 The stored data and programs can be retrieved and used whenever required.
 Secondary memory is the key for data storage. Some examples of secondary devices
include floppy disks, optical disks (CDs and DVDs), hard disk drives (HDDs), and pen
drives.

7. No IQ
 Although the trend today is to make computers intelligent by inducing artificial
intelligence (AI) in them, they still do not have any decision-making abilities of their
own. They need guidance to perform various tasks.

8. Economical
 Today, computers are considered as short-term investments for achieving long-term
gains. Using computers also reduces manpower requirements and leads to an elegant and
efficient way of performing various tasks.
 Hence, computers save time, energy, and money. When compared to other systems,
computers can do more work in lesser time.
 For example, using the conventional postal system to send an important document takes
at least two to three days, whereas the same information when sent using the Internet (e-
mail) will be delivered instantaneously.

1.1.1 Generations of Computers


1. First Generation (1942–1955)
 Hardware Technology
First generation computers were manufactured using thousands of vacuum tubes.

 Memory
Electromagnetic relay was used as primary memory and
Punched cards were used to store data and instructions.
Software Technology
Programming was done in machine or assembly language.

Used for Scientific applications

Examples ENIAC, EDVAC, EDSAC, UNIVAC I, IBM 701


Highlights
They were the fastest calculating device.
Computers were too bulky and required a complete room for storage
Highly unreliable as vacuum tubes emitted a large amount of heat and burnt frequently.
Required air-conditioned rooms for installation
Costly
Difficult to use
Required constant maintenance because vacuum tubes used filaments that had
limited life time. Therefore, these computers were prone to frequent hardware
failures.

2. Second Generation (1955–1964)


Hardware Technology
Second generation computers were manufactured using transistors.
Transistors were reliable, powerful, cheaper, smaller, and cooler than vacuum tubes.

Memory
Magnetic core memory was used as primary memory;
Magnetic tapes and magnetic disks were used to store data and instructions.
These computers had faster and larger memory than the first generation computers.
Software Technology
Programming was done in high level programming languages. Batch operating
systemwas used.

Used for Scientific and commercial applications

Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC

Highlights
Faster, smaller, cheaper, reliable, and easier to use
They consumed 1/10th the power consumed by first generation computers
Bulky in size
Dissipated less heat than first generation computers
Costly
Difficult to use.

3. Third Generation (1964–1975)


Hardware Technology
Third generation computers were manufactured using integrated chips (ICs).
ICs consist of several components such as transistors, capacitors, and resistors
on asingle chip to avoid wired interconnections between components.
These computers used SSI and MSI technology. Minicomputers came into existence.
Memory
Larger magnetic core memory was used as primary memory; larger capacity
magnetictapes and magnetic disks were used to store data and instructions.

Used for Scientific, commercial, and interactive online applications.

Highlights
Faster, smaller, cheaper, reliable, and easier to use than the second generation computers
They consumed less power than second generation computers.
Bulky in size and required a complete room for installation
Dissipated less heat than second generation computers
Costly
Easier to use and upgrade.
Software Technology
Programming was done in high level programming languages such as
FORTRAN, COBOL, Pascal, and BASIC.
Time sharing operating system was used.
Software was separated from the hardware.

4. Fourth Generation (1975–1989)


Hardware Technology
Fourth generation computers were manufactured using ICs with LSI
(Large ScaleIntegrated) and later with VLSI technology (Very Large Scale
Integration).
Microcomputers came into existence.
Use of personal computers became widespread.
High speed computer networks in the form of LANs, WANs, and MANs
startedgrowing.

Memory
Semiconductor memory was used as primary memory; large capacity magnetic
diskswere used as built in secondary memory.
Magnetic tapes and floppy disks were used as portable storage devices.

Software Technology
Programming was done in high level programming language such as C and C++.
Graphical User Interface (GUI) based operating system (e.g. Windows) was
introduced. It had icons and menus among other features to allow computers to
be used as a general purpose machine by all users.
UNIX was also introduced as an open source operating system. Apple Mac OS
and MS DOS were also released during this period.
All these operating systems had multi-processing and multiprogramming capabilities.

Used for Scientific, commercial, interactive online, and network applications.

Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY1, CRAY-2, CRAY-X

Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the
previousgeneration computers.
5. Fifth Generation (1989–Present)
Hardware Technology
Fifth generation computers are manufactured using ICs with ULSI (Ultra Large
ScaleIntegrated) technology.
The use of Internet became widespread and very powerful mainframes,
desktops, portable laptops, and smartphones are being used commonly.
Supercomputers use parallel processing techniques.

Memory
Semiconductor memory is used as primary memory;
large capacity magnetic disks are used as built-in secondary memory.
portable storage devices like optical disks and USB flash drives are used
Software Technology
Programming is done in high-level programming languages such as Java,
Python, andC#.
Graphical User Interface (GUI)-based operating systems such as Windows, Unix,
Linux, Ubuntu, and Apple Mac are being used.
These operating systems are more powerful and user friendly than the ones
available inthe previous generations.

Used for Scientific, commercial, interactive online, multimedia (graphics, audio, video),
and network applications.

Examples IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2, Param supercomputer

Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the
previousgeneration computers.
Speed of microprocessors and the size of memory are growing rapidly.
High-end features available on the microprocessors
They consume less power than computers of prior generations.

1.2 Classification of Computers


 Computers can be broadly classified into four categories based on their speed, amount
of datathat they can process, and price:
Supercomputers
Mainframe computers
Minicomputers
Microcomputers
Figure : Classification of computers
Super Computers: The supercomputer is the fastest, most powerful, and most expensive computer.
 Process large amounts of data and to solve complex scientific problems.
 Supercomputers use parallel processing technology and can perform more than one
trillioncalculations in a second.
 A single supercomputer can support thousands of users at the same time.
 Such computers are mainly used for weather forecasting, nuclear energy research,
aircraft design, automotive design, online banking, controlling industrial units, etc.
1. Mainframe Computers
 Mainframe computers are large-scale computers (but smaller than supercomputers).
 These are very expensive and need a very large clean room with air conditioning, thereby
making them very costly to deploy.
 Support multiple processors.
 The two types of terminals that can be used with mainframe systems are as follows:
1. Dumb Terminals
 Dumb terminals consist of only a monitor and a keyboard (or mouse). They do not
have their own CPU and memory and use the mainframe system‘s CPU and storage
devices.
2. Intelligent Terminals:
 Intelligent terminals have their own processor and thus can perform some
processingoperations.
 Usually, PCs are used as intelligent terminals to facilitate data access and other services
fromthe mainframe system.
 Mainframe computers are typically used as servers on the World Wide Web.
 They are also used in organizations such as banks, airline companies, and universities,
where a large number of users frequently access the data stored in their databases.

3. Minicomputers
 Minicomputers are smaller, cheaper, and slower than mainframes.
 They are called minicomputers because they were the smallest computer of their times.
Also known as midrange computers.
 Minicomputers are widely used in business, education, hospitals, government
organizations, etc. While some minicomputers can be used only by a single user, others
are specifically designed to handle multiple users simultaneously.
 Minicomputers can also be used as servers in a networked environment.

4. Microcomputers
 Microcomputers, commonly known as PCs, are very small and cheap.
 Many computer hardware companies copied this design and termed their
microcomputers as PC-compatible.
 PCs can be classified into the following categories:
Desktop PCs, Laptops, Workstations, Network Computers and Handheld Computers.
(i) Desktop PCs A desktop PC is the most popular model of PCs.
(ii) Laptops: Laptops operate on a battery. The memory and storage capacity of a laptop
is almost equivalent to that of a desktop computer. laptops have the same features and
processing speed as the most powerful PCs.
(iii) Workstations: Workstation computers have advanced processors, more RAM and
storage capacity than PCs.
(iv) Network Computers: Network computers have less processing power, memory,
andstorage than a desktop computer. Some network computers do not have any storage
space and merely rely on the network‘s server for data storage and processing tasks
(v) Handheld Computers: Handheld computers are very small in size, and hence they
have small-sized screens and keyboards. Some examples of handheld computers are as
follows: Smartphones, Tablet PCs.
a. Smartphones: These days, cellular phones are web-enabled telephones. Such phones
are also known as smartphones because, in addition to basic phone capabilities, they also
facilitate the users to access the Internet and send e-mails, edit Word documents, generate
an Excel sheet, create a presentation, and lots more.
b. Tablet PCs: A tablet PC is a computing device that is smaller than a laptop, but bigger
than asmartphone. Features such as user-friendly interface, portability, and touch screen
have made them very popular in the last few years.
Uses The following are the uses of Tablet PCs:
• View presentations
• Videoconferencing
• Reading e-books, e-newspaper
• Watching movies
• Playing games
• Sharing pictures, video, songs, documents, etc.
• Browsing the Internet
• Keeping in touch with friends and family on popular social networks, sending emails
• Business people use them to perform tasks such as editing a document,
exchangingdocuments, taking notes, and giving presentations
• Tablets are best used in crowded places such as airports and coffee shops.

Applications of Computers
1. Word processing
 Word processing software enables users to read and write documents.
 Users can also add images, tables, and graphs for illustrating a concept.
 The software automatically corrects spelling mistakes and includes copy–paste features.

2. Internet
 The Internet is a network of networks that connects computers all over the world.
 It gives the user access to an enormous amount of information, much more than available
in anylibrary.
 Using e-mail, the user can communicate in seconds with a person who is located
thousands ofmiles away.
 Chat software enables users to chat with another person in real-time.
 Video conferencing tools are becoming popular.

3. Digital video or audio composition


 Computers make audio or video composition and editing very simple.
 Graphics engineers use computers for developing short or full-length films and
creating 3-Dmodels and special effects in science fiction and action movies.

4. Desktop publishing
 Desktop publishing software enables us to create page layouts for entire books.

5. e-Business
 e-Business or electronic business is the process of conducting business via the Internet.
 This may include buying and selling of goods and services using computers and the Internet.
 Companies today use e-commerce applications for marketing, transaction,
processing, andproduct and customer services processing.
Business-to-consumer or B2C: In this form of electronic commerce, business
companiesdeploy their websites on the Internet to sell their products and services to the
customers. On their websites, they provide features such as catalogues, interactive order
processing system, secure electronic payment system, and online customer support.
Business-to-business or B2B: This type of electronic commerce involves business
transactions performed between business partners (customers are not involved). For
example, companies usecomputers and networks (in the form of extranets) to order raw
materials from their suppliers. Companies can also use extranets to supply their products
to their dealers.
Consumer-to-consumer or C2C: This type of electronic commerce enables customers
to carry business transactions among themselves. For example, on auction websites, a
customer sells his/her product which is purchased by another customer.
Electronic banking Electronic banking, also known as cyber banking or online
banking, supports various banking activities conducted from home, a business, or on the
road instead of aphysical bank location.

6. Bioinformatics
 Bioinformatics is the application of computer technology to manage large amount of
biologicalinformation.
 Computers are used to collect, store, analyse, and integrate biological and genetic
information tofacilitate gene-based drug discovery and development.
 Bioinformatics is an interdisciplinary field of molecular biology, computer science,
statistics, and mathematics.

7. Health care
 Computers have also become a necessary device in the health care industry. The
following areareas in which computers are extensively used in the health care industry:
Storing records: computers are first and foremost used to store the medical records of
patients. Surgical procedures Computers are used for certain surgical procedures. They
enable the surgeon to use computer to control and move surgical instruments in the
patient‘s body for avariety of surgical procedures.
Better diagnosis and treatment Computers help physicians make better diagnoses and
recommend treatments.

8. Geographic Information System and Remote Sensing


 A geographic information system (GIS) is a computer based tool for mapping and
analysingearth.
 It integrates database operations and statistical analysis to be used with maps.
 Remote sensing is a sub-field of geography, which can be applied in the following areas
to collect data of dangerous or inaccessible areas for the following: Monitoring
deforestation, Studying features of glaciers, etc.

9. Meteorology
 Meteorology is the study of the atmosphere. Meteorology has applications in many
diverse fields. Some of the applications include the following:
 Weather forecasting It includes application of science and technology to predict the state
of the atmosphere (temperature, precipitation, etc.) for a future time and a given location.
 Aviation meteorology Aviation meteorology studies the impact of weather on air traffic
management.
 Agricultural meteorology Agricultural meteorology deals with the study of effects of
weather and climate on plant distribution, crop yield, water-use efficiency, plant and
animal development.
 Nuclear meteorology Nuclear meteorology studies the distribution of radioactive
aerosols and gases in the atmosphere. Maritime meteorology Maritime meteorology is
the study of air and wave forecasts for ships operating at sea.
 Multimedia and Animation Multimedia and animation that combines still images,
moving images, text, and sound in meaningful ways is one of most powerful aspects of
computer technology. We all have seen cartoon movies, which are nothing but an
example of computer animation.

10. Legal System


 Lawyers use computers to look through millions of individual cases and find whether
similar or parallel cases have been approved, denied, criticized, or overruled in the past.

11. Retail Business


 Computers are used in retail shops to enter orders, calculate costs, and print receipts.

12. Sports
 In sports, computers are used to compile statistics, identify weak players and strong
players by analysing statistics, sell tickets, create training programs and diets for athletes,
and suggest game plan strategies based on the competitor‘s past performance.

13. Travel and Tourism


 Computers are used to prepare tickets, monitor the train‘s or airplane‘s route, and guide
the plane to a safe landing.

14. Simulation
 Simulation of automobile crashes or airplane emergency landings is done to identify
potential weaknesses in designs without risking human lives.

15. Education
 A computer is a powerful teaching aid and can act as another teacher in the classroom.
Teachersuse computers to develop instructional material.

16. Industry and Engineering


 Computers are found in all kinds of industries, such as thermal power plants, oil
refineries, and chemical industries, for process control, computer-aided designing
(CAD), and computer-aided manufacturing (CAM).

17. Robotics
 Robots are computer-controlled machines mainly used in the manufacturing process in
extreme conditions where humans cannot work.

18. Decision Support Systems


 Computers help managers to analyse their organization‘s data to understand the present
scenario of their business, view the trends in the market, and predict the future of their
products.

19. Expert Systems


 Expert systems are used to automate the decision-making process in a specific area, such
as analysing the credit histories for loan approval and diagnosing a patient‘s condition
for prescribing an appropriate treatment.

Programming Tools: Algorithms, Flowcharts, Pseudocode


Algorithms:

 An algorithm provides a blueprint to writing a program to solve a particular


problem.
 It is considered to be an effective procedure for solving a problem in a finite
number of steps.
 A well-defined algorithm always provides an answer, and is guaranteed to
terminate.
 Algorithms are mainly used to achieve software re-use.
 A good algorithm must have the following characteristics
o Be precise
o Be unambiguous
o Not even a single instruction must be repeated infinitely
o After the algorithm gets terminated, the desired result must be obtained

Control Structures used in Algorithms


Sequence: Sequence means that each step of the algorithm is executed in the specified order.
Example: Algorithm to Add two numbers

Decision: Decision statements are used when the outcome of the process depends on
some condition. For example, if x=y, then print “EQUAL”. Hence, the general form of
the if construct can be given as if condition then process.
Example: Algorithm to test Equality of two number

Repetition: Repetition, which involves executing one or more steps for a number of times,
can be implemented using constructs such as while, do-while, and for loops. These loops
execute one or more steps until some condition is true.
Example: Algorithm to print first 10 Natural numbers

Algorithm Examples:
1. Write an algorithm to compute the area and perimeter of a circle.
Step 1: Start
Step 2: Read r
Step 3: a= 3.142*r*r
p= 2* 3.142*r
Step 4: Print a, p
Step 5: Stop
2. Write an algorithm to compute the area and perimeter of a rectangle.
Step 1: Start
Step 2: Read l, b
Step 3: a= l*b
p= 2* (l + b)
Step 4: Print a, p
Step 5: Stop
3. Write an algorithm to compute the perimeter and area of a triangle.
Step 1: Start
Step 2: Read a, b, c
Step 3: s= (a + b + c)/2
a= sqrt(s*(s-a)*(s-b)*(s-c))
p= a + b + c
Step 4: Print a, p
Step 5: Stop

4. Write an algorithm to find the larger of two numbers.


5. Write an algorithm to find whether a number is even or odd.

6. Write an Algorithm to Swap two numbers.

7. Write an algorithm to print the grade obtained by a student using the following rules:
8. Write an algorithm to compute the simple
interest. Solution:
Step 1: [Initialize] Start
Step 2: [Input the values of P, T, R] Read
P, T, R
Step 3: [Compute the Simple Interest]
SI= (P*T*R)/100
Step 4: [Display the Simple Interest]
Print SI
Step 5: [Finished] Stop
9. Write an algorithm to compute the area and perimeter of a circle.
Solution:
Step 1: Start
Step 2: Read r
Step 3: a= 3.142*r*r
p= 2*3.142*r
Step 4: Print a,p
Step 5: Stop

10. Write an algorithm to compute the area and perimeter of a


rectangle. Solution:
Step 1: Start
Step 2: Read l,b
Step 3: a= l*b
p= 2*(l+b)
Step 4: Print a, p
Step 5: Stop
11. Write an algorithm to compute the perimeter and area of a triangle when three sides
are given.
Solution:
Step 1: Start
Step 2: Read a, b, c Step
3: s= (a + b + c)/2
a= sqrt(s*(s-a)*(s-b)*(s-c))
p= a + b + c
Step 4: Print a, p
Step 5: Stop

12. Write an algorithm to simulate simple calculator or to perform arithmetic


operations. Solution:
Step 1: Start
Step 2: Read n1, n2
Step 3: sum = n1 + n2

sub = n1 - n2
mul = n1 * n2
div = n1 / n2

Step 4: Print sum, sub, mul, div Step


5: Stop
13. Write an algorithm to calculate the area and volume of sphere.
Solution:
Step 1: Start
Step 2: Read r
Step 3: A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
Step 4: Print A, V
Step 5: Stop

14. Write an algorithm to calculate the area and volume of cube.


Solution:
Step 1: Start
Step 2: Read s
Step 3: A=6*s*s
V= s*s*s
Step 4: Print A, V
Step 5: Stop

15. Write an algorithm to convert degrees in Fahrenheit to degrees in Celsius.


Solution:
Step 1: Start
Step 2: Read f
Step 3: c=(5/9)*(f-32)
Step 4: Print c
Step 5: Stop
Flowchart:
• Flowchart is a graphical or symbolic representation of a process.
• It is basically used to design and document virtually complex processes to
help the viewers to visualize the logic of the process, so that they can gain a better
understanding of the process and find flaws, bottlenecks, and other less obvious
features within it.

• When designing a flowchart, each step in the process is depicted by a different


symbol and is associated with a short description. The symbols in the flowchart
are linked together with arrows to show the flow of logic in the process.
Advantages of Flowcharts:
 They act as a guide or blueprint for the programmer to code the solution in any
programming language.
 It helps programmers to understand the logic of complicated and lengthy problems.
 They are very good communication tools to explain the logic of a system to all concerned.
 They help to analyze the problem in a more effective manner.
 Flowchart can be used to debug programs that have error(s).

Limitations of Flowcharts:
 Drawing flowcharts is a laborious and time consuming activity.
 Flowchart of a complex program becomes complex and clumsy.
 A little bit of alteration in the solution may require complete redrawing of the flowchart.
 There are no well-defined standards that limit the details that must be incorporated in a flow
chart.

Examples:

1. Draw a flowchart to add two numbers.


Solution:

2.Draw a flowchart to find Difference of two numbers


Start

Read the values A, B

Diff = A - B

Print Diff

Stop
2.Draw a Flowchart to display sum of first 10 natural numbers.
Solution:

3.Draw a Flowchart to calculate the salary of a wager.


Solution:

4.Draw a Flowchart to determine the largest of three numbers.


6. Draw the flowchart to compute Simple Interest.
Solution:
Start

Read P, T, R

SI= (P*T*R)/100

Print SI

Stop

7. Draw the flowchart to compute the area and perimeter of a circle. Solution:
Start

Read r

A = 3.142*r*r
P = 2*3.142*r

Print A, P

Stop

8. Draw the flowchart to compute the area and perimeter of a rectangle. Solution:

Start

Read l, b

A = l*b
P = 2*(l + b)

Print A, P

Stop
9. Draw the flowchart to compute the area and perimeter of a triangle when three sides are given.

Solution:

Start

Read a, b, c

s = (a + b + c)/2
A = sqrt(s*(s-a)*(s-b)*(s-c)) P=a
+b + c

Print A, P

Stop

10. Draw the flowchart to simulate the simple calculator. Solution:


Start

Read n1, n1

sum=n1+n2
sub=n1-n2
mul=n1*n2
div=n1/n2
mod=n1%n2

Print sum, sub, mul, div,mod

Stop
11. Draw the flowchart to compute Compound Interest.
Solution:
Start

Read P, T, R

CI= P*(1+R/100)T-P

Print CI

Stop

12. Draw the flowchart to compute the area and volume of sphere.
Solution:
Start

Read r

A= 4*3.142*r*r V=
(4/3)*3.142*r*r*r

Print A, V

Stop

13.Draw the flowchart to compute the area and volume of cube.


Solution:
Start

Read s

A= 6*s*s
V= s*s*s

Print A, V

Stop
14.Draw the flowchart to convert from degrees in Fahrenheit to degrees in Celsius.
Solution:
Start

Read f

c=(5/9)*(f-32)

Print c

Stop

Pseudocode

 Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language.
or
“Pseudo code is nothing but a series of steps to solve a given problem written using a mixture of
English language and C like language.”

 Pseudo code consists of statements which are a combination of English and C.


 It is not quite ‘C’ code but can be translated.
 Pseudo code is an outline of a program that can easily be converted into programming language.
 Flowcharts can be considered as graphical alternatives to pseudo codes but requires more space
on paper.

Examples:
1. Write a pseudocode for calculating the price of a product after adding the sales tax to its
original price.
Solution:

2. Write a pseudocode to calculate the weekly wages of an employee. The pay depends on wages
per hour and the number of hours worked. Moreover, if the employee has worked for more than
30 hours, then he or she gets twice the wages per hour, for every extra hour he or she has worked.
Solution:
3. Write a Pseudo code for printing the number and its square starting from 4 to 9.
Solution:
Begin
Input 4
square=4*4
Print 4,16
do the same for each of the other numbers from 5 to 9
End

4. Write a Pseudo code to compute the Simple Interest.


Solution:
Begin
Input P, T, R
SI= (P*T*R)/100
Print SI
End

5. Write a Pseudo code to compute the Compound Interest.


Begin
Input P, T, R
CI= P*(1+R/100)T-P
Print CI
End
6. Write a Pseudo code to calculate area and perimeter of circle.
Solution:
Begin
Input r
A=3.142*r*r
P=2*3.142*r
Print A, P
End
7. Write a Pseudo code to calculate the area and perimeter of rectangle. Solution:
Begin
Input l, b A=l*b
P=2*(l+b)
Print A,P
End

8. Write a Pseudo code to calculate the area and perimeter of triangle when three sides are given.
Solution:
Begin Input a,b,c
s= (a + b + c)/2 A=sqrt(s*(s-a)*(s-
b)*(s-c)) P= a + b +c
Print A, P End

9. Write a Pseudo code to calculate the area and perimeter of sphere. Solution:
Begin Input r
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r Print A,
V
End

10. Write a Pseudo code to calculate the area and perimeter of cube. Solution:
Begin Input s A=
6*s*s V= s*s*s
Print A, V End

11. Write a Pseudo code to convert from degrees in Fahrenheit to degrees in Celsius. Solution:
Begin
Input f
c=0.56*(f-32)
Print c
End
Introduction to C :

C is a general purpose, procedural, structured computer programming language developed by


Dennis Ritchie in the year 1972 at AT&T Bell Labs. C language was developed on UNIX and was invented
to write UNIX system software. C is a successor of B language. There are different C standards: K&R C
std, ANSI C, ISO C.

Characteristics of C
 C is a robust language whose rich set of built-in functions and operators can be used to write
complex programs. The C compiler combines the features of assembly languages and high-level
languages, which makes it best suited for writing system software as well as business packages.
Some basic characteristics of C language that define the language and have led to its popularity as a
programming language are listed below:

a high-level programming language, which enables the programmer to concentrate on theproblem


at hand and not worry about the machine code on which the program would be run.

to learn as compared to other


languages.

ming approach, C enables users to


think of a problem in terms of functions/modules where the collection of all the modules makes up
a complete program. This feature facilitates ease in program debugging, testing, and maintenance.

Unlike PASCAL it supports loose typing (as a character can be treated as integer and vice versa).

code can be organized as a collection of one or more functions

program written in any other language.

-level programming.

Perl, etc) are based on C.

run on another computer with little or no modification.

Uses of C

C is a very simple language that is widely used by software professionals around the globe. The
uses of C language can be summarized as follows:

stem programming. The portability, efficiency, the ability to accessspecific


hardware addresses and low runtime.

rogramming languages are often implemented


in C. For portability and convenience reasons, C is sometimes used as an intermediate language for
implementation of other languages. Major parts of popular operating systems like windows, UNIX,
Linux are still written in C.
C is widely used to implement end-user applications

ike cellular phones and palmtops consisting of microprocessor, operating system


and some applications are written in C.

chines and digital cameras are


consisting of many programs which are written in C language.

ar gaming frameworks have been built


using C language.

Basic Concepts of a C Program or Structure of a C Program

The basic concepts of a C program can be explained by writing the structure of a C program.
Thestructure of a C program is nothing but the rules that are to be followed while writing a C
program.

The structure of a C program is shown below:


1. Comments

At the beginning of each program is a comment with a short description of the problem to

be solved.

Ex: 1. /* Program1: To find the sum of two numbers*/

// Program2: To calculate the area and perimeter of circle

symbol /* and ends with */ represents the multiline comment.

2. Preprocessor directives

The preprocessor statements start with # symbol.


.h says this file is a header file.

include some of the files in the beginning of the


program.
Ex: #define PI 3.142
.
#include<stdio.h>

#include<math.h>

The line containing #include<stdio.h> tells the compiler to


allow our program to standard input and output “stdio”
operations to perform.

The ‘#include‘ directive tells the compiler that

we will be using parts of the standard function

library.
3. Global Declarations

iables that are declared above (before) the main program are called global variables.

functions.

4. Function declarations and Definitions

this section the functions are declared.

5. The program header: main()

6. Body of the program

statements which comprise the ‗body‘- this is called the action portion of the program.

Ex: #include<stdio.h>

main()

/* action portion of the program*/

1. Declaration section

2. Executable section
Declaration section:

section. For example ,consider the declaration shown below:


int sum=0;

int a;

float b;

Here, the variable sum is declared as an integer variable and it is initialized to zero. The variable

a is declared as an integer variable whereas the variable b is declared as a floating point variable.

 Executable section
The instructions
can be input/output statements, expressions to be evaluated, simple assignment statements, control
statements such as if statement, for statement etc.Each executable statement ends with ―;‖.

Example: Write a C program to display ―Hello World‖.

#include<stdio.h>

void main()

printf(“Hello World”);

}
Files used in a C Program
A C program uses four types of files as follows:

1. Source Code File:

 This file includes the source code of the program.


 The extension for these kind of files are ‘.c’.
 It defines the main and many more functions written in C.
 main() is the starting point of the program. It may also contain other source code files.
2.Header Files

various source files.

Advantages of header files:

1. At times the programmer may want to use the same subroutines for different programs. To do

this, he would just compile the code of the subroutine once and link to the resulting object file in

any file in which the functionalities of this subroutine are required.

2. At times the programmer may want to change or add the subroutines and reflect those changes in
all the programs. For doing this, he will have to only change the source file for the subroutines,
recompile the source code and then recompile and re-link the program. This tells us that including a
header file will make it easier at all levels of the program. If we need to modify anything then changes
are made only in the subroutines after which all the changes will be reflected.

2.Standard header files

Common standard header files are:

-used for handling string functions.

-used for handling string functions.

-used for some miscellaneous functions.

used for giving standardized input and output.

– used for mathematical functions.

– used for dynamic memory allocation.

– used for clearing the screen.

e added at the start of the source code so that they can be used by more than

one function of the same file.


3.Object files

binary code of the function definitions.

files together. It has a '.o' extension.

4.Executable file

object files are linked by the linker for producing a binary file which will be

executed directly.

Compiling and Executing C Programs:

e that consists of the statements of the

program written in C language. This source file usually contains ASCII characters and can be

produced with a text editor, such as Windows notepad, or in an Integrated Design Environment.

processed by a special program called a compiler.

system API (Application Programming Interface).

However, even the object file is not an executable file. Therefore, in the next step, the object

file is processed with another special program called a linker.

e, the same linker is used for


object files regardless of the original language in which the new program was written. The output of the linker is an
executable or runnable file. The process is shown in Figure 4.3.

• In C language programs, there are two kinds of source files. In addition to the main (.c)
source file, which contains executable statements there are also header (.h) source files.

a. Every C program uses standard header files, which are written as part of the source
code for modular C programs.

b. The compilation process shown in Figure 4.4 is done in two steps.

c. In the first step, the preprocessor program reads the source file as text, and produces
another text file as output. The output of the preprocessor is a text file which does
not contain any preprocessor statements. This file is ready to be processed by the
compiler.

d. The linker combines the object file with library routines (supplied with the
compiler) to producethe final executable file.

e. In modular programming, the source code is divided into two or more source
files. All these source files are compiled separately thereby producing
multiple object files.

f. These object files are combined by the linker to produce an executable file (Figure 4.5).
Using Comments

 Many times the purpose of the file code is not clear to the reader.

the reader understand the code clearly.

is merely an internal program documentation.

The compiler ignores the comments when forming the object file means that the comments

are non-executable statements.

C supports two types of comments.

// is used to comment a single statement. This is known as a line comment. A line comment

can be placed anywhere on the line and it does not require to be specifically ended as the end of

the line automatically ends the line.

/* is used to comment multiple statements. A /* is ended with */ and all statements that lie

within these characters are commented. This type of comment is known as block comment.

C Tokens

nstructed using a combination of these tokens.


1. Keywords:

cannot be changed by the user.

Keywords are basically a sequence of characters that have a fixed meaning.

int, float, if, while, void etc are valid keywords.

Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).

List of keywords:

2. Variables: A variable is a data item whose value changes during the execution of program.

Ex: int a,b,sum;

3. Constants: A constant is a data item which will not change during the execution of a

program. Ex: #define PI 3.142


4. Strings: String is an array of characters and terminated by NULL character which is denoted
by

‗\0‘.

Ex: char name[21];

5. Operators: Operator is a symbol (or token) that specifies the operation to be performed on

various types of data.

Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=)

and Assignment operator (=) etc.

6. Special characters: [ ], { }, ( ) etc. used in the program to execute the code correctly and helps

to write a complex codes by special symbols.

CHARACTER SET IN C :

character set that defines the

fundamental units used to represent information.

represent information.

that act as basic building blocks of a C


program.

a. English alphabet: Include both lower case (a z) as well as upper case (A Z) letters

b. Digits: Include numerical digits from 0 to 9

c. Special characters: Include symbols such as, % & ) < > * S / ) [ " etc.,

d. White space characters: These characters are used to print a blank space on the screen.

They are shown in Figure 4.6.


e. Escape sequence: ‗\n‘ is an escape sequence and represents a newline character. It is used to

print the message on a new line on the screen. Like the newline character, the other escape

sequences supported by C language are shown in Table 4.1

4.10 Identifiers

Identifiers help us to identify data and other objects in the program.

functions.
Rules for Forming ldentifier Names:

Some rules have to be followed while forming identifier names. They are as follows:

except the underscore “_”.

 There cannot be two successive underscores.

 ‗FIRST‘ is different from ‗first‘ and ‗First‘.

 character must be avoided because several compiler-defined identifiers in the standard

C libraryhave underscore as their first character.

be of any reasonable length. They should not contain more than 31 characters.

They can actually be longer than 31, but the compiler looks at only the first 31 characters of the name.

Examples of valid identifiers include:

roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code, DeptCode, RollNo,

EMP_NO

Examples of invalid identifiers include:

23 student, %marks, @name, #emp_number, basic.pay, -HRA, (DA), &dept_code, auto

Data types and Sizes:


 The data type defines the type of data stored in a memory location.
 The data type determines how much memory should be allocated for a variable.
 The data types that can be manipulated by machine instructions are called ‗basic or primitive data types‘.

int

char
Basic Datatypes float
double
void
i. int
 An int is a keyword which is used for defining integers in C language.
 Using int the programmer can inform the compiler that the data associated with this should be
treated as integer.
 Using “int” compiler determines the size of the data (2 bytes) and reserve space in memory to storethe
data.
 Integer data types namely:
1. short int 2. int 3.long int

Type Size
short int 2 bytes
int 2 bytes
long int 4 bytes
Ex: int a,b,c;

ii. float:
 A float is a keyword which is used to define floating point numbers in C language.
 The programmer can inform the compiler that the data associated with this keyword should be
treated as floating point number.
 The default precision of floating point number is 6 digits after dot(.).
Size of float
16-bit Machine 4 bytes
32-bit Machine 8 bytes

Ex: float x,y,z;

iii. double:
 It is a keyword which is used to define long floating point numbers in C language.
 The default precision of floating point number is 14 digits after dot(.).
Size of double
16-bit Machine 8 bytes
32-bit Machine 16 bytes

Ex: double p,q,r;

iv. char:
 It is a keyword which is used to define single character or a sequence of characters called String in C
language.

 Using this keyword, the compiler determines the size of the data and reserve space in memory to
store the data.

 Each character stored in the memory is associated with a unique value called an ASCII (American
Standards Code for Information Interchange).
Size of char
16/32-bit Machine 1 byte

Ex: char ch; // ch variable stores a single character Ex: ch= ‗a‘;
char s[20]; // s variable stores a string(group of characters) Ex: s= ―jit dvg‖;
v. void:
 It is an empty data type, since no value is associated with this data type.
 It does not occupy any space in the memory.
Size of void
16/32-bit Machine 0

Ex: void main( )


{
}

Constants
 A constant is a data item which will not change during the execution of a program.
 The constants cannot be modified in the program.

D
e
c
i
m
a
l

Backslash Constant (Escape Sequence Character):


 An escape sequence character begins with a backslash and is followed by one character.
 A backslash (\) along with some characters give rise to special print effects by changing (escaping) the
meaning of some characters.
 Backslash characters are normally used during printing using printf() function. These characters will not
appear physically on screen. But when printed they produce special effects.

Escape Character Character Meaning


\t Horizontal tab Cursor moves towards right by 8 position
\n New line Cursor moves to the beginning of next line
\0 Null Null character

Declaration, Assignment and Print Statements


Declarations

 Declaration‟ tells the computer which storage locations or variables to use in the program.
 All variables must be declared before used.
Ex: int a,b,c;
char ch;
Initialization
 A variable may also be initialized in its declaration. The name is followed by an assignment operator (=)
sign in an expression.
Ex: int i=5;
float pi=3.142;
 A semicolon(;) terminates every complete statement in C and variables are separated by (,) commas.
 The line containing #include does not need (;) because it is a compiler directive, not a C statement.
 The main() program header does not need (;) because it is not a complete C statement.
Variable
 A variable is a name given to a memory location within the computer that can hold one value at a
time.
OR
A variable is a data item whose value changes during the execution of program.
 Every variable should be associated with type, size and value.
 Whenever a new value is placed into a variable, it replaces the previous value.

Rules for defining variables (or Identifiers):


 The first character in the variable should be a letter (A to Z or a to z) or an underscore.
 The first character can be followed by any number of letters or digits (0 to 9) or underscores.
 No extra symbols are allowed other than letters, digits and underscore.
 The length of an identifier (variables/constants) can be up to maximum of 31 characters.
 C keywords should not be used as variable names.
 The variable name should not begin with a digit or any other special characters other then

underscore.
Ex: Classify the following into valid and invalid variable names in C. If invalid give reasons:

Variable Valid/Invalid Reason


principle_amount Valid
A Valid
Sum1 Valid
for1 Valid
If Invalid It is a keyword
For Invalid It is a keyword
3_factorial Invalid Should not start with digit
Sum,1 Invalid Comma should not be there
sum-of-digits Invalid Minus sign should not be there
sum_of_digits Valid
sum of digits Invalid No spaces are allowed
$sum Invalid $ sign should not be there
sum= Invalid = sign should not be there
one+two Invalid + sign should not be there
sum! Invalid ! sign should not be there
Int Invalid It is a keyword
$roll no Invalid $ sign should not be there
_name1 Valid
James bond Invalid No spaces are allowed

Declaring/Defining a Variable:

 It is a method of informing the compiler to reserve the memory space for the program data based on
the type of variables.

Syntax: datatype v1,v2,…….,vn ;

Where datatype: it can be int, float,char, double etc.


v1,v2,---,vn: is a list of variables, which are separated by commas.

Ex: int a,b,c;


float p,t,r,si;

Initializing the variables


 Initialization is the process of assigning values to the variables.
Syntax:
datatype var_name=data;

 datatype: is the type of the data to be stored in memory location. (int,float,char,double)


 var_name: name of a variable
= is assignment operator
 Data: is the value to be stored in memory associated with variable var_name.
Ex: int a=10;

Formatted Output Function: print statement


 The data stored in memory locations has to be converted into appropriate data type and then it is displayed
on the screen for human understanding in the proper format. This can be done by ―printf statement‖.
 Print and Format: The function printf (print+f) prints the data in the specified memory location or
variables after “formatting” the data.
printf(): print format
 There are two simple forms of printf:
1. One that has just a literal string (a sequence of characters within quotation marks) General
form: printf (“… ........................... ”);
literal string
Ex : printf (“welcome to C Program”);
Literal string is placed within a parenthesis. The symbols within that string are printed.

2. One that has values of one or more expressions to be printed.


General form : printf (“………” , ……);
(i) (ii)
(i) Control String, including conversion characters
(ii) list of variables or expressions to be printed.

Ex: printf (“ %d%f%c”, x,y,z);

Format specifiers list of variables.

Guidelines/Rules for printf()


 A printf() always contains a string or format string in quotation marks.
 The control string may or may not be followed by some variables or expressions whose value we want
printed.
 Each value to be printed needs a ‗conversion specification‘ like %d to hold its place in the control string.
 This conversion specification describes the exact way the value is to be printed.
 When printf() is executed each conversion specification is replaced by the value of the corresponding
expression, then print according to the rules in specification.
 The symbols \n or \t in control string tell the machine to skip to new line or tab. It affects the appearance of
the output but not displayed as part of it.
 A word or blank space or punctuation symbols within the control string will print exactly as it appears.
 If there are variables or expressions to be printed, commas are used to separate them from the control string
and each other, once comma is used as separator, it is not necessary to add blank spaces (not allowed).
Ex: printf (“%d%d \n”,a,b);
and Both are same
printf (“%d%d \n”, a, b);

Control String or Format Specifier Newline character

Variable list
Format specifiers used in printf()

Data type Format specifier Description


int %d data is displayed as decimal signed integer
%o data is displayed as octal integer
%x or %X data is displayed as hexadecimal integer
%u data is displayed as unsigned integer.
float %f data is displayed as floating point value without Exponent
%e or %E data is displayed as floating point value with exponent
char %c data is displayed as character
%s data is displayed as string
double %lf data is displayed as long float
long int %ld data is displayed as long integer.

Formatted input Function: scanf () function


 The function scanf (scan+ f) means scan the data in the buffer and format the data.
 Scan and Format: if data is in buffer, it is converted into appropriate data type using format string
with the help of conversion codes.
 scanf() function is used to read the data from the keyboard.
Syntax:
scanf (“format string”, address list);

Ex : scanf (“%d%f%c”,&x,&y,&z);

format specifiers address list


 A format specifiers starts with % sign and is followed by conversion code (i.e., d, f, c, s)
 Address list is a list of variables, each variable name must be preceded by an (&) ampersand symbol.
 The numbers of variables must be equal to the number of format specifiers.
 ‗&‘ is an ‗Address of‘ operator. It gives the location number used by the variable in memory.

Format specifiers used in scanf()

Data type Format specifier Description


int %d Converts the data into decimal signed integer
%o Converts the data into octal integer
%x or %X Converts the data into hexadecimal integer
%u Converts the data into unsigned integer.
float %f Converts the data into floating point value without Exponent
%e or %E Converts the data into floating point value with exponent
char %c Converts the data into character
%s Converts the data into string
double %lf Converts the data into long float
long int %ld Converts the data into long integer.
Guidelines/Rules for scanf()
 Syntax:
scanf (“format string”, address list);

 Always a format string should be enclosed within double quotes.


 No words, punctuation symbols, escape sequence characters (such as \t, \n etc) are allowed, only format
specifiers are used in format string.
 A format specifiers starts with % sign and is followed by conversion code (i.e., d, f, c, s)
 There must be format specifier for each variable. i.e., number of format specifiers must be equal to the
number of variables.
Ex1: 1 + 1 + 1 = 3 format specifiers

scanf(“%d %f %c”, &x, &y, &z); //valid

1 + 1 + 1 = 3 variables

Ex2: 1 + 1 + 1 = 3 format specifiers

scanf(“ %d %f %c”, &x, &y); //invalid

1 + 1 = 2 variables
 The variables present in scanf must represent the address of memory locations.
Ex1: int a;
scanf(“%d”,&a); //valid
 The type conversion specified in each format specifier must match with the corresponding type of variable
present.
Ex1: int=a;
scanf(“%d”,&a);
//valid
integer integer value

Ex2: int=a;
scanf(“%f”,&a); //invalid

float integer value


BITS and BYTES
Bits:
 Definition: A bit (short for binary digit) is the smallest unit of data in a computer.
 Values: It can have a value of either 0 or 1.
 Usage: Bits are the building blocks of digital information. Everything in a computer is ultimately represented by bits.
Bytes:
 Definition: A byte is a unit of digital information that consists of 8 bits.
 Representation: Each byte can represent 256 different values (from 0 to 255).
 Usage: Bytes are used to encode a single character of text in a computer. For example, the letter 'A' is represented as 65
in the ASCII encoding.
Relationship between Bits and Bytes:
 Bit: 1 bit = 0 or 1
 Byte: 1 byte = 8 bits
 Kilobyte (KB): 1 KB = 1024 bytes
 Megabyte (MB): 1 MB = 1024 KB
 Gigabyte (GB): 1 GB = 1024 MB
 Terabyte (TB): 1 TB = 1024 GB

Example programs:

1. C program to print “WELCOME TO Programming”.

#include<stdio.h>

int main()
{
printf(“WELCOME TO Programming”);
return 0;
}
2. C program to add 2 integer numbers.

#include<stdio.h>

int main()
{
int a,b,c;
printf(“\n Enter the value of a:”);
scanf(“%d”,&a);
printf(“\n Enter the value of b:”);
scanf(“%d”,&b);
c=a+b;
printf(“\n The addition of 2 numbers is:%d”,c);
return 0;
}
3. C program to calculate the circumference and area of a circle.

#include<stdio.h>

int main()
{
float r,area,circum;
printf(“\n Enter the value of radius:”);
scanf(“%f”,&r);
circum=2*3.142*r;
area=3.142*r*r;
printf(“\n The circumference of a circle is: %f”,circum);
printf(“\n The area of a circle is:%f”,area);
return 0;
}

4. C program to calculate the Simple Interest

#include<stdio.h>

int main()
{
float p,t,r,si;
printf(“\n Enter the values of p,t and r values”);
scanf(“%f%f%f”,&p,&t,&r);
si=(p*t*r)/100;
printf(“Simple Interest=%f”,si);
return 0;
}
5. C program to calculate the area of triangle by using the values of sides of a triangle.

#include<stdio.h>
#include<math.h>

void main()
{
float area,a,b,c,s;
printf("Enter the values for its sides a,b,c:\n");
scanf("%f%f%f",&a,&b,&c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("\n The area of the triangle=%f \n",area);
}

6. C program to calculate the area of triangle by using Length and breadth

#include<stdio.h>
#include<math.h>

void main()
{
float area,l,b;
printf("Enter the values for l and b:\n");
scanf(“%f%f”,&l.&b);
area=0.5*l*b;
printf(“Area of Triangle=%f”,area);
}

7. C Program to print largest of 2 numbers.

#include<stdio.h>

void main()
{
int a,b;
printf(“\n Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“\n A is largest”);
}

else {
printf(“\n B is largest”);

}
}

8. C program to determine whether the given number is positive or negative.

#include<stdio.h>

int main()
{
int num;
printf("\n Enter the number:\n");
scanf("%d",&num);
if(num>0){
printf("\n Given number is Positive\n");
else
printf("\n Given number is Negative\n");
}
return 0;
}

9. C program to check whether the given number is even or odd.

#include<stdio.h>

void main()
{
int rem,n;
printf("\n Enter the number\n");
scanf("%d",&n);
rem=n%2;//calculate the remainder of the number
if(rem==0) {
printf("\n Given number %d is Even number\n",n);
}

else {
printf("\n Given number %d is Odd number\n",n);

}
}
[Type here]

10. C program to find biggest of 3 numbers.

#include <stdio.h>
int main() {
int a,b,c;
printf(“\n Enter the values of a,b and c:”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b && a>c)
{
printf(“\n A is largest”);
}
else if(b>c && b>a)
{
printf(“\n B is largest”);
}
else

{
printf(“\n C is largest”);
}
return 0;
}

You might also like