0% found this document useful (0 votes)
11 views

Unit 1

The document provides an overview of computer programming and software, detailing the distinction between hardware and software, the role of programming languages, and the classification of software into system and application software. It explains key components such as compilers, interpreters, linkers, and loaders, as well as the evolution of programming languages from machine language to high-level languages. Additionally, it discusses the functions of operating systems and utility software in managing computer resources and enhancing user productivity.

Uploaded by

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

Unit 1

The document provides an overview of computer programming and software, detailing the distinction between hardware and software, the role of programming languages, and the classification of software into system and application software. It explains key components such as compilers, interpreters, linkers, and loaders, as well as the evolution of programming languages from machine language to high-level languages. Additionally, it discusses the functions of operating systems and utility software in managing computer resources and enhancing user productivity.

Uploaded by

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

UNIT 1

INTRODUCTION TO PROGRAMMING
• Hardware wine

• Application software

• Assembly language

• System software

• Generation of programming languages

• Procedural and non-procedural languages

• Compiler, interpreter, linker, loader

•Machinelanguage

INTRODUCTION TO COMPUTER SOFTWARE


When we talk about a computer, we actually mean two things (Figure 1.1):

• First is the computer hardware that does all the physical work computers are
known for.

• Second is the computer software that commands the hardware what to do and
how to do it.

If we think of computer as a living being, then the hardware would be the body
that does things like seeing with eyes and lifting objects with hands, where- as
the software would be the intelligence which helps in interpreting the images
that are seen by the eyes and instructing the arms how to lift objects.
Since computer hardware is a digital machine, it can only understand two basic
states: on and off. Computer software was developed to make efficient use of
this binary system which is used internally by all computers to instruct the
hardware to perform meaningful tasks.

The computer hardware cannot think and make decisions on its own. So, it
cannot be used to analyse a given set of data and find a solution on its own. The
hardware needs a software (a set of programs) to instruct what has to be done. A
program is a set of instructions that are arranged in a sequence to guide a
computer to find a solution for a given problem. The process of writing a
program is called programming.

Computer software is written by computer programmers using a programming


language. The programmer writes a set of instructions (program) using a
specific programming language. Such instructions are known as the source
code. Another computer program called a compiler is used which transforms the
source code into a language that the computer can understand. The result is an
executable computer program, which is another software.

Examples of computer software include:

• Computer games which are widely used as a form of

• Driver software which allows a computer to interact with hardware devices


such as printers, scanners, and video cards.

• Educational software which includes programs and games that help in


teaching and providing drills to help memorize facts. Educational software can
be diversely used from teaching computer-related activities like typing to higher
education subjects like Chemistry.

• Media players and media development software that are specifically designed
to play and/or edit digital media files such as music and videos.
• Productivity software is an older term used to denote any program that allows
users to be more productive in a business environment. Examples of such
software include word processors, database management utilities, and
presentation software.

• Operating system software which helps in coordinating system resources and


allows execution of other programs. Some popular operating systems are
Windows Vista, Mac

CLASSIFICATION OF COMPUTER SOFTWARE

Computer software can be broadly classified into two groups: system software
and application software.

• System software [according to Nutt, 1997] provides a general programming


environment in which programmers can create specific applications to suit their
needs. This environment provides new functions that are not available at the
hardware level

System software represents programs that allow the hardware to run properly.
System software is transparent to the user and acts as an interface between the
hardware of the computer and the application software that users need to run on
the computer. Figure 1.2 illustrates the relationship between application
software, system software, and hardware.

• Application software is designed to solve a particular problem for users. It is


generally what we think of when we say the word 'computer programs'.
Examples of application software include spreadsheets, database systems,
desktop publishing systems, program development software, games, web
browsers, among others. Simply put, application software represents programs
that allow users to do something besides simply running the hardware.
System Software

System software is software designed to operate the computer hardware and to


provide and maintain a platform for running application software.

The most widely used system software are discussed in the following sections:

Computer BIOS and Device Drivers

The computer BIOS and device drivers provide basic functionality to operate
and control the hardware connected to or built into the computer.

BIOS or Basic Input/Output System is a de facto standard defining a firmware


interface. BIOS is built into computer and is the first code run by the computer
when it is switched on. The key role of BIOS is to load and start the operating
system.

When the computer starts, the first function that BIOS performs is to initialize
and identify system devices such as the video display card, keyboard and
mouse, hard disk, CD/DVD drive, and other hardware. In other words, the code
in the BIOS chip runs a series of tests called POST (Power On Self Test) to
ensure that the system devices are working correctly.
BIOS then locates software held on a peripheral device such as a hard disk or a
CD, and loads and executes that software, giving it control of the computer.
This process is known as booting.

BIOS is stored on a ROM chip built into the system and has a user interface
like that of a menu (Figure 1.3) that can be accessed by pressing a certain key
on the keyboard when the computer starts. The BIOS menu can enable the user
to configure hardware, set the system clock, enable or disable system
components, and most importantly, select which devices are eligible to be a
potential boot device and set various password prompts.

To summarize, BIOS performs the following functions:

• Initializes the system hardware

• Initializes system registers

• Initializes power management system


• Tests RAM

• Tests all the serial and parallel ports

• Initializes CD/DVD drive and hard disk controllers

• Displays system summary information

Operating System

The primary goal of an operating system is to make the computer system (or
any other device in which it is installed like a cell phone) convenient and
efficient to use. An operating system offers generic services to support user
applications.

From users' point of view the primary consideration is always the convenience.
Users should find it easy to launch an application and work on it. For example,
we use icons which give us clues about applications. We have a different icon
for launching a web browser, e-mail application, or even a document
preparation application. In other words, it is the human-computer interface
which helps to identify and launch an application. The interface hides a lot of
details of the instructions that perform all these tasks.

Similarly, if we examine the programs that help us in using input devices like
keyboard/mouse, all the complex details of the character reading programs are
hidden from users. We as users simply press buttons to perform the input
operation regardless of the complexity of the details involved.

An operating system ensures that the system resources (such as CPU, memory,
I/O devices) are utilized efficiently.

For example, there may be many service requests on a web server and each user
request needs to be serviced. Moreover, there may be many programs residing
in the main memory. Therefore, the system needs to determine which programs
are currently being executed and which programs need to wait for some I/O
operation. This information is necessary because the programs that need to wait
can be suspended temporarily from engaging the processor. Hence, it is
important for an operating system to have a control policy and algorithm to
allocate the system resources.
Utility Software

Utility software is used to analyse, configure, optimize, and maintain the


computer system. Utility programs may be requested by application programs
during their execution for multiple purposes. Some of them are as follows:

• Disk defragmenters can be used to detect computer files whose contents are
broken across several locations on the hard disk, and move the fragments to one
location in order to increase efficiency.

• Disk checkers can be used to scan the contents of a hard disk to find files or
areas that are either corrupted in some way, or were not correctly saved, and
eliminate them in order to make the hard drive operate more efficiently. • Disk
cleaners can be used to locate files that are either not required for computer
operation, or take up considerable amounts of space. Disk cleaners help users to
decide what to delete when their hard disk is full.

• Disk space analysers are used for visualizing the disk space usage by getting
the size for each folder (including subfolders) and files in a folder or drive.

• Disk partitions utilities are used to divide an individual drive into multiple
logical drives, each with its own file system. Each partition is then treated as an
individual drive.

• Backup utilities can be used to make a copy of all information stored on a


disk. In case a disk failure occurs, backup utilities can be used to restore the
entire disk. Even if a file gets deleted accidentally, the backup utility can be
used to restore the deleted file.

• Disk compression utilities can be used to enhance the capacity of the disk by
compressing/decompressing the contents of a disk.

• File managers can be used to provide a convenient method of performing


routine data management tasks such as deleting, renaming, cataloguing,
moving, copying, merging, generating, and modifying data sets.

• System profilers can be used to provide detailed information about the


software installed and hardware attached to the computer.

• Anti-virus utilities are used to scan for computer viruses.


• Data compression utilities can be used to output a file with reduced file size.

• Cryptographic utilities can be used to encrypt and decrypt files.

• Launcher applications can be used as a convenient access point for application


software.

• Registry cleaners can be used to clean and optimize the Windows operating
system registry by deleting the old registry keys that are no longer in use.

• Network utilities can be used to analyse the computer's network connectivity,


configure network settings, check data transfer, or log events.

• Command line interface (CLI) and Graphical user interface (GUI) can be used
to make changes to the operating system.

Compiler, Interpreter, Linker, and Loader

Compiler It is a special type of program that transforms the source code written
in a programming language (the Source language) into machine language
comprising just two digits, 1s and Os (the target language). The resultant code
in 1s and Os is known as the object code. The object code is the one which will
be used to create an executable program.

Therefore, a compiler is used to translate source code from a high-level


programming language to a lower level language (e.g., assembly language or
machine code).

If the source code contains errors then the compiler will not be able to perform
its intended task. Errors resulting from the code not conforming to the syntax of
the programming language are called syntax errors. Syntax errors may be
spelling mistakes, typing mistakes, etc. Another type of error is logical error
which occurs when the program does not function accurately. Logical errors are
much harder to locate and correct.

The work of a compiler is simply to translate human readable source code into
computer executable machine code. It can locate syntax errors in the program
(if any) but cannot fix it. Until and unless the syntactical errors are rectified the
source code cannot be converted into the object code.
Interpreter Like the compiler, the interpreter also executes instructions written
in a high-level language. Basically, a program written in a high-level language
can be executed in any of the two ways. First by compiling the program and
second, to pass the program through an interpreter.

While the compiler translates instructions written in high-level programming


language directly into the machine language, the interpreter, on the other hand,
translates the instructions into an intermediate form, which it then executes.
This clearly means that the interpreter interprets the source code line by line.
This is in striking contrast with the compiler which compiles the entire code in
one go.

Usually, a compiled program executes faster than an interpreted program.


However, the big advantage of an interpreted program is that it does not need to
go through the compilation stage during which machine instructions are
generated. This process can be time consuming if the program is long.
Moreover, the interpreter can immediately execute high-level programs.

All in all, compilers and interpreters both achieve similar purposes, but
inherently different as to how they achieve that purpose.

Linker (link editor binder) It is a program that combines object modules to


form an executable program. Gener- ally, in case of a large program, the
programmers prefer to break a code into smaller modules as this simplifies the
programming task. Eventually, when the source code of all the modules has
been converted into object code, we need to put all the modules together. This is
the job of the linker. Usually, the compiler automatically invokes the linker as
the last step in compiling a program.

Loader It is a special type of program that copies programs from a storage


device to main memory, where they can be executed. However, in this book we
will not go into the details of how a loader actually works. This is because the
functionality of a loader is generally hidden from the programmer. As a
programmer, it suffices to learn that the task of a loader is to bring the program
and all its related files into the main memory from where it can be executed by
the CPU.

Application Software
Application software is a type of computer software that employs the
capabilities of a computer directly to perform a user-defined task. This is in
contrast with system

software which is involved in integrating a computer's capabilities, but typically


does not directly apply them in the performance of tasks that benefit users.

To better understand application software consider an analogy where hardware


would depict the relationship of an electric light bulb (an application) to an
electric power generation plant (a system) that depicts the software.

The power plant merely generates electricity which is not by itself of any real
use until harnessed to an application like the electric light that performs a
service which actually benefits users.

Typical examples of software applications are word processors, spreadsheets,


media players, education software, CAD, CAM, data communication software,
and statistical and operational research software. Multiple applications bundled
together as a package are sometimes referred to as an application suite.

PROGRAMMING LANGUAGES

A programming language is a language specifically designed to express


computations that can be performed by the computer. Programming languages
are used to create programs that control the behaviour of a system, to express
algorithms, or as a mode of human-computer communication.

Usually, programming languages have a vocabulary of syntax and semantics for


instructing a computer to perform specific tasks. The term programming
language usually refers to high-level languages, such as BASIC, C, C++,
COBOL, FORTRAN, Ada, and Pascal to name a few. Each of these languages
has a unique set of keywords (words that it understands) and a special syntax for
organizing program instructions.

While high-level programming languages are easy for humans to read and
understand, the computer actually understands the machine language that
consists of numbers only. Each type of CPU has its own unique machine
language.
In between the machine languages and high-level languages, there is another
type of language known as assembly language. Assembly languages are similar
to machine languages, but they are much easier to program because they allow a
programmer to substitute names for numbers.

However, irrespective of what language the programmer uses, the program


written using any programming language has to be converted into machine
language so that the computer can understand it. There are two ways to do this:
compile the program or interpret the program

The question of which language is the best depends on the following factors:

• The type of computer on which the program has to be executed

• The type of program

• The expertise of the programmer

For example, FORTRAN is a particularly good language for processing


numerical data, but it does not lend itself very well to organizing large
programs. Pascal can be used for writing well-structured and readable programs,
but it is not as flexible as the C programming language. C++ goes one step
ahead of C by incorporating powerful object-oriented features, but it is complex
and difficult to learn.

GENERATION OF PROGRAMMING LANGUAGES

We now know that programming languages are the primary tools for creating
software. As of now, hundreds of programming languages exist in the market,
some more used than others, and each claiming to be the best. However, back in
the 1940s when computers were being developed there was just one language-
the machine language.

The concept of generations of programming languages (also known as levels) is


closely connected to the advances in technology that brought about computer
generations. The four generations of programming languages include:

• Machine language

• Assembly language
• High-level language (also known as third generation language or 3GL)

• Very high-level language (also known as fourth generation language or 4GL)

First Generation: Machine Language

Machine language was used to program the first stored program on computer
systems. This is the lowest level of programming language. The machine
language is the only language that the computer understands. All the commands
and data values are expressed using 1 and Os, corresponding to the 'on' and 'off'
electrical states in a computer.

In the 1950s each computer had its own native language, and programmers had
primitive systems for combining numbers to represent instructions such as add
and subtract. Although there were similarities between each of the machine
languages, a computer could not understand programs written in another
machine language (Figure 1.4).
In machine language, all instructions, memory locations, numbers, and
characters are represented in strings of 1s and Os. Although machine-language
programs are typically displayed with the binary numbers represented in octal
(base 8) or hexadecimal (base 16), these programs are not easy for humans to
read, write, or debug.

The main advantage of machine language is that the code can run very fast and
efficiently, since it is directly executed by the CPU.

However, on the downside, the machine language is difficult to learn and is far
more difficult to edit if errors occur. Moreover, if you want to add some
instructions into memory at some location, then all the instructions after the
insertion point would have to be moved down to make room in memory to
accommodate the new instructions.

Last but not the least, the code written in machine language is not portable
across systems and to transfer the code to a different computer it needs to be
completely rewritten since the machine language for one computer could be
significantly different from another computer.

Architectural considerations made portability a tough issue to resolve.

Second Generation: Assembly Language

The second generation of programming language includes the assembly


language. Assembly languages are symbolic programming languages that use
symbolic notation to represent machine-language instructions. These languages
are closely connected to machine language and the internal architecture of the
computer system on which they are used. Since they are close to the machine,
assembly language is also called low-level language. Nearly all computer
systems have an assembly language available for use.

Assembly language developed in the mid 1950s was a great leap forward. It
used symbolic codes also known as mnemonic codes that are easy-to-remember
abbreviations, rather than numbers. Examples of these codes include ADD for
add, CMP for compare, MUL for multiply, etc.nel iw gat how now

Assembly language programs consist of a series of individual statements or


instructions that instruct the computer what to do. Basically, an assembly
language statement consists of a label, an operation code, and one or more
operands.

Labels are used to identify and reference instructions in the program. The
operation code (opcode) is a mnemonic that specifies the operation that has to
be performed such as move, add, subtract, or compare. The operand specifies
the register or the location in main memory where the data to be processed is
located.

However, like the machine language, the statement or instruction in the


assembly language will vary from machine to another because the language is
directly related to the internal architecture of the computer and is not designed
to be machine independent. This makes the code written in assembly language
less portable as the code written for one machine will not run on machines from
a different or sometimes even the same manufacturer.

No doubt, the code written in assembly language will be very efficient in terms
of execution time and main memory usage as the language is also close to the
computer.

Programs written in assembly language need a translator often known as


assembler to convert them into machine language. This is because the computer
will understand only the language of 1s and Os and will not understand
mnemonics like ADD and SUB.

The following instructions are a part of assembly language code to illustrate


addition of two numbers:

Although assembly languages are much better to program as compared to the


machine language, they still require the programmer to think on the machine's
level. Even today, some programmers still use assembly language to write parts
of applications where speed of execution is critical, such as video games but
most programmers today have switched to third or fourth generation
programming languages.

Third Generation Programming Languages

A third generation programming language (3GL) is a refinement of the second-


generation programming language. The 2GL languages brought logical
structure to software. The third generation was introduced to make the
languages more programmer friendly.

Third Generation Programming Languages spurred the great increase in data


processing that occurred in the 1960s and 1970s. In these languages, the
program statements are not closely related to the internal architecture of the
computer and is therefore often referred to as high-level languages.

Generally, a statement written in a high-level program- ming language will


expand into several machine language instructions. This is in contrast to
assembly languages, where one statement would generate one machine lan-
guage instruction. Third Generation Programming Lan- guages made
programming easier, efficient, and less prone to errors.

High-level languages fall somewhere between natu- ral languages and machine
languages. Third Generation Programming Languages include languages such
as FOR- TRAN (FORmula TRANslator) and COBOL (Common Business
Oriented Language) that made it possible for scientists and business people to
write programs using fa- miliar terms instead of obscure machine instructions.

The first widespread use of high-level languages in the early 1960s changed
programming into something quite different from what it had been. Programs
were written in statements like English language statements, making them more
convenient to use and giving the programmer more time to address a client's
problems.

Although 3GLs relieve the programmer of demanding details, they do not


provide the flexibility available in low- level languages. However, a few high-
level languages like C and FORTRAN combine some of the flexibility of
assembly language with the power of high-level languages, but these languages
are not well suited to an amateur programmer.
While some high-level languages were designed to serve a specific purpose
(such as controlling industrial robots or creating graphics), other languages were
flexible and considered to be general-purpose languages. Most of the
programmers preferred to use general-purpose high-level languages like BASIC
(Beginners' All-purpose Symbolic Instruction Code), FORTRAN, PASCAL,
COBOL, C++, or Java to write the code for their applications.

Again, a translator is needed to translate the instructions written in high-level


language into computer-executable machine language. Such translators are
commonly known as interpreters and compilers. Each high-level language has
many compilers.

For example, the machine language generated by one computer's C compiler is


not the same as the machine language of some other computer. Therefore, it is
necessary to have a C compiler for each type of computer on which the C
program has to be executed.

Third generation programming languages have made it easier to write and


debug programs, which gives programmers more time to think about its overall
logic. The programs written in such languages are portable between machines.
For example, a program written in standard C can be compiled and executed on
any computer that has a standard C compiler.

Fourth Generation: Very High-Level On Languages

With each generation, programming languages started becoming easier to use


and more like natural languages. However, fourth generation programming
languages (4GLs) are a little different from their its prior generation because
they are basically non-procedural. When writing code using a procedural
language, the programmer has to tell the computer how a task is done-add this,
compare that, do this if the condition is true, and so on, in a very specific step-
by-step manner. In striking contrast, while using a non-procedural language the
programmers define only what they want the computer to do, without supplying
all the details of how it has to be done.

There is no standard rule that defines what a 4GL is but certain characteristics
of such languages include:

• the code comprising instructions are written in English- like sentences;


• they are non-procedural, so users concentrate on 'what' instead of the 'how'
aspect of the task;

• the code is easier to maintain;

• the code enhances the productivity of the programmers as they have to type
fewer lines of code to get something done. It is said that a programmer becomes
10 times more productive when he writes the code using a 4GL than using a
3GL.

A typical example of a 4GL is the query language that allows a user to request
information from a database with precisely worded English-like sentences. A
query language is used as a database user interface and hides the specific details
of the database from the user. For example, when working with structured query
language (SQL), the programmer just needs to remember a few rules of syntax
and logic, and it is easier to learn than COBOL or C.

Let us take an example in which a report has to be generated that displays the
total number of students enrolled in each class and in each semester. Using a
4GL, the request would look similar to one that follows:

TABLE FILE ENROLLMENT

SUM STUDENTS BY SEMESTER BY CLASS

So we see that a 4GL is much simpler to learn and work with. The same code if
written in C language or any other 3GL would require multiple lines of code to
do the same task.

Fourth generation programming languages are still evolving, which makes it


difficult to define or standardize them. The only downside of a 4GL is that it
does not 229 make efficient use of the e machine's resources. However, the
benefit of executing a program fast and easily, far outweighs the extra costs of
running it.

Fifth Generation Programming Languages

Fifth generation programming languages (5GLs) are cen- tred on solving


problems using constraints given to the program, rather than using an algorithm
written by a pro- grammer. Most constraint-based and logic programming
languages and some declarative languages form a part of the fifth-generation
languages. Fifth generation program- ming languages are widely used in
artificial intelligence research. Typical examples of 5GLs include Prolog, OPS5,
and Mercury.

Another aspect of a 5GL is that it contains visual tools to help develop a


program. A good example of a fifth generation language is Visual Basic.

So taking a forward leap than the 4GLs, 5GLs are designed to make the
computer solve a given problem without the programmer. While working with a
4GL, the programmer had to write specific code to do a work but with 5GL, the
programmer only needs to worry about what problems need to be solved and
what conditions need to be met, without worrying about how to implement a
routine or algorithm to solve them.

Generally, 5GLs were built upon Lisp, many originating on the Lisp machine,
such as ICAD. Then, there are many frame languages such as KL-ONE.

In the 1990s, 5GLs were considered to be the wave of the future, and some
predicted that they would replace all other languages for system development
(except the low- level languages). In 1982 to 1993 Japan had put much research
and money into their fifth generation computer systems project, hoping to
design a massive computer network of machines using these tools. But when
larger programs were built, the flaws of the approach became more apparent.
Researchers began to observe that starting from a set of constraints for defining
a particular problem, then deriving an efficient algorithm to solve the problem is
a very difficult task. All these things could not be automated and still requires
the insight of a programmer.

However, today the fifth-generation languages are back as a possible level of


computer language. Software vendors across the globe currently claim that their
software meets the visual 'programming' requirements of the 5GL concept.

Unit – I : Basics of C Programming

CHAPTER 2 : INTRODUCTION TO C

Takeaways
• Writing a C program.

• Keywords

• Variables and constants

• Operator precedence chart

• Compiling and executing C programs

• C Tokens

• Identifiers

• I/O statements

• Type conversion and typecasting

• Basic data types

• Operators

INTRODUCTION
The programming language C was developed in the early 1970s by Dennis
Ritchie at Bell Laboratories to be used by the UNIX operating system. It was
named 'C' because many of its features were derived from an earlier language
called 'B'. Although C was designed for implementing system software, it was
later on widely used for developing portable application software.

C is one of the most popular programming languages. It is being used on several


different software platforms. In a nutshell, there are a few computer
architectures for which a C compiler does not exist.

It is a good idea to learn C because few other programming languages such as


C++ and Java are also based on C which means you will be able to learn them
more easily in the future.

Background
Like many other modern languages, C is derived from ALGOL (the first
language to use a block structure). Although ALGOL was not accepted widely
in the United States, it was widely used in Europe. ALGOL's introduction in the
1960s led the way for the development of structured programming concepts.
Before C, several other programming languages were developed. For example,
in 1967 Martin Richards developed a language called BCPL (Basic Combined
Programming Language). BCPL was basically a type-less (had no concept of
data types) language which facilitated direct access of memory. This made it
useful for system programmers. Then in 1970, Ken Thompson developed a
language called B. B was used to develop the first version of UNIX. C was
developed by Dennis Ritchie in 1972 that took concepts from ALGOL, BCPL,
and B. In addition to the concepts of these languages, C also supports the
concept 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.

For many years, C was mainly used in academic institutions, but with the
release of different C compilers for commercial use and popularity of UNIX, C
was widely accepted by computer professionals.

C (also known as Traditional C) was documented and popularized in the book


The C Programming Language by Brian W. Kernighan and Dennis Ritchie in
1978. This book was so popular that the language came to be known as 'K & R
C'. 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 standard was
approved in December 1989 and came to be known as ANSI C. In 1990, the
International Standards Organization (ISO) adopted the ANSI standard. This
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. Figure 2.1 shows
the taxonomy of C language. During 1990s C++ and Java programming
languages became 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 types, so that they can support even non-English
characters

• Boolean data type

• Extension to the integer data type


• Including type definitions in the for statement

• Inclusion of imaginary and complex types

• Addition of //, better known as C++ style line comment

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

• C is a high-level programming language which enables the programmer to


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

• Small size-C has only 32 keywords. This makes it relatively easy to learn as
compared to other languages.
• C makes extensive use of function calls.

• C is well suited for structured programming. In this programming approach, C


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

• Unlike PASCAL it supports loose typing (as a character can be treated as an


integer and vice versa).

• Structured language as the code can be organized as a collection of one or


more functions.

• Stable language. ANSI C was created in 1983 and since then it has not been
revised.

• Quick language as a well written C program is likely to be as quick as or


quicker than a program written in any other language. Since C programs make
use of operators and data types, they are fast and efficient. For example, a
program written to increment a value from 0-15000 using BASIC would take 50
seconds whereas a C program would do the same in just 1 second.

• Facilitates low level (bitwise) programming.

• Supports pointers to refer computer memory, array, structures, and functions.

• Core language. C is a core language as many other programming languages


(like C++, Java, Perl, etc.) are based on C. If you know C, learning other
computer languages becomes much easier.

• C is a portable language, i.e., a C program written for one computer can be run
on another computer with little or no modification.

• C is an extensible language as it enables the user to add his own functions to


the C library.

• C is often treated as the second best language for any given programming task.
While the best language depends on the particular task to be performed, the
second best language, on the other hand, will always be C.

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

• C language is primarily used for system programming. The portability,


efficiency, the ability to access specific hardware addresses, and low runtime
demand on system resources make it a good choice for implementing operating
systems and embedded system applications.

• C has been so widely accepted by professionals that com- pilers, libraries, and
interpreters of other programming languages are often implemented in C.

• For portability and convenience reasons, C is sometimes used as an


intermediate language for implementations of other languages. Examples of
compilers who use C this way are BitC, Gambit, the Glasgow Haskell
Compiler, Squeak, and Vala.

Basically, C was designed as a programming language and was not meant to be


used as a compiler target language. Therefore, although C can be used as an
intermediate language it is not an ideal option. This led to the development of
C-based intermediate languages such as C.

• C is widely used to implement end-user applications.

STRUCTURE OF A C PROGRAM

A C program is composed of preprocessor commands, a global declaration


section, and one or more functions (Figure 2.2).

The preprocessor directives contain special instructions that indicate how to


prepare the program for compilation. One of the most important and commonly
used preprocessor commands is include which tells the compiler that to execute
the program, some information is needed from the specified header file.
In this section we will omit the global declaration part and will revisit it in the
chapter on Functions.

A C program contains one or more functions, where a function is defined as a


group of C statements that are exe- cuted together. The statements in a C
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. The
execution of a C program begins at this function.

All functions (including main()) are divided into two parts the declaration
section and the statement section. The declaration section precedes the
statement section and is used to describe the data that will be used in the
function. Note that data declared within a function are known as local
declaration as that data will be visible only within that function. Stated in other
terms, the life-time of the data will be only till the function ends. The statement
section in a function contains the code that manipulates the data to perform a
specified task.
From the structure given above we can conclude that a C program can have any
number of functions depending on the tasks that have to be performed, and each
function can have any number of statements arranged according to specific
meaningful sequence.

Note

Programmers can choose any name for functions. It is not mandatory to write
Function1, Function2, etc., but with an exception that every program must
contain one function that has its name as main().

WRITING THE FIRST C PROGRAM

To write a C program, we first need to write the code. For this, open a text
editor. If you are a Windows user you may use Notepad and if you prefer
working on UNIX/Linux you can use emacs or vi. Once the text editor is
opened on your screen, type the following statements:

#include <stdio.h>

int main()

printf("\n Welcome to the world of C");

return 0;

Output

Welcome to the world of C

#include <stdio.h>

This is a preprocessor command that comes as the first statement in our code.
All preprocessor commands start with symbol hash (#). The #include statement
tells the compiler to include the standard input/output library or header
file (stdio.h) in the program. This file has some in-built functions. By simply
including this file in our code we can use these functions directly. The standard
input/ output header file contains 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 written, the last statement of the program will return
an integer value to the operating system. The concepts will be clear to us when
we read the chapter on Functions. So even if you do not understand certain
things, do not worry.

Programming Tip: If you do not place a parenthesis after 'main', a compiler


error will be generated.

{} The two curly brackets are used to group all the related statements of
the main function. All the statements between the braces form the function
body. The function body contains a set of instructions to perform the given task.

printf("\n Welcome to the world of C ");

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.

Programming Tip: Placing a semi- colon after the parenthesis of main


function will generate a compiler error.

The message is quoted because in C a text (also known as a string or a sequence


of characters) is always put between inverted commas. '\n' is an escape
sequence and represents a newline character. It is used to print the message on a
new line on the screen. Like the newline character, the other escape sequences
supported by C language are shown in Table 2.1.
Note

Escape sequences are actually non-printing control characters that begin


with a backslash (\).

return 0;

This is a return command that is used to return the value 0 to the operating
system to give an indication that there were no errors during the execution of
the program.

Note

Every statement in the main function ends with a semi- colon (;).

Now that you have written all the statements using the text editor, save the text
file as first.c. If you are a Windows user then open the command prompt by
clicking Start->Run and typing 'command' and clicking Ok. Using the command
prompt, change to the directory in which you had saved your file and then type:

C:\>tc first.c
In case you are working on UNIX/Linux operating system, then exit the text
editor and type

$cc first.c -ofirst

The -o is for the output file name. If you leave out the -o then the file
name a.out is used.

This command is used to compile your C program. If there are any mistakes in
the program then the compiler will tell you the mistake you have made and on
which line you made it. In case of errors you need to re-open your .c file and
correct those 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

'hello.exe' for Windows and ‘./hello' 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

Note

The printf and return statements have been indented or moved away from the
left side. This is done to make the code more readable.

FILES USED IN A C PROGRAM

Every C program has four kinds of files associated with it (Figure 2.3). These
include:
Source Code Files

The source code file contains the source code of the program. The file extension
of any C source code file is ‘.c'. This file contains C source code that defines the
main function and maybe other functions. The main() function is the starting
point of execution when you successfully compile and run the program. A C
program in general may include even other source code files (with the file
extension. c).

Header Files

When working with large projects, it is often desirable to separate out certain
subroutines from the main() function of the program. There also may be a case
that the same subroutine has to be used in different programs. In the latter case,
one option is to copy the code of the desired subroutine from one program to
another. But copying the code is often tedious as well as error prone and makes
maintainability more difficult.

So, another option is to make subroutines and store them in a different file
known as header file. The advantages of header files can be realized in the
following cases:

• The programmer wants to use the same subroutines in different programs. For
this, he simply has to compile the source code of the subroutines once, and then
link to the resulting object file in any other program in which the functionalities
of these sub-routines are required.

• The programmer wants to change or add subroutines, and have those changes
reflected in all the other programs. In this case, he just needs to change the
source file for the subroutines, recompile its source code, and then re-link
programs that use them. This way time can be saved as compared to editing the
subroutines in every individual program that uses them.

Programming Tip: Missing the inclusion of appropriate header files in a C


program will generate an error. Such a program may compile but the linker
will give an error message as it will not be able to find the functions used in
the program.
Thus, we see that using a header file produces the same results as copying the
header file into each source file that needs it. Also when a header file is
included, the related declarations appear in only one place. If in future we need
to modify the subroutines, we just need to make the changes in one place, and
programs that include the header file will automatically use the new version
when recompiled later. There is no need to find and change all the copies of the
subroutine that has to be changed.

Conventionally, header files names ends with a 'dot h' (.h) extension and names
can use only letters, digits, dashes, and underscores. Although some standard
header files are automatically available to C programmers, in addition to those
header files, the programmer may have his own user-defined header files.

Standard Header Files In the program that we have written till now, we
used printf() function that has not been written by us. We do not know the
details of how this function works. Such functions that are provided by all C
compilers are included in standard header files. Examples of these standard
header files include:

• string.h : for string handling functions

• stdlib.h : for some miscellaneous functions

• stdio.h : for standardized input and output functions

• math.h : for mathematical functions

• alloc.h : for dynamic memory allocation

• conio.h : for clearing the screen

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

Object Files

Object files are generated by the compiler as a result of processing the source
code file. Object files contain compact binary code of the function definitions.
Linker uses these object files to produce an executable file (.exe file) by
combining the object files together. Object files have a ‘.o' extension, although
some operating systems including Windows and MS-DOS have
a ‘.obj' extension for the object file.

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 system, the executable files have an '.exe' extension.
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 a machine-readable file available in an executable form.

The mechanical part of running a 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 that consists of the
statements of the program written in C language. This source file usually
contains ASCII characters and can be produced with a text editor, such as
Windows notepad, or in an Integrated Design Environment. The source file is
then processed by a special program called a compiler.

Note

Every programming language has its own 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).

However, even the object file is not an executable file. Therefore, in the next
step, the object file is processed with another special program called a linker.
While there is a different compiler 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. The process is shown in Figure 2.4.
In C language programs, there are two kinds of source files. In addition to the
main (.c) source file, which contains executable statements there are also
header (.h) source files. Since all input and output in C programs is done
through library functions, every C program therefore uses standard header files.
These header files should be written as part of the source code for modular C
programs.

The compilation process shown in Figure 2.5 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 begin 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 (supplied with the compiler) to produce the final executable file.

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 (Figure 2.6).
USING COMMENTS
Many a time the meaning or the purpose of the program code is not clear to the
reader. Therefore, it is a good programming practice to place some comments in
the code to help the reader understand the code clearly. Comments are just a
way of explaining what a program does. It is merely an internal program
documentation. The compiler ignores the comments when forming the object
file. This means that the comments are non-executable statements. C supports
two types of comments.

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


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

Programming Tip: Not putting the */ after the termination of the block
comment is a compiler error.

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


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

Note that commented statements are not executed by the compiler. Rather, they
are ignored by the compiler as they are simply added in the program to make
the code uple who understandable by the programmer to other people who read
it. It is a good habit to always put a comment at the top of a program that tells
you what the program does. This will help in defining the usage of the program
the moment you open it.

Ppppppppppppppppppppppppp
Commented statements can be used anywhere in the program. You can also use
comments in between your code to explain a piece of code that is a bit
complicated. The code given below shows the way in which we can make use
of comments in Our first program.

/* Author: Reema Thareja

Description: To print 'Welcome to the world of C' on the screen */

#include <stdio.h>

int main()

printf("\n Welcome to the world of C ");

// prints message

return 0; // returns a value 0 to the operating system

Output

Welcome to the world of C

Since comments are not executed by the compiler, they do not affect the
execution speed and the size of the compiled program. Therefore, using
comments liberally in your programs aid other users in understanding the
operations of the program as well as in debugging and testing.
C 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. There are six main types of
tokens in C. They are shown in Figure 2.7.
CHARACTER SET IN C

Like in natural languages, computer languages also use a character set that
defines the fundamental units used to represent information. In C, a character
means any letter from English alphabet, digit or special symbol used to
represent information. These characters when combined together form tokens
that act as basic building blocks of a C program. The character set of C can
therefore be given as:

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


letters

b. Digits: Include numerical digits from 0 to 9

c. Special characters: Include symbols such as ~, @, 응, ^,&, *, {, }, <. >, =,_,


+,-,$, /, (, ), \, ;,:,[, ],’,”,?,.,!,.

d. White space characters: These characters are used to print a blank space on
the screen. They are shown in Figure 2.8.

e. Escape sequence: Escape sequences have already been discussed in section


2.3. They include \\, \', \", \n, \a, \0, \?.
KEYWORDS

Like every computer language, 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. Table 2.2 shows the list of
keywords in C.

When you read this book, the meaning and utility of each keyword will become
automatically clear to you.

IDENTIFIERS

Identifiers, as the name suggests, help 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 consist of sequence of letters,
numerals, or underscores.

Rules for Forming Identifier Names


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

• Identifiers cannot include any special characters or punctuation marks (like #,


$, ^, ?,., etc.) except the underscore’_’

• There cannot be two successive underscores.

• Keywords cannot be used as identifiers.

• The case of alphabetic characters that form the identifier name is significant.
For example, 'FIRST' is different from 'first' and 'First'.

• Identifiers must begin with a letter or an underscore. However, use of


underscore as the first character must be avoided because several compiler-
defined identifiers in the standard C library have underscore as their first char-
acter. Hence, inadvertently dupli- cated names may cause definition conflicts.

Programming Tip: C is a case sensitive language. If you type printf function


as Printf, then an error will be generated.

• Identifiers can be of any reasonable length. They should not contain more than
31 characters. They can actually be longer than 31, but the compiler looks at
only the first 31 characters of the name.

Although it is a good practice to use meaningful identifier names, it is not


compulsory. Good identifiers are descriptive but short. To cut short the
identifier, you may use abbreviations. C allows identifiers (names) to be up to
63 characters long. If a name is longer than 63 characters, then only the first 31
characters are used.

As a general practice, if the identifier is a little long, then you may use an
underscore to separate the parts of the name or you may use capital letters for
each part. Examples of valid identifiers include:

roll_number, marks, name, emp_number, basic_ pay, HRA, DA, dept code,
Dept Code, RollNo, EMP NO

Examples of invalid identifiers include:


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

Note

C is a case-sensitive language. Therefore rno, Rno, RNo, RNO are considered


as different identifiers.

BASIC DATA TYPES IN C

C language provides very few basic data types. Table 2.3 lists the basic data
types, their size, range, and usage for a C programmer on a 16-bit computer. In
addition to this, we also have variants of int and float data types.

The char data type is of one byte and is used to store single characters. Note
that C does not provide any data type for storing text. This is because text is
made up of xt is individual characters.

You will be surprised to see that the range of char is given as -128 to
127. char is supposed to store characters not numbers, so why this range? The
answer is that, in memory characters are stored in their ASCII codes. For
example, the character A has the ASCII code 65. In memory we will not store
'A' but 65 (in binary number format).

In addition, C also supports four modifiers-two sign specifiers (signed and


unsigned) and two size specifiers (short and long).
Table 2.4 shows the variants of basic data types.

In Table 2.4, we have unsigned char and signed char. Do we have negative
characters? No, then why do we have such data types? The answer is that we
use signed and unsigned char to ensure portability of programs that store non-
character data as char.

While the smaller data types take less memory, the larger types incur a
performance penalty. Although the data type we use for our variables does not
have a big impact on the speed or memory usage of the application, we should
always try to use int unless there is a special need to use any other data type.

Last but not the least the void type holds no value. It is primarily used in 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. We will read about generic pointers in the chapter
on Pointers.

We will discuss the void data type in detail in the coming chapters.

Note

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.

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
format, a floating point value in its binary form is known as a normalized form.
In the normalized form, the exponent is adjusted in such a way that the binary
point in the mantissa always lies to the right of the most significant non-zero
digit.

Example 2.1

Convert the floating point number 5.32 into an IEEE normalized form.
Moreover, the IEEE format for storing floating point numbers uses a sign bit,
mantissa, and the exponent (Figure 2.9). The sign bit denotes the sign of the
value. If the value is positive, the sign bit contains 0 and in case the value is
negative it stores 1.

Generally, exponent is an integer value stored in unsigned binary format after


adding a positive bias. In other words, because exponents are stored in an
unsigned form, the exponent is biased by half its possible value. For type float,
the bias is 127; for type double, it is 1023. You can compute the actual exponent
value by subtracting the bias value from the exponent value. Finally, the
normalized binary equivalent is stored in such a way that lower byte is stored at
higher memory address. For example, ABCD is actually stored as DCBA.

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 basic kinds of
variables-numeric and character.

Numeric Variables
Numeric variables can be used to store either integer values or floating point
values. While an 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 like short, long,
signed, and unsigned. The difference between signed and unsigned numeric
variables is that signed variables can be either negative or positive but unsigned
variables can only be positive. Therefore, by using an unsigned variable we can
increase the maximum positive range. When we do not specify the signed/
unsigned modifier, C language automatically takes it as a signed variable. To
declare an unsigned variable, the unsigned modifier must be explicitly added
during the declaration of the variable.

Character Variables

Character variables are just single characters enclosed within single quotes.
These characters could be any character from the ASCII character set-letters ('a',
'A'), numerals ('2'), or special characters ('&'). In C, a number that is given in
single quotes is not the same as a number without them. This is because 2 is
treated as an integer value but '2' is a considered character not an integer.

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 variable will store. Variable names should
always be meaningful and must reflect the purpose of their usage in the
program. The memory location of the variable is of importance to the compiler
only and not to the programmer. Programmers must only be concerned with
accessing data through their symbolic names. In C, variable declaration always
ends with a semicolon, for example:

int emp_num;

float salary;

char grade;
double balance_amount;

unsigned short int acc_no;

In C variables can be declared at any place in the program but two things must
be kept in mind. First, variables should be declared before using them. Second,
variables should be declared closest to their first point of use to make the source
code easier to maintain.

C allows multiple variables of the same type to be declared in one statement. So


the following statement is absolutely legal in C.

float temp_in_celsius, temp_in_farenheit;

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 formal parameter (we will study this in the chapter on Functions). of
boon

• When the variable is declared outside all functions, it is known as a global


variable.

Note

A variable cannot be of type void.

Initializing Variables

While declaring the variables, we can also initialize them with some value. For
example,

int emp_num = ?;

float salary = 2156.35;

char grade = 'A';

double balance_amount = 100000000;


The initializer applies only to the variable defined immediately before it.
Therefore, the statement

int count, flag = 1;

initializes the variable flag and not count. If you want both the variables to be
declared in a single statement then write,

int count = 0, flag = 1;

When variables are declared but not initialized they usually contain garbage
values (there are exceptions to this that we will study later).

CONSTANTS

Constants are identifiers whose values do not change. While values of variables
can be changed at any time, values of constants can never be changed.
Constants are used to define fixed values like pi or the charge on an electron so
that their value does not get changed in the program even by mistake.

A constant is an 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 constants of integer type, floating point type, character
type, and string type (Figure 2.10).

Integer Constants

A constant of integer type consists of a sequence of digits. For example, 1, 34,


567, 8907 are valid integer constants. A literal integer like 1234 is of
type int by default. For a long integer constant the literal is succeeded with
either 'L' or 'l' (like 1234567L). Similarly, an unsigned int literal is written with
a 'U' or 'u' suffix (ex, 12U). Therefore, 1234L, 1234I, 1234U, 1234u, 1234LU,
1234ul are all valid integer constants.

Integer literals can be expressed in decimal, octal or hexadecimal notation. By


default an integer is expressed in decimal notation. Decimal integers consist of a
set of digits, 0 through 9, preceded by an optional - or + sign. Examples of
decimal integer constants include: 123,-123, +123, and 0.

While writing integer constants, embedded spaces, commas, and non-digit


characters are not allowed. There- fore, integer constants given below are totally
invalid in C.

123 456

12,34,567

$123

An integer constant preceded by a zero (0) is an octal number. Octal integers


consist of a set of digits, 0 through

7. Examples of octal integers include

012 0 01234

Similarly, an integer constant is expressed in hexadecimal notation if it is


preceded with Ox or OX. Hexadecimal numbers contain digits from 0-9 and
letters A through F, which represent numbers 10 through 15. For example,
decimal 72 is equivalent to 0110 in octal notation and Ox48 in hexadecimal
notation. Examples of hexadecimal integers are 0X12, 0x7F, 0xABCD,
0X1A3B.

Note

In C, a decimal integer constant is treated as an unsigned long if its


magnitude exceeds that of signed long. An octal or hexadecimal integer that
exceeds the limit of int is taken to be unsigned. If even this limit is exceeded,
it is taken as long; and in case this limit is exceeded, it is treated as unsigned
long.
Floating Point Constants

Integer numbers are inadequate to express numbers that have a fractional part.
A floating point constant therefore consists of an integer part, a decimal point, a
fractional part, and an exponent field containing an e or E (e means exponent)
followed by an integer where the fraction part and integer part are a sequence of
digits. However, it is not necessary that every floating point constant must
contain all these parts. Some floating point numbers may have certain parts
missing. Some valid examples of floating point numbers are: 0.02, -0.23,
123.456, +0.34 123, 0.9, -0.7, +0.8 etc.

A literal like 0.07 is treated as of type double by default. To make it a float type
literal, you must specify it using suffix 'F' or 'f'. Consider some valid floating
point literals given below. (Note that suffix L is for long double.)

0.02F 0.34f 3.141592654L 0.002146 2.146E-3

A floating point number may also be expressed in scientific notation. In this


notation, the mantissa is either a floating point number or an integer and
exponent is an integer with an optional plus or minus sign. Therefore, the
numbers given below are valid floating point numbers

0.5e2 14E-2 1.2e+3 2.1E-3 -5.6e-2

Thus, we see that scientific notation is used to express numbers that are either
very small or very large. For example,

120000000= 1.2E8 and -0.000000025= -2.5E-8

Character Constants

A character constant consists of a single character enclosed in single quotes. For


example, 'a' and `@' are character constants. In computers, characters are stored
using machine's character set using ASCII codes. All escape sequences
mentioned in Table 2.1 are also character constants.

String Constants
A string constant is a sequence of characters enclosed in double quotes.
So "a" is not the same as 'a'. The characters comprising the string constant are
stored in successive memory locations. When a string constant is encountered in
a 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. Thus, length of a
string constant is equal to number of characters in the string plus 1 (for the null
character). Therefore, the length of string literal "hello" is 6.

Declaring Constants

To declare a constant, precede the normal variable declaration with const


keyword and assign it a value. For example,

const float pi = 3.14;

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

However, another way to designate a constant is to use the pre-processor


command define. Like other preprocessor commands, define is preceded with a
# symbol. Although #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. Look at the
example given below which defines the value of pi using define.

#define pi 3.14159

#define service_tax 0.12

In these examples, the value of pi will never change but service tax may change.
Whenever the value of the service tax is altered, it needs to be corrected only in
the define statement.

When the preprocessor reformats the program to be compiled by the compiler, it


replaces each defined name (like pi, service_tax) in the source program with its
corresponding value. Hence, it just works like the Find- and-Replace command
available in a text editor.

Let us take a look at some rules that need to be applied to a #define statement
which defines a constant.
Rule 1: Constant names are usually written in capital letters to visually
distinguish them from other variable names which are normally written in lower
case characters. Note that this is just a convention and not a rule.

Rule 2: No blank spaces are permitted between the # symbol


and define keyword.

Rule 3: Blank space must be used between #define and constant name and
between-0 constant name and constant value.

Rule 4: #define is a pre-processor compiler directive and not a statement.


Therefore, it does not end with a semi-colon.

INPUT/OUTPUT STATEMENTS IN C

Before performing input and output in C programs let us first understand the
concept from scratch. This section deals with the basic understanding of the
streams involved in accepting input and printing output in C programs.

Streams

A stream acts in two ways. It is the source of data as well as the destination of
data. Streams are associated with a physical device such as a monitor or with a
file stored on the secondary memory. C uses two forms of streams-text and
binary, as shown in Figure 2.11.

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, a binary stream
contains data values using their memory representation.
We can do input/output from the keyboard/monitor or from any file but in this
chapter we will assume that the source of data is the keyboard and destination of
the data is the monitor (Figure 2.12). File handling, i.e., handling input and
output via C programs, will be discussed later as a separate chapter.

Formatting Input/Output

C language supports two formatting functions printf and scanf. printf is used to
convert data stored in the program into a text stream for output to the monitor,
and scanf is used to convert the text stream coming from the keyboard to data
values and stores them in program variables. In this section, we will discuss
these functions.

Background

The most fundamental operation in a C program is to accept input values from a


standard input device (keyboard) and output the data produced by the program
to a standard output device (monitor). So far we had been assigning values to
variables using the assignment operator =. For example,

int a = 3;

But what if we want to assign value to variable that is inputted by the user at
run-time. This is done by using the scanf function that reads data from the
keyboard. Similarly, for outputting results of the program, printf function is
used that sends results to a terminal. Like printf and scanf, there are different
functions in C that can carry out the input/output operations. These functions
are collectively known as Standard Input/Output Library. A program that uses
standard input/output functions must contain the statement
#include <stdio.h>

at the beginning of the program.

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. For this, the
printf function takes data values, converts them to a text stream using
formatting specifications in the control string and passes the resulting text
stream to the standard output. The control string may contain zero or more
conversion specifications, textual data, and control characters to be displayed
(Figure 2.13).

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 value's type, size and specific format
information as shown in Figure 2.13.

The syntax of printf function can be given as

printf ("control string", variable list);

The function accepts two parameters-control string and variable list. The control
string may also contain text to be printed like instructions to the user, captions,
identifiers, or any other text to make the output readable. In
some printf statements you may find only a text string that has to be displayed
on screen (as seen in the first program in this chapter). The control characters
can also be included in the printf statement. These control characters include \n,
\t, \r, \a, etc.

After the control string, the function can have as many additional arguments as
specified in the control string. The parameter control string in
the printf() function is nothing but a C string that contains the text that has to be
written on to the standard output device.

Note that there must be enough arguments, otherwise the result will be
completely unpredictable. However, if by mistake you specify more number of
arguments, the excess arguments will simply be ignored. The prototype of the
control string can be given as below.

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

Each control string must begin 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


numerical sign, trailing zeros or octal, decimal, or hexadecimal prefixes. Table
2.5 shows the different types of flags with their decription.

Note that when data is shorter than the specified width then by default the data
is right justified. To left justify the data use minus sign (-) in the flags field.

When the data value to be printed is smaller than the width specified, then
padding is used to fill the unused spaces.
By default, the data is padded with blank spaces. If zero is used in the flag field
then the data is padded with zeros. One thing to remember here is that zero flag
is ignored when used with left justification because adding zeros after a number
changes its value.

Width is an optional argument which specifies the minimum number of


positions in the output. If data needs more space than specified,
then printf overrides the width specified by the user. However, 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. Width is a very important field
especially when you have to align output in columns. However, if the user does
not mention any width then the output will take just enough room for data.

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. However, if the value to be written is shorter
than this number, the result is padded with leading zeros. Otherwise, if the value
is longer, it is not truncated.

• For character strings, precision specifies the maximum number of characters to


be printed.

• For floating point numbers, the precision flag specifies the number of decimal
places to be printed.
Its format can be given as .m, where m specifies the number of decimal digits.
When no precision modifier is specified, printf prints six decimal positions.

When both width and precision fields are used, width must be large enough to
contain the integral value of the number, the decimal point and the number of
digits after the decimal point. Therefore, a conversion
specification %7.3f means print a floating point value of maximum 7 digits
where 3 digits are allotted for the digits after the decimal point.

Length modifiers can be explained as given in Table 2.6

Type specifiers are used to define the type and the interpretation of the value of
the corresponding argument (Table 2.7).
Note that if the user specifies a wrong specifier then some strange things will be
seen on the screen and the error might propagate to other values in
the printf() list. The most simple printf statement is

printf ("Welcome to the world of C language");

When executed, the function prompts the message enclosed in the quotation to
be displayed on the screen.

Note

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.

Examples

Programming Tip: Not placing a comma after the format string in a read or
write statement is a compiler error.

printf("\n Result: %d%c%f", 12, 'a', 2.3);

Result: 12a2.3

printf("\n Result: %d %c %f", 12, 'a', 2.3);

Result: 12 a 2.3

printf("\n Result: %d\t%c\t%f", 12, 'a', 2.3);

Result:12 a 2.3

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 OXEA

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

The number is 12

printf("\n The number is %2d", 1234);

The number is 1234

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

The number is 1234

printf("\n The number is %-6d", 1234);

The number is 1234_ // 2 indicates 2_ white spaces

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

The number is 001234

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

The price of this item is 000123.45 rupees

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

This is 'so' beautiful

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

This is "so" beautiful

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

This is \so beautiful

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

a = +1.20 b = 0001.20 c = 1.20


(Note that in this example, - means left justify, + means display the sign, 7
specifies the width, and 2 specifies the precision.)

printf("\n %7.4f \n %7.2f \n %-7.2f \n %f\n %10.2e \n %11.4e \n %-10.2e \


n %e", 98.7654, 98.7654, 98.7654, 98.7654, 98.7654, 98.7654, 98.7654,
98.7654);

98.7654

98.77

98.77

98.7654

9.88e+01

9.8765e+01

9.88e+01

9.876540e+01

char ch = 'A';

printf("\n %c \n %3c \n %5c", ch, ch, ch);

char str[] = "Good Morning";

printf("\n %s", str);

printf("\n %20s", str);

printf("\n %20.10s", str);

printf("\n %.7s", str);


printf("\n %-20.10s", str);

printf("\n %7s", str);

Programming Tip: Placing an address operator with a vari- able in the printf
statement will gener- ate a run-time error.

Good Morning

Good Morning

Good Morni

Good Mo

Good Morni

Good Morning

(Note that in the last printf statement the complete string "Good Morning" is
printed. This is because if data needs more space than specified, then printf
function overrides the width specified by the user.)

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. 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
arguments arg1, arg2,..., argn, i.e., the arguments are actually the variable
addresses where each piece of data are to be stored.

The prototype of the control string can be give as:

% [*] [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 (not stored in
the memory location).

Width is an optional argument that specifies the maximum number of


characters to be read. However, fewer characters will be read if
the scanf function encounters a white space or an inconvertible character
because the moment scanf function encounters a white space character it will
stop processing further.

Modifier is an optional argument that can be h, 1, or L for the data pointed by


the corresponding additional arguments. Modifier h is used for short
int or unsigned short int, 1 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. The type specifiers for scanf function
are same as given for printf() function in Table 2.7.

The scanf function ignores any blank spaces, tabs, and newlines entered by the
user. The function simply returns the number of input fields successfully
scanned and stored.

We will not discuss functions in detial in this chapter. So


understanding scanf function in depth will be a bit difficult here, but for now
just understand that the scanf function is used to store values in memory
locations associated with variables. For this, the function should have the
address of the variables. The address of the variable is denoted by an '&' sign
followed by the name of the variable.

Note

Whenever data is read from the keyboard, there is always a return character
from a previous read operation. So we should always code at least one white
space character in the conversion specification in order to flush that
whitespace character. For example, to read two or more data values together
in a single scanf statement, we must insert a white space between two fields as
shown below: scanf("%d %c", &i, &ch);
Now let us quickly summarize the rules to use a scanf function in our C
programs.

Rule 1: The scanf function works until:

(a) the maximum number of characters has been processed,

(b) a white space character is encountered, or

(c) an error is detected.

Rule 2: 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.

scanf("%d %d", &num1, &num2, &num3);

Rule 3: There must be a variable address for each conversion specification.


Therefore, the following scanf statement will generate an error as no variable
address is given for the third conversion specification.

scanf("%d %d %d", &num1, &num2);

Remember that the ampersand operator (&) before each variable name specifies
the address of that variable name.

Rule 4: An error would be generated if the format string is ended with a white
space character.

Rule 5: The data entered by the user must match the character specified in the
control string (except white space or a conversion specification), otherwise an
error will be generated and scanf will stop its processing. For example, consider
the scanf statement given below.

scanf("%d/%d", &num1, &num2);

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

Rule 6: Input data values must be separated by spaces.


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

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

Look at the code given below that shows how we input values in variables of
different data types.

int num;

scanf("%d", &num);

The scanf function reads an integer value (because the type specifier is %d) into
the address or the memory location pointed by num.

float salary;

scanf("%f", salam &salary);

The scanf function reads a floating point number (because the type specifier
is %f) into the address or the memory location pointed by salary.

char ch;

scanf("%c", &ch);

The scanf function reads a single character (because the type specifier is %c)
into the address or the memory location pointed by ch.

char str[10]; scanf("%s", str);

The scanf function reads a string or a sequence of characters (because the type
specifier is %s) into the address or the memory location pointed by str. Note
that in case of reading strings, we do not use the & sign in the scanf function.
This will be discussed in the chapter on Strings.

Programming Tip: A compiler error will be generated if the read and write
parameters are not separated by commas.

Look at the code given below which 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);

Look at the scanf statement given below for the same code. The statement
ignores the character variable and does not store it (as it is preceded by *).

scanf("%d %f %*c %s", &num, &fnum, &ch, str);

Remember that if an attempt is made to read a value that does not match the
expected data type, the scanf function will not read any further and would
immediately return the values read.

Examples of printf/scanf

Look at the codes given below that show how we output values of variables of
different data types.

int num;

scanf("%d", &num);

printf("%d", num);

The printf function prints an integer value (because the type specifier is %d)
pointed by num on the screen.

float salary;

scanf("%f", &salary);

printf(".2%f", salary);
The printf function prints the floating point number (because the type specifier
is %f) pointed by salary on the screen. Here, the control string specifies that
only two digits must be displayed after the decimal point.

Programming Tip: A float specifier cannot be used to read an integer value.

char ch;

scanf("%c", &ch);

printf("%c", ch);

The printf function prints a single character (because the type specifier is %c)
pointed by ch on the screen.

char str[10];

scanf("%s", str);

The printf function prints a string or a sequence of characters (because the type
specifier is %s) pointed by str on the screen.

scanf("%2d %5d", &num1, &num2);

The scanf statement will read two integer numbers. The first integer number
will have two digits while the second can have maximum of 5 digits.

Look at the code given below which combines printing all these variables of
different data types in one single statement.

int num;

float fnum;

char ch;

char str[10];

double dnum;

short snum;
long int lnum;

printf("\n Enter the values : ");

scanf("%d %f %c %s %e %hd %ld", &num, &fnum, &ch, str, &dnum, &snum,


&lnum);

printf("\n num = %d\n fnum = %.2f \n ch = %c \n str %s\n dnum %e \n snum


%hd \n lnum = %ld", num, fnum, ch, str, dnum, snum, lnum);

Note

In the printf statement, `\n', is called the newline character and is used to
print the succeeding text on the new line. The following output will be
generated on execution of the print function.

Enter the values

2 3456.443 a abcde 24.321E-2 1 12345678

num = 2

fnum = 3456.44

ch = a

str = abcde

dnum = 0.24321

snum = 1

lnum = 12345678

Remember one thing that scanf terminates as soon as it encounters a white


space character so if you enter the string as abc def, then only abc is assigned to
str.

1. Find out the output of the following program.

#include <stdio.h>
int main()

int a, b;

printf("\n Enter two four digit numbers: ");

scanf("%2d %4d", &a, &b);

printf("\n The two numbers are: %d and %d", a, b);

return 0;

Output

Enter two four digit numbers : 1234 5678

The two numbers are : 12 and 34

Programming Tip: Using an incorrect specifier for the data type being read
or written will generate a run-time error.

Here, the variable a is assigned the value 12 because it is specified as %2d, so it


will accept only the first two digits. The rest of the number will be assigned
to b. The value 5678 that is unread will be assigned to the first variable in the
next call to the scanf function.

Note

The %n specifier is used to assign the number of characters read till the point
at which the %n was encountered to the variable pointed to by the
corresponding argument. The code fragment given below illustrates its use.

int count;

printf("Hello %n World!", &count);

printf("%d", count);
The output would be-Hello World! 6 because 6 is the number of characters
read before the %n modifier.

2. Write a program to demonstrate the use of printf statement to


print values of variables of different data types.

#include <stdio.h>

int main()

// Declare and initialize variables

int num = 7;

float amt = 123.45;

char code = 'A';

double pi = 3.1415926536;

long int population_of_india = 10000000000;

char msg [ ] "Hi=";

// Print the values of variables

printf("\n NUM %d\n AMT = %f \n CODE = %c \n PI = %e \n POPULATION


OF INDIA %ld \n MESSAGE = %s", num, amt, code, pi, population_of_india,
msg);

return 0;

Output

NUM = 7

AMT = 123.450000
CODE = A

PI = 3.141590e+00

POPULATION OF INDIA = 10000000000

MESSAGE = Hi

3. Write a program to demonstrate the use


of printf and scanf statements to read and print values of
variables of different data types.

#include <stdio.h>

int main()

int num;

float amt;

char code;

double pi;

long int population_of_india;

char msg [10];

printf("\n Enter the value of num : ");

scanf("%d", &num);

printf("\n Enter the value of amt : ");

scanf("%f", &amt);

printf("\n Enter the value of pi : ");

scanf("%e", &pi);

printf("\n Enter the population of India : ");


scanf("%ld", &population_of_india);

printf("\n Enter the value of code : ");

scanf("%c", &code);

printf("\n Enter the message: ");

scanf("%s", msg);

printf("\n NUM = %d\n AMT = %f \n PI = %e \n POPULATION OF INDIA =


%ld\n CODE = %c \n MESSAGE = %s", num, amt, pi, population_of_india,
code, msg);

return 0;

Output

Enter the value of num : 5

Enter the value of amt : 123.45

Enter the value of pi : 3.14159

Enter the population of India : 12345

Enter the value of code : с

Enter the message : Hello

NUM = 5

AMT = 123.450000

PI = 3.141590e+00

POPULATION OF INDIA = 12345

CODE = c

MESSAGE = Hello
4. Write a program to calculate the area of a triangle using Hero's
formula.

#include <stdio.h>

#include <conio.h>

#include <math.h>

int main()

float a, b, c, area, S;

printf("\n Enter the lengths of the three sides of the triangle: ");

scanf("%f %f %f", &a, &b, &c);

S = (a + b + c)/2;

// sqrt is a mathematical function defined in math.h header file

area = sqrt (S* (S-a) * (S-b) * (S-c)); printf("\n Area %f", area);

return 0;

Output

Enter the lengths of the three sides of the triangle: 12 16 20

Area = 96

5. Write a program to calculate the distance between two points.

#include <stdio.h>

#include <conio.h>

#include <math.h>

int main()
{

int x1, x2, y1, y2;

float distance;

printf("\n Enter the x and y coordinates of the first point: ");

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

printf("\n Enter the x and y coordinates of the second point :");

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

// sqrt and pow are mathematical functions defined in math.h header file

distance = sqrt (pow((x2-x1), 2)+pow ((y2-yl), 2));

printf("\n Distance = %f", distance);

return 0;

Output

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

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

Distance = 2.236068

Detecting Errors During Data Input

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

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 data
expected and the type of data entered.
OPERATORS IN C
An operator is a symbol that specifies the mathematical, logical, or relational
operation to be performed. C language supports different types of operators,
which can be used with variables and constants to form expressions. These
operators can be categorized into the following major groups:

• Arithmetic operators

• Relational operators

• Equality operators

• Logical operators

• Unary operators

• Conditional operators

• Bitwise operators

• Assignment operators

• Comma operator

• Sizeof operator

In this section, we will discuss all these operators.

Arithmetic Operators
Consider three variables declared as,

int a=9, b=3, result;

We will use these variables to explain arithmetic operators. Table 2.8 shows the
arithmetic operators, their syntax, and usage in C language.

In Table 2.8, a and b (on which the operator is applied) are called operands.
Arithmetic operators can be applied to any integer or floating-point number.
The addition, subtraction, multiplication, and division (+,-,*,/) operators
perform the usual arithmetic operations in C programs, so you are already
familiar with these operators.

However, the operator % must be new to you. The modulus operator (%) finds
the remainder of an integer division. This operator can be applied only to
integer operands and cannot be used on float or double operands. Therefore, the
code given below generates a compiler error.

#include <stdio.h>

#include <conio.h>

int main()

float c = 20.0;

printf("\n Result = %f", c% 5);

// WRONG. Modulus operator is being applied to a float operand

return 0;

}
While performing modulo division, the sign of the result is always the sign of
the first operand (the dividend). Therefore,

16 % 3 = 1

16 % -3 = 1

-16% 3 = -1

-16% -3 = -1

When both operands of the division operator (/) are integers, the division is
performed as an integer division. Integer division always results in an integer
result. So, the result is always rounded-off by ignoring the remainder.
Therefore,

9/4 = 2 and -9/4 = -3

From the above observation, we can conclude two things. If op1 and op2 are
integers and the quotient is not an integer, then we have two cases:

• If op1 and op2 have the same sign, then op1/op2 is the largest integer less than
the true quotient.oginos

• If op1 and op2 have opposite signs, then op1/op2 is the smallest integer
greater than the true quotient.

Note that it is not possible to divide any number by zero. This is an illegal
operation that results in a run-time division- by-zero exception, thereby
terminating the program.

Except for modulus operator, all other arithmetic operators can accept a mix of
integer and floating point numbers. If both operands are integers, the result will
be an integer. If one or both operands are floating point numbers, then the result
would be a floating point number.

All the arithmetic operators bind from left to right. As in mathematics the
multiplication, division, and modulus operators have higher precedence over the
addition and subtraction operators, i.e., if an arithmetic expression consists of a
mix of operators, then multiplication, division, and modulus will be carried out
first in a left to right order, before any addition and subtraction could be
performed. For example,

3+4*7
= 3 + 28

= 31

6. Write a program to perform addition, subtraction, division,


integer division, multiplication, and modulo division on two
integer numbers.
#include <stdio.h>

#include <conio.h>

int main()

int num1, num2;

int add_res=0, sub_res=0, mul_res=0, idiv_res=0, modiv_res=0;

float fdiv res=0.0;

clrscr();

printf("\n Enter the first number : ");

scanf("%d", &num1);

printf("\n Enter the second number: ");

scanf("%d", &num2);

add_res = num1 + num2;

sub_res = num1 - num2;

mul_res = num1 * num2;

idiv_res = num1/num2;

modiv_res = num1%num2;

fdiv_res = (float) num1/num2;

printf("\n %d + %d = %d", num1, num2, add_res);


printf("\n %d - %d = %d", num1, num2, sub_res);

printf("\n %d × %d = %d", num1, num2, mul_res);

printf("\n %d/%d = %d (Integer Division)", num1, num2, idiv_res);

printf("\n %d %% %d = %d (Moduluo Division)", numl, num2, modiv_res);

printf("\n %d %d = %.2f (Normal live the Division)", num1, num2, fdiv_res);

return 0;

Output

Enter the first number: 9

Enter the second number: 7

9 + 7 = 16

9-7=2

9 * 7 = 63

9 / 7 = 1 (Integer Division)

9 % 7 = 2 (Moduluo Division)

9 / 7 = 1.29 (Normal Division)

7. Write a program to subtract two long integers.


#include <stdio.h>

#include <conio.h>

int main()

long int num1= 1234567, num2, diff=0;

clrscr();
printf("\n Enter the number: ");

scanf("%ld", &num2);

diff = num1 num2;

printf("\n Difference = %ld", diff);

return 0;

Output

Enter the number: 1234

Difference = 1233333

Relational operators
A relational operator, also known as a comparison operator, is an operator that
compares two values. Expressions that contain relational operators are
called relational expressions. Relational operators return true or false value,
depending on whether the conditional relationship between the two operands
holds or not.

For example, to test if x is less than y, relational operator < is used as x < y.
This expression will return TRUE if x is less than y; otherwise the value of the
expression will be FALSE.

Relational operators can be used to determine the relationships between the


operands. These relationships are illustrated in Table 2.9.

The relational operators are evaluated from left to right. The operands of a
relational operator must evaluate to a number. Characters are considered valid
operands since they are represented by numeric values in the computer system.
So, if we say, 'A' < 'B', where A is 65 and B is 66 then the result would be 1
as 65 < 66.

When arithmetic expressions are used on either side of a relational operator,


then first the arithmetic expression will be evaluated and then the result will be
compared. This is because arithmetic operators have a higher priority over
relational operators.

However, relational operators should not be used for comparing strings as this
will result in comparing the address of the string and not their contents. You
must be wondering why so? The answer to this question will be clear to you in
the later chapters. A few examples of relational operators are given below.

Note

Although blank spaces are allowed between an operand and an operator, no


space is permitted between the components of an operator (like > = is not
allowed, it should be >=). Therefore, writing x==y is correct but writing x = =
y is not acceptable in C language.

8. Write a program to show the use of relational operators.


#include <stdio.h>

main ()

int x=10, y=20;


printf("\n %d < %d = %d", x, y, x < y);

printf("\n %d = = %d = %d", x, y, x = = y);

printf("\n %d ! = %d = %d", x, y, x ! = y);

printf("\n %d > %d = %d", x, y, x > y);

printf("\n %d > = %d = %d", x, y, x > = y):

printf("\n %d < = %d = %d", x, y, x<=y);

return 0;

Output

10 < 20 = 1

10 = = 20 = 0

10 ! = 20= 1

10 > 20 =0

10 > = 20 = 0

10 < = 20 = 1

Equality Operators
C language supports two kinds of equality operators to compare their operands
for strict equality or inequality. They are equal to (= =) and not equal to (!=)
operators. The equality operators have lower precedence than the relational
operators.

The equal-to operator (= =) returns true (1) if operands on both the sides of the
operator have the same value; otherwise, it returns false (0). On the contrary,
the not- equal-to operator (!=) returns true (1) if the operands do not have the
same value; else it returns false (0).
Logical Operators
C language supports three logical operators--logical AND (&&), logical OR (||),
and logical NOT (!). As in case of arithmetic expressions, the logical
expressions are evaluated from left to right.

Logical AND
Logical AND operator is a binary operator, which simultaneously evaluates two
values or relational expressions. If both the operands are true, then the whole
expression evaluates to true. If both or one of the operands is false, then the
whole expression evaluates to false. The truth table of logical AND operator is
given in Table 2.11.

For example,

(a < b) && (b > c)

The expression to the left is (a < b) and that on the right is (b> c). The whole
expression is true only if both expressions are true, i.e., if b is greater than
both a and c.

Logical OR
Logical OR returns a false value if both the operands are false. Otherwise it
returns a true value. The truth table of logical OR operator is given in Table
2.12.

For example,

(a < b) || (b> c)

The expression to the left is (a < b) and that on the right is (b> c). The whole
expression is true if either b is greater than a or b is greater than c or b is greater
than both a and c.

Logical NOT
The logical NOT operator takes a single expression and negates the value of the
expression. That is, logical NOT produces a zero if the expression evaluates to
a non-zero value and produces a 1 if the expression produces a zero. In other
words, it just reverses the value of the expression. The truth table of logical
NOT operator is given in Table 2.13.

For example,

int a = 10, b;

b = !a;

Now the value of b = 0. This is because value of a = 10. !a = 0. The value of !


a is assigned to b, hence, the result.
Logical expressions operate in a short cut fashion and stop the evaluation when
it knows for sure what the final outcome would be. For example, in a logical
expression involving logical AND, if the first operand is false, then the second
operand is not evaluated as it is for sure that the result will be false. Similarly,
for a logical expression involving logical OR, if the first operand is true, then
the second operand is not evaluated as it is for sure that the result will be true.

But this approach has a side effect. For example, consider the following
expression:

(x > 9) && (y > 0)

OR

(x > 9) || (y > 0)

In the above logical AND expression if the first operand is false then the entire
expression will not be evaluated and thus the value of y will never be
incremented. Same is the case with the logical OR expression. If the first
expression is true then the second will never be evaluated and value of y will
never be incremented.

Unary Operators
Unary operators act on single operands. C language supports three unary
operators: unary minus, increment, and decrement operators.

Unary Minus
Unary minus (-) operator is strikingly different from the binary arithmetic
operator that operates on two operands and subtracts the second operand from
the first operand. When an operand is preceded by a minus sign, the unary
operator negates its value. For example, if a number is positive then it becomes
negative when preceded with a unary minus operator. Similarly, if the number is
negative, it becomes positive after applying the unary minus operator. For
example,

int a, b = 10;

a = - (b);
The result of this expression is a = -10, because variable b has a positive value.
After applying unary minus operator (-) on the operand b, the value becomes -
10, which indicates it as a negative value.

Increment Operator (++) and Decrement Operator (--)


The increment operator is a unary operator that increases the value of its
operand by 1. Similarly, the decrement operator decreases the value of its
operand by 1. For example, --x is equivalent to writing x = x - 1.

The increment/decrement operators have two variants— prefix and postfix. In a


prefix expression (++x or --x), the operator is applied before an operand is
fetched for computation and, thus, the altered value is used for the computation
of the expression in which it occurs. On the contrary, in a postfix
expression (x++ or x--) an operator is applied after an operand is fetched for
computation. Therefore, the unaltered value is used for the computation of the
expression in which it occurs.

Therefore, an important point to note about unary increment and decrement


operators is that x++ is not same as ++x. Similarly, x-- is not same as --x.
Both x++ and ++x increment the value of x by 1. In the former case, the value
of x is returned before it is incremented, whereas, in the latter case, the value
of x is returned after it is incremented. For example,

int x = 10, y;

y = x++;

is equivalent to writing

y = x;

x= x + 1;

whereas,

y = ++x;

is equivalent to writing

x = x+ 1;

y = x;
The same principle applies to unary decrement operators. The unary operators
have a higher precedence than the binary operators. If in an expression we have
more than one unary operator then unlike arithmetic operators, they are
evaluated from right to left.

When applying the increment or decrement operator, the operand must be a


variable. This operator can never be applied to a constant or an expression.

Note

When postfix ++ or − − is used with a variable in an expression, then the


expression is evaluated first using the original value of the variable and then
the variable is incremented or decremented by one.

Similarly, when prefix ++ or − — is used with a variable in an expression,


then the variable is first incremented or decremented and then the expression
is evaluated using the new value of the variable.

9. Write a program to illustrate the use of unary prefix increment


and decrement operators.
#include <stdio.h>

int main()

int num = 3;

// Using unary prefix increment operator

printf("\n The value of num = %d", num);

printf("\n The value of ++num = %d", ++num);

printf("\n The new value of num = %d", num);

// Using unary prefix decrement operator operator

printf("\n\n The value of num = %d", num);

printf("\n The value of --num %d", --num);

printf("\n The new value of num = %d", num);


return 0;

Output

The value of num = 3

The value of ++num = 4

The new value of num = 4

The value of num = 4

The value of –num = 3

The new value of num = 3

10. Write a program to illustrate the use of unary postfix


increment and decrement operators.
#include <stdio.h>

int main()

int num = 3;

// Using unary postfix increment operator

printf("\n The value of num = %d", num);

printf("\n The value of num++ = %d", = num++);

printf("\n The new value of num = %d", num);

// Using unary postfix decrement operator

printf("\n\n The value of num = %d", num);

printf("\n The value of num-- = %d", num--);

printf("\n The new value of num = %d", num);


return 0;

Output

The value of num = 3

The value of num++ = 3

The new value of num = 4

The value of num = 4

The value of num-- = 4

The new value of num = 3

Conditional Operator
The conditional operator or the ternary (?:) is just like an if-else statement that
can be used within expressions. Such an operator is useful in situations in which
there are two or more alternatives for an expression. The syntax of the
conditional operator is

expl ? exp2 : exp3

exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the result
of the expression, otherwise exp3 is evaluated and becomes the result of the
expression. For example,

large = (a > b) ? a : b

The conditional operator is used to find the larger of two given numbers.
First exp1, that is (a> b) is evaluated. If a is greater than b, then large = a, else
large = b. Hence, large is equal to either a or b but not both.

Hence, conditional operator is used in certain situations, replacing if-


else condition phrases. Conditional operator makes the program code more
compact, more readable, and safer to use, as it is easier to check any error (if
present) in one single line itself. Conditional operator is also known as ternary
operator as it is neither a unary nor a binary operator; it takes three operands.
An expression using conditional operator can be used as an operand of another
conditional operation. That means C allows you to have nested conditional
expressions. Consider the expression given below which illustrates this concept.

int a = 5, b = 3, c = 7, small;

small = (a < b ? (a < c ? a : c) : ( b < c ? b : c));

11. Write a program to find the largest of three numbers using


ternary operator.
#include <stdio.h>

#include <conio.h>

int main()

int numl, num2, num3, large;

clrscr();

printf("\n Enter the first number: ");

scanf("%d", &num1);

printf("\n Enter the second number: ");

scanf("%d", &num2);

printf("\n Enter the third number: ");

scanf("%d", &num3);

large = num1 > num2? (num1 > num3 ? num1 : num3) : (num2 > num3 ?
num2: num3);

printf("\n The largest number is: %d", large);

return 0;

Output
Enter the first number: 12

Enter the second number: 34

Enter the third number: 23

The largest number is: 34

Bitwise Operators
As the name suggests, bitwise operators are those operators that perform
operations at bit level. These operators include: bitwise AND, bitwise OR,
bitwise XOR, and shift operators. The bitwise operators expect their operands to
be integers and treat them as a sequence of bits.

Bitwise AND
Like boolean AND (&&) bitwise AND operator (&) per- forms operation on
bits instead of bytes, chars, integers, etc. When we use the bitwise AND
operator, the bit in the first operand is ANDed with the corresponding bit in the
second operand. The truth table is same as we had seen in logical AND
operation, i.e., the bitwise AND operator com- pares each bit of its first operand
with the corresponding bit of its second operand. If both bits are 1, the
corresponding bit in the result is 1 and 0 otherwise. For example,

10101010 & 01010101 = 00000000

In a C program, the & operator is used as follows.

int a = 10, b = 20, c= 0;

c = a&b;

Bitwise OR
When we use the bitwise OR operator (|), the bit in the first operand is ORed
with the corresponding bit in the second operand. The truth table is same as we
had seen in logical OR operation, i.e., the bitwise-OR operator compares each
bit of its first operand with the corresponding bit of its second operand. If one or
both bits are 1, the corresponding bit in the result is 1 and 0 otherwise. For
example,

10101010 & 01010101 = 11111111


In a C program, the | operator is used as follows.

int a = 10, b =20, c = 0;

c = a|b

Bitwise XOR
The bitwise XOR operator (^) performs operation on individual bits of the
operands. When we use the bitwise XOR operator, the bit in the first operand is
XORed with the corresponding bit in the second operand. The truth table of
bitwise XOR operator is shown in Table 2.14.

The bitwise XOR operator compares each bit of its first operand with the
corresponding bit of its second operand. If one of the bits is 1, the
corresponding bit in the result is 1 and 0 otherwise. For example,

10101010 ^ 01010101 = 11111111

In a C program, the operator is used as follows:

int a =10, b = 20, c = 0;

c = a^b

Bitwise NOT
The bitwise NOT, or complement, is a unary operator that performs logical
negation on each bit of the operand. By performing negation of each bit, it
actually produces the 1s complement of the given binary value. Bitwise NOT
operator sets the bit to 1 if it was initially 0 and sets it to 0 if it was initially 1.
For example,

~10101011 = 01010100

Note
Bitwise operators are used for testing the bits or shifting them left or right.
Always remember that bitwise operators cannot be applied to float or double
variables.

Shift Operator
C supports two bitwise shift operators. They are shift-left (<<) and shift-right
(>>). These operations are simple and are responsible for shifting bits either to
the left or to the right. The syntax for a shift operation can be given as

operand op num

where the bits in operand are shifted left or right depending on the operator (left
if the operator is << and right if the operator is >>) by the number of places
denoted by num. For example, if we have x = 0001 1101, then

x << 1 produces 0011 1010

When we apply a left-shift, every bit in x is shifted to the left by one place. So,
the MSB (most significant bit) of x is lost, and the LSB of x is set to 0.

Therefore, if we have x = 0001 1101, then

x << 4 produces 1101 0000.

If you observe carefully, you will notice that shifting once to the left multiplies
the number by 2. Hence, multiple shifts of 1 to the left, results in multiplying
the number by 2 over and over again.

On the contrary, when we apply a shift-right operator, every bit in x is shifted to


the right by one place. So, the LSB (least significant bit) of x is lost, the MSB of
x is set to 0. For example, if we have x = 0001 1101, then

x >> 1 produces = 0000 1110

Similarly, if we have x = 0001 1101, then

x >> 4 produces 0000 0001.

If you observe carefully, you will notice that shifting once to the right divides
the number by 2. Hence, multiple shifts of 1 to the right, results in dividing the
number by 2 over and over again.

12. Write a program to show use of bitwise operators.


#include <stdio.h>

#include <conio.h>

void main()

int a=27, b= 39;

clrscr();

printf("\n a & b = %d", a&b);

printf("\n a | b = %d", alb);

printf("\n ~a = %d", ~a);

printf("\n ~b = %d", ~b);

printf("\n a ^ b = %d", a^b);

printf("\n a << 1 = %d", a<<1);

printf("\n b >> 1 = %d", b>>1);

Output

a&b=3

a | b =6

~a =-28

~b = -40

a ^ b = 60

a << 1 = 54

b >> 1 = 19

Assignment Operators
In C, the assignment operator is responsible for assigning values to the
variables. While the equal sign (=) is the fundamental assignment operator,
Clanguage also supports other assignment operators that provide shorthand
ways to represent common variable assignments.

When an equal sign is encountered in an expression, the compiler processes the


statement on the right side of the sign and assigns the result to the variable on
the left side. For example,

int x;

x = 10;

assigns the value 10 to variable x. If we have,

int x = 2, y = 3, sum = 0;

sum = x + y;

then sum = 5.

The assignment operator has right-to-left associativity, so the expression be

a = b = с= 10;

is evaluated as

(a = (b = (c = 10)));

First 10 is assigned to c, then the value of c is assigned to b. Finally, the value


of b is assigned to a.

The operand to the left of the assignment operator must always be a variable
name. C does not allow any expression, constant, or function to be placed to the
left of the assignment operator. Therefore, the statement a + b = 0, is invalid in
C language.

To the right of the assignment operator you may have an arbitrary expression. In
that case, the expression would be evaluated and the result would be stored in
the location denoted by the variable name.

Other Assignment Operators


C language supports a set of shorthand assignment operators of the form
variable op = expression

where op is a binary arithmetic operator. Table 2.15 shows the list of other
assignment operators that are supported by C.

The advantage of using shorthand assignment operators are as follows:

• Shorthand expressions are easier to write as the expression on the left side
need not be repeated.

• The statements involving shorthand operators are easier to read as they are
more concise.

• The statements involving shorthand operators are going more efficient and
easy to understand.

13. Write a program to demonstrate the use of assignment


operators.
#include <stdio.h>

int main()

int num1 = 3, num2 = 5;

printf("\n Initial value of num1 = %d and num2 %d", num1, num2);

num1 + = num2 * 4 - 7;

printf("\n After the evaluation of the expression num1 = %d and num2 = %d",
num1, num2);

return 0;

Output

Initial value of num1 = 3 and num2 = 5

After the evaluation of the expression num1 = 16 and num2 = 5


Comma Operator
The comma operator in C takes two operands. It works by evaluating the first
and discarding its value, and then evaluates the second and returns the value as
the result of the expression. Comma separated operands when chained together
are evaluated in left-to-right sequence with the right most value yielding the
result of the expression. Among all the operators, the comma operator has the
lowest precedence.

Therefore, when a comma operator is used, the entire expression evaluates to


the value of the right expression. For example, the following statement first
increments a, then increments b and then assigns the value of b to x.

int a=2, b=3, x=0;

x = (++a, b+=a);

Now, the value of x = 6.

Sizeof Operator
The sizeof operator is a unary operator used to calculate the size of data types.
This operator can be applied to all data types. When using this operator, the
keyword sizeof is followed by a type name, variable, or expression. The
operator returns the size of the variable, data type, or expression in bytes, i.e.,
the sizeof operator is used to determine the amount of memory space that the
variable/ expression/data type will take.

When a type name is used, it is enclosed in parentheses, but in case of variable


names and expressions they can be specified with or without parentheses.
A sizeof expression returns an unsigned value that specifies the space in bytes
required by the data type, variable, or expression. For example, sizeof
(char) returns 1, i.e., the size of a character data type. If we have,

int a = 10;

unsigned int result;

result = sizeof (a);

Then result = 2, which is the space required to store the variable a in memory.
Since a is an integer, it requires 2 bytes of storage space.
Operator Precedence Chart
C operators have two properties: priority and associativity. When an expression
has more than one operator then it is the relative priorities of the operators with
respect to each other that determine the order in which the expression will be
evaluated. Associativity defines the direction in which the operator having the
same precedence acts on the operands. It can be either left-to-right or right-to-
left. Priority is given precedence over associativity to determine the order in
which the expressions are evaluated. Associativity is then applied, if the need
arises.
Table 2.16 lists the operators that C language supports in the order of
their precedence (highest to lowest). The associativity indicates the order in
which the operators of equal precedence in an expression are evaluated.
You must be wondering why the priority of the assignment operator is so low.
This is because the action of assignment is performed only when the entire
computation is done. It is not uncommon for a programmer to forget the priority
of the operators while writing any program. So it is recommended that you use
the parentheses operator to override default priorities. From Table 2.16 you can
see that the parenthesis operator has the highest priority. So any operator placed
within the parenthesis will be evaluated before any other operator.

Example 2.2

Evaluating expressions using the precedence chart

1. x = 3 * 4 5 *6

= 12 + 5 * 6

= 12 + 30
= 42

2. x = 3 * (4 + 5) * 6

=3*9*6

= 27 * 6

= 162

3. x = 3 * 4 % 5 / 2

= 12 % 5 / 2

=2/2

=1

4. x = 3 * (4 % 5) / 2

=3*4/2

= 12 / 2

=6

5. x = 3 * 4 % (5/2)

=3*4%2

= 12 % 2

=0

6. x = 3 *((4 % 5) / 2)

= 3 *(4 / 2)

=3*2

=6

Take the following variable declarations,

int a = 0, b = 1, c = -1;
float x = 2.5, y = 0.0;

If we write,

a = b = c = 7;

Since the assignment operator works from right-to-left, therefore

c = 7. Then since b = c, therefore b = 7. Now a = b, so a = 7.

7. a + = b - = c * = 10

This is expanded as

a = a + (b = b – (c = c * 10))

= a + (b = 1 – (-10)

= a + (b = 11)

= 0 + 11

= 11

8. - - a * (5 + b) / 2 - C++ * b

= - - a * 6 / 2 – c++ * b

=--a*6/2--1*b

(Value of c has been incremented but its altered value will not be visible for the
evaluation of this expression)

= -1 * 6 / 2 - - 1 * 1

(Value of a has been incremented and its altered value will be used for the
evaluation of this expression)

= -1 * 3 - -1 1 * 1

= -3 - -1 * 1

=-3--1

= -2
9. a * b * c

= (a* b) * C (because associativity of * is from left-to-right)

=0

10. a && b

=0

11. a < b && c < b

=1

12. b + c || ! a

= ( b + c) || (!a)

= 0 || 1

=1

13. x * 5 && 5 || (b / c)

= ((x * 5) && 5) || (b / c)

= (12.5 && 5) || (1/-1)

=1

14. a < = 10 && x > = 1 && b

= ((a < = 10) && (x > = 1)) && b

=1

15. !x || !c || b + c

= ((!x) || (!c)) || (b + c)

= (0 || 0) || 0

=0

16. x * y < a + b || c
= ( (x * y) < (a + b)) || c

= (0 < 1) | | -1

=1

17. (x > y) + !a || c++

= ( (x > y) + (!a)) || (c++)

= (1 + 1) || 0

=1

14. Write a program to calculate the area of a circle.


#include <stdio.h>

#include <conio.h>

int main()

float radius;

double area, circumference;

clrscr();

printf("\n Enter the radius of the circle: ");

scanf("%f", &radius);

area = 3.14 radius * radius;

circumference 2 * 3.14 * radius;

printf(" Area = %.21e", area);

printf("\n CIRCUMFERENCE = %.2e", circumference);

return 0;

}
Output

Enter the radius of the circle: 7

Area = 153.86

CIRCUMFERENCE = 4.40e+01

15. Write a program to print the ASCII value of a character.


#include <stdio.h>

#include <conio.h>

int main()

char ch;

clrscr() ;

printf("\n Enter any character: ");

scanf("%c", &ch);

printf("\n The ASCII value of %c is: %d", ch, ch);

return 0;

Output

Enter any character: A

The ASCII value of A is: 65

16. Write a program to read a character in upper case and then


print it in lower case.
#include <stdio.h>

#include <conio.h>
int main()

char ch;

clrscr();

printf("\n Enter any character in upper case: ");

scanf("%c", &ch);

printf("\n The character in lower case is: %c", ch+32);

return 0;

Output

Enter any character: A

The character in lower case is: a

17. Write a program to print the digit at ones place of a number.


#include <stdio.h>

#include <conio.h>

int main()

int num, digit_at_ones_place;

clrscr()

printf("\n Enter any number: ");

scanf("%d", &num);

digit_at_ones_place = num% 10;

printf("\n The digit at ones place of %d is %d", num, digit_at_ones_place);


return 0;

Output

Enter any number: 123

The digit at ones place of 123 is 3

18. Write a program to swap two numbers using a temporary


variable.
#include <stdio.h>

#include <conio.h>

int main()

int num1, num2, temp;

clrscr();

printf("\n Enter the first number: ");

scanf("%d", &num1);

printf("\n Enter the second number: ");

scanf("%d", &num2);

temp = num1;

num1 = num2;

num2=temp;

printf("\n The first number is %d", num1);

printf("\n The second number is %d", num2);

return 0;
}

Output

Enter the first number: 3

Enter the second number: 5

The first number is 5

The second number is 3

19. Write a program to swap two numbers without using a


temporary variable.
#include <stdio.h>

#include <conio.h>

int main()

int numl, num2;

clrscr();

printf("\n Enter the first number: ");

scanf("%d", &num1);

printf("\n Enter the second number: ");

scanf("%d", &num2);

num1 = num1 + num2;

num2 = num1 - num2;

num1 = num1 - num2;

printf("\n The first number is %d", num1);

printf("\n The second number is %d", num2);


}

return 0;

Output

Enter the first number : 3

Enter the second number: 5

The first number is 5

The second number is 3

20. Write a program to convert degrees Fahrenheit into degrees


celsius.
#include <stdio.h>

#include <conio.h>

int main()

float fahrenheit, celsius;

printf("\n Enter the temperature in fahrenheit: ");

scanf("%f", &fahrenheit);

celsius = (0.56) * (fahrenheit - 32);

printf("\n Temperature in degrees celsius = %f", celsius);

return 0;

Output

Enter the temperature in fahrenheit: 32

Temperature in degree celsius 0


21. Write a program that displays the size of every data type.
#include <stdio.h>

#include <conio.h>

int main()

clrscr();

printf("\n The size of short integer is: %d", sizeof (short int));

printf("\n The size of unsigned integer is: %d", sizeof (unsigned int));

printf("\n The size of signed integer is: %d", sizeof (signed int));

printf("\n The size of integer is: %d", sizeof (int));

printf("\n The size of long integer is: %d", sizeof (long int));

printf("\n The size of character is: %d", sizeof (char));

printf("\n The size of unsigned character is: %d", sizeof (unsigned char));

printf("\n The size of signed character is: %d", sizeof (signed char));

printf("\n The size of floating point number is: %d", sizeof (float));

printf("\n The size of double number is: %d", sizeof (double));

return 0;

Output

The size of short integer is: 2

The size of unsigned integer is: 2

The size of signed integer is: 2

The size of integer is: 2


The size of long integer is: 2

The size of character is: 1

The size of unsigned character is: 1

The size of signed character is: 1

The size of floating point number is: 4

The size of double number is: 8

22. Write a program to calculate the total amount of money in the


piggybank, given the coins of Rs 10, Rs 5, Rs 2, and Re 1.
#include <stdio.h>

#include <conio.h>

int main()

int num_of_10_coins, num_of_5_coins, num_of_2_coins, num_of_1_coins;

float total amt = 0.0;

clrscr();

printf("\n Enter the number of Rs10 coins in the piggybank: ");

scanf("%d", &num_of_10_coins);

printf("\n Enter the number of Rs5 coins in the piggybank: ");

scanf("%d", &num_of_5_coins);

printf("\n Enter the number of Rs2 coins in the piggybank: ");

scanf("%d", &num_of_2_coins);

printf("\n Enter the number of Re1 coins in the piggybank: ");

scanf("%d", &num_of_1_coins);
total_amt = num_of_10_coins * 10 + num_of_5_coins * 5 + num_of_2_coins
* 2 + num_of_1_coins;

printf("\n Total amount in the piggybank = %f", total_amt);

getch();

return 0;

Output

Enter the number of Rs10 coins in the piggybank: 10

Enter the number of Rs5 coins in the piggybank: 23

Enter the number of Rs2 coins in the piggybank: 43

Enter the number of Re1 coins in the piggybank: 6

Total amount in the piggybank = 307

23. Write a program to calculate the bill amount for an item given
its quantity sold, value, discount, and tax.
#include <stdio.h>

#include <conio.h>

int main()

float total_amt, amt, sub_total,

discount_amt, tax_amt, qty, val,

discount, tax;

printf("\n Enter the quantity of item sold: ");

scanf("%f", &qty);

printf("\n Enter the value of item: ");


scanf("%f", &val);

printf("\n Enter the discount percentage: ");

scanf("%f", &discount);

printf("\n Enter the tax: ");

scanf("%f", &tax);

amt = qty * val;

discount_amt = (amt * discount)/100.0;

sub_total = amt_discount_amt;

tax_amt = (sub_total*tax) /100.0;

total_amt = sub_total + tax_amt;

printf("\n\n\n ****** BILL******");

noiz printf("\n Quantity Sold: %f", qty);

printf("\n Price per item: %f", val);

printf("\n--------------------");

printf("\n Amount: %f", amt);

printf("\n Discount: - %f", discount_amt);

printf("\n Discounted Total: %f", sub_total);

printf("\n Tax: + %f", tax_amt);

printf("\n---------------------");

printf("\n Total Amount %f", total_amt);

return 0;

Output
Enter the quantity of item sold: 20

Enter the value of item: 300

Enter the discount percentage: 10

Enter the tax: 12

************ BILL *************

Quantity Sold : 20

Price per item :300

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

Amount : 6000

Discount : - 600

Discounted Total : 5400

Tax : + 648

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

Total Amount 6048

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy