Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Module-1

The document outlines the course 'Principles of Programming Using C' (BPOPS103) taught by Dr. Purushotham U and Dr. Vikhyath K B, covering fundamental concepts of C programming across five modules. Key topics include computer architecture, C program structure, operators, functions, arrays, strings, pointers, and user-defined data structures. The course aims to equip students with practical programming skills to solve real-world problems using C language constructs.

Uploaded by

naxibew907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module-1

The document outlines the course 'Principles of Programming Using C' (BPOPS103) taught by Dr. Purushotham U and Dr. Vikhyath K B, covering fundamental concepts of C programming across five modules. Key topics include computer architecture, C program structure, operators, functions, arrays, strings, pointers, and user-defined data structures. The course aims to equip students with practical programming skills to solve real-world problems using C language constructs.

Uploaded by

naxibew907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 225

Course Title : Principles of Programming Using C

Course Code: BPOPS103

Faculty:
Dr Purushotham. U & Dr. Vikhyath K B

Dr H N National College of Engineering


1
Course Content
Module 1
— Introduction to C: Introduction to computers, input
and output devices, designing efficient programs.
Introduction to C, Structure of C program, Files used
in a C program, Compilers, Compiling and executing
C programs, variables, constants, Input/output
statements in C,

— Textbook: Chapter 1.1-1.9, 2.1-2.2, 8.1 - 8.6 ,9.1-9.14


Dr H N National College of Engineering
2
Course Content
Module 1I
— Operators in C, Type conversion and typecasting.
Decision control and Looping statements:
Introduction to decision control, Conditional
branching statements, iterative statements, nested
loops, break and continue statements, goto statement.

— Textbook: Chapter 9.15-9.16, 10.1-10.6

Dr H N National College of Engineering


3
Course Content
Module III
— Functions: Introduction using functions, Function
definition, function declaration, function call, return
statement, passing parameters to functions, scope of
variables, storage classes, recursive functions. Arrays:
Declaration of arrays, accessing the elements of an array,
storing values in arrays, Operations on arrays, Passing
arrays to functions, two dimensional arrays, operations on
two-dimensional arrays, two-dimensional arrays to
functions, multidimensional arrays, applications of arrays.

— Textbook: Chapter 11.1-11.10, 12.1-12.10,12.12

Dr H N National College of Engineering


4
Course Content
Module IV
— Strings and Pointers: Introduction, string taxonomy,
operations on strings, Miscellaneous string and
character functions, arrays of strings. Pointers:
Introduction to pointers, declaring pointer variables,
Types of pointers, Passing arguments to functions
using pointers

— Textbook: Chapter 13.1-13.6, 14-14.7


Dr H N National College of Engineering
5
Course Content
Module V
— Structure, Union, and Enumerated Data Type:
Introduction, structures and functions, Unions, unions
inside structures, Enumerated data type. Files:
Introduction to files, using files in C, reading and
writing data files. , Detecting end of file

— Textbook: Chapter 15.1 – 15.10, 16.1-16.5

Dr H N National College of Engineering


6
Course Content
Textbooks
— 1. Computer fundamentals and programming in c,
“Reema Thareja”, Oxford University, Second edition,
2017.
Reference Books:
— 1. E. Balaguruswamy, Programming in ANSI C, 7th
Edition,Tata McGraw-Hill.
— 2. Brian W. Kernighan and Dennis M. Ritchie, The ‘C’
Programming Language, Prentice Hall of India
Dr H N National College of Engineering
7
Course Outcomes :
At the end of the course the student will
be able to:
— CO1. Elucidate the basic architecture and functionalities of a
computer and also recognize the hardware parts.
— CO 2. Apply programming constructs of C language to solve the
real world problem
— CO 3.Explore user-defined data structures like arrays in
implementing solutions to problems like searching and sorting
— CO 4.Explore user-defined data structures like structures,
unions and pointers in implementing solutions
— CO5.Design and Develop Solutions to problems using modular
programming constructs using functions

Dr H N National College of Engineering 8


Module-1

Ø Introduction to computers
Ø Input and output devices
Ø Designing efficient programs
Ø Structure of C program
Ø Files used in a C program
Ø Compilers - Compiling and Executing C programs
Ø Variables and Constants
Ø Input/output statements in C

Dr H N National College of Engineering 9


Introduction to computers
— What is a Computer?

— An electronic device designed to accept data, perform the required


mathematical and logical operations at high speed, and output the
result.

— Accepting input, processing it and producing information are the


main tasks of computer.

— These days, computers have become so prevalent in the market that


all interactive devices such as cellular phones, global positioning
system (GPS) units, portable organizers, automated teller machines
(ATMs), and petrol pumps, work with computers.

Dr H N National College of Engineering 10


Introduction to computers
— A computer performs the following tasks:

üInput
üProcessing
üOutput
üStorage

üHowever, with technological advancements, the size of computers


became smaller and their energy requirements reduced accordingly.

Dr H N National College of Engineering 11


Application Programs
qEasy-to-use programs designed to perform specific tasks.

qExamples of an application include a word processor, a


spreadsheet, a web browser, an email client, a media player,
a file viewer, an aeronautical flight simulator, a console
game or a photo editor.

Dr H N National College of Engineering 12


System Programs
Programs that support the execution and development of other
programs
ü Two major types
Ø Operating systems
Ø Translation systems (compilers & linkers)

Dr H N National College of Engineering 13


System Programs
ü Different types of translators:

Ø Compiler – A compiler is a translator used to convert high-level


programming language to low-level programming language. It converts the
whole program in one session and reports errors detected after the conversion.

Ø The compiler takes time to do its work as it translates high-level code to


lower-level code all at once and then saves it to memory. A compiler is
processor-dependent and platform-dependent.

Ø It has been addressed by alternate names as the following: special compiler,


cross-compiler and, source-to source compiler.

Dr H N National College of Engineering 14


— Interpreter – The interpreter is similar to compiler, it is a translator used to
convert high-level programming language to low-level programming language.
The difference is that it converts the program one line of code at a time and reports
errors when detected, while also doing the conversion.

— An interpreter is faster than a compiler as it immediately executes the code upon


reading the code.

— It is often used as a debugging tool for software development as it can executes a


single line of code at a time. An interpreter is also more portable than a compiler
as it is processor-independent , you can work between different hardware
architectures.

Dr H N National College of Engineering 15


— Assembler - An assembler is a translator used to translate assembly language into
machine language. It has the same function as a compiler for the assembly
language but works like an interpreter .

— Assembly language is difficult to understand as it is a low-level programming


language .

— An assembler translates a low-level language , such as an assembly language to an


even lower-level language, such as the machine code.

Dr H N National College of Engineering 16


Introduction to computers
— The important characteristics of a computer:

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.

Dr H N National College of Engineering 17


Introduction to computers
— 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.

— In the event of an error, it is the user who has fed the incorrect
data/program is responsible.

— This clearly means that the output generated by a computer depends


on the given instructions and 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) .

Dr H N National College of Engineering 18


Introduction to computers
— Automation: Besides being very fast and accurate, computers are
automatable devices that can perform a task without any user
intervention.

— The user just needs to assign the task to the computer, after which it
automatically controls different devices attached to it and executes
the program instructions.

— Diligence: Unlike humans, computers never get tired of a repetitive


task. It can continually work for hours without any errors.

— Even if there are large number of instructions to be executed, each


requires the same duration, and is executed with the same accuracy.

Dr H N National College of Engineering 19


Introduction to computers
— 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 simultaneously.

— On the PC that you use at home, you may play a game, compose and
send e-mails, listen to music, etc.

— Therefore, computers are versatile devices as they can perform


multiple tasks of different nature at the same time

Dr H N National College of Engineering 20


Introduction to computers
— Memory: Computers have internal or primary memory (storage space) as well
as external or secondary memory.

— While the internal memory of computers is very expensive and limited in size,
the secondary storage is cheaper and of bigger capacity.

— 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.

— When data and programs have to be used, they are copied from the secondary
memory into the internal.

Dr H N National College of Engineering 21


Introduction to computers
— 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.

— Economical: Today, computers are considered as short term investments for


achieving long-term gains. Using computers also reduces manpower
requirements leading to an efficient way of performing various tasks thus
saving time, energy, and money.

— 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.

Dr H N National College of Engineering 22


Stored Program Concept
All systems are based on the principle of stored program concept introduced by Neumann,
with the following characteristic features:

Ø Before any data is processed, instructions are read into memory.

Ø Instructions are stored in the computer’s memory for execution in binary form (only 0s
and 1s).

Ø Processing starts with the first instruction in the program, which is copied into a control
unit which executes the instructions.

Ø Instructions written by the users are executed sequentially until there is a break in the
current flow.

Ø Input/output and processing operations are performed parallelly. While data is being
read/written, the central processing unit (CPU) executes another program in the
memory that is ready for execution.
Dr H N National College of Engineering 23
Types of Stored Program Concept
Ø Same memory for Instructions and Data
Ø Different memory for Instructions and Data

Same memory for Instructions and Data:

— A computer with a Von Neumann architecture stores data and


instructions in the same memory.

— Serial machine selects data and instructions one at a time.

— Data and instructions are transferred to and from memory through a


shared data bus. Since there is a single bus to carry data and
instructions, process execution becomes slower.

Dr H N National College of Engineering 24


Types of Stored Program Concept
Same memory for Instructions and Data:

— Address bus carries the address of data instructions.

— Data bus carries the data and instructions to be


executed.

Dr H N National College of Engineering 25


Types of Stored Program Concept
Different memory for Instructions and Data:

— Harvard University proposed a stored program concept in which there


was a separate memory to store data and instructions.

— Instructions are selected serially from the instruction memory and


executed in the processor. When an instruction needs data, it is selected
from the data memory.

— Since there are dedicated memories used, execution becomes faster.

Dr H N National College of Engineering 26


History of Computers
— Early computers were designed not for entertainment but for solving number-
crunching problems. These computers were punch-card based computers that
took up entire rooms.

— Today, our smart phones have much more computing power than that was
available in those early computers.

— Timeline of Developments:

— 300 BC: The abacus was an early aid for mathematical computations and was
designed to aid human’s memory while performing calculations.

— A skilled abacus operator can add and subtract with the same speed as that of a
person performing the same calculation using a hand calculator.

Dr H N National College of Engineering 27


History of Computers
— Timeline of Developments:

— 1822: English mathematician Charles Babbage designed a steam-driven


calculating machine that could compute tables of numbers. Though the project
failed as he could not complete the construction of the engine, it laid the
foundation for the first computer.

— 1890: Herman Hollerith, an American inventor, designed a punched card


system to calculate the 1880 census. The system completed the task in three
years saving the US government $5 million. Later Herman established a
company that we today know as IBM.

— 1936: British mathematician Alan Turing introduced a universal machine called


the Turing machine capable of computing anything that is computable. The
central concept of the modern computer is based on this machine.

Dr H N National College of Engineering 28


History of Computers
— Timeline of Developments:

— 1941: John Vincent Atanasoff, a Bulgarian-American physicist, and his


graduate student, Clifford Berry, at Iowa State College designed Atanasoff–
Berry computer (ABC) that could solve 29 equations simultaneously. It was the
first time a computer could store information in its main memory.

— 1943–1944: John W. Mauchly and J. Presper Eckert built the Electronic


Numerical Integrator and Calculator (ENIAC), which is considered as the
grandfather of digital computers. It filled a 20 × 40 feet room and had 18,000
vacuum tubes.

— 1946: Mauchly and Presper designed the UNIVAC, which was the first
commercial computer for business and government applications.

Dr H N National College of Engineering 29


History of Computers
— Timeline of Developments:

— 1947: William Shockley, John Bardeen, and Walter Brattain of Bell Laboratories
invented the transistor. Soon vacuum tubes in computers were replaced by transistors.

— 1953: Grace Hopper developed the first computer language COBOL. 1954: The
FORTRAN programming language was developed.

— 1958: Jack Kilby of Texas Instruments and Robert Noyce at Fairchild Semiconductor
Corporation separately invented integrated circuit, which is commonly known as the
computer chip.

— 1964: Douglas Engelbart developed a prototype of the modern computer, with a mouse
and a graphical user interface (GUI). This was a remarkable achievement as it shifted
computers from a specialized machine for scientists and mathematicians to general
public.

Dr H N National College of Engineering 30


History of Computers
— Timeline of Developments:

Dr H N National College of Engineering 31


History of Computers

Dr H N National College of Engineering 32


History of Computers

Dr H N National College of Engineering 33


History of Computers
— First Generation (1942–1955):

— Hardware Technology: First generation computers were manufactured using thousands


of vacuum tubes; a vacuum tube is a device made of fragile glass.

— 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.

Dr H N National College of Engineering 34


History of Computers
First Generation (1942–1955)

Highlights:

— They were the fastest calculating device of those times

— 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 and 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

Dr H N National College of Engineering 35


History of Computers
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 system was used. Used for Scientific and commercial applications
Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC

Dr H N National College of Engineering 36


History of Computers
Second Generation (1955–1964)
Highlights:

— Faster, smaller, cheaper, reliable, and easier to use than the first generation computers.

— They consumed 1/10th the power consumed by first generation computers

— Bulky in size and required a complete room for its installation

— Dissipated less heat than first generation computers but still required air-conditioned
rooms

— Costly

— Difficult to use

Dr H N National College of Engineering 37


History of Computers
— 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 a single chip to avoid wired interconnections between
components. These computers used SSI and MSI technology .
Minicomputers came into existence

Dr H N National College of Engineering 38


History of Computers
Memory: Larger magnetic core memory was used as primary
memory; larger capacity magnetic tapes and magnetic disks were
used to store data and instructions.
Software Technology: Programming was done in high level
programming languages such as FORTRAN, COBOL, Pascal, and
BASIC.
Used for: Scientific, commercial, and interactive online
applications.

Examples: IBM 360/370, PDP-8, PADP-11, CDC6600

Dr H N National College of Engineering 39


History of Computers
Third Generation (1964–1975)
Highlights:
— Faster, smaller, cheaper, reliable, and easier to use than the second generation
computers

— They consume less power compared to second generation.

— Bulky in size and required a complete room for installation.

— Dissipated less heat than second generation computers but still required air-conditioned
rooms.

— Costly

— Easier to use and upgrade.

Dr H N National College of Engineering 40


History of Computers
Fourth Generation (1975–1989):

— Hardware Technology Fourth generation computers were


manufactured using ICs with LSI (Large Scale Integrated) 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 started
growing. Besides mainframes, supercomputers were also
used.

Dr H N National College of Engineering 41


History of Computers

Dr H N National College of Engineering 42


History of Computers
— Memory: Semiconductor memory is used as primary
memory; large capacity magnetic disks are used as built-
in secondary memory. Magnetic tapes and floppy disks
were used as portable storage devices, which have now
been replaced by optical disks and USB flash drives.
— Software Technology: Programming is done in high-level
programming languages such as Java, Python, and C#.
Graphical User Interface (GUI)-based operating systems
such as Windows, Unix, Linux, Ubuntu, and Apple Mac
are being used.

Dr H N National College of Engineering 43


History of Computers
Fourth Generation (1975–1989):

— Used for Scientific, commercial, interactive online, and


network applications.

— Examples IBM PC, Apple II, TRS-80, VAX 9000,


CRAY1, CRAY-2, CRAY-X/MP.

— Highlights Faster, smaller, cheaper, powerful, reliable,


and easier to use than the previous generation computers

Dr H N National College of Engineering 44


History of Computers
Fifth Generation (1989– Present):

— Hardware Technology: Fifthgeneration computers are


manufactured using ICs with ULSI (Ultra Large Scale
Integrated) technology.

— Memory: Semiconductor memory is used as primary


memory; large capacity magnetic disks are used as built-
in secondary memory. Magnetic tapes and floppy disks
were used as portable storage devices, which have now
been replaced by optical disks and USB flash drives.
Dr H N National College of Engineering 45
History of Computers
Fifth Generation (1989– Present):

— Programming is done in
Software Technology:
high-level programming languages such as
Java, Python, and C#. Graphical User
Interface (GUI)-based operating systems
such as Windows, Unix, Linux, Ubuntu, and
Apple Mac are being used.

Dr H N National College of Engineering 46


History of Computers
Fifth Generation (1989– Present):
Used for: Scientific, commercial, interactive online, multimedia (graphics,
audio, video), and network applications.

Examples: IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2,


Param super computer.

Dr H N National College of Engineering 47


History of Computers
Fifth Generation (1989– Present):
Highlights:
• Faster, smaller, cheaper, powerful, reliable, and easier to use than the
previous generation computers.
•Speed of microprocessors and the size of memory are growing
rapidly.
•High-end features available on mainframe computers in the fourth
generation are now available on the microprocessors.
• They consume less power than computers of prior generations.
• Air-conditioned rooms required for mainframes and supercomputers
but not for microprocessors.
Dr H N National College of Engineering 48
Classification of Computers
— Computers can be broadly classified into four
categories based on their speed, amount of data that
they can process, and price

Dr H N National College of Engineering 49


Supercomputer:
— Among the four categories, the supercomputer is the
fastest, most powerful, and most expensive computer.

— Supercomputers were first developed in the 1980s to


process large amounts of data and to solve complex
scientific problems.

— Supercomputers use parallel processing technology


and can perform more than one trillion calculations
per second.
Dr H N National College of Engineering 50
Supercomputer:
— 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.

— PARAM is a series of made in Bharat supercomputers designed and assembled


by the Centre for Development of Advanced Computing (C-DAC) in Pune.

— PARAM means “Supreme" in the Sanskrit language, whilst also creating an


acronym for "Parallel Machine".
—
Some other examples of supercomputers are CRAY-1, CRAY-2, Control Data
CYBER 205, and ETA A-10.

Dr H N National College of Engineering 51


Classification of Computers
Mainframe computer:

— 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.

— As with supercomputers, mainframes can also support multiple


processors. For example, the IBM S/390 mainframe can support
50,000 users at the same time.

Dr H N National College of Engineering 52


Classification of Computers
Mainframe computer:
— Users can access mainframes by either using terminals
or via PCs. The two types of terminals that can be
used with mainframe systems are as follows:

Dr H N National College of Engineering 53


Classification of Computers
Dumb Terminal:

— Dumb terminal consists of only a monitor and a


keyboard. They do not have their own CPU and
memory and use the mainframe system’s CPU and
storage devices.

Dr H N National College of Engineering 54


Classification of Computers
Intelligent Terminals:

— In contrast to dumb terminals, intelligent terminals


have their own processor and thus can perform some
processing operations. However just like the dumb
terminals, they do not have their own storage space.
Usually PCs are used as intelligent terminals to
facilitate data access and other services from the
mainframe system.

Dr H N National College of Engineering 55


Classification of Computers
Intelligent Terminals:

— 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. IBM is the major manufacturer of
mainframe computers. Some examples of mainframe
computers include IBM S/390, control data CYBER 176,
and Amdahl 580.

Dr H N National College of Engineering 56


Classification of Computers
Minicomputer:
— Smaller, cheaper, and slower than mainframes
— Can be used as servers in a networked environment.
— Widely used in business, education, hospitals,
government
— Example: AS/400 computers (IBM corporation),

Dr H N National College of Engineering 57


Classification of Computers
Microcomputer:
Desktop PCs:
— Most popular model
— Widely used in homes and offices
Laptops:
— Very handy and easily portable.
— Storage capacity is almost equivalent to that of a desktop
computer.
— For input, laptops have a built-in keyboard and a touchpad.
— More expensive than desktop computers.

Dr H N National College of Engineering 58


Classification of Computers

Workstation:
— Single user computer.
— Same features as PCs with higher processing speed.
— Have advanced processors, more RAM and storage capacity.
— Can be used as servers in a networked environment.

Dr H N National College of Engineering 59


Classification of Computers

Network Computers:
— Designed to be used as terminals in a networked environment.
— Have less processing power, memory and storage.
— Those used to access internet or intranet are often known as
internet PCs or internet boxes.
— Some used in homes do not even have a monitor. They may be
connected to a TV. They are called WebTV.

Dr H N National College of Engineering 60


Classification of Computers
Tablet PCs: A tablet PC is a computing device that is smaller than a
laptop, but bigger than a smartphone. Features such as user-friendly
interface, portability, and touch screen have made them very popular in
the last few years. These days, a wide range of high-performance
tablets are available in the market. While all of them look similar from
outside, they may differ in features such as operating system, speed of
data connectivity, camera specifications, size of the screen, processing
power, battery life, and storage capability.

— While users can easily type directly on the surface of a tablet, some
users prefer a wireless or bluetooth-connected keyboard. These days,
tablets also offer an optional docking station with keyboards that
transforms the tablet into a full-featured notebook.

Dr H N National College of Engineering 61


Classification of Computers
Tablet PCs:

— The following are the uses of Tablet PCs:

— View presentations
— Video-conferencing
— Reading e-books, e-newspaper Watching movies, Playing games
— Sharing pictures, video, songs, documents
— 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,
exchanging documents, taking notes, and giving presentations
— Tablets are best used in crowded places such as airports and coffee shops,
where size and portability become more important.

Dr H N National College of Engineering 62


Applications of Computers
— When the first computers were developed, they were used only in the fields of
mathematics and science. In fact, the first effective utilization of computers
was for decoding messages in military applications.

— Later on, computers were used in real-time control systems, like for landing on
the moon, radar/missile

— However, with the advancement of technology, the cost of computers and their
maintenance declined. This opened the way for computers to be extensively
used in the business and commercial sector for information processing.

— Today, computers are widely used in fields such as engineering, health care,
banking, education, etc.

Dr H N National College of Engineering 63


Applications of Computers
— Let us discuss how computers are being effectively utilized to perform
important tasks:

— 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 (which is very useful where the same text has to be
repeated several times).

— Internet: 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 any library. Using e-mail, the user can communicate in seconds
with a person who is located thousands of miles away. Chat software enables
users to chat with another person in real-time. Video conferencing tools are
becoming popular for conducting meetings with people who are unable to be
present at a particular place.

Dr H N National College of Engineering 64


Applications of Computers
— 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.
— Word Digital video or audio composition Computers make
audio or video composition and editing very simple. This has
drastically reduced the cost of equipment to compose music or
make a film. Graphics engineers use computers for developing
short or full-length films and creating 3-D models and special
effects in science fiction and action movies. Desktop publishing
Desktop publishing software enables us to create page layouts
for entire books.

Dr H N National College of Engineering 65


Basic Terminologies
q Bit: A bit (short for binary digit) is the smallest unit of data
in a computer. A bit has a single binary value, either 0 or 1.
q Byte: Eight bits makes one byte
q Nibble: Half a byte (four bits) is called a nibble.
q Word: Normally, four eight-bit bytes (4 bytes) form a 32-bit
word.

Dr H N National College of Engineering 66


Basic Organization of a Computer
— A computer is an electronic device that performs the
following major operations:
— Accepting data or instructions (input)
— Storing data
— Processing data
— Displaying results (output)
— Controlling and coordinating all operations inside a
computer

Dr H N National College of Engineering 67


Basic Organization of a Computer

Dr H N National College of Engineering 68


Basic Organization of a Computer
— Input is the process of entering data and instructions (also known as programs )
into the computer system. The data and instructions can be entered by using
different input devices such as keyboard, mouse, scanner, and trackball.

— Note that computers understand binary language, which consists of only two
symbols (0 and 1), so it is the responsibility of the input devices to convert the
input data into binary codes.

— Storage is the process of saving data and instructions permanently in the


computer so that they can be used for processing. The computer storage space
not only stores the data and programs that operate on that data but also stores
the intermediate results and the final results of processing.

— A computer has two types of storage areas:

Dr H N National College of Engineering 69


Basic Organization of a Computer
— Primary storage, also known as the main memory, is the storage area that is
directly accessible by the CPU at very high speeds.

— It is used to store the data and parts of programs, the intermediate results of
processing, and the recently generated results of jobs that are currently being
worked on by the computer.

— Primary storage space is very expensive and therefore limited in capacity.

— Another drawback of main memory is that it is volatile in nature; that is, as


soon as the computer is switched off, the information stored gets erased.

— Hence, it cannot be used as a permanent storage of useful data and programs


for future use.

Dr H N National College of Engineering 70


Basic Organization of a Computer
— Secondary storage Also known as auxiliary memory, this memory is just the
opposite of primary memory.

— It overcomes all the drawbacks of the primary storage area.

— It is cheaper, non-volatile, and used to permanently store data and programs of


those jobs that are not being currently executed by the CPU.

— Secondary memory supplements the limited storage capacity of the primary


memory.

— An example is the magnetic disk used to store data, such as C and D drives, for
future use.

Dr H N National College of Engineering 71


Basic Organization of a Computer
— Processing: The process of performing operations on the data as per the
instructions specified by the user (program).

— Output: The process of giving the result of data processing to the outside world
(external to the computer system).

— Control Unit: It is the central nervous system of the computer system that
manages and controls all the other components.

Dr H N National College of Engineering 72


Basic Organization of a Computer
— Types of Memory:
— Computer memory is any physical device capable of
storing information temporarily like RAM (random
access memory), or permanently, like ROM (read-
only memory).

Dr H N National College of Engineering 73


Basic Organization of a Computer

Dr H N National College of Engineering 74


Basic Organization of a Computer

Dr H N National College of Engineering 75


Read Only Memory (ROM)
q Stores crucial information essential to
operate the system, like the program
essential to boot the computer.
q It is not volatile.
q Always retains its data.
q Used in embedded systems or where the
programming needs no change.
q Used in calculators and peripheral devices.

Dr H N National College of Engineering 76


q PROM (Programmable read-only memory) – It can be
programmed by user. Once programmed, the data and
instructions in it cannot be changed.

q EPROM (Erasable Programmable read only memory) – It can be


reprogrammed. To erase data from it, expose it to ultra violet
light. To reprogram it, erase all the previous data.

q EEPROM (Electrically erasable programmable read only


memory) – The data can be erased by applying electric field, no
need of ultra violet light. We can erase only portions of the
chip.

Dr H N National College of Engineering 77


Basic Organization of a Computer
— Output is the process of giving the result of data processing to the outside
world (external to the computer system).

— The results are given through output devices such as monitor, and printer.

— Since the computer accepts data only in binary form and the result of
processing is also in binary form, the result cannot be directly given to the user.

— The output devices, therefore, convert the results available in binary codes into
a human readable language before displaying it to the user.

— CPU is the combination of the arithmetic logic unit (ALU) and the CU. It is the
brain of the computer system because the entire processing of data is done in
the ALU, and the CU activates and monitors the operations of other units (such
as input, output, and storage) of the computer system.

Dr H N National College of Engineering 78


Basic Organization of a Computer
— Control unit (CU) is the central nervous system of the entire computer system. It
manages and controls all the components of the computer system. It decides the
manner in which instructions will be executed and operations performed. It takes care
of the step-by-step processing of all operations that are performed in the computer.

— Processing is the process of performing operations on the data as per the instructions
specified by the user (program) is called processing.

— Data and instructions are taken from the primary memory and transferred to the ALU,
which performs all sorts of calculations. The intermediate results of processing may be
stored in the main memory, as they might be required again.

— When the processing completes, the final result is then transferred to the main memory.
Hence, the data may move from main memory to the ALU multiple times before the
processing is over

Dr H N National College of Engineering 79


Basic Organization of a Computer :Input
Output Devices
Input Devices:
— These are the devices through which data and instructions are fed to the computer.

Dr H N National College of Engineering 80


Basic Organization of a Computer :Input
Output Devices

— Keyboards:

— The most common of all input devices is the keyboard. Several versions of
keyboards are available. The best and most expensive of these is the full-stroke
keyboard.

— This is ideal for word processing and other volume data and program entry
activities. This type of keyboard is available with most mainframe computer
terminals or the expensive microcomputer systems.

— Some popular microcomputers offer enhanced keyboard for easy entry of


numbers. This is accomplished with a smaller group of keys known as a
numeric keypad at the right of the keyboard.

Dr H N National College of Engineering 81


Basic Organization of a Computer :Input
Output Devices
— Keyboards:

— Keyboards generally utilize integrated circuits to perform essential functions,


such as determining the combination of 1s and 0s, or binary code, to send to
the CPU, corresponding to each key depressed, switching between shifted and
non-shifted keys, repeating a key code if a key is held down for a prolonged
period of time, and temporarily storing or "buffering" input when keys are
typed too fast.

— The keyboard arrangement provided as standard on most keyboards is the


QWERTY arrangement, named for the six letters beginning the row at the top
left of the keyboard.

— This QWERTY keyboard arrangement has been used for nearly a century.

Dr H N National College of Engineering 82


Basic Organization of a Computer :Input
Output Devices
— Keyboards:

— The Dvorak Simplified Keyboard (DSK) arrangement, designed in 1932 by August


Dvorak, is the result of extensive ergonomic studies. Dvorak noted that with the
QWERTY keyboard arrangement, typists used the weakest fourth and fifth fingers of
their left hand a large proportion of the time.

— Thus, Dvorak rearranged the keyboard so that the five more frequently used vowels (a,
o, e, u, and i) and the five most frequently used consonants (d, h, t, n, and s) were
positioned on the home row where the fingers of the left and right hands rest,
respectively.

— Thus, 70 percent of the typing is done on the home row. He then placed the next most
frequently used characters in the row above the home row and the least frequently used
characters in the row below the home row. This resulted in a reduction of finger
movement of approximately 80 percent and overall, an increase in productivity of
nearly 40 percent.

Dr H N National College of Engineering 83


Basic Organization of a Computer :Input
Output Devices
— Keyboards:

— Expert typists and word processors generally agree that using the Dvorak
arrangement increases productivity while simultaneously decreasing fatigue.

— The world's fastest typing speed, nearly 200 words per minute, was achieved
on a Dvorak keyboard. Despite these improvements the QWERTY keyboard
arrangements is still the most common because of the difficulty of overcoming
inertia and retraining.

— In the mean while, microcomputer manufacturers and software vendors are


producing software that will convert your keyboard from QWERTY to Dvorak,
and back again at will. To date, larger computer systems employ the traditional
QWERTY arrangement only.

Dr H N National College of Engineering 84


Basic Organization of a Computer :Input
Output Devices
— Mouse:

Dr H N National College of Engineering 85


Basic Organization of a Computer :Input
Output Devices
— Trackball:

Dr H N National College of Engineering 86


Basic Organization of a Computer :Input
Output Devices
— Touchpad:

Dr H N National College of Engineering 87


Basic Organization of a Computer :Input
Output Devices
— Handheld Devices:

Dr H N National College of Engineering 88


Basic Organization of a Computer :Input
Output Devices
— Optical Input Devices:

Dr H N National College of Engineering 89


Basic Organization of a Computer :Input
Output Devices
— Barcode Reader:

Dr H N National College of Engineering 90


Basic Organization of a Computer :Input
Output Devices
— Image Scanner:

Dr H N National College of Engineering 91


Basic Organization of a Computer :Input
Output Devices
— Optical Character Recognition (OCR) :

Dr H N National College of Engineering 92


Basic Organization of a Computer :Input
Output Devices
— Optical Mark Recognition (OMR)

Dr H N National College of Engineering 93


Basic Organization of a Computer :Input
Output Devices
— Magnetic Ink Character Reader (MICR)

Dr H N National College of Engineering 94


Basic Organization of a Computer :Input
Output Devices
— Audio/Video Input Devices

Dr H N National College of Engineering 95


Basic Organization of a Computer :Input
Output Devices
Output Devices:
— These are the devices that display or print the processed results from the
computer.

Dr H N National College of Engineering 96


Basic Organization of a Computer :Input
Output Devices
Output Devices:
— These are the devices that display or print the processed results from the
computer.

— Monitors: most commonly used display device that utilizes a cathode ray tube
(CRT).

— CRT monitors generally produce images by the raster-scan method. In this


method, an electron beam varying in intensity, is moved back and forth
horizontally across the face of the monitor.

— As the beam is directed to each spot on the phosphor-coated screen, it


illuminates the spot in proportion to the voltage applied to the beam.

Dr H N National College of Engineering 97


Basic Organization of a Computer :Input
Output Devices

Dr H N National College of Engineering 98


Basic Organization of a Computer :Input
Output Devices
— Monitors:
— Each spot represents a picture element or pixel.

— When the electron beam has scanned the entire screen and
illuminated each pixel, one can see a complete image.

— The image that can be seen is the one traced on the retinas of eyes by
the light beam. However, this image will fade unless it is refreshed.

— Thus, the electron beam must scan the screen very rapidly (a
minimum of 60 times per second), so that the intensity of the image
remains approximately the same and the screen does not appear to
flicker.

Dr H N National College of Engineering 99


Basic Organization of a Computer :Input
Output Devices
— Monitors:

— The screen resolution of a particular monitor is determined by the


number of pixels that make up the screen.

— Monitors are currently available with 64,000 to more than 2 million


pixels per screen.

— The greater the resolution of a monitor the greater the storage


demand on the computer.

— This is because the image must be stored in memory before it can be


displayed

Dr H N National College of Engineering 100


Basic Organization of a Computer :Input
Output Devices
— Projectors:

Dr H N National College of Engineering 101


Basic Organization of a Computer :Input
Output Devices
— Printers:

— The printer is the most common output device.

— It produces permanent visual record of the data output from a computer.

— It is capable of producing business reports and documents currently available.

— Printers are capable of printing from 150 to over 20,000 lines per minute, with
each line having up to 150 characters.

— Thus, a maximum printing speeds of approximately 50,000 characters per


second is possible.

Dr H N National College of Engineering 102


Basic Organization of a Computer :Input
Output Devices
Printers:

Dr H N National College of Engineering 103


Basic Organization of a Computer :Input
Output Devices
Impact Printers:

Dr H N National College of Engineering 104


Basic Organization of a Computer :Input
Output Devices
Dot Matrix Printers:
— Print characters as a pattern of dots
— Have a print head (or Hammer) that consists of pins representing the
character or image.
— The print head prints by striking an ink-soaked cloth ribbon against the
paper.

Daisy Wheel Printers


— The print head is a circular wheel
— To print a character, the wheel is rotated in such a way that the character to
be printed is positioned just in front of the printer ribbon

Dr H N National College of Engineering 105


Basic Organization of a Computer :Input
Output Devices
Printers:

— Printers print on plain paper or on specially prepared single-or


multiple copy forms, such as invoices, stationery, labels, checks, bills
and other special-purpose forms used in business and industry.
— They can print both text and graphics in black and white or in color.

— https://www.ebookbou.edu.bd/Books/Text/SST/DCSA/dcsa_1201/Un
it-04.pdf

— https://www.scribd.com/presentation/460442828/computer-Chapter-2

Dr H N National College of Engineering 106


Basic Organization of a Computer :Input
Output Devices
Plotters:
— Used to print vector graphics with high-print quality
— Widely used to draw maps, in scientific applications, and in CAD, CAM, and CAE

Drum plotters
— Used to draw graphics on paper that is wrapped around a drum
— Usually used with mainframe and minicomputer systems

Flatbed plotters

— The paper is spread on the flat rectangular surface of the plotter, and the pen is moved
over it
— Less expensive, and are used in many small computing systems

Dr H N National College of Engineering 107


Basic Organization of a Computer :Input
Output Devices
Inkjet Printers
— The print head has several tiny nozzles, also called jets. As the paper moves
past the print head, the nozzles spray ink onto it, forming characters and
images.
— Cartridges have to be changed frequently.

Laser Printers
— Work at very high speeds and produce high-quality text and graphics.
— A laser beam ‘draws’ the document on a drum which is coated with a photo-
conductive material.
— After the drum is charged , it is rolled in a toner (a dry powder type of ink)
— The toner sticks to the charged image on the drum and transferred onto a piece
of paper.

Dr H N National College of Engineering 108


Basic Organization of a Computer :Input
Output Devices
Non-Impact Printers
— Much quieter as their printing heads do not strike the paper
— Offer better print quality, faster printing, and the ability to create prints that
contain sophisticated graphics
— Use either solid or liquid cartridge-based ink, which is either sprayed,
dripped, or electrostatically drawn onto the page

Advantages
— Produce prints of good quality
— Noiseless, fast
— Can print text in different fonts
Disadvantage
— Expensive as ink cartridges used by them are costly
Dr H N National College of Engineering 109
Designing Efficient Programs
PROGRAMMING PARADIGMS
— A programming paradigm is a fundamental style of programming that defines
how the structure and basic elements of a computer program will be built.

— The style of writing programs and the set of capabilities and limitations that a
particular programming language has depends on the programming paradigm it
supports.

These paradigms, in sequence of their application, can be classified as follows:

— Monolithic programming — emphasizes on finding a solution


— Procedural programming—lays stress on algorithms
— Structured programming—focuses on modules
— Object-oriented programming—emphasizes on classes and objects

Dr H N National College of Engineering 110


Designing Efficient Programs

— Logic Oriented Programming – Focus on goals usually expressed in predicate


calculus.

— Rule Oriented Programming – make use of ‘if-then-else’ rules for computation.

— Constraint oriented programming – utilizes invariant relationships to solve a


problem.

Dr H N National College of Engineering 111


Designing Efficient Programs

— Monolithic programs have just one program module as such programming


languages do not support the concept of subroutines. Therefore, all the actions
required to complete a particular task are embedded within the same
application itself. This not only makes the size of the program large but also
makes it difficult to debug and maintain.

— Programs written using monolithic programming languages consist of global


data and sequential code. The global data can be accessed and modified from
any part of the program. Examples are Assembly Language and BASIC.

Dr H N National College of Engineering 112


Designing Efficient Programs

Dr H N National College of Engineering 113


Designing Efficient Programs

Dr H N National College of Engineering 114


Designing Efficient Programs

Dr H N National College of Engineering 115


Designing Efficient Programs

Dr H N National College of Engineering 116


Designing Efficient Programs

Dr H N National College of Engineering 117


Designing Efficient Programs

Dr H N National College of Engineering 118


Designing Efficient Programs

Dr H N National College of Engineering 119


Designing Efficient Programs

Dr H N National College of Engineering 120


Designing Efficient Programs

Dr H N National College of Engineering 121


Designing Efficient Programs

Dr H N National College of Engineering 122


Designing Efficient Programs

Dr H N National College of Engineering 123


Designing Efficient Programs

Dr H N National College of Engineering 124


Designing Efficient Programs

Dr H N National College of Engineering 125


Designing Efficient Programs

Dr H N National College of Engineering 126


Designing Efficient Programs

Dr H N National College of Engineering 127


Designing Efficient Programs

Dr H N National College of Engineering 128


Designing Efficient Programs

Dr H N National College of Engineering 129


Designing Efficient Programs

Dr H N National College of Engineering 130


Designing Efficient Programs

Dr H N National College of Engineering 131


Introduction to C
— The programming language ‘C’ was developed in the early 1970s by Dennis Ritchie at
Bell Laboratories.

— Although C was initially developed for writing system software, today it has become
such a popular language that a variety of software programs are written using this
language.

— The greatest advantage of using C for programming is that it can be easily used on
different types of computers.

— Many other programming languages such as C++ and Java are also based on C which
means that you will be able to learn them easily in the future. Today, C is widely used
with the UNIX operating system.

— https://www.ebookbou.edu.bd/Books/Text/SST/DCSA/dcsa_1201/Unit-04.pdf
— https://www.scribd.com/presentation/460442828/computer-Chapter-2

Dr H N National College of Engineering 132


Introduction to C
Taxonomy of C Language

Dr H N National College of Engineering 133


Introduction to C
— C language is derived from ALGOL (the first language to use a block structure).

— ALGOL’s introduced in 1960s led the way for the development of structured
programming concept.

— In 1967 Martin Richards developed a language called BCPL (Basic Combined


Programming language).

— In 1970, Ken Thompson developed a language called B, which was used to develop a
first version of UNIX.

— C was developed by Dennis Ritchie in 1972 that took concepts from ALGOL, BCPL,
and B.
— The traditional C was documented and popularized in the book The C Programming
Language by Brain W. Kernighan and Dennis Rictchie in 1978.

Dr H N National College of Engineering 134


Introduction to C
— C also supports the concepts of data types. Since UNIX operating system was
also developed at Bell Laboratories along with C language, C and UNIX are
strongly associated with each other.

— The tremendous growth of C language resulted in the development of different


versions of the language that were similar but incompatible with each other.
Therefore in the year 1983, the American National Standards Institute (ANSI)
started working on defining the standard for C. This was approved in
December 1989 and came to known as ANSI C.

— In 1990, the International Standard Organization (ISO) adopted the ANSI


standard. The version of C came to be known as C89.

— In 1995, some minor changes were made to C89; the new modified version
was known as C95.

Dr H N National College of Engineering 135


— During 1990s C++ and Java Programming languages become more popular
among the users so the Standardization Committee of C felt that a few features
of C++/Java if added to C would enhance its usefulness. So, in 1999 when
some significant changes were made to C95, the modified version came to be
known as C99.

Some of the changes made in the C99 version are as follows:

— Extension to the character type so that they can support even non-English
types.
— Boolean Data Type
— Extension to the integer data type
— Inclusion of type definitions in the for statements
— Inclusion of imaginary and complex types
— Addition of //, better known as C++ style line comment

Dr H N National College of Engineering 136


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


language, which makes it best suited for writing system software as well as
business packages.

Characteristics of C language:

— C is a high level programming language, which enables the programmer to


concentrate on the problem at hand and not to worry about the machine code
on which the program would run.
— Small size C has only 32 keywords. This makes it relatively easy to learn.
— C makes extensive use of function calls.
— C is well suited for structured programming.

Dr H N National College of Engineering 137


Characteristics of C
— Structured language as the code can be organized as a collection of one or more
functions.
— Quick language as well written C program is likely to be as quick as or quicker than a
program written in any other language.
— Facilitates low level (bitwise) programming.
— Supports pointers to refer computer memory, arrays, structures and functions.
— C is a core language as many other programming languages (like C++, Java, Perl, etc.)
are based on C.
— C is a portable language, i.e., a C program written for one computer can be run on
another computer with a little or no modification.
— C is a extensible language as it enables user to add his own functions to C library.
— C is often treated as second best language for any given programming task.

Dr H N National College of Engineering 138


Uses of C
Ø Primarily used for system programming.

Ø Developing compilers, libraries and interpreters.

Ø For portability and convenience reasons, C is used as


intermediate language. Example, BitC, Haskell
Compiler.

ØC is widely used to implement end-user applications


Dr H N National College of Engineering 139
Structure of a C Program
— A C program contains one or more functions, where a function is defined as a
group of statements that perform a well-defined task.
— The statements in a function are written in a logical sequence to perform a
specific task.

— The main() function is the most important function and is a part of every C
program. Rather, the execution of a C program begins with this function.

— C program can have any number of functions depending on the tasks that have
to be performed, and each function can have any number statements.

— You can choose any name for functions with an exception that every program
must contain one function that has its name as main().

Dr H N National College of Engineering 140


Structure of a C Program
Preprocessor directives
Global declarations
main()
{
Local declaration
Statements
}
Function1()
{
local declarations
statements
}
Function2()
{
local declarations
statements
}

Dr H N National College of Engineering 141


Structure of a C Program

Dr H N National College of Engineering 142


Structure of a C Program
— All the functions are divided into two parts the declaration section and
the statement section.

— The declaration section proceeds the statement section and is used to


describe the data that will be used in the function.

— Note: Data declaration section within the functions are known as local
declaration as that data will be visible only within that function. The
statement section in a function contains the code that manipulates the
data to perform a specific task.

Dr H N National College of Engineering 143


Writing the first C Program

#include<stdio.h>: stdio basically stands for Standard Input/Output, which means it has
functions for input and output of data like reading values from the keyboard and printing
the results on the screen.

int main(): Every C program contains a main() function which is the starting point of the
program. int is the return value of the main function. After all the statements in the
program have been executed, the last statement of the program will return an integer
value to the operating system.

{ } The two curly brackets are used to group all the related statements of the main
function.

Dr H N National College of Engineering 144


Writing the first C Program
— The printf function is defined in the stdio.h file and is
used to print text on the screen. The message that has
to be displayed on the screen is enclosed within
double quotes and put inside brackets.
— \n is an escape sequence and represents a newline
character. It is used to print the message on a new line
on the screen.

Dr H N National College of Engineering 145


Writing the first C Program
— return 0; used to return value 0 to the operating
system to give an indication that there were no
errors during the execution of the program.

— Name the C program as first.c


— on UNIX/Linux OS, type $cc first.c -o first.
— The –o is for the output file name. If you leave
out the –o, then the file name a.out is used.

Dr H N National College of Engineering 146


Writing the first C Program

Dr H N National College of Engineering 147


Writing the first C Program
— The cc command is used to compile your C program.

— If there are any mistakes in the program, then the compiler will tell you what
mistake(s) you have made and on which line the error has occurred.

— In case of errors, you need to re-open your .c file and correct the mistakes.
However, if everything is right, then no error(s) will be reported and the
compiler will create an .exe file for your program.

— This .exe file can be directly run by typing "first.exe" for Windows and "./first"
for UNIX/Linux operating system. When you run the .exe file, the output of
the program will be displayed on screen. That is,

— Welcome to the world of C

Dr H N National College of Engineering 148


Writing the first C Program

Dr H N National College of Engineering 149


Files used in C Program
Every C program has four kinds of files associates with it. These includes:

Dr H N National College of Engineering 150


Files used in C Program
— Source Code File:
— Contains the source code of the program with extension .c and defines the main
function. The main function is the starting point of C program. A C program in general
may include even other source code files.
— Standard Header Files: Examples of these standard header files include:

— All the header files are referenced at the start of the source code file that uses one or
more functions from these files.

Dr H N National College of Engineering 151


Files used in C Program
— Advantages of header files:

Ø Compile the subroutines once and use them many times in different programs
(where these subroutines are by linking to the object file at run time.

Ø If you want to make changes to the subroutines, then change is done at one
place and only Change is reflected in the programs wherever the subroutines
(defined in the header file) are called.

— Object files: Generated by the compiler as a result of processing the source


code. These files contain the compact binary code of the function definitions.
Linker uses these object files and links them to produce en executable file.

Dr H N National College of Engineering 152


Files used in C Program
— Binary Executable files: Generated by the linker by linking the various object
files.

— SourceFile->Preprocessor->Compiler->ObjectFiles->Linker->ExecutableFiles

— Linker is a program in a system which helps to link object modules of a


program into a single object file.

— Compiling and Executing C Programs :


— Once the C program is written, you must run through the C compiler. While
the C program is human-readable, the executable file on the other hand is in
binary form readable by machine.

— Note: Every programming language has its own compiler.

Dr H N National College of Engineering 153


Object Files
— Object files are generated by the compiler as a result of
processing the source code file. Object files contains
compact binary code of the function definitions.

— Linker uses these object files to produce an executable


file(.exe) by combining the object files together.

— Object files have ‘.o’ extension, although some operating


systems includes Windows and MS-DOS have a ‘.obj’
extension for the object files.

Dr H N National College of Engineering 154


Binary Executable Files
— The binary executable file is generated by the linker.
The linker links the various object files to produce a
binary file that can be directly executed.

— On windows operating systems executable files have a


‘.exe’ extension.

Dr H N National College of Engineering 155


Compiling and Executing C Programs
— C is a compiled language. So once a C program is written, you must run it through a C
compiler that can create an executable file to be run by the computer.

— While the C program is human-readable, the executable file on the other hand is
machine-readable.

— The mechanical parts of running the C program begins with one or more program
source files, and ends with an executable file, which can be run on a computer.

— The programming process starts with creating a source file and this is then processed
by a special program called a compiler.

— The compiler translates the source code into an object code. The object code contains
the machine instructions for the CPU, and calls to the operating system API
(Application Programming Interface).

Dr H N National College of Engineering 156


Compiling and Executing C Programs
— However, even the object file is not an executable file. Therefore, in the
next step, the object file is processed with another special programs
called the linker.

— While there is a different compilers for every individual language, 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.

Dr H N National College of Engineering 157


Compiling and Executing C Programs

Overview of compilation and execution process.

Dr H N National College of Engineering 158


Compiling and Executing C Programs

Preprocessing before compilation

Dr H N National College of Engineering 159


Compiling and Executing C Programs
— The compilation process as shown is done in two steps. In the first step,
the preprocessor program reads the source file as text, and produces
another text file as output.

— Source code lines which begins with the # symbol are actually not
written in C but in the preprocessor language.

— 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. The linker combines the object file with library routines to
produce the final executable file.

Dr H N National College of Engineering 160


Compiling and Executing C Programs

Modular programming-the complete compilation and execution process.

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. These object files
are combined by the linker to produce an executable file.

Dr H N National College of Engineering 161


Using Comments
— Comments are just a way of explaining what a program does.
The compiler ignores the comments when forming the object
file. This means that the comments are non-executable
statements.

— C supports 2 types of comments:

— // Is used to comment a single line statement.

— /* is used to comment multiple line statements.


Example: /* is ended with */.

Dr H N National College of Engineering 162


Using Comments
/* Author: JSSATEB
Description: to print ‘welcome to the world of C’ */

#include<stdio.h>
int main()
{
printf(“ \n Welcome to the world of C \n”);
// prints message
return 0;
// return a value 0 to the operating system
}

Dr H N National College of Engineering 163


Tokens
— Tokens are the basic building blocks in C language.
— You may think of a token as the smallest individual unit in a C program. This means
that a program is constructed using a combination of these tokens.

Dr H N National College of Engineering 164


Character set in C
— Like natural languages, computer language also use a character set that defines that
fundamental units used to represent information.

— In C character means any letter from English alphabet, a digit or a special symbol used to
represent information.

— These characters when combined together form tokens that acts as basic building blocks of
a C program.
— The character set of C is as below:
— a. English alphabet: Include both lower case (a-z) as well as upper case (A-Z).
— b. Digit: Include numerical digits from 0 to 9
— c. Special character: Include symbols such as ~, @, %, ^, #, &, ….etc.,
— d. White space characters: These characters are used to print a blank space on the screen.
— e. Escape sequence: Escape sequences ‘\’

Dr H N National College of Engineering 165


Character set in C
White Space Character Meaning

\b Blank Space

\t Horizontal Tab

\v Vertical return

\r Carriage Return

\f Form feed

\n New Line

White Space Characters in C

Dr H N National College of Engineering 166


Keywords
— C has a set of reserved words often known as keywords that cannot be used as an
identifier.
— All keywords are basically a sequence of characters that have a fixed meaning.
— By convention all keywords must be written in lowercase (small) letters.

Dr H N National College of Engineering 167


Identifiers
— Identifiers, helps us to identify data and other objects in the program.
— Identifiers are basically the names given to program elements such as variables, arrays, and
functions.
— Identifiers may consists of sequence of letters, numerals, or underscores.

Rules for forming identifier names:


— Identifiers cannot include any special characters or punctuation marks (#, $, ^, ., etc.,) except
the underscore ‘_’.
— There can not be two successive underscores.
— Keywords can not be used as identifiers.
— The case of alphabetic characters that form the identifier name is significant. Example,
‘FIRST’ is different from ‘first’.
— Identifiers must begin with a letter or an underscore.
— Identifiers can be of any reasonable length. They should not contain more than 31
characters. Dr H N National College of Engineering 168
Basic Data Types in C
C language provides very few basic data types.

Data Keyword Size in Range Use


Type Used bytes
Character char 1 -128 to 127 To store characters
Integer Int 2 -32768 to 32768 To store integer values

Floating float 4 3.4E-38 to To store floating point


point 3.4E+38 numbers
Double double 8 1.7E-308 to To store big floating
1.7E+308 point numbers
Valueless void 0 Valueless -

Dr H N National College of Engineering 169


Basic Data Types in C

Dr H N National College of Engineering 170


Basic Data Types in C
— The char data type is of one byte and is used to store single characters.

The void type holds no value. It is primarily used in below three cases:

— To specify the return type of a function (when the function returns no value).
— To specify the parameters of the function (when the function accepts no arguments from the
caller).
— To create generic pointers.

— Unsigned int/char keeps the sign bit free and makes the entire word available for storage of
the non-negative numbers.
— Sign bit is the leftmost bit of a memory word which is used to determine the sign of the
content stored in that word. When it is 0, the. Value is positive and when it is 1, the value is
negative.
Dr H N National College of Engineering 171
How are Float and Double stored?
— In computer memory, float and double values are stored in mantissa and
exponent forms where the exponent represents power of 2 (not 10).

— The number of bytes used to represent a floating point number generally


depends on the precision of the value. While float is used to declare single-
precision values, double is used to represent double-precision values.

— Floating point numbers use the IEEE (Institute of Electrical and Electronics
Engineers) format to represent mantissa and exponents. According to the
IEEE formats, a floating point value in its binary form is known as a
normalized form.

Dr H N National College of Engineering 172


How are Float and Double stored?

Dr H N National College of Engineering 173


Variables
— A variable is defined as a meaningful name given to a data storage location in computer
memory. When using a variable, we actually refer to address of the memory where the data
is stored.
— C language supports two kinds of variables: numeric and character.

9.12.1 Numeric Variables


— Numeric variables can be used to store either integer values or floating point values.
— While a integer value is a whole number without a fraction part or decimal point, a floating
point value can have a decimal point.
— Numeric variables may also be associated with modifiers, such as short, long, signed, and
unsigned.
— The difference between signed and unsigned numeric variables is that signed can be either
negative or positive but unsigned variables can only be positive.

Dr H N National College of Engineering 174


Variables
9.12.2 Character Variables:
— Character variables are just single characters enclosed within single quotes. These characters
could be any character from ASCII character set letters (‘a’, ‘A’), or special characters (‘&’).

9.12.3 Declaring Variables:


— Each variable to be used in the program must be declared. To declare a variable, specify the data
type of the variable followed by its name. The data type indicates the kind of values that the
variables will store.

Example: int emp_num;


float salary;

Dr H N National College of Engineering 175


Variables
— In C variables are declared at three basic places as follows:
— When a variable is declared inside a function it is known as a local variable.
— When a variable is declared in the definition of function parameters it is known as a
formal parameter.
— When the variable is declared outside all functions, it is known as global variables.

9.12.4 Initializing Variables:


— While declaring the variables, we can also initialize them as some value.
— Example:
— int emp_num = 7;
— float salary = 2156.35;
— char grade = ‘A’;

Dr H N National College of Engineering 176


Constants
— Constants are identifiers whose value do not change. While the values of the
variables can change at any time, values of constants can never be changed.

— Constants are used to define fixed values like mathematical constant pi.

— A constant is a explicit data value specified by the programmer.

— The value of the constant is known to the compiler at the compile time.

— C allows the programmer to specify the constant of integer type, float type,
char type, and string type.

Dr H N National College of Engineering 177


Constants

Dr H N National College of Engineering 178


Integer Constants
— A constant of integer type consists of sequence of digits.
Example: 1, 34, 567 are valid integer constants.

— 1234 is of type integer by default. For a long integer constant the


literal is succeeded with either ‘L’ or ‘l’, (like 1234L).

— Similarly an unsigned integer literal is written with a ‘U’ or ‘u’


suffix.
— Example: 1234u, 1234U.

Dr H N National College of Engineering 179


Floating Point Constants
— Integer numbers are inadequate to express numbers that have a fractional part.

— A floating point constant consists of an integer part, a decimal point, a fractional


part, and an exponent field containing an e or E followed by an integer where the
fraction part and integer part are a sequence of digits.

Examples: 0.02, -0.23, 123.456, +0.34, etc.,

— A literal like 0.07 is treated as of type double by default. To make it a float literal,
we must specify it using. Suffix F or f.

Examples: 0.02F, 0.34f

Dr H N National College of Engineering 180


Character Constant
— A character constant consists of a single character enclosed in single quotes.
Example: ‘a’, ’@’ are character constants.

— In computer characters are stored as ASCII codes.

9.13.4 String Constants


— A string constant is a sequence of characters enclosed in double quotes. So “a”, is not
same as ‘a’.
— The characters comprising the string constants are stored in successive memory
locations.
— When the string constant is encountered in C program, the compiler records the address
of the first character and appends a null character (‘\0’) to the string to mark the end of
the string.
Example: the length of the string literal “hello” is 6.
Dr H N National College of Engineering 181
Declaring constants
— To declare a constant, precede the normal variable declaration with const keyword and assign
it a value.
Example: const float pi=3.14

— The const keyword specifies that the value of pi cannot change.

— Another way to designate a constant is to use the pre-processor command define. Define is
preceded with # symbol.

— Although the #define statements can be placed anywhere in a C program, it is always


recommended that these statements be placed at the beginning of the program to make them
easy to find and modify at a later stage.
Example: #define pi 3.14159
#define service_tax 0.12
Dr H N National College of Engineering 182
Rules to followed in #define statement:
— Rule1: Constant names are usually written in capital letters to visually
distinguish them from other variable names which are normally written in
lower case characters. It is just a convention and not a rule.

— Rule2: No blank spaces are permitted between the # symbol and define
keyword.

— Rule3: Blank space must be used between #define and constant name and
between constant name and constant value.

— Rule4: #define is a pre-processor compiler directive and not a statement.


Therefore it does not end with a semi-colon.

Dr H N National College of Engineering 183


Input/Output Statement in C
— This deals the streams involved in accepting input and printing output in C.

9.14.1 Streams:

— A stream is the source of data as well as the destination of data. Streams are associated with a
physical device such as a monitor or a file stored on the secondary memory.

Dr H N National College of Engineering 184


Input/Output Statement in C
— In a text stream, sequence of characters is divided into lines with each line
being terminated with a new line character (\n). On the other hand binary
streams contains data values using their memory representation.

— Here the source of data is keyboard and destination of the data is the monitor.

Out
put

Dr H N National College of Engineering 185


Formatting Input/Output
— C language supports two formatting functions printf and scanf. Prntf is used to convert data
stored in the program into a text stream for output to the monitor.

— Scanf is used to concert the text stream coming from the keyboard to the data values and
stores them in program variables.

— 9.14.3 printf()

— The printf function ( stands for print formatting) is used to display information required by
the user and also prints the values of the variables.

— The printf function takes data values, convert them to a text stream using formatting
specifications in the control string and passes the resulting text stream to the standard output.

Dr H N National College of Engineering 186


Formatting Input/Output
— The control string may contain zero or more conversion specifications, textual data, and
control characters to be displayed.

— Each data value to be formatted into the text stream is described using a separate conversion
specification in the control string. The specification in the control string describes the data
values types , size and specific format information.

Dr H N National College of Engineering 187


Formatting Input/Output
— The syntax of printf function is:

printf(“ control string”, variable list);

— The function accepts two parameters – control string and variable list. The control string may
also contains the text to be printed like instruction to the user, captions, identifiers or any
other text.

— The control characters can also be included in the printf statement. These control characters
include \n, \t,\r, \a, etc.

— The protype of the control string can be given as follows:

%[flags][width][.precision][length modifier] type specifier


Dr H N National College of Engineering 188
Formatting Input/Output
— Each control string must begins with a % sign. The % character specifies how the next
variable in the list of variables has to be printed. After % sign follows:

— Flags: Is an optional argument which specifies output justification such as nunerical sign,
trailing zeros or octal, decimal, or hexadecimal prefixes.

Flags Description
¨ - ¨ Left-justify within the given field width
¨ + ¨ Display the data with its numeric sign (either + or -)
¨ # ¨ Used to provide additional specifiers like o, x, X, O, Ox, OX, for
octal and hexadecimal values, respectively, for values different
than zero.
¨ 0 ¨ The number is left-padded with zero (0) instead of spaces.

Dr H N National College of Engineering 189


Formatting Input/Output
— Width: Is an optional argument which specifies the minimum number of positions in the
output. If the data needs more space than specified, then printf overrides the width specified
by the user.

— Precision: Is an optional argument which specifies the maximum number of characters to


print.

— For integer specifiers (d, I, o, u, x, X): Precision flag specifies the minimum number of digits
to be written.

— For character string, precision specifies the maximum number of character to be printed.

— For floating point number, the precision flag specifies the number of decimal places to be
printed.

Dr H N National College of Engineering 190


Formatting Input/Output
— Length Modifiers:

Length Description
¨ h ¨ When the argument is a short int or unsigned short int
¨ l ¨ When the argument is a long int or unsigned long int (Used for integer
specifier)

¨ L ¨ When the argument is a long double (Used for floating point specifier)

Dr H N National College of Engineering 191


Formatting Input/Output
— Type Specifiers: Are used to define the type and the interpretation of the value of the
corresponding argument.

Type Description
¨ c ¨ For single character
¨ d ¨ For integer value
¨ f ¨ For floating type numbers
¨ E, e ¨ Floating point numbers in exponent format
¨ G, g ¨ Floating point numbers in the shorter of e format
¨ o ¨ For octal numbers
¨ s ¨ For a sequence of characters
¨ U ¨ For unsigned integer values
¨ X, x ¨ For hexadecimal values

Dr H N National College of Engineering 192


Formatting Input/Output
— The minimum field width and precision specifiers are usually constants. However, they may
also be provided by arguments to printf(). This is done by using the * modifier as shown in
the printf statement below.

— Printf(“%*.*f”, 10, 4, 1234.34);

— Here, the minimum field width is 10, the precision is 4, and the value to be displayed is
1234.34

Dr H N National College of Engineering 193


Formatting Input/Output
Examples:

— printf(“ \n Result: %d%c%f”, 12, ‘a’, 2.3);


— Result: 12a2.300000

— printf(“ \n Result: %d %c %f”, 12, ‘a’, 2.3);


— Result: 12 a 2.300000

— printf(“ \n Result: %d\t %c\t %f”, 12, ‘a’, 2.3);


— Result: 12 a 2.300000

Dr H N National College of Engineering 194


Formatting Input/Output
Examples:

— printf(“ \n Result: %d\t%c\t%6.2f”, 12, ‘a’, 245.37154);


— Result: 12 a 245.37

— printf(“ \n Result: %5d \t %x \t %#x”, 234, 234, 234);


— Result: 234 ea 0xea

— printf(" The number is %6d", 12);


— Result: The number is 12

— printf(" The number is %6d", 1234);


— Result: The number is 1234
Dr H N National College of Engineering 195
Formatting Input/Output
Examples:
— printf(" The number is %-6d", 1234);
— Result: The number is 1234__

— printf(" The number is %06d", 1234);


— Result: The number is 001234

— printf(" The price of this item is %09.2f rupees", 123.456);


— Result: The price of this item is 000123.46 rupees

— printf(" \n This is \'so\' beautiful");


— Result: This is 'so' beautiful

Dr H N National College of Engineering 196


Formatting Input/Output
Examples:

— printf(" \n This is \”so\” beautiful");


— Result: This is "so" beautiful

— printf(" \n a = |%-+7.2f| b=%0+7.2f c=%-0+8.2f", 1.2, 1.2, 1.2);


— Result: a = |+1.20 | b=+001.20 c=+1.20_____

Dr H N National College of Engineering 197


Formatting Input/Output
scanf()
— The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard.

— The scanf function takes a text stream from the keyboard, extracts and formats data from the
stream according to a format control string and then stores the data in specified program
variables.

— Syntax:

— scanf(“control string”, arg1, arg2, arg3, ……argn);

— The string specifies the type and format of the data that has to be obtained from the keyboard
and stored in the memory locations pointed by arguments arg1, arg2, arg3,….., argn, i.e.., The
arguments are the actually the variable addresses where each piece of data is to be stored.
Dr H N National College of Engineering 198
Formatting Input/Output
— The prototype of the control string is:

— %[*][width][modifier]type

— Here * is an optional argument that suppresses assignment of the input field, i.e., it indicates
that data should be read from the stream but ignored.

— Width: Is an optional argument that specifies the maximum number of character to be read.

— Modifier: Is an optional argument that can be h, l, or L for the data pointed by the
corresponding additional arguments.

— Type: Specifies the type of the data that has to be read. It also indicates how this data is
expected to be read from the user.

Dr H N National College of Engineering 199


Formatting Input/Output
Rules to use scanf function in C program:

Rule1: The scanf function works until:


¨ The maximum number of characters has been processed
¨ A white space character is encountered, or
¨ An error is detected

Rule2: Every variable that has to be processed must have a conversion specification associated with it.
Therefore the following scanf statement will generate an error as num3 has no conversion specification
associated with it.
¨ Example: scanf(“%d %d”, &num1, &num2, &num3);

Dr H N National College of Engineering 200


Formatting Input/Output
Rule3: There must be a variable address for each conversion specification. Therefore, the
following scanf statement will genearate an error as no variable address is given for the third
conversion specification.

Example: scanf(“%d %d %d”, &num1, &num2);


Rule4: An error will be generated if the format string is ended with a white space character.

Rule5: The data entered by the user must match the character specified in the control string,
otherwise an error will be generated and scanf will stop its processing.
Example: scanf(“%d / %d”, &num1, &num2, &num3);

Here the slash in the control string is neither a white space character nor a part of conversion
specification, so the user must enter data of the form 21/46.

Dr H N National College of Engineering 201


Formatting Input/Output
Rule6: Input data values must be separated by spaces.

Rule7: Any unread data value will be considered as a part of the data input in the next call to
scanf.

Rule8: When the field width specifier is used, it should be large enough to contain the input data
size.

Dr H N National College of Engineering 202


Formatting Input/Output
The following code shows how we input values in variables of different data types:

int num;
scanf(“%d ”, &num);

float salary;
scanf(“%f ”, &salary);

char ch;
scanf(“%c”, &ch);

char str[10];
scanf(“%s”, str);
Dr H N National College of Engineering 203
Formatting Input/Output
Example: The below code combines reading of variables of different data types in one single
statement.

int num;
float fnum;
char ch;
char str[10];
scanf(“%d %f %c %s”, &num, &fnum, &ch, str);

Dr H N National College of Engineering 204


Examples of printf/scanf
int num;
scanf(“%d”, &num);
printf(“%d”, num);
The printf function prints an integer value pointed by num on the screen.

float salary;
scanf(“%f”, &salary);
Printf(“.2%f”,salary);
The printf function prints the floating point value.

Dr H N National College of Engineering 205


Examples of printf/scanf
Find the output of the following program.
#include<stdio.h>
int main()
{
int a,b;
printf(“\n Enter the two four digit numbers:”);
scanf(”%2d %4d”, &a, &b);
printf(“\n The two numbers are: %d and %d”, a, b);
return 0;
}
Output:
Enter the two four digit numbers:1234 5678
The two numbers are: 12 and 34

Dr H N National College of Engineering 206


Write a program to demonstrate the use of printf statement to print values of different
data types.

#include<stdio.h>
int main()
{
//Declare and initiaze the variables
int num=7;
float amt=123.45;
char code= 'A';
double pi=3.1415926536;
long int population=10000000000;
char msg[]= "Hi";

// print the values of variables


printf(" \n Num=%d \n AMT=%f \n CODE=%c \n PI=%e \n POPULATION=%ld \n MESSAGE=%s", num, amt, code, pi,
population, msg);
return 0;
}
Dr H N National College of Engineering 207
Write a program to demonstrate the use of printf statement to print values of different
data types.

Output:
Num=7
AMT=123.450000
CODE=A
PI=3.141593e+00
POPULATION=10000000000
MESSAGE=Hi

Dr H N National College of Engineering 208


Write a program to calculate the area of a triangle using Hero’s formula

#include<stdio.h>
#include<math.h>
int main()
{
float a, b, c, area, s;
printf("\n Enter the length of the three sides of the triangle \n");
scanf("%f %f %f", &a, &b, &c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf(" \n Area=%f", area);
return 0;
}

Dr H N National College of Engineering 209


Write a program to calculate the area of a triangle using Hero’s formula

Output:
Enter the length of the three sides of the triangle
12
16
20
Area=96.000000

Dr H N National College of Engineering 210


Write a program to calculate the distance between two points.

#include<stdio.h>
#include<math.h>
int main()
{
int x1, x2, y1, y2;
float distance;
printf("\n Enter the x and y coordinates of first point: ");
scanf("%d %d", &x1, &y1);
printf("\n Enter the x and y coordinates of second point: ");
scanf("%d %d", &x2, &y2);
distance=sqrt((pow(x2-x1),2)+pow((y2-y1),2));
printf(" \n Distance =%f", distance);
return 0;
}
Dr H N National College of Engineering 211
Write a program to calculate the distance between two points.

Output:

Enter the x and y coordinated of the first point: 2 5


Enter the x and y coordinated of the second point: 3 7

Distance = 2.236068

Dr H N National College of Engineering 212


Detecting Errors During Data Input
When the scanf function completes reading all the data values, it returns the number of values
that are successfully read. This returns value can be used to determine whether there was any
error while reading the input.

scanf(“ %d %f %c”, &a, &b, &c);

Will return 3 if the user enters, say


12 12.34 A

It will return 1 if the user enters erroneous data like


12 ABC 12.34
This is because a string was entered while the user was expecting a floating point value. So the
scanf function reads only first data value correctly and then terminates as soon as it encounters a
mismatch between the type of the data expected and the type of data entered.
Dr H N National College of Engineering 213
Input/output Statements in C
— scanf: The scanf()function is used to read formatted data from the keyboard. The
syntax of the scanf() function can be given as

— scanf ("control string", arg1, arg2, arg3...argn);

— The control string specifies the type and format of the data that has to be obtained from
the keyboard and stored in the memory locations pointed by the arguments, arg1, arg2,
...,argn.

— The prototype of the control string can be given as,

— %[*][width][modifier]type

— * is an optional argument that suppresses assignment of the input field. That is, it
indicates that data should be read from the stream but ignored (not stored in the
memory location).

Dr H N National College of Engineering 214


Input/output Statements in C
— width is an optional argument that specifies the maximum number of
characters to be read.

— However, if the scanf function encounters a white space or an unconvertible


character, input operation is terminated.

— modifier is an optional argument (h, l, or L) , which modifies the type specifier.

— Modifier h is used for short int or unsigned short int, l is used for long int,
unsigned long int, or double values.

— Finally, L is used for long double data values. type specifies the type of data
that has to be read. It also indicates how this data is expected to be read from
the user.

Dr H N National College of Engineering 215


Input/output Statements in C
— // Create an integer variable that will
store the number we get from the user
int myNum;
// Ask the user to type a number
printf("Type a number: \n");
// Get and save the number the user types
scanf("%d", &myNum);
// Output the number the user typed
printf("Your number is: %d", myNum);

Dr H N National College of Engineering 216


Input/output Statements in C
— // Create an int and a char variable
int myNum;
char myChar;

// Ask the user to type a number AND a character


printf("Type a number AND a character and press enter:
\n");
// Get and save the number AND character the user types
scanf("%d %c", &myNum, &myChar);
// Print the number
printf("Your number is: %d\n", myNum);

// Print the character


printf("Your character is: %c\n", myChar);

Dr H N National College of Engineering 217


Input/output Statements in C

The scanf function ignores any blank spaces, tabs, and newlines entered by the
user.
It is used to store values in memory locations associated with variables. For this,
the function should have the address of the variables which is denoted by an &
sign followed by the name of the variable.
int num;
scanf(" %4d ", &num); //read first four digits

Dr H N National College of Engineering 218


Input/output Statements in C
printf:

flags is an optional argument, which specifies output justification like decimal point,
numerical sign, trailing zeros or octadecimal or hexadecimal prefixes

Dr H N National College of Engineering 219


Input/output Statements in C
— int myNum = 15;
printf("%d", myNum); // Outputs 15

— // Create variables
int myNum = 15; // Integer (whole
number)
float myFloatNum = 5.99; // Floating point
number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

Dr H N National College of Engineering 220


Input/output Statements in C

— width is an optional argument which specifies the minimum number of


positions that the output characters will occupy. If the number of output
characters is smaller than the specified width, then the output would be right
justified with blank spaces to the left.

— However, if the number of characters is greater than the specified width, then
all the characters would be printed. precision is an optional argument which
specifies the number of digits to print after the decimal point or the number of
characters to print from a string.

Dr H N National College of Engineering 221


Input/output Statements in C
— int myNum = 15;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum,
myLetter);

— // Create a string
char firstName[30];
// Ask the user to input some text
printf("Enter your first name: \n");
// Get and save the text
scanf("%s", firstName);

// Output the text


printf("Hello %s", firstName);

Dr H N National College of Engineering 222


Input/output Statements in C
Detecting errors during data input:

— When the scanf function completes reading all the data values, it returns the
number of values that are successfully read. This return value can be used to
determine whether there was any error while reading the input.

Example:
— scanf (“%d %f %c”, &a, &b, &c);

— Will return 3 if the user enters, say

— 12 12.34 A
Dr H N National College of Engineering 223
Input/output Statements in C
— It will return 1 if the user enters erroneous data like

— 12 ABC 12.34

— This is because a string was entered while the user was expecting a floating
point value. So, the scanf function reads only first data value correctly and then
terminates as soon as it encounters a mismatch between the type of data
expected and the type of data entered.

Dr H N National College of Engineering 224


Thank You

Dr H N National College of Engineering 225

You might also like