Bassic C
Bassic C
Bassic C
Tech
ch
SOE, CUSAT
aSOE, CUSAT
Te
1101B / 1201A
SP
Computer Programming
Chapter 1
Module I
ch
1.1.1.1 What is a Computer?
A computer is a general-purpose device that can be programmed to carry out a set of arithmetic or logical
operations automatically. Since a sequence of operations can be readily changed, the computer can solve
more than one kind of problem.
A computer consists of at least one processing element, typically a central processing unit (CPU), and some
form of memory. The processing element carries out arithmetic and logic operations, and a sequencing and
a
control unit can change the order of operations in response to stored information. Peripheral devices allow
information to be retrieved from an external source, and the result of operations saved and retrieved.
Advantages
Te
1. High Speed
2. Accuracy
3. Storage Capability
4. Diligence - It can work continuously without any error and boredom. It can do repeated work with
same speed and accuracy.
SP
7. Automation - Automation means ability to perform the given task automatically. Once a program
is given to computer i.e., stored in computer memory, the program and instruction can control the
program execution without human interaction.
8. Reduction in Paper Work - The use of computers for data processing in an organization leads to
reduction in paper work and results in speeding up a process. As data in electronic files can be
retrieved as and when required, the problem of maintenance of large number of paper files gets
reduced.
9. Reduction in Cost - Though the initial investment for installing a computer is high but it substantially
reduces the cost of each of its transaction.
Disadvantages
1
B.Tech - IT Semester 1
3. Environment - The operating environment of computer should be dust free and suitable.
4. No Feeling - Computers have no feelings or emotions. It cannot make judgment based on feeling,
taste, experience, and knowledge unlike a human being.
• Second Generation: 1959-1965. Transistor based. E.g.: UNIVAC III, 7070, CDC 1604, FORTRAN,
COBOL, ALGOL
• Third Generation: 1965-1971. Integrated Circuit based. E.g.: UNIVAC 1100, PDP 11
ch
1.1.1.3 Categories of Computers
1. Supercomputers
It’s a term used to describe computers that have the most capable processing power of its time.
Modern supercomputers run hundreds of thousands of processors, capable of computing quadrillions
of calculations in just a few nanoseconds. Supercomputers are used in computational science to
a
calculate and carry out a plethora of complex tasks. Modeling molecular structures, weather fore-
casting, and the field of quantum mechanics, among others, rely on supercomputers and their intense
processing power to solve their equations. Supercomputers are measured in FLOPS, or floating point
operations per seconds. Popular Supercomputers are
Te
• IBM’s Sequoia, in United States
• Fujitsu’s K Computer in Japan
• IBM’s Mira in United States
• IBM’s SuperMUC in Germany
• NUDT Tianhe-1A in China
SP
2. Mainframe Computers
Like supercomputers, mainframe computers are huge, towering machines with lots of processing
power. Mainframe computers are mostly used by corporations, government agencies, and banks
- organizations that need a way to store large quantities of information. They are not the same
as supercomputers. The processing capabilities of mainframe computers are measured in MIPS, or
millions of instructions per second. Popular Mainframe computers are
3. Minicomputers
A minicomputer is a multiprocessing machine that can support up to about 200 users at the same
time. It’s like a less powerful mainframe computer, and is about the size of a refrigerator. A server
can be an example of a minicomputer, but not all servers are minicomputers. Despite their name, a
minicomputer is not a personal computer like the desktop machine you might have at home or work.
They are much larger than that. Popular Minicomputers are
• K-202
• Texas Instrument TI-990
• SDS-92
Programming in C Page 2
B.Tech - IT Semester 1
4. Microcomputers
Microcomputers are the ones people are most familiar with on a daily, non-professional basis, but
of course that doesn’t mean they’re exclusive to the home. Microcomputers are smaller computers
that run on microprocessors in their central processing units. They are much, much cheaper than
supercomputers, mainframe computers and even minicomputers, because they’re meant for everyday
uses that are more practical than professional. The range of capabilities for microcomputers are still
vast, though. A film editor might use a microcomputer to run many intensive editing programs at
once, while a student might use a microcomputer for Facebook and word processing.
• Desktop computers: Desktop are popular for the user’s ability to customize them, replace
parts and fix them with much more ease than they would a laptop. It’s also more convenient
to be able to connect peripherals like screens and keyboard and computer mice that fit your
needs. In this sense, desktop computers could be used at the office for professional tasks, or at
the home. Desktop computers can be specialized for things like gaming as well, equipped with
high-end graphics cards and more RAM.
ch
• Video game consoles: They have many of the same hardware components as computers, but
are usually less advanced, which is why they’re able to cost much less than a top-notch gaming
computer.
5. Mobile Computers
Mobile computers usually describe computers that are meant to be carried around and taken from
place to place.
a • Laptops: Portable computers designed to be carried from place to place. All of its components
are contained inside a panel that functions also as the keyboard, with an attached screen that
can be folded over. Because of their size and convenience, these are some of the most popular
Te
computers for everyday use.
• Netbooks: Much smaller laptops.
• Tablet: A flat, keyboard-less screen that utilizes touch-screen functionality for navigation and
use.
• Handheld game console: Devices like the Game Boy, Game Boy Color, Game Boy Advance,
Sega Nomad, PlayStation Portable (PSP), and PlayStation Vita are handheld game consoles.
SP
• CPU consists of three basic units: Control unit, Arithmetic Logical Unit (ALU) and memory unit.
• Control unit controls communication within ALU and memory unit and decides which circuit is to
be activated. For reading instruction it uses Fetch-execute mechanism. Control unit gets instruction
from memory. Control unit decides what to do of that instruction and transfers it to the ALU.
• ALU performs various arithmetic operations like addition, subtraction, multiplication, division and
logical operations like AND, OR, NOT, NAND etc. on that instruction. Results of ALU are stored
in the memory or resistor for its further operations.
• After completing the instruction, stored results are passed to the output devices.
Programming in C Page 3
B.Tech - IT Semester 1
• To synchronize all these operations CPU uses its own system clock. CPU executes stored instructions
called as program. It tells rest of the computer system what to do. It executes arithmetic calculation
and data manipulation. It holds data and instruction which are in the current use. It is responsible
for storing and retrieving information on disks and other media.
a ch
Te
1.1.2.2 Hardware
Hardware represents the physical and tangible components of a computer i.e. the components that can be
seen and touched. Examples of Hardware are following:
1. Input devices – keyboard, mouse etc.
2. Output devices – printer, monitor etc.
SP
Programming in C Page 4
B.Tech - IT Semester 1
Output Devices Output devices are the opposite of input devices. These are peripherals that essentially
allow the computer to interact with us âĂŞ they display information that we need to make decisions
about how we interface with them. In more technical terms, output devices convey results from
processes run by the computer. The most obvious example of an output device is a computer
monitor, or screen, because this lets us see the various processes our computers are running in a
substantial, visual manner. Other output devices include headphones and speakers, which convey
sound, printers, and even CDs, which we can tell the computer to output information onto.
a ch
Processing Devices Processing devices are the devices that enable the computer to process information.
All computers have some form of a processor. The computer has a CPU, or central processing unit,
embedded onto its motherboard. This is where the computer carries out its complex calculations,
processes info, and sends it out to its output devices to be conveyed to you in a manner that makes
sense. CPU consists of the following features:
Te
• CPU is considered as the brain of the computer.
• CPU performs all types of data processing operations.
• It stores data, intermediate results and instructions (program).
• It controls the operation of all parts of computer.
Control Unit This unit controls the operations of all parts of computer but does not carry out any actual
data processing operations. Functions of this unit are:
• It is responsible for controlling the transfer of data and instructions among other units of a
computer.
• It manages and coordinates all the units of the computer.
• It obtains the instructions from the memory, interprets them, and directs the operation of the
computer.
• It communicates with Input/Output devices for transfer of data or results from storage.
• It does not process or store data.
ALU (Arithmetic Logic Unit) This unit consists of two subsections namely
Programming in C Page 5
B.Tech - IT Semester 1
2. Logic Section - Function of logic section is to perform logic operations such as comparing,
selecting, matching and merging of data.
Memory or Storage Unit This unit can store instructions, data and intermediate results. This unit sup-
plies information to the other units of the computer when needed. It is also known as internal storage
unit or main memory or primary storage or Random access memory (RAM).
Its size affects speed, power and capability. Primary memory and secondary memory are two types
of memories in the computer. Functions of memory unit are:
• It stores all the data and the instructions required for processing.
• It stores intermediate results of processing.
• It stores final results of processing before these results are released to an output device.
• All inputs and outputs are transmitted through main memory.
Computer memory is the storage space in computer where data is to be processed and instructions
required for processing are stored. The memory is divided into large number of small parts called
cells. Each location or cell has a unique address which varies from zero to memory size minus one.
ch
For example if computer has 64k words, then this memory unit has 64 ∗ 1024 = 65536 memory
locations. The address of these locations varies from 0 to 65535.
a
Te
SP
1. Cache Memory is a very high speed semiconductor memory which can speed up CPU. It acts as
a buffer between the CPU and main memory. It is used to hold those parts of data and program
which are most frequently used by CPU. The parts of data and programs are transferred from
disk to cache memory by operating system, from where CPU can access them.
Advantages
• Cache memory is faster than main memory.
• It consumes less access time as compared to main memory.
• It stores the program that can be executed within a short period of time.
• It stores data for temporary use.
Disadvantages
• Cache memory has limited capacity.
Programming in C Page 6
B.Tech - IT Semester 1
• It is very expensive.
2. Primary Memory/Main Memory - Primary memory holds only those data and instructions
on which computer is currently working. It has limited capacity and data is lost when power is
switched off. It is generally made up of semiconductor device. These memories are not as fast
as registers. The data and instruction required to be processed reside in main memory. It is
divided into two subcategories RAM and ROM.
Characteristics of Main Memory
• These are semiconductor memories
• It is known as main memory.
• Usually volatile memory.
• Data is lost in case power is switched off.
• It is working memory of the computer.
• Faster than secondary memories.
• A computer cannot run without primary memory.
ch
(a) RAM (Random Access Memory) is the internal memory of the CPU for storing data,
program and program result. It is read/write memory which stores data until the machine
is working. As soon as the machine is switched off, data is erased.
Access time in RAM is independent of the address that is, each storage location inside the
memory is as easy to reach as other locations and takes the same amount of time. Data
in the RAM can be accessed randomly but it is very expensive.
a RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there
is a power failure. Hence a backup uninterruptible power system (UPS) is often used with
computers. RAM is small, both in terms of its physical size and in the amount of data it
can hold.
Te
RAM is of two types
i. Static RAM (SRAM) - The word static indicates that the memory retains its contents
as long as power is being supplied. However, data is lost when the power gets down
due to volatile nature. SRAM chips use a matrix of 6-transistors and no capacitors.
Transistors do not require power to prevent leakage, so SRAM need not have to be
refreshed on a regular basis. Because of the extra space in the matrix, SRAM uses
more chips than DRAM for the same amount of storage space, thus making the man-
SP
ufacturing costs higher. So SRAM is used as cache memory and has very fast access.
Characteristic of the Static RAM
• It has long life
• There is no need to refresh
• Faster
• Used as cache memory
• Large size
• Expensive
• High power consumption
ii. Dynamic RAM (DRAM) - DRAM, unlike SRAM, must be continually refreshed in
order to maintain the data. This is done by placing the memory on a refresh circuit that
rewrites the data several hundred times per second. DRAM is used for most system
memory because it is cheap and small. All DRAMs are made up of memory cells which
are composed of one capacitor and one transistor.
Characteristics of the Dynamic RAM
• It has short data lifetime
• Need to be refreshed continuously
• Slower as compared to SRAM
• Used as RAM
Programming in C Page 7
B.Tech - IT Semester 1
• Lesser in size
• Less expensive
• Less power consumption
(b) ROM (Read Only Memory). The memory from which we can only read but cannot write
on it. This type of memory is non-volatile. The information is stored permanently in such
ch
memories during manufacture. A ROM, stores such instructions that are required to start
a computer. This operation is referred to as bootstrap. ROM chips are not only used in
the computer but also in other electronic items like washing machine and microwave oven.
Advantages of ROM
• Non-volatile in nature
• These cannot be accidentally changed.
a
• Cheaper than RAMs
• Easy to test
• More reliable than RAMs
Te
• These are static and do not require refreshing.
• Its contents are always known and can be verified.
Following are the various types of ROM
MROM (Masked ROM) - The very first ROMs were hard-wired devices that contained a
pre-programmed set of data or instructions. These kind of ROMs are known as masked
ROMs which are inexpensive.
SP
PROM (Programmable Read only Memory) - PROM is read-only memory that can be
modified only once by a user. The user buys a blank PROM and enters the desired
contents using a PROM program. Inside the PROM chip there are small fuses which are
burnt open during programming. It can be programmed only once and is not erasable.
EPROM (Erasable and Programmable Read Only Memory) - The EPROM can be
erased by exposing it to ultra-violet light for a duration of up to 40 minutes. Usually,
an EPROM eraser achieves this function. During programming, an electrical charge is
trapped in an insulated gate region. The charge is retained for more than ten years
because the charge has no leakage path. For erasing this charge, ultra-violet light
is passed through a quartz crystal window (lid). This exposure to ultra-violet light
dissipates the charge. During normal use the quartz lid is sealed with a sticker.
EEPROM (Electrically Erasable and Programmable Read Only Memory) - The EEP-
ROM is programmed and erased electrically. It can be erased and reprogrammed about
ten thousand times. Both erasing and programming take about 4 to 10 ms (milli
second). In EEPROM, any location can be selectively erased and programmed. EEP-
ROMs can be erased one byte at a time, rather than erasing the entire chip. Hence,
the process of re-programming is flexible but slow.
3. Secondary Memory - This type of memory is also known as external memory or non-volatile. It
is slower than main memory. These are used for storing data / information permanently. CPU
directly does not access these memories instead they are accessed via input-output routines.
Programming in C Page 8
B.Tech - IT Semester 1
Contents of secondary memories are first transferred to main memory, and then CPU can
access it. E.g.: disk, CD-ROM, DVD etc.
Characteristic of Secondary Memory
• These are magnetic and optical memories
• It is known as backup memory.
• It is non-volatile memory.
• Data is permanently stored even if power is switched off.
• It is used for storage of data in a computer.
• Computer may run without secondary memory.
• Slower than primary memories.
Standard personal computer will come with a primary storage device, which is a storage device
that is a part of the hardware itself. This includes RAM and processor registers or caches.
Computer’s central processing unit is continuously retrieving and scanning data from these
storage devices, and computing as required. On the other hand, secondary storage devices are a
more permanent means of storage, that do not require the central processing unit to be running
ch
in order to save its information. Devices like a hard drive, drive, and other external storage
devices like USB flash drives, DVDs, CDs, and floppy disks, are all secondary storage devices.
1. Application software
Application software uses the computer system to perform special functions or provide entertainment
functions beyond the basic operation of the computer itself. There are many different types of
application software, because the range of tasks that can be performed with a modern computer is
so large.
Application software products are designed to satisfy a particular need of a particular environment.
All software applications prepared in the computer lab can come under the category of Application
software.
Application software may consist of a single program, such as a Microsoft’s notepad for writing and
editing simple text. It may also consist of a collection of programs, often called a software package,
which work together to accomplish a task, such as a spreadsheet package.
Examples of Application software are following:
Programming in C Page 9
B.Tech - IT Semester 1
• Microsoft PowerPoint
• Payroll
a ch
Te
2. System software System software is designed to directly operate the computer hardware, to provide
basic functionality needed by users and other software, and to provide a platform for running appli-
cation software.
The system software is collection of programs designed to operate, control, and extend the processing
SP
capabilities of the computer itself. System software are generally prepared by computer manufactures.
These software products comprise of programs written in low-level languages which interact with the
hardware at a very basic level. System software serves as the interface between hardware and the
end users.
Features of system software are as follows:
• Close to system
• Fast in speed
• Difficult to design
• Difficult to understand
• Less interactive
• Smaller in size
• Difficult to manipulate
• Generally written in low-level language
Some examples of system software are Operating System, Compilers, Interpreter, and Assemblers
etc.
Programming in C Page 10
B.Tech - IT Semester 1
Operating systems which are essential collections of software that manage resources and provides
common services for other software that runs ”on top” of them. Supervisory programs, boot
loaders, shells and window systems are core parts of operating systems. In practice, an operating
system comes bundled with additional software (including application software) so that a user
can potentially do some work with a computer that only has an operating system. An operating
system has three main responsibilities:
(a) Perform basic tasks, such as recognizing input from the keyboard, sending output to the
display screen, keeping track of files and directories on the disk, and controlling peripheral
devices such as disk drives and printers.
(b) Ensure that different programs and users running at the same time do not interfere with
each other.
(c) Provide a software platform on top of which other programs (i.e., application software) can
run.
a ch
Device drivers which operate or control a particular type of device that is attached to a computer.
Each device needs at least one corresponding device driver; because a computer typically has at
Te
minimum at least one input device and at least one output device, a computer typically needs
more than one device driver.
Utilities which are computer programs designed to assist users in maintenance and care of their
computers.
• Hardware without set of programs to operate upon cannot be utilized and is useless.
• To get a particular job done on the computer, relevant software should be loaded into the hardware
Programming in C Page 11
B.Tech - IT Semester 1
• If hardware is the ’heart’ of a computer system, then software is its ’soul’. Both are complimentary
to each other.
• Payroll calculations
• Budgeting
• Sales analysis
• Financial forecasting
ch
• Managing employees database
• Maintenance of stocks etc.
Banking • Banks provide online accounting facility, which includes current balances, deposits, over-
drafts, interest charges, shares, and trustee records.
• ATM machines are making it even easier for customers to deal with banks.
a
Insurance Insurance companies are keeping all records up-to-date with the help of computers. The insur-
ance companies, finance houses and stock broking firms are widely using computers for their concerns.
Insurance companies are maintaining a database of all clients with information showing
Te
• starting date of the policies
• next due installment of a policy
• maturity date
• interests due
• survival benefits
SP
• bonus
• procedure to continue with policies
Education The computer has provided a lot of facilities in the education system. The computer provides
a tool in the education system known as CBE (Computer Based Education).
Marketing .
• Advertising - With computers, advertising professionals create art and graphics, write and revise
copy, and print and disseminate ads with the goal of selling more products.
• At Home Shopping - Home shopping has been made possible through use of computerized
catalogues that provide access to product information and permit direct entry of orders to be
filled by the customers.
Programming in C Page 12
B.Tech - IT Semester 1
Health Care Computers have become important part in hospitals, labs, and dispensaries. The computers
are being used in hospitals to keep the record of patients and medicines. It is also used in scanning
and diagnosing different diseases. ECG, EEG, Ultrasounds and CT Scans etc., are also done by
computerized machines. Some major fields of health care in which computers are used are:
• Diagnostic System - Computers are used to collect data and identify cause of illness.
• Lab-diagnostic System - All tests can be done and reports are prepared by computer.
• Patient Monitoring System - These are used to check patient’s signs for abnormality such as in
Cardiac Arrest, ECG etc.
• Pharma Information System - Computer checks Drug-Labels, Expiry dates, harmful drug’s side
effects etc.
• Surgery: Nowadays, computers are also used in performing surgery.
Engineering Design Computers are widely used in engineering purpose. One of major areas is CAD
(Computer aided design). That provides creation and modification of images. Some fields are:
ch
• Structural Engineering - Requires stress and strain analysis for design of Ships, Buildings, Bud-
gets, and Airplanes etc.
• Industrial Engineering - Computers deal with design, implementation and improvement of inte-
grated systems of people, materials and equipment.
• Architectural Engineering - Computers help in planning towns, designing buildings, determining
a range of buildings on a site using both 2D and 3D drawings.
a
Military Computers are largely used in defense. Modern tanks, missiles, weapons etc. Military also employs
computerized control systems. Some military areas where a computer has been used are:
• Missile Control
Te
• Military Communication
• Military Operation and Planning
• Smart Weapons
Communication Communication means to convey a message, an idea, a picture or speech that is received
and understood clearly and correctly by the person for whom it is meant for. Some main areas in
SP
• E-mail
• Chatting
• Usenet
• FTP
• Telnet
• Video-conferencing
Government Computers play an important role in government. Some major fields in this category are:
• Budgets
• Sales tax department
• Income tax department
• Male/Female ratio
• Computerization of voters lists
• Computerization of driving licensing system
• Computerization of PAN card
• Weather forecasting
Programming in C Page 13
B.Tech - IT Semester 1
The Importance of Information Technology in Business Using computers and software, businesses use
information technology to ensure that their departments run smoothly. They use information tech-
nology in a number of different departments including human resources, finance, manufacturing, and
security.
Using information technology, businesses have the ability to view changes in the global markets far
faster than they usually do. They purchase software packages and hardware that helps them get their
job done. Larger businesses have their own information technology department designed to upkeep
the software and hardware.
Information technology has allowed businesses to keep up with the supply and demand as consumers
ch
grow more anxious to have their items instantly. Using information technology, businesses like Ama-
zon are working to help busy consumers do their grocery shopping. Just a few clicks on a website
allows the consumer to submit an order, and information technology sends that order to the company.
The Importance of Information Technology in Education Information technology plays a key role in
students being able to keep their jobs and go to school. Now, most schools offer online classes that
can be accessed on computers or laptops, tablets, and even mobile phones. A busy student at work
a
can easily check in or submit assignments while on their lunch break.
Using technology, teachers can prepare their students for a future flooded with gadgets including
tablets, mobile phones, computers, and so much more.
Information technology is helping to prevent more high school and college dropouts as well. Life
Te
events can happen to anyone at any time, and even high schools are taking advantage of online
classes so that students can continue their education instead of considering dropping out.
The Importance of Information Technology in Finance Information technology might just working its
hardest with internet transactions. As more transactions are done, the internet requires more net-
works, more computers, and more security programs to keep its consumers safe. Without information
technology, these purchases would be impossible, and it would be impossible for banks to keep these
SP
purchases secure.
Information technology has also made it faster and easier than ever to send or receive money. It’s
now also easier to open an online small business to sell whatever you might want. If you don’t want
to have to file for a domain name, set up a website, and all the other steps required for registering
an online business, you can use other websites like Amazon, eBay, and Etsy to sell things.
Information technology also makes it easy for finance to function on a global level. In this modern
age, your credit score and credit rating is available online securely. This allows lenders, insurance
companies, and businesses to run a quick credit check on you making it far easier to open credit.
Programming in C Page 14
B.Tech - IT Semester 1
The Importance of Information Technology in Security With so many transactions done online and
so much information available online, it’s important to keep all of that safe. Information technology
makes it possible for your online data to stay secure until accessed by the proper channels. Using
passwords and encryption, information technology hides your personal digital data away, and the only
way it can be accessed is by companies who have permission from you.
ch
ment of the modern digital computers. Analog computers are widely used for certain specialized
engineering and scientific applications, for calculation and measurement of analog quantities. They
are frequently used to control process such as those found in oil refinery where flow and temperature
measurements are important. They are used for example in paper making and in chemical industry.
Analog computers do not require any storage capability because they measure and compare quantities
in a single operation. Output from an analog computer is generally in the form of readings on a
series of dial (Speedometer of a car) or a graph on strip chart.
a
Digital Computers A Digital Computer works with digits to represent numerals, letters or other special
symbols. Digital Computers operate on inputs which are ON-OFF type and its output is also in the
form of ON-OFF signal. Digital computers process information which is based on the presence or
Te
the absence of an electrical charge or we prefer to say a binary 1 or 0.
A digital computer can be used to process numeric as well as non-numeric data. It can perform
arithmetic operations like addition, subtraction, multiplication and division and also logical operations.
Most of the computers available today are digital computers. The most common examples of digital
computers are accounting machines and calculators.
The results of digital computers are more accurate than the results of analog computers. Analog
computers are faster than digital. Analog computers lack memory whereas digital computers store
SP
information.
Hybrid Computers A hybrid is a combination of digital and analog computers. It combines the best
features of both types of computers. It has the speed of analog computer and the memory and
accuracy of digital computer. Hybrid computers are used mainly in specialized applications where
both kinds of data need to be processed. Therefore, they help the user, to process both continuous
and discrete data. In hospital Intensive Care Unit (ICU), an analog device is used which measures
patient’s blood pressure and temperature etc., which are then converted and displayed in the form
of digits. Hybrid computers for example are used for scientific calculations, in defense and radar
systems.
Programming in C Page 15
B.Tech - IT Semester 1
Corporation for Assigned Names and Numbers (ICANN). ICANN is the authority that coordinates the
assignment of unique identifiers for use on the Internet, including domain names, Internet Protocol (IP)
addresses, application port numbers in the transport protocols.
ch
1.1.5.2 Telnet
Telnet is an Internet service that allows the user logs on and run on a remote computer and use programs
installed on the remote computer. The remote computer must be enabled in the user access rights to the
computer.
Today’s programs use SSH (Secure Shell) connections over TCP / IP as the carrier of connection, but all
traffic is encrypted.
a
1.1.5.3 Electronic Mail
Te
Email is an important communications service available on the Internet. The concept of sending electronic
text messages between parties in a way analogous to mailing letters or memos. Pictures, documents and
other files are sent as email attachments. Emails can be carbon copied to multiple email addresses.
Internet telephony is another common communications service made possible by the creation of the
Internet. VoIP stands for Voice-over-Internet Protocol, referring to the protocol that underlies all Internet
communication.
SP
1.1.5.5 Chat
This service allows the Internet to one or more of Internet users who are hooked to the same channel at
the same time see the text that you type on your computer, and the texts of other active users typing on
his computer. This system is much faster than e-mail because it is conducted almost simultaneously send
and read messages. It is much more expensive than e-mail, because it requires a long term connection with
the Internet
1.1.5.6 Newsgroups
As part of this service, it is possible to follow the discussion on any topic or even start a new topic for
discussion. Similar to the e-mail message is sent to all members of the group, and everyone signed on the
group read the message and optionally answer them.
Programming in C Page 16
B.Tech - IT Semester 1
1.1.5.7 Gopher/WAIS/Archie/Veronica
Gopher is a server that helps you find information on the Internet using menus. Gopher began as the Uni-
versity of Minnesota’s version of PennInfo, a menu-driven campus-wide information system (CWIS).
By providing a menu of all Gopher servers that any other Gopher could access, an inter-operating set
of information systems linking several hundred organizations around the world, all with a common
user interface, was made available.
The next step in Gopher’s evolution was addition of gateways to FTP, Telnet , Archie, WAIS, and
WWW. Gopher was thus transformed from an integrated set of CWIS programs into the most suc-
cessful Internet navigation tool.
WAIS - Wide Area Information Servers searches for documents on the Internet. Wide Area Informa-
tion System provides a uniform interface to many full-text databases, together with a sophisticated
”relevance search” capability. WAIS databases are commonly collections of related data , primary
source documents , or reference works . There are currently almost 400 WAIS databases, and new
ones appear frequently. Since it can be difficult to determine the focus of a WAIS database from its
name, a Directory of Servers, itself a WAIS database, was developed.
ch
Archie servers that contain a list of files that can be downloaded using FTP . Archie (ARCHIvE server)
was developed at McGill University to index the contents of all FTP servers and provide keyword
searching of the index. Every night it re-indexes roughly one thirtieth of the servers; the result is a
database that is completely refreshed each month.
Veronica is a program to search Gopherspace, the world of Gopher menus. A search tool, Veronica, was
contributed to Gopher. It provides a search through all menus using a single keyword. The result is
a
a dynamically created menu of all Gopher resources that contain the keyword in their menus.
Program Planning Type and format of data at each step is identified. Algorithm / Pseudo code /
Flowchart are used to derive at the solution. The aim of the programmer is to create algorithms that
Programming in C Page 17
B.Tech - IT Semester 1
are clear and simple. Algorithms are expressed first in logical hierarchical form known as modulariza-
tion. Using modules, the programmer creates a logical thought process for the computer to follow.
After that the program is broken down in greater detail using pseudo code.
Two mini steps:
• Determine program logic through top down approach and modularization, using a hierarchy
chart.
• Design details using pseudo code and/or flowcharts, preferably involving control structure.
ch
1. Sequence control structure - No decision making
2. Selection control structure
3. Loop control structure / Repetition or Iteration Structure
Coding In Coding, programmer writes the instructions in a computer language to solve the problem. All
a
coding process depends upon the information we obtained in previous steps. Choice of language
depends upon the requirements and facilities available with a language.
After the program has been designed it must be coded or written. An appropriate programming
language must be selected. Once the appropriate code language has been chosen, it is imperative
Te
that the programmer follow the syntax rules with as little deviation as possible in order for the
program to have high accuracy.
Two mini steps:
Debugging / Testing After the program is written it then enters the programming debugging and testing
phase of the Program Development Life Cycle (PDLC).
Debug means locate and correct errors or bugs in the source program. There are two types of errors
- logical errors and syntax errors. Debugging will uncover errors in both logic and syntax.
Syntax errors will prevent the program from executing. They can be such simple things as misspelled
words or can involve breaking the syntax rules of the programming language used. Logic errors will
allow the program to run but will provide incorrect results. Errors of this kind may consist of merely
using the wrong relational operator or other, larger, mistakes in writing formulas.
Once the programmer locates the errors they are then fixed and the program is run again. This will
happen multiple times, often called ”execute, check, and correct”, until the program runs flawlessly.
The program will then enter the testing phase. The program is tested to ensure accuracy and
effectiveness of the program. The test is executed on test data.
Testing the program comes in two phases:
• Alpha testing is the process of reading through the program in search of errors in logic. The
second step is to run a diagnostic program to search for syntax or input errors.
• Beta testing involves using the program in the real world to see if it contains any bugs or other
deficiencies.
Documentation and maintenance The above step are documented clearly. The documents include prob-
lem definition, description of input data, flow chart or algorithms, operating instructions, sample test
Programming in C Page 18
B.Tech - IT Semester 1
data and final results. Documentation should be ongoing from the very.
Four mini steps:
ch
Flowchart A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the
steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic
representation illustrates a solution model to a given problem.
Flowcharts are used in analyzing, designing, documenting or managing a process or program. The
two most common types of boxes in a flowchart are:
Pseudo code Pseudo code is an informal high-level description of the operating principle of a computer
SP
program or other algorithm. It uses the structural conventions of a programming language, but is
intended for human reading rather than machine reading.
Pseudo code typically omits details that are essential for machine understanding of the algorithm,
such as variable declarations, system-specific code and some subroutines.
The purpose of using pseudo code is that it is easier for people to understand than conventional
programming language code, and that it is an efficient and environment-independent description of
the key principles of an algorithm. It is commonly used in textbooks and scientific publications that
are documenting various algorithms, and also in planning of computer program development, for
sketching out the structure of the program before the actual coding takes place.
No standard for pseudo code syntax exists, as a program in pseudo code is not an executable program.
Programming in C Page 19
B.Tech - IT Semester 1
External Data .
ch
It uses decimal point, but punctuation are not allowed. E.g. 24.45, -48.606. Real numbers can
be represented in decimal form or exponential form.
• ASCII (American Standard Code for Information Interchange) is used for representing alphabets
and symbols. ASCII encodes 128 specified characters into seven-bit binary integers. The
characters encoded are numbers 0 to 9, lowercase letters a to z, uppercase letters A to Z,
basic punctuation symbols, control codes and a space.
a
Internal Data Only binary data i.e. bits (0 and 1). A sequence of bits is used to represent a unit of
numeric / non-numeric data.
Te
1.2.3.3 What is Information?
Information is organized or classified data which has some meaningful values for the receiver. Information
is the processed data on which decisions and actions are based. For the decision to be meaningful, the
processed data must qualify for the following characteristics:
Input In this step the input data is prepared in some convenient form for processing. The form will depend
on the processing machine. For example, when electronic computers are used, the input data could
be recorded on any one of several types of input medium, such as magnetic disks, tapes and so on.
Programming in C Page 20
B.Tech - IT Semester 1
Processing In this step input data is changed to produce data in a more useful form. For example, pay-
checks may be calculated from the time cards, or a summary of sales for the month may be calculated
from the sales orders.
Output Here the result of the proceeding processing step are collected. The particular form of the output
data depends on the use of the data. For example, output data may be pay-checks for employees.
• Base-10.
• Decimal numbers uses digits from 0..9.
• These are the regular numbers that we use.
ch
2. Binary number system
• Base-2.
• Binary numbers uses only 0 and 1 digits. These are called bits.
• Binary numbers or bits are used in digital computers.
a
3. Octal number system
• Base-8.
Te
• Octal numbers uses digits from 0..7.
• Prefix is 0.
• Base-16.
• Hex numbers uses digits from 0..9 and A..F.
SP
The decimal number system is used in general. However, the computers use binary number system.
The octal and hexadecimal number systems are used in the computer.
Programming in C Page 21
B.Tech - IT Semester 1
Machine languages .
• Absolute language
• Language of 0 and 1
• Programmer has to remember list of code numbers to represent operation codes and storage
locations of data and instructions.
• Time consuming
ch
• Expensive
• Error prone.
• Format is op-code operand E.g. 0001 10011001
Assembly Languages .
Programming in C Page 22
B.Tech - IT Semester 1
Drawbacks are
ch
and each line of assembly can be replaced by the equivalent line of object (machine) code. Assembly
code is often used when writing low level fast code for specific hardware. Benefits are
Drawbacks are
• Code produced might not make the best use of processor specific features unlike first and second
gen.
Fourth-generation languages (very high level languages) are designed to reduce programming effort
and the time it takes to develop software, resulting in a reduction in the cost of software development.
They are non-procedural languages, because they allow programmers and users to specify what the
computer is supposed to do without having to specify how the computer is supposed to do it. They
need approximately one tenth the number of statements that a high level languages needs to achieve
the same results.
4GL include languages to query databases (SQL), languages to make reports and languages to
construct user interface (XUL). An example of 4th generation programming type is the declarative
language. Declarative languages describe what computation should be performed and not how to
perform it.
Programming in C Page 23
B.Tech - IT Semester 1
Fifth generation languages Natural Languages represent the next step in the development of program-
ming languages, i-e fifth generation languages. The text of a natural language statement very closely
resembles human speech. These languages are also designed to make the computer ”smarter”.
Natural languages already available for microcomputers include Clout, Savvy Retriever (for use with
databases) and HAL (Human Access Language). The use of natural language touches on expert sys-
tems, computerized collection of the knowledge of many human experts in a given field, and artificial
intelligence, independently smart computer systems.
Compiler A compiler is a special program that processes statements written in a particular programming
language and turns them into machine language or ”code” that a computer’s processor uses. Typically,
a programmer writes language statements in a language such as Pascal or C. The file that is created
contains what are called the source statements. The programmer then runs the appropriate language
ch
compiler, specifying the name of the file that contains the source statements.
Translates source code (C, C++ etc.) and generates Object code (machine readable but not directly
executable).
Interpreter Same as compiler but do that interactively (simply saying line by line). Interpreted languages
don’t usually require a linker, and employ a loading process different from that of a compiled program.
The interpreter itself is linked and loaded like a compiled program, but the program interpreted by
a
the interpreter is typically loaded through interpreter-specific means.
Linker Linker performs the linking of libraries with the object code to make the object code into an
Te
executable machine code.
Connects the compiler generated object code with library code to generated independent executable
(like in C, you dont write how printf() works, linker add the code for printf() function in your program).
Loader In a computer operating system, a loader is a component that locates a given program (which can
be an application or part of the operating system) in offline storage (such as a hard disk), loads it into
main storage (in a personal computer, it’s RAM), and gives that program control of the compute.
Load the machine readable codes in memory to be executed. This step typically includes relocating
SP
the code output by the linker to a specific memory location into which the program was being loaded.
Programming in C Page 24
Chapter 2
Module II
2.1 Basics of C
2.1.1 Character set
ch
1. Letters - A to Z and a to z
2. Digits - 0 to 9
4. White spaces - Blank space, Horizontal tab, Carriage return, New line, Form feed
2.1.2 Identifiers
a
Te
• Refer to a name of variable, function, array.
• Case sensitive.
2.1.3 Keywords
• Convey special meaning to compiler.
• Eg: auto, break, case, char, const, do, double, else, enum, extern, float, for, if, int, long, register,
return, short, static, struct, switch, union, void, while
25
B.Tech - IT Semester 1
// h e l l o w o r l d program
# i n c l u d e < s t d i o . h>
main ( )
{
p r i n t f ( ” H e l l o World ” ) ;
}
ch
• String data are enclosed in double quotes.
from 0 to 255).
2. int
• No fractions.
• Fixed point.
• Decimal point and Punctuation are not allowed.
• short int is at least two bytes.
• int is two bytes in 16 bits compiler and four bytes in 32 bits compiler.
• long int is four bytes.
3. float
4. double
Programming in C Page 26
B.Tech - IT Semester 1
1. short
• A short int may require less memory than an ordinary int or it may require the same amount of
memory as an ordinary int , but it will never exceed an ordinary int in word length.
• If short int and int both have the same memory requirements (e.g., 2 bytes), then long int will
generally have double the memory requirements (e.g., 4 bytes).
2. long
• A long int may require the same amount of memory as an ordinary int or it may require the
ch
more memory than an ordinary int , but it will never be less than an ordinary int in word length.
• If int and long int both have the same memory requirements (e.g., 4 bytes), then short int will
generally have half the memory requirements (e.g., 2 bytes).
3. signed
• The unsigned qualifier can also be applied to other qualified unsigned ints , e.g., unsigned short
int or unsigned long int.
2.1.5 Variables
• It is an identifier that change values in the program.
• Variable can be assigned any value. Information represented by variable can be changed during
execution of the program.
• A declaration associated a group of variables with a specific data type. A declaration consists of a
data type, followed by one or more variable names, ending with a semicolon.
• All variables must be declared before they can be used in executable statements.
Programming in C Page 27
B.Tech - IT Semester 1
ch
2.1.6 Constants
Items that never change their value during a program execution. Keyword const is used. THe following
rules apply to all integer and floating point constants.
3. The value of the constant cannot exceed specified the minimum and maximum bounds.
Te
1. Integer Constant
(a) Base 10 number that contains either decimal point or an exponent or both.
(b) Can contain + or - symbol.
(c) Single precision floating point - append F or f at the end
Programming in C Page 28
B.Tech - IT Semester 1
3. Character Constant
ch
(d) \n . . . \b . . . \t . . . \v . . . \” . . . \0 . . . \? . . . \\ . . . \0.
(e) \0 represents the null character - ASCII 000. It is used to indicate the end of a string.
Eg: ’A’, ’x’, ’\ n’
4. String Constant
2. Block Statements
Programming in C Page 29
B.Tech - IT Semester 1
2.1.8 Operators
Specific tasks are called operations. Operations are represented by operators. Objects of operations are
called operands. Operators can be classified based on the number of operands or based on the purpose
of the operator.
Classification based on the purpose of the operator:
1. Arithmetic operators
• Addition +
• Subtraction -
• Multiplication *
• Division / - requires that the second operand be non-zero. For integer division, the quotient is
truncated toward zero.
• Remainder % - works only with int. - requires that the second operand be non-zero.
• Unary + and Unary - is also supported.
ch
2. Increment / Decrement operator
4. Logical Operators
5. Bitwise Operators
6. Conditional Operator
• Ternary operator
• result = expression 1 ? expression 2 : expression 3
Programming in C Page 30
B.Tech - IT Semester 1
• If expression 1 is true, then result = value of expression 2, otherwise result = value of expression
3.
7. Assignment operator
• Assignment operators are used to form assignment expressions. It is used to assign a value to
an identifier.
• The associativity is from right to left.
• =, + =, − =, ∗ =, / =, % =
• Assignment expression is written in the form identifier = expression.
Eg. area = length ∗ breadth
• Assignment expression is written in the form
expression1 += expression2.
expression1 = expression1 + expression2
Eg. count+ = 2
8. sizeof operator
9. Comma operator
Te
• b = (a=3, a+1); First 3 is assigned to a. Then a + 1 is evaluated and result stored in b.
• Lower precedence than Assignment operator.
1. Unary operators
2. Binary operators
3. Ternary operators
Programming in C Page 31
B.Tech - IT Semester 1
• Precedence tells you the order in which operators are executed when they are found in the same
expression.
• Associativity tells you how the operators are evaluated; either from right to left or from left to right.
// a d d i n g two numbers , u s i n g i / o
ch
# i n c l u d e < s t d i o . h>
main ( )
{
i n t num1 , num2 , sum ;
p r i n t f ( ” E n t e r two numbers ” ) ;
s c a n f ( ”%d %d ” , &num1 , &num2 ) ;
sum = num1 + num2 ;
}
a
p r i n t f ( ”Sum o f %d and %d = %d ” , num1 , num2 , sum ) ;
Te
2.1.9 Expressions
An expression represents
1. Arithmetic Expressions
Programming in C Page 32
B.Tech - IT Semester 1
• Can contain unsigned and signed variables, constants joined by relation or logical operators.
• Expression results in 1 or 0.
3. Compound Expressions
• Assignment statement.
• variable operator= expression
// s o l u t i o n o f q u a d r a t i c e q u a t i o n
# i n c l u d e < s t d i o . h>
ch
main ( )
{
f l o a t a , b , c , roo1 , r o o t 2 , d e t e r ;
p r i n t f ( ” E n t e r t h r e e numbers a s a , b , c ” ) ;
s c a n f ( ”%f %f %f ” , &a , &b , &c ) ;
d e t e r = s q r t ( b∗b − 4∗ a ∗ c ) ;
a
r o o t 1 = (−b + d e t e r ) / 2 ∗ a ;
r o o t 2 = (−b − d e t e r ) / 2 ∗ a ;
p r i n t f ( ” D e t e r m i n e n t = %f \n R o o t s a r e %f and %f ” , d e t e r , r o o t 1 , r o o t 2 ) ;
}
Te
2.1.10 Input and Output statements
1. getchar()
2. putchar()
3. gets()
• read string
• Eg: char sentence[50]; gets (sentence);
4. puts()
• write string
Programming in C Page 33
B.Tech - IT Semester 1
• Eg: puts(sentence);
5. scanf()
• formatted input
• enters data from standard input device and stores it in the computer’s memory.
• Syntax scanf(control string, arg1, arg2, . . ., argn);
Control string refers to a string containing certain required formatting information, and arg1,
arg2, . . ., argn are arguments that represent the individual input data items.
• The control string consists of individual groups of characters, with one character group for each
input data item. Each character group must begin with a percent sign (%). In its simplest form,
a single character group will consist of the percent sign, followed by a conversion character
which indicates the type of the corresponding data item.
• The arguments are written as variables or arrays, whose types match the corresponding character
groups in the control string. Each variable name must be preceded by an ampersand (&).
• Eg: scanf(”%d %f %15s”, &integer, &real, &string );
ch
scanf(”%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line ); - enter a string consisting of up-
percase letters and whitespace.
• formatted output
• used to output any combination of string, single character, numerical values to standard output
device.
• moves data from computer’s memory to standard output device.
SP
// c o n v e r s i o n o f c a s e o f a s i n g l e c h a r a c t e r
# i n c l u d e < s t d i o . h>
# i n c l u d e <c t y p e . h>
main ( )
{
i n t ch ;
p r i n t f ( ” E n t e r any c h a r a c t e r v a l u e ” ) ;
ch = g e t c h a r ( ) ;
p r i n t f ( ” The e q u i v a l e n t u p p e r c a s e l e t t e r i s ” ) ;
p u t c h a r ( t o u p p e r ( ch ) ) ;
}
ch
2.2 Control Statements
• C program may require that a logical test be carried out and one of several possible actions will then
be carried out, depending on the outcome of the logical test. This is known as branching.
• There is also a special kind of branching, called selection, in which one group of statements is
selected from several available groups.
a
• A program may require that a group of instructions be executed repeatedly, until some logical con-
dition has been satisfied. This is known as looping.
• Use the four relational operators ¡, <=, >, >= and the two equality operators, ==, ! =, two logical
Te
operators && (AND) and || (OR), and the unary negation operator !
2.2.1 Selection
1. if statement
• Used to carry out a logical test and then take one of two possible actions, depending on the
SP
// B i g g e s t o f two numbers
# i n c l u d e < s t d i o . h>
main ( )
{
int f i r s t , second ;
s c a n f ( ”%d %d ” , & f i r s t , &s e c o n d ) ;
i f ( f i r s t > second )
p r i n t f ( ” F i r s t number i s b i g g e r . \n ” ) ;
i f ( f i r s t < second )
Programming in C Page 35
B.Tech - IT Semester 1
p r i n t f ( ” Second number i s b i g g e r . \n ” ) ;
i f ( f i r s t == s e c o n d )
p r i n t f ( ” Both numbers a r e e q u a l . \n ” ) ;
}
i f ( p a s t d u e >0)
credit = 0;
// a n o t h e r e x a m p l e
i f ( x <=3.0) {
y= 3 ∗pow ( x , 2 ) ;
p r i n t f ( ( ”%f ” , y ) ;
}
// a n o t h e r e x a m p l e
i f ( ( b a l a n c e < 1 0 0 0 ) | | ( s t a t u s ==’R ’ ) )
p r i n t f ( ”%f ” , b a l a n c e ) ;
ch
2. if - else statement
• If a condition is true an action is taken and another action if the condition is false.
• Syntax if (expression) statement 1 else statement 2
• If the expression has a nonzero value (i.e., if expression is true), then statement 1 will be
a
executed. Otherwise (i.e., if expression is false), statement 2 will be executed.
else
p r i n t f ( ” The g i v e n number i s odd . \n ” ) ;
}
i f ( p a s t d u e >0)
credit = 0;
else
c r e d i t = 1000;
// a n o t h e r e x a m p l e
i f ( x <=3.0) {
y= 3 ∗pow ( x , 2 ) ;
p r i n t f ( ( ” 3 t i m e s x power 2 = %f ” , y ) ;
}
else {
y= 2 ∗pow ( x − 3 , 2 ) ;
p r i n t f ( ( ” 2 t i m e s ( x −2) power 2 = %f ” , y ) ;
}
Programming in C Page 36
B.Tech - IT Semester 1
// a n o t h e r e x a m p l e
i f ( s t a t u s ==’R ’ )
t a x = 0 . 2 0 ∗ pay ;
else
t a x = 0 . 1 4 ∗ pay ;
2.2.2 Iteration
Program construct to repeat a block of statements.
2.2.2.1 while
• Condition is checked first.
ch
• Syntax while ( expression) statement
• Best suited for situations where the iteration continues indefinitely until the specified logical condi-
tional has been satisfied.
main ( )
{
SP
char l e t t e r [ 8 0 ] ;
i n t length , count = 0;
// r e a d l o w e r c a s e t e x t
w h i l e ( ( l e t t e r [ c o u n t ] = g e t c h a r ( ) ) != ’ \n ’ )
++c o u n t ;
l e n g t h = count ;
// d i s p l a y u p p e r c a s e t e x t
while ( count < l e n g t h )
{
putchar ( toupper ( l e t t e r [ count ] ) ) ;
c o u n t ++;
}
}
Example: Average of list of numbers
// A v e r a g e o f l i s t o f numbers
# i n c l u d e < s t d i o . h>
main ( )
Programming in C Page 37
B.Tech - IT Semester 1
{
i n t len , count = 1;
f l o a t num , avg , sum =0;
// r e a d number o f numbers
p r i n t f ( ’ ’How many numbers ? : ’ ’ ) ;
s c a n f ( ’ ’%d ’ ’ , &l e n ) ;
// r e a d numbers
w h i l e ( c o u n t <= l e n )
{
p r i n t f ( ’ ’ Number = ’ ’ ) ;
s c a n f ( ’ ’%f ’ ’ , &num ) ;
sum += num ;
c o u n t ++;
}
ch
// c a l c u l a t e a v e r a g e and d i s p l a y i t
avg = sum / l e n ;
p r i n t f ( ’ ’ \n A v e r a g e = %f ’ ’ , avg ) ;
}
2.2.2.2 do...while a
• Condition is checked at the each iteration.
• Atleast once the statements are executed before the condition is checked.
Te
• Syntax do statement while ( expression);
• Best suited for situations where the statements are to be executed atleast once before the expression
is evaluated.
main ( )
{
char l e t t e r [ 8 0 ] ;
i n t length , count = 0;
// r e a d l o w e r c a s e t e x t
do
++c o u n t ;
w h i l e ( ( l e t t e r [ c o u n t ] = g e t c h a r ( ) ) != ’ \n ’ ) ;
l e n g t h = count ;
// d i s p l a y u p p e r c a s e t e x t
do
{
Programming in C Page 38
B.Tech - IT Semester 1
main ( )
{
i n t len , count = 1;
f l o a t num , avg , sum =0;
// r e a d number o f numbers
p r i n t f ( ’ ’How many numbers ? : ’ ’ ) ;
s c a n f ( ’ ’%d ’ ’ , &l e n ) ;
ch
// r e a d numbers
do
{
p r i n t f ( ’ ’ Number = ’ ’ ) ;
s c a n f ( ’ ’%f ’ ’ , &num ) ;
a sum += num ;
c o u n t ++;
} w h i l e ( c o u n t <= l e n );
Te
// c a l c u l a t e a v e r a g e and d i s p l a y i t
avg = sum / l e n ;
p r i n t f ( ’ ’ \n A v e r a g e = %f ’ ’ , avg ) ;
}
2.2.2.3 for
SP
• Third expression allows the index to be modified at the end of each pass.
• Best suited for situations where the number of iterations is known in advance.
Programming in C Page 39
B.Tech - IT Semester 1
main ( )
{
int d i g i t ;
f o r ( d i g i t = 1 ; d i g i t <= 1 0 ; d i g i t +=2)
p r i n t f ( ’ ’%d \ t ’ ’ , d i g i t ) ;
}
// A v e r a g e o f l i s t o f numbers
# i n c l u d e < s t d i o . h>
main ( )
{
i n t len , count = 1;
f l o a t num , avg , sum =0;
ch
// r e a d number o f numbers
p r i n t f ( ’ ’How many numbers ? : ’ ’ ) ;
s c a n f ( ’ ’%d ’ ’ , &l e n ) ;
a // r e a d numbers
f o r ( c o u n t =1; count<= l e n ; c o u n t++)
{
p r i n t f ( ’ ’ Number = ’ ’ ) ;
s c a n f ( ’ ’%f ’ ’ , &num ) ;
Te
sum += num ;
c o u n t ++;
}
// c a l c u l a t e a v e r a g e and d i s p l a y i t
avg = sum / l e n ;
p r i n t f ( ’ ’ \n A v e r a g e = %f ’ ’ , avg ) ;
SP
2.2.3 Branching
2.2.3.1 switch
• The switch statement causes a particular group of statements to be chosen from several available
groups.
• The selection is based upon the current value of an expression which is included within the switch
statement.
• For each alternative, the first statement within the group must be preceded by one or more case
labels (also called case prefixes).
Programming in C Page 40
B.Tech - IT Semester 1
Example
switch ( c h o i c e = toupper ( g e t c h a r ( ) ) ) {
case ’R ’ :
p r i n t f ( ”RED” ) ;
break ;
case ’W’ :
p r i n t f ( ”WHITE” ) ;
break ;
case ’B ’ :
p r i n t f ( ”BLUE” ) ;
break ;
ch
default :
printf (” error ” );
}
2.2.3.2 break
a
• The break statement is used to terminate loops or to exit from a switch.
• In nested loop, using break statement in the inner loop exits to outer loop.
2.2.3.3 continue
• The continue statement is used to bypass the remainder of the current pass through a loop.
SP
• The loop does not terminate when a continue statement is encountered. The remaining loop state-
ments are skipped and the computation proceeds directly to the next pass through the loop.
• The continue statement can be included within a while, a do -while or a for statement.
• Syntax continue;
2.2.3.4 goto
• The goto statement is used to alter the normal sequence of program execution by transferring control
to some other part of the program.
• Label is an identifier that is used to label the target statement to which control will be transferred.
• Label must have a unique ; i.e., no two statements can have the same label.
Programming in C Page 41
B.Tech - IT Semester 1
ch
if ( ( t i m e >= 0 ) && ( t i m e < 1 2 ) ) p r i n t f ( ” Good Morning ” ) ;
else i f ( ( t i m e >= 1 2 ) && ( t i m e < 1 8 ) ) p r i n t f ( ” Good A f t e r n o o n ” ) ;
else i f ( ( t i m e >= 1 8 ) && ( t i m e < 2 4 ) ) p r i n t f ( ” Good E v e n i n g ” ) ;
e l s e p r i n t f ( ” Time i s o u t o f r a n g e ” ) ;
Find biggest of three numbers
i f ( num1 > num2 )
i f ( num1 > num3 )
else
printf ( ’
printf ( ’
a ’Num1 = %d i s b i g g e s t ’ ’ , num1 ) ;
’Num3 = %d i s b i g g e s t ’ ’ , num3 ) ;
Te
else
i f ( num2 > num3 )
printf ( ’ ’Num2 = %d i s b i g g e s t ’ ’ , num2 ) ;
else
printf ( ’ ’Num3 = %d i s b i g g e s t ’ ’ , num3 ) ;
SP
main ( )
{
float princi , rate , years , i n t e r e s t ;
p r i n t f ( ” E n t e r v a l u e f o r p r i n c i p a l \n ” ) ;
p r i n t f ( ”To e x i t from t h e program t y p e 0 f o r p r i n c i p a l \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , & p r i n c i ) ;
i f ( p r i n c i < 0) {
p r i n t f ( ” E r r o r : p l e a s e t r y a g a i n \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , & p r i n c i ) ;
}
while ( p > 0) {
p r i n t f ( ” E n t e r v a l u e f o r i n t e r e s t r a t e \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , &r a t e ) ;
Programming in C Page 42
B.Tech - IT Semester 1
i f ( r a t e < 0) {
p r i n t f ( ” E r r o r : p l e a s e t r y a g a i n \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , &r a t e ) ;
}
p r i n t f ( ” E n t e r v a l u e f o r number o f y e a r s \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , &y e a r s ) ;
i f ( y e a r s < 0) {
p r i n t f ( ” E r r o r : p l e a s e t r y a g a i n \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , &y e a r s ) ;
}
r a t e /= 1 0 0 ;
i n t e r e s t = p r i n c i ∗ pow ( ( 1 + r a t e ) , y e a r s ) ;
// d i s p l a y o u t p u t
p r i n t f ( ” I n t e r e s t = %0.2F \n ” , i n t e r e s t ) ;
ch
// r e p e a t i n p u t
p r i n t f ( ” E n t e r v a l u e f o r p r i n c i p a l \n ” ) ;
p r i n t f ( ”To e x i t from t h e program t y p e 0 f o r p r i n c i p a l \n ” ) ;
s c a n f ( ’ ’%f ’ ’ , & p r i n c i ) ;
i f ( p r i n c i < 0) {
p r i n t f ( ” E r r o r : p l e a s e t r y a g a i n \n ” ) ;
a }
}
s c a n f ( ’ ’%f ’ ’ , & p r i n c i ) ;
Te
}
Programming in C Page 43
Chapter 3
Module III
a ch
Te
SP
44
B.Tech - IT Semester 1
3.1 Functions
• Funciton is a self contained program segment that carries out some specific, well defined task.
• The use of a finction avoids the need for redundant (repeated) programming of the same instructions.
• Function will carry out its intended action whenever it is accessed from some other portion of the
program. Once the function has carried out is action, control will be returned to the point from
which the function was accessed.
• Library functions
ch
– Used to carry out a number of commonly used operations or calculations
• The first line of a function definition contains the data type of the value returned by the function,
SP
followed by the function name, and a set of arguments, separated by commas and enclosed in
parentheses.
• An empty pair of parentheses must follow the function name if the function definition does not include
any arguments.
• Syntax: return data type function name( data type arg1, ... data type arg n) { ... }
• The arguments are called formal arguments, because they represent the names of data items that
are transferred into the function from the calling portion of the program. They are also known as
parameters or formal parameters.
• The corresponding arguments in the function reference are called actual arguments, since they
define the data items that are actually transferred. They call also be referred as arguments, or as
actual parameters.
Programming in C Page 45
B.Tech - IT Semester 1
• The identifiers used as formal arguments are ”local” in the sense that they are not recognized outside
of the function. Hence, the names of the formal arguments need not be the same as the names of
the actual arguments in the calling portion of the program.
• Each formal argument must be of the same data type, however, as the data item it receives from
the calling portion of the program.
• Information is returned from the function to the calling portion of the program via the return
statement. It causes control to be returned to the point from which the function was accessed.
• If expression is omitted the return statement causes the control to revert back to the calling portion
of the program without any information transfer.
• A function can return only one value to the calling portion of the program via return.
ch
• A function can be accessed or called by specifLing its name, followed by a list of arguments enclosed
in parentheses and separated by commas.
• If the function call does not require any arguments, an empty pair of parentheses must follow the
name of the function.
• The arguments appearing in the function call are referred to as actual arguments.
a
• Each actual argument must be of the same data type as its corresponding formal argument.
• The value of each actual argument is transferred into the function and assigned to the corresponding
Te
formal argument.
• The programmer-defined function will have to be defined before the first function access.
SP
• In ”top-down” approach, main appears ahead of the programmer-defined function definition. Then
the function access (within main) will precede the function definition. This confuses the compiler.
• The compiler should be alerted that the function being accessed will be defined later in the program.
A function prototype is used for this purpose.
• Function prototypes are usually written at the beginning of a program, ahead of any programmer-
defined functions (including main).
• Syntax: return data type function name( data type arg1, ... data type arg n);
• Function prototype announces the properties of a function and its data type.
• If function definition precedes all function calls, then it is not necessary to include function declaration.
• Facilitates error checking between the calls to a function and the corresponding function definition.
• Funciton data type is the return data type of function data type. It appears before the function
name. If omitted, int data type is assumed. float and double, long int all needs to be specified.
Programming in C Page 46
B.Tech - IT Semester 1
• When a single value is passed to a function via an actual argument, the value of the actual
argument is copied into the function. Therefore, the value of the corresponding formal argument
can be altered within the function, but the value of the actual argument within the calling routine
will not change.
• Advantages
– It allows a single-valued actual argument to be written as an expression rather than being
restricted to a single variable.
– If the actual argument is expressed simply as a single variable, it protects the value of this
variable. from alterations within the function.
• Disadvantages
– It does not allow information to be transferred back to the calling portion of the program
via arguments. Thus, passing by value is restricted to a one-way transfer of information.
ch
2. Passing by Reference
• If an array name is specified as an actual argument, the individual array elements are not copied.
Instead, the location of the array ( the location of the first element) is passed to the function.
• If an element of the array is then accessed within the function, the access will refer to the
location of that array element relative to the location of the first element.
3.1.5
a • Any alteration to an array element within the function will carry over to the calling routine.
Recursion
Te
• Recursion is a process by which a funciton calls itself repeatedly, until some specified condition has
been satisfied.
• The process is used for repetitive computations in which each action is stated in terms of a previous
result.
• When a recursive program is executed, the recursive function calls are not executed immediately.
• They are placed on a stuck until the condition that terminates the recursion is encountered.
• The function calls are then executed in reverse order, as they are popped off the stack.
• This reversal in the order of execution is a characteristic of all functions that are executed recursively.
Programming in C Page 47
B.Tech - IT Semester 1
3. Function which accepts two integer quantities and displays the larger of the two.
4. Largest of three numbers using a function to calcualte the largest of two numbers.
a ch
Te
SP
Programming in C Page 48
B.Tech - IT Semester 1
3.2 Arrays
• Array is a collection of variables of same type, but referenced by a common name.
• The data items must all be of the same type (e.g., all integers, all characters, etc.).
• Array is given a variable name and its elements are referred by it subscripts of indices.
• Each array element is referred by its array name and subscript or position in square brackets.
ch
• 2D - x [ m ] [ n ]
• 3D - x [ m ] [ n ] [ k ]
\\ L o w e r c a s e t o U p p e r c a s e Word C o n v e r s i o n u s i n g a r r a y
#i n c l u d e < s t d i o . h>
SP
#i n c l u d e <c t y p e . h>
#d e f i n e SIZE 80
main ( )
{
char l e t t e r [ SIZE ] ;
i n t count ;
/∗ r e a d i n t h e l i n e ∗ /
f o r ( c o u n t = 0 ; c o u n t < SIZE ; ++c o u n t )
l e t t e r ( count1 = getchar ( ) ;
/∗ d i s p l a y t h e l i n e i n u p p e r c a s e ∗ /
f o r ( c o u n t = 0 ; c o u n t < SIZE ; ++c o u n t )
putchar ( toupper ( l e t t e r [ count ] ) ) ;
}
Programming in C Page 49
B.Tech - IT Semester 1
• int size=5;
float height[size];
for(int p = 0; p<size; p++)
scanf(”%f”, &height[p] );
ch
• Array is initialized to zero if no value is specified.
• Array size need not be specified when initial values are included.
a
• int y [ ] = 2,4,6;
size = 3;
Te
• String constant
• arrayName[index]
• Similar arrays are arrays with same data type, same size and same dimensionality.
• Loop is required, where each pass through the loop is used to process one array element.
Programming in C Page 50
B.Tech - IT Semester 1
• In 1D array as a formal argument, data type or array name is written with a pair of empty square
brackets.
ch
• Array name is interpreted as the address of the first array element.
• Address of the memory location containing first array element. This address is assigned to the
corresponding formal argument when the function call is made.
• Array are passed by reference i.e pointer to the first array element.
a
• float average ( int a, int x[ ] )
{}
• When a reference is made to an array element within the function, the value of the elements subscript
is added to the value of the pointer to indicate the address of the specified array element. Any array
element can be accessed from with in the function If an array element is altered within the function,
the alteration will be recognized in the calling portion of the program and the entire scope of the
array definition.
SP
• Pass the array to the function and alter its elements within the function.
• If the original array must be preserved, copy the array, element-by-element within the calling portion
of the program, pass the copy to the function, and perform the alterations.
• float table [ 50 ] [ 50 ];
Programming in C Page 51
B.Tech - IT Semester 1
• int array[2][3];
• int point[3][3][2];
ch
2. Reordering a List of Numbers, from smallest to largest.
3. A Piglatin Generator Piglatin is an encoded form of English that is often used by children as a
game. A piglatin word is formed from an English word by transposing the first sound (usually
the first letter) to the end of the word, and then adding the letter âĂIJaâĂİ. Thus, the word
âĂIJdogâĂİ becomes âĂIJogda,âĂİ âĂIJcomputerâĂİ becomes âĂIJomputerca,âĂİ âĂIJpiglatinâĂİ
a
becomes âĂIJiglatinpaâĂİ (or âĂIJigpa atinla,âĂİ if spelled as two separate words), and so on.
7. Transpose of a matrix.
SP
Programming in C Page 52
B.Tech - IT Semester 1
3.3 Strings
• Strings are represented as single dimensional character arrays.
• char city[50];
• Array of Strings
char city[number][string-length];
ch
3.3.2 Reading and displaying strings
• Reading a string
scanf(”%s”, city);
• Reading a line
char line[80];
a
scanf(”%[ˆ\n]”, line);
• Writing a string
printf(”%s”, city);
Te
• Writing a line
printf(”%s”, line);
Programming in C Page 53
B.Tech - IT Semester 1
10. strncmp(string1, string2, num) - compare left-most num characters of string1 to string2.
11. strstr(chars, string1) - searches chars in string1. If yes, it returns the position of the first occurrence
of chars.
a ch
Te
SP
Programming in C Page 54
B.Tech - IT Semester 1
3.4 Structures
3.4.1 Defining a structure variable
3.4.2 Accessing members
3.4.3 Array of structures
3.4.4 Passing structure to function
3.5 Unions
3.5.1 Difference with structure
3.5.2 Defining union variable
3.5.3 Accessing members
a ch
Te
SP
Programming in C Page 55