Unit 1
Unit 1
INTRODUCTION TO PROGRAMMING
• Hardware wine
• Application software
• Assembly language
• System software
•Machinelanguage
• 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.
• 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.
Computer software can be broadly classified into two groups: system software
and application software.
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.
The most widely used system software are discussed in the following sections:
The computer BIOS and device drivers provide basic functionality to operate
and control the hardware connected to or built into the computer.
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.
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
• 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.
• Disk compression utilities can be used to enhance the capacity of the disk by
compressing/decompressing the contents of a disk.
• 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.
• Command line interface (CLI) and Graphical user interface (GUI) can be used
to make changes to the operating system.
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.
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.
All in all, compilers and interpreters both achieve similar purposes, but
inherently different as to how they achieve that purpose.
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
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.
PROGRAMMING LANGUAGES
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.
The question of which language is the best depends on the following factors:
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.
• Machine language
• Assembly language
• High-level language (also known as third generation language or 3GL)
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.
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
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.
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.
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.
There is no standard rule that defines what a 4GL is but certain characteristics
of such languages include:
• 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:
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.
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.
CHAPTER 2 : INTRODUCTION TO C
Takeaways
• Writing a C program.
• Keywords
• C Tokens
• Identifiers
• I/O statements
• 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.
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.
• Extension to the character types, so that they can support even non-English
characters
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.
• 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.
• Stable language. ANSI C was created in 1983 and since then it has not been
revised.
• 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 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 has been so widely accepted by professionals that com- pilers, libraries, and
interpreters of other programming languages are often implemented in C.
STRUCTURE OF A C PROGRAM
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().
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()
return 0;
Output
#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.
{} 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.
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.
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
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
When you run the .exe file, the output of the program will be displayed on
screen. That is,
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.
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.
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:
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.
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
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.
Programming Tip: Not putting the */ after the termination of the block
comment is a compiler error.
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.
#include <stdio.h>
int main()
// prints message
Output
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:
d. White space characters: These characters are used to print a blank space on
the screen. They are shown in Figure 2.8.
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.
• The case of alphabetic characters that form the identifier name is significant.
For example, 'FIRST' is different from 'first' and 'First'.
• 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.
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
Note
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 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.
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.
VARIABLES
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
int emp_num;
float salary;
char grade;
double balance_amount;
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.
Note
Initializing Variables
While declaring the variables, we can also initialize them with some value. For
example,
int emp_num = ?;
initializes the variable flag and not count. If you want both the variables to be
declared in a single statement then write,
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.
Integer Constants
123 456
12,34,567
$123
012 0 01234
Note
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.)
Thus, we see that scientific notation is used to express numbers that are either
very small or very large. For example,
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
#define pi 3.14159
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.
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 3: Blank space must be used between #define and constant name and
between-0 constant name and constant value.
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
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>
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 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.
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:
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.
• 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 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.
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
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.
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.
Result: 12a2.3
Result: 12 a 2.3
Result:12 a 2.3
Result: 12 a 245.37
The number is 12
98.7654
98.77
98.77
98.7654
9.88e+01
9.8765e+01
9.88e+01
9.876540e+01
char ch = 'A';
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:
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.
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.
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.
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.
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 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;
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.
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];
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 *).
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.
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.
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;
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.
num = 2
fnum = 3456.44
ch = a
str = abcde
dnum = 0.24321
snum = 1
lnum = 12345678
#include <stdio.h>
int main()
int a, b;
return 0;
Output
Programming Tip: Using an incorrect specifier for the data type being read
or written will generate a run-time error.
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("%d", count);
The output would be-Hello World! 6 because 6 is the number of characters
read before the %n modifier.
#include <stdio.h>
int main()
int num = 7;
double pi = 3.1415926536;
return 0;
Output
NUM = 7
AMT = 123.450000
CODE = A
PI = 3.141590e+00
MESSAGE = Hi
#include <stdio.h>
int main()
int num;
float amt;
char code;
double pi;
scanf("%d", &num);
scanf("%f", &amt);
scanf("%e", &pi);
scanf("%c", &code);
scanf("%s", msg);
return 0;
Output
NUM = 5
AMT = 123.450000
PI = 3.141590e+00
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: ");
S = (a + b + c)/2;
area = sqrt (S* (S-a) * (S-b) * (S-c)); printf("\n Area %f", area);
return 0;
Output
Area = 96
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
float distance;
// sqrt and pow are mathematical functions defined in math.h header file
return 0;
Output
Distance = 2.236068
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,
12 12.34 A
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
Arithmetic Operators
Consider three variables declared as,
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;
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,
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
#include <conio.h>
int main()
clrscr();
scanf("%d", &num1);
scanf("%d", &num2);
idiv_res = num1/num2;
modiv_res = num1%num2;
return 0;
Output
9 + 7 = 16
9-7=2
9 * 7 = 63
9 / 7 = 1 (Integer Division)
9 % 7 = 2 (Moduluo Division)
#include <conio.h>
int main()
clrscr();
printf("\n Enter the number: ");
scanf("%ld", &num2);
return 0;
Output
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.
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.
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
main ()
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,
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;
But this approach has a side effect. For example, consider the following
expression:
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.
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.
Note
int main()
int num = 3;
Output
int main()
int num = 3;
Output
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
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.
int a = 5, b = 3, c = 7, small;
#include <conio.h>
int main()
clrscr();
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);
large = num1 > num2? (num1 > num3 ? num1 : num3) : (num2 > num3 ?
num2: num3);
return 0;
Output
Enter the first number: 12
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,
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,
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,
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
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.
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.
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.
#include <conio.h>
void main()
clrscr();
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.
int x;
x = 10;
int x = 2, y = 3, sum = 0;
sum = x + y;
then sum = 5.
a = b = с= 10;
is evaluated as
(a = (b = (c = 10)));
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.
where op is a binary arithmetic operator. Table 2.15 shows the list of other
assignment operators that are supported by C.
• 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.
int main()
num1 + = num2 * 4 - 7;
printf("\n After the evaluation of the expression num1 = %d and num2 = %d",
num1, num2);
return 0;
Output
x = (++a, b+=a);
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.
int a = 10;
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
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
int a = 0, b = 1, c = -1;
float x = 2.5, y = 0.0;
If we write,
a = b = c = 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
=0
10. a && b
=0
=1
12. b + c || ! a
= ( b + c) || (!a)
= 0 || 1
=1
13. x * 5 && 5 || (b / c)
= ((x * 5) && 5) || (b / c)
=1
=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
= (1 + 1) || 0
=1
#include <conio.h>
int main()
float radius;
clrscr();
scanf("%f", &radius);
return 0;
}
Output
Area = 153.86
CIRCUMFERENCE = 4.40e+01
#include <conio.h>
int main()
char ch;
clrscr() ;
scanf("%c", &ch);
return 0;
Output
#include <conio.h>
int main()
char ch;
clrscr();
scanf("%c", &ch);
return 0;
Output
#include <conio.h>
int main()
clrscr()
scanf("%d", &num);
Output
#include <conio.h>
int main()
clrscr();
scanf("%d", &num1);
scanf("%d", &num2);
temp = num1;
num1 = num2;
num2=temp;
return 0;
}
Output
#include <conio.h>
int main()
clrscr();
scanf("%d", &num1);
scanf("%d", &num2);
return 0;
Output
#include <conio.h>
int main()
scanf("%f", &fahrenheit);
return 0;
Output
#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 long integer is: %d", sizeof (long int));
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));
return 0;
Output
#include <conio.h>
int main()
clrscr();
scanf("%d", &num_of_10_coins);
scanf("%d", &num_of_5_coins);
scanf("%d", &num_of_2_coins);
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;
getch();
return 0;
Output
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()
discount, tax;
scanf("%f", &qty);
scanf("%f", &discount);
scanf("%f", &tax);
sub_total = amt_discount_amt;
printf("\n--------------------");
printf("\n---------------------");
return 0;
Output
Enter the quantity of item sold: 20
Quantity Sold : 20
----------------------------------
Amount : 6000
Discount : - 600
Tax : + 648
----------------------------------