0% found this document useful (0 votes)
6 views50 pages

POP Module 2

The document provides an introduction to computing, covering the definition, characteristics, and basic structure of computers, including the CPU, input and output devices, and software types. It explains algorithms, flowcharts, and the evolution of programming languages, particularly focusing on the C programming language. Key concepts such as machine language, assembly language, and high-level languages are discussed, along with their advantages and disadvantages.

Uploaded by

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

POP Module 2

The document provides an introduction to computing, covering the definition, characteristics, and basic structure of computers, including the CPU, input and output devices, and software types. It explains algorithms, flowcharts, and the evolution of programming languages, particularly focusing on the C programming language. Key concepts such as machine language, assembly language, and high-level languages are discussed, along with their advantages and disadvantages.

Uploaded by

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

Module 1 – Introduction to Computing

CHAPTER 1: INTRODUCTION TO COMPUTING

1.1 Introduction:

Computers have become the basic necessity of any organization with serious objectives. They have
made great inroads in everyone’s everyday life and thinking. Used in Engineering simulations,
teaching, satellite control weather forecasting and what not. Literally there is no field left without the
use of computers.

1.2 Definition of a computer:

You get many definitions of computer. Different authors interpret in different way. I define it
something like this:

“It is an electronic device capable of performing complex calculations at an incomprehensive


speed.“

1.3 Characteristics of computers:

The characteristics possessed by computers can be listed as follows:

1. Speed: Computers perform various operations at a tremendous speed. The speed do varies
from few micro second (millionth of a second) to nanoseconds (billionth of a second).
2. Accuracy: Computers are very accurate. They can perform their hundreds and thousands of
operations with great accuracy as their circuits have no mechanical parts to wear and malfunction.
They can run error less for days at a time.
3. Reliablity: Computer output is generally very reliable, subject to the condition that the input
data entering the computer should be correct and the program of instructions should be reliable
and correct. Incorrect input data and unreliable programs give us computer errors and wrong
results. Hence the phrase “ GARBAGE IN – GARBAGE OUT (GIGO) “

1.4 Basic Structure of Computer

All types of computers follow a same basic logical structure and perform the following five basic
operations for converting raw input data into information useful to their users.

Following diagram shows the basic structure of Computer:

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 1


Module 1 – Introduction to Computing

1.5 CPU:

The central processing unit (CPU) is the unit which performs most of the processing inside a computer.
To control instructions and data flow to and from other parts of the computer, the CPU relies heavily
on a chipset, which is a group of microchips located on the motherboard.

The CPU has two components:


1) Control Unit: extracts instructions from memory and decodes and executes them
2) Arithmetic Logic Unit (ALU): handles arithmetic and logical operations

To function properly, the CPU relies on the system clock, memory, secondary storage, and data and
address buses. This term is also known as a central processor, microprocessor or chip.

The CPU is the heart and brain of a computer. It receives data input, executes instructions, and
processes information. It communicates with input/output (I/O) devices, which send and receive data
to and from the CPU.

1.6 Input devices:

An input device is any hardware device that sends data to a computer, allowing you to interact with
and control it. The picture shows a SAITEK keyboard, which is an example of an input device.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 2


Module 1 – Introduction to Computing

The most commonly used or primary input devices on a computer are the keyboard and the mouse.
However, there are dozens of other devices that can also be used to input data into the computer.

Some more examples of input devices are as follows:


1) Bar code reader
2) Biometrics
3) Digital camera
4) Joystick
5) Light Gun, pen
6) Magnetic Ink
7) Microphone
8) Optical Mark reader(OMR)
9) Punch card reader
10) Remote
11) Scanner

1.7 Output devices:

An output device is any device used to send data from a computer to another device or user. Most
computer data output that is meant for humans is in the form of audio or video. Thus, most output
devices used by humans are in these categories. Examples include monitors, printers etc.

Output devices allow computers to communicate with users and with other devices. This can include
peripherals, which may be used for input/output (I/O) purposes, like network interface cards (NICs),
modems, IR ports, RFID systems and wireless networking devices, as well as mechanical output
devices, like solenoids, motors and other electromechanical devices.

Some examples of input devices are as follows:


1) Projectors
2) Speakers
3) Headphones
4) Braille embosser
5) Computer Output Microfilm (COM)
6) Plotter

1.8 Software basics and types:

Software is a generic term for organized collections of computer data and instructions, often broken
into two major categories: system software that provides the basic non-task-specific functions of the
computer, and application software which is used by users to accomplish specific tasks.

Two types of Software:

1) System software.
2) Application software.

System software

Programs that is responsible to control and support operation of computer systems. System software
includes a variety of programs such as operating system, data base management systems,

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 3


Module 1 – Introduction to Computing

communications control programs, service and utility programs and programming language
translators.

Machine language:

1) This is the only language which the computer can understand.


2) It consists of 0s and 1s.
3) Machine language consists of two parts, the operation code and the operand.
4) Operand refers to memory address of data to be performed on data specified by operand.
5) So, these languages require the user to be conversant with memory addresses and op-codes, which
vary from system to system.
6) Each CPU has a different set of op-codes for various operations and hence machine level programs
are machine dependent and not portable.

Advantages:

1) Machine language can be used to manipulate individual bits in a byte of storage.


2) Execution of the program is faster.
3) Programs written in these languages make efficient use of the storage available.
4) Computers need not have any type of translators.

Disadvantages:

1) It is machine dependent and hence not portable.


2) Coding, testing and debugging are very difficult.
3) To remember all the op-codes is difficult and impossible.

Assembly language:

1) In assembly language mnemonics replace op-codes and programs are written using symbols and
mnemonics, which represent different operations to be performed.
2) But assembly language programs are not understood by computer and have to be translated to
machine code before they can execute.
3) Such a translator program is called an assembler.
4) Assembly language is machine dependant i.e symbols and mnemonics which represent operations
are different for different computers.

Advantages:

1) The programmer need not know memory locations.


2) Programs are comparatively easier to write, test and debug.
3) Assembly language program requires fewer codes to execute the same tasks.
4) Programs are easy to understand.

Disadvantages:

1) It is machine dependent and hence not portable.


2) Time required for execution is more since the code has to be translated to machine code.

High level language:

1) High level languages consist of commands, written using languages like English it-self.
2) So the programs can be written easily.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 4


Module 1 – Introduction to Computing

3) But computers do not understand programs written in high level language and so translator is
required to convert High level code to machine code.

Advantages:

1) Machine independent, therefore portable.


2) Programmer need not know the internal structure of the computer.
3) Easy to write, modify test and debug.
4) High level programs are much shorter than assembly code.
5) Automatic code generation tools are available for High level languages.

Disadvantages:

1) Lack of flexibility. Since the automatic features of HLL are not under the control of the
programmer, HLL are not as flexible as assembly languages.
2) Storage space required is more, since compiler, source and object programs have to be stored.
3) Execution is slower.
4) Sometimes correcting errors is very cumbersome.

Assemblers:

1) Assembler translates programs written in Assembly language to machine code.


2) It checks for syntax errors and lists all the errors with suitable messages.
3) Only if the source code is error free it is translated to machine code and this code is called the
object program.
4) The Assembler also allocates memory space in the main memory for the object code and makes an
executable version of it.

Compilers:

1) A compiler is a program written to translate programs written in high level language to its
equivalent machine code.
2) The process of translation is called compilation.
3) The program written is called the source program and the compiled version is called the object
program.
4) To translate a source program the compiler must analyze it thoroughly and synthesize an
equivalent object program.
5) Compilers Compile a program once for all and list out all the errors.

Interpreters:

A computer program that translates and executes each source language statement before translating
and executing the next one

Difference between compiler and interpreter is depicted below :

Sl. No Compiler Interpreter


Takes entire source code and converts into Takes one statement and converts into
1
machine language machine language
2 Displays all the errors at one stretch Displays errors one by one
3 Costlier Cheaper
4 Debugging is faster Debugging is slower
5 Requires more memory Requires less memory

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 5


Module 1 – Introduction to Computing

Operating systems:

1) Operating systems is a set of programs which control, coordinate and supervise the functioning
of the computers.
2) They help the user to use the resources offered by the computer in a n organized and efficient
manner.
3) Operating system acts as an interface between the user and the computer.

Main functions:

1) Protecting itself from the user.


2) It handles multiprogramming, multiprocessing etc.
3) It supervises the overall operations of the computer and hence minimizes the computer
operations intervention.
4) Loads and calls application programs utilities.
5) It schedules and controls I/O operations.
6) It performs functions of virtual memory, spooling, linkage, etc.
7) It communicates error messages.
8) It controls the flow of jobs by loading and unloading programs.
9) It maintains a list of file names and their memory locations.
10) It allocates peripherals to programs.
11) Managing assembly, compilation and execution of programs.
12) Allocating control of the processor to each program depending on its priority.
13) Protecting one program’s data by being overwritten by other program.

The operating system contains certain utility programs that allow you to perform activities such as:

1) Formatting a diskette for processing.


2) Copying the contents of one diskette to another diskette.
3) Renaming, copying or deleting a file.
4) Listing the files in a particular directory.

Application software:

Programs that specify the information processing activities required for the completion of specific
tasks of computer users. Examples are electronic spread sheets, word processing programs and
inventory or payroll programs.

1.9 ALGORITHMS:

The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means a
procedure or a technique. Software Engineer commonly uses an algorithm for planning and solving the
problems. An algorithm is a sequence of steps to solve a particular problem or algorithm is an ordered
set of unambiguous steps that produces a result and terminates in a finite time

Algorithm has the following characteristics:

1) Finiteness: An algorithm must always terminate after a finite number of steps. It means after every
step one reach closer to solution of the problem and after a finite number of steps algorithm reaches to
an end point.

2) Definiteness: Each step of an algorithm must be precisely defined. It is done by well thought
actions to be performed at each step of the algorithm. Also the actions are defined unambiguously for
each activity in the algorithm.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 6


Module 1 – Introduction to Computing

3) Input: Any operation you perform need some beginning value/quantities associated with different
activities in the operation. So the value/quantities are given to the algorithm before it begins.

4) Output: One always expects output/result (expected value/quantities) in terms of output from an
algorithm. The result may be obtained at different stages of the algorithm. If some result is from the
intermediate stage of the operation then it is known as intermediate result and result obtained at the
end of algorithm is known as end result. The output is expected value/quantities always have a
specified relation to the inputs.

5) Effectiveness: Algorithms to be developed/written using basic operations. Actually operations


should be basic, so that even they can in principle be done exactly and in a finite amount of time by a
person, by using paper and pencil only.

Advantages
1) Easy to write.
2) Human readable techniques to understand the logic.
3) Algorithms for big problems can be written with moderate efforts.

Disadvantages
1) Difficult to debug.
2) Difficult to show branching and looping.
3) Jumping (goto) makes it hard to trace some problems.

Algorithm 1: Add two numbers entered by the user


Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

Algorithm for swapping of two values


Step 1: Input value of first number in P
Step 2: Input value of second number in Q
Step 3: Set Temp = P
Step 4: Set P = Q
Step 5: Set Q= Temp
Step 6: Print P and Q
Step 7: End.

FLOWCHART

A flowchart is a pictorial or graphical representation of a process

Flowcharts normally use standard symbols to represent the different types of instructions. These
symbols are used to construct the flowchart and show the step-by-step solution to the problem. The
flow chart symbols are linked together with arrows showing the process flow direction. This pictorial
representation can give a step-by-step solution to the given problem.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 7


Module 1 – Introduction to Computing

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 8


Module 1 – Introduction to Computing

1. Add two numbers entered by the user.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 9


Module 1 – Introduction to Computing

Example 2: Draw a flowchart to read the two sides of a rectangle and calculate its area

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 10


Module 1 – Overview of C

Origin of C Programming

'ALGOL' was the foundation or progenitor of programming languages. It was first introduced in 1960.
'ALGOL' was widely used in European countries. The ALGOL had introduced the concept of structured
programming to the developer community. The year 1967 marked the introduction of a novel
computer programming language known as 'BCPL', an acronym for Basic Combined Programming
Language. BCPL was designed by Martin Richards in the mid-1960s.

Dennis Ritchie created C at Bell Laboratories in the early 1970s. It developed from an older language
named B that Ken Thompson created. The main purpose of C's creation was to construct the UNIX
operating system, which was crucial in the advancement of contemporary computers. BCPL, B, and C
all fit firmly in the traditional procedural family typified by FORTRAN and ALGOL 60. BCPL, B and C
differ syntactically in many details, but broadly they are similar.

Development of C Programming

In 1971, Dennis Ritchie started working on C, and he and other Bell Labs developers kept improving it.
The language is appropriate for both system programming and application development because it
was made to be straightforward, effective, and portable.

Where C stands:
As we know programming language can be divided into 2 categories:
1. Problem oriented or H.L.L: Designed to give better program efficiency. i.e faster program development
.ex: FORTRAN, PASCAL etc.
2. Machine oriented or L.L.L: designed to give better machine efficiency i.e faster program execution. Ex:
assembly language & machine language.

C stands in between these two categories. that’s why it is called Middle level Language. since it was
developed to have both :relatively good programming efficiency (compared to machine oriented
language)and relatively good machine (compared to problem oriented language)

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 1


Module 1 – Overview of C

Various stages in compilation of a C program:

Knowing how compilation works can be very helpful both when writing code and when debugging.

Compiling a C program is a multi-stage process. At an overview level, the process can be split into four
separate stages: Pre-processing, compilation, assembly, and linking.

Preprocessing

The first stage of compilation is called pre-processing. In this stage, lines starting with a # character
are interpreted by the pre-processor as pre-processor commands. These commands form a simple
macro language with its own syntax and semantics. This language is used to reduce repetition in
source code by providing functionality to inline files, define macros, and to conditionally omit code.

Compilation

The second stage of compilation is confusingly enough called compilation. In this stage, the pre-
processed code is translated to assembly instructions specific to the target processor architecture.
These form an intermediate human readable language. The existence of this step allows for C code to
contain inline assembly instructions and for different assemblers to be used. Some compilers also
support the use of an integrated assembler, in which the compilation stage generates machine code
directly, avoiding the overhead of generating the intermediate assembly instructions and invoking the
assembler.

Assembly

During this stage, an assembler is used to translate the assembly instructions to object code. The
output consists of actual instructions to be run by the target processor.

Linking

The object code generated in the assembly stage is composed of machine instructions that the
processor understands but some pieces of the program are out of order or missing. To produce an
executable program, the existing pieces have to be rearranged and the missing ones filled in. This
process is called linking.

The linker will arrange the pieces of object code so that functions in some pieces can successfully call
functions in other ones. It will also add pieces containing the instructions for library functions used by
the program. In the case of the “Hello, World!” program, the linker will add the object code for the puts
function.

The following flowchart depicts the various stages in the compilation and execution of C program.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 2


Module 1 – Overview of C

Editor

C Source Code

Preprocessor
(Expanded code)

Compiler

Assembly Language
Code

Assembler

Object Code &


Library files

Linker

Executable Code

Loader

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 3


Module 1 – Overview of C

Compiler is a program which converts the source code (human understandable) to the machine code
(computer understandable). Today’s C-language is the heart of practically every mainstream operating
system and device, from Unix to Linux, Windows NT to Windows 8, Apple OSX to IOS, even many
systems that claim to be written in C++ are often written predominantly in the C subset of C++. So C is
everywhere and its relevance cannot be overstated.

In order to execute/run any C-program, compiler is must. There are many different compilers
available. Dev C++ is a free compiler used in Windows and Linux(GCC compiler) and can compile and
execute C and C++ programs by using this compiler

Characteristics of C:
1. It has no input output operations. The compiler compiles the language of functions and all input and
output is done with functions. Due to this standard library function has evolved and this standard gives
C its most endearing quality.
2. It is a language of functions, data types, assignments and flow controls. The value returned from
functions, value of data variable or value of constant can be used in an assignment statement to change
value of another variable.
3. C is noted for its ability to perform pointer arithmetic. You can declare a pointer variable that points to
any data type. The address arithmetic of C is sensitive to properties of the pointer being adjusted.
4. C’s functions are recursive by default. you can code a function that does not work in recursive
operation, but language tends to naturally support recursion and requires little recursion programming
effort.
5. The code in C function is grouped into blocks. Each block can have its own local variables.

C allows you to develop a program in multiple source files that are independently compiled. The re-
locatable object modules of individual source files are linked into single executable program. This feature
allows the compiler to support object libraries of reusable functions as well as large programs made up of
many small source code components.

Importance of ‘C’ language

C language is a famous programming language due to its qualities. Some qualities are:

1. It is robust language whose rich setup of built in functions and operator can be used to write any
complex program.

2. Program written in C are efficient due to several variety of data types and powerful operators.

3. The C compiler combines the capabilities of an assembly language with the feature of high level language.
Therefore it is well suited for writing both system software and business package.

4. There are only 32 keywords; several standard functions are available which can be used for developing
program.

5. C is portable language; this means that C programs written for one computer system can be run on
another system, with little or no modification.

6. C language is well suited for structured programming, this requires user to think of a problems in terms
of function or modules or block. A collection of these modules make a program debugging and testing
easier.

7. C language has its ability to extend itself. A c program is basically a collection of functions that are

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 4


Module 1 – Overview of C

supported by the C library. We can continuously add our own functions to the library with the availability
of the large number of functions.

8. In India and abroad mostly people use C programming language because it is easy to learn and
understand.

Structure of a C program

Basic component of C program is depicted below:

Documentation section
Link section
Definition Section
Global declaration Section
main() Function section
{
Declaration part
Executable part
}

Subprogram Section - User defined functions

Function 1
Function 2

Documentation section is used for giving the comments regarding the title, author, more detailed
information about the program etc.

Eg: Single line comments

/my first C program */

Multi-line comments

/* my first C program
Will be interesting to code */

Link section is used to link the compiler to the library function using header files.

Eg:

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

Definition section consists of symbolic constants.

Eg: #define A 3

Global declaration: The variables used anywhere in the program are called as global variables. In this
section, global variables are declared which can be also used in user-defined functions.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 5


Module 1 – Overview of C

Eg: int a=10

Main function section is the main part of the program. It mainly consists of two parts which are
written between the braces {} and every line have to end with a semicolon(;).

Declaration Section: In declaration section, all the required variables are declared which can be used
in the executable part.

Executable Section: In executable section, statements are given which are helpful in executing the
program and giving the output

Sub-programming section consists of user-defined functions. These functions are called by the main
function section.

All the rules should be followed in every section to get a successful output from a program.

 C-Structure is built-up based on 6 sections.


 Execution starts from main section.
 Sub-programming section and definition sections are optional.

Using documentation section (comments) is the best practice because it explains the program clearly .

Executing a C program

Executing a C program involves a series of steps. They are,

1. Creating the program.


2. Compiling the program.
3. Linking the program with functions that are needed from the C library.
4. Executing the program.

Although these steps remain the same irrespective of the operating system, system command for
implementing the steps and conventions for naming files may differ on different system.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 6


Module 1 – Managing I/O Operations

Introduction:

In any programming language, an interface plays an important role. Takes data from the user and
display the output. Data is provided in two ways. One is known as non-interactive mode where we
assign values to the variables and the other one is known as interactive mode where data is supplied
by the user through standard input device.

Input / Output (I/O) functions

Reading the data from the input devices and producing the output on output devices are major tasks of
any program. Normally keyboard is used to input the data while monitor (screen) is used to get
(display) the output.

C programming language provides many built-in functions to read any given input and to display data
on screen when there is a need to output the result.

All these built-in functions are present in C header files, we will also specify the name of header files in
which a particular function is defined while discussing about it.

There are two types of I/O functions:


1) Formatted I/O functions – specifies the data type and the way in which it should be read and
written.
2) Un-formatted I/O functions – do not specify the data type and the way in which it should be
read and written.

Input and Output Functions

Formatted I/O Unformatted I/O


Functions Functions

Output Input
Input Output
printf() getch()
scanf() putch()
getche()
putchar()
getchar()
puts()
gets()

Before we dwell into the I/O functions in more depth, let us understand two points. Format
specifications and ESCAPE sequence.

FORMAT SPECIFICATIONS:

Also called as format specifiers. These actually specify the type of data that can be displayed from the
variables. They should match the variables in number, order and type. Also called as conversion
symbols

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 1


Module 1 – Managing I/O Operations

C supports following format specifications:

Format Specifier Description


%d integer
%f float
%c character
%u unsigned integer
%o octal
%x hexadecimal
%ld long decimal integer
%lu long unsigned decimal integer
%lf double
%L long double
%s string

ESCAPE SEQUENCE: Escape sequence is a pair of character. The first letter is a slash followed by a
character. Escape sequence help us to represent within the format string invisible and non-printed
character although there are physically two characters in any escape sequence. It actually represents
only one. The various escape sequences are

Escape Sequence Description


\n new line character
\t tab
\b back space
\a bell
\0 null character
\? To print question mark
\\ To print slash
\’ To print single quote
\” To print double quote

FORMATTED INPUT & OUTPUT FUNCTIONS

Formatted Input

This is achieved using library function called as scanf(). It is included in stdio.h header file.

Syntax: scanf(“<format specification>”,<list of variables>);

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


In this case num is a variable of integer data type.

Formatted Output

This is achieved using library function called as print(). It is also included in stdio.h header file.

Syntax: printf(“<format specification>”,<list of variables>);

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 2


Module 1 – Managing I/O Operations

Example: printf(“%d”, num);


In this case num is a variable of integer data type.

PROGRAM: Write a C program to enter a number and display it.

int main() {
int num;
printf(“\n Enter a number: “);
scanf(“%d”,&num);
printf(“\n You entered %d “,num);
}

OUTPUT:
Enter a number: 10
You entered 10

PROGRAM: To demonstrate floating point I/O.

int main() {
float num;
num=12.34;
printf(“\n Value of num is %f “,num);
}

OUTPUT:
Value of num is 12.34

WIDTH SPECIFICATION

We have seen that we can print an integer value by specifying the value (either by a variable or an
expression) in a printf statement. When we do so, C prints the value using as many “print columns" as
needed. For instance, if the value is 782, it is printed using 3 print columns since 782 has 3 digits. If the
value is -2345, it is printed using 5 print columns (one for the minus sign).

While this is usually sufficient for most purposes, there are times when it is useful to be able to tell C
how many print columns to use. For example, if we want to print the value of n in 5 print columns, we
can do this by specifying a field width of 5, as in: printf("%5d", n);

Instead of the specification %d, we now use %5d. The field width is placed between % and d. The
value of n is printed “in a field width of 5".

Suppose n is 279; there are 3 digits to print so 3 print columns are needed. Since the field width is 5,
the number 279 is printed with 2 spaces before it, thus: bb279 (b denotes a space). We also say
“printed with 2 leading blanks/spaces" and “printed padded on the left with 2 blanks/spaces".

A more technical way of saying this is “n is printed right-justified in a field width of 5". “Right-justify"
means that the number is placed as far right as possible in the field and spaces added in front of it to
make up the field width. If the number is placed as far left as possible and spaces are added after it to
make up the field width, the number is left-justified. For example, 279bb (b is space) is left-justified in a
field width of 5.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 3


Module 1 – Managing I/O Operations

The minus sign can be used to specify left-justification; %-wd will print a value left-justified in a field
width of w. For example, to print an integer value left-justified in field width of 5, we use %-5d.

For another example, suppose n is -7 and the field width is 5. Printing n requires two print columns
(one for - and one for 7); since the field width is 5, it is printed with 3 leading spaces, thus: bbb-7.

You may ask, what will happen if the field width is too small? Suppose the value to be printed is 23456
and the field width is 3. Printing this value requires 5 columns which is greater than the field width 3.
In this case, C ignores the field width and simply prints the value using as many columns as needed (5,
in this example).

In general, suppose the integer value v is printed with the format specification %wd where w is an
integer, and suppose n columns are needed to print v. There are 2 cases to consider:

1) If n is less than w (the field width is bigger), the value is padded on the left with (w - n) spaces.
For example, if w is 7 and v is -345 so that n is 4, the number is padded on the left with (7-4) =
3 spaces and printed as bbb-345.
2) If n is greater than or equal to w (field width is the same or smaller), the value is printed using
n print columns. In this case, the field width is ignored.

Field Width Example


A field width is useful when we want to line up numbers one below the other. Suppose we have three
int variables a, b and c with values 9876, -3 and 501, respectively. The statements

printf("%d\n", a);
printf("%d\n", b);
printf("%d\n", c);
will print

9876
-3
501

Each number is printed using just the number of columns required. Since this varies from one number
to the next, they do not line up. If we want to, we could get the numbers lined up using a field width of
5, say. The statements
printf("%5d\n", a);
printf("%5d\n", b);
printf("%5d\n", c);

will print (b denotes a space)


b9876
bbb-3
bb501
all nicely lined up.

As a matter of interest, we don’t really need 3 printf statements. We can replace the last 3 printf
statements with printf("%5d\n%5d\n%5d\n", a, b, c);

Each \n forces the following output onto a new line.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 4


Module 1 – Managing I/O Operations

Field width for integer:


You can optionally specify a field-width before the type conversion code, e.g., %3d, %6f, %20s. If the
value to be formatted is shorter than the field width, it will be padded with spaces (by default).
Otherwise, the field-width will be ignored. For example,

int number = 123456;


printf("number=%d.\n", number);
// number=123456.
printf("number=%8d.\n", number);
// number= 123456.
printf("number=%3d.\n", number); // Field-width too short. Ignored.
// number=123456.

Field width for float:


For floating-point numbers, you can optionally specify the number of decimal places to be printed, e.g.,
%6.2f, %8.3f. For example,

double value = 123.14159265;


printf("value=%lf;\n", value);
//value=123.141593;
printf("value=%6.2lf;\n", value);
//value=123.14;
printf("value=%9.4lf;\n", value);
//value= 123.1416;
printf("value=%3.2lf;\n", value); // Field-width too short. Ignored.
//value=123.14;

Alignment

The output are right-aligned by default. You could include a "-" flag (before the field width) to ask for
left-aligned. For example,

int i1 = 12345, i2 = 678;


printf("Hello, first int is %d, second int is %5d.\n", i1, i2);
//Hello, first int is 12345, second int is 678.
printf("Hello, first int is %d, second int is %-5d.\n", i1, i2);
//Hello, first int is 12345, second int is 678 .

char msg[] = "Hello";


printf("xx%20sxx\n", msg);
//xx Helloxx
printf("xx%-20sxx\n", msg);
//xxHello xx

EXAMPLE: printing integers right-justified


#include <stdio.h>

int main() {
printf(" Printing integers right-justified.\n");
printf("Compare the output with the source code\n");
printf("---------------------------------------\n\n");
printf("%4d\n", 1);

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 5


Module 1 – Managing I/O Operations

printf("%4d\n", 12);
printf("%4d\n", 123);
printf("%4d\n", 1234);
printf("%4d\n\n", 12345);
printf("%4d\n", -1);
printf("%4d\n", -12);
printf("%4d\n", -123);
printf("%4d\n", -1234);
printf("%4d\n", -12345);
return 0;
}

Output:
1
12
123
1234
12345
-1
-12
-123
-1234
-12345

EXAMPLE: // printing numbers with and without the + flag


#include <stdio.h>

int main() {
printf("Printing numbers with and without the + flag.\n");
printf(" Compare the output with the source code\n");
printf("---------------------------------------------\n\n");
printf("%d\n%d\n", 100, -100);
printf("%+d\n%+d\n", 100, -100);
return 0;
}

Output:
100
-100
+100
-100

UNFORMATTED INPUT & OUTPUT FUNCTIONS

Unformatted Input
Unformatted input and output functions are only work with character data type. Unformatted input
and output functions do not require any format specifiers. Because they only work with character data
type.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 6


Module 1 – Managing I/O Operations

Character IO Functions

getchar() Function

The getchar() function reads character type data form the input. The getchar() function reads one
character at a time till the user presses the enter key.

Program

#include <stdio.h>
#include <conio.h>
int main() {
char c;
printf("Enter a character : ");
c = getchar();
printf("\nEntered character : %c ", c);
return 0;
}

OUTPUT:

Enter a character : y
Entered character : y

getch() Function

The getch() function reads the alphanumeric character input from the user. But, that the entered
character will not be displayed.

#include <stdio.h>
#include <conio.h>
int main() {
printf("\n Press any character: ");
getch();
return 0;
}

OUTPUT:
Press any character:

Note: The above program will run until you press one of many alphanumeric characters. The key
pressed by you will not be displayed.

getche() Function

getche() function reads the alphanumeric character from the user input. Here, character you entered
will be echoed to the user until he/she presses any key.

#include <stdio.h>
#include <conio.h>
int main() {
printf("\n Press any character: ");

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 7


Module 1 – Managing I/O Operations

getche();
return 0;
}

OUTPUT:
Press any character:
A

Note: The above program will run until you press one of many alphanumeric characters. The key
pressed by you will be echoed.

Unformatted Output

putchar() Function

putchar() function prints only one character at a time.

#include <stdio.h>
#include <conio.h>
int main() {
char c = 'K';
putchar(c);
return 0;
}

Here, variable c is assigned to a character 'K'. The variable c is displayed by the putchar(). Use Single
quotation mark ' ' for a character.

putch() Function

The putch() function prints any alphanumeric character.

#include <stdio.h>
#include <conio.h>
int main() {
char c;
printf("Press any key to continue\n ");
c = getch();
printf("input : ");
putch(c);
return 0;
}

OUTPUT:
Press any key to continue
input : d

The getch() function will not echo a character. The putch() function displays the input you pressed.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 8


Module 1 – Constants, Variables & Data Types

CONSTANTS, VARIABLES & DATA TYPES

Similar to other programming languages, C language also uses data types, constants, variables, modifiers,
to execute the program.

CHARACTER SET

It denotes any alphabet, digit or special symbol used to represent information. These characters can be
combined to form variables. C uses constants, variables, operators, keywords and expressions as
building blocks to form a basic C program. The character set is the fundamental raw material of any
language and they are used to represent information. Like natural languages, computer language will
also have well defined character set, which is useful to build the programs.

The characters in C are grouped into the following two categories:

1) Source character set: consists of

a) Alphabets: consists of 26 alphabets both upper case (A to Z) as well as lower case. (a to z)


b) Digits: consists of 10 numerical digits from 0 to 9
c) Special Characters: like tilde (~), ampersand (&), dollar ($), at symbol (@) etc

2) Execution character set:

Certain ASCII characters are unprintable, which means they are not displayed on the screen or printer.
Those characters perform other functions aside from displaying text. Examples are backspacing,
moving to a newline, or ringing a bell.

They are used in output statements. Escape sequence usually consists of a backslash and a letter or a
combination of digits. An escape sequence is considered as a single character but a valid character
constant.

These are employed at the time of execution of the program. Execution characters set are always
represented by a backslash (\) followed by a character. Note that each one of character constants
represents one character, although they consist of two characters. These characters combinations are
called as escape sequence.

Example: blank space (\b), horizontal tab (\t), new line (\n), back slash (\\), single quote (\’), double
quote (\”) etc

C TOKENS

The basic and smallest unit of a C program is called C tokens.

There are six types of token in C.

1. Keywords: Keywords are special words that are used to give a special meaning to the program
and can’t be used as variable and constant. They are basically a sequence of characters that
have fixed to mean for example break, for, while, do-while, do, if, int, long, char.
2. Identifiers: Identifiers are the sequence of alphabets and digit, but keyword should not be
used as an identifier.
3. Constants: The quantity which does not change during the execution of a program is known as
constant. There are types of constant.
4. Variables: Variables are used to give the name and allocate memory space. An entity that may
vary data during execution. For example, sum, area, a, b, age, city.
Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 1
Module 1 – Constants, Variables & Data Types

5. String: String is a collection of more than one character. For example, “RAM”, “Meerut”, “Star”
String is represented by a pair of double quotes.
6. Operators: Operators acts as connectors and they indicate what type of operation is being
carried out. The values that can be operated by these operators are called operands. They are
used to perform basic operations, comparison, manipulation of bits and so on.

C KEYWORDS & IDENTIFIERS

Keywords are predefined, reserved words used in programming that have special meanings to the
compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example: int
money;
Here, int is a keyword that indicates 'money' is a variable of type integer.

As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all
keywords allowed in ANSI C.

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

Along with these keywords, C supports other numerous keywords depending upon the compiler.

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifier must be unique. They are created to give unique name to a entity to identify it during the
execution of the program. For example: int money; double accountBalance;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an identifier
because int is a keyword.

Rules for writing an identifier


1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore. However, it is
discouraged to start an identifier name with an underscore.
3. There is no rule on length of an identifier. However, the first 31 characters of identifiers
are discriminated by the compiler.

Good Programming Practice

You can choose any name for an identifier (excluding keywords). However, if you give meaningful
name to an identifier, it will be easy to understand and work on for you and your fellow programmers.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 2


Module 1 – Constants, Variables & Data Types

CONSTANTS & VARIABLES

 C Constants are also like normal variables. But, only difference is, their values cannot be
modified by the program once they are defined.
 Constants refer to fixed values. They are also called as literals
 Constants may be belonging to any of the data type.

C constants can be divided into two major categories:


1. Primary Constants: integer, real and character
2. Secondary Constants: array, pointer, structure, union

Rules for constructing C constant:

1. Integer Constants in C:
 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.

2. Real constants in C:
 A real constant must have at least one digit
 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.

3. Character and string constants in C:


 A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.

4. Backslash Character Constants in C:


 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of them.

VARIABLES

When we want to store any information (data) on our computer/laptop, we store it in the computer's
memory space. Instead of remembering the complex address of that memory space where we have
stored our data, our operating system provides us with an option to create folders, name them, so that
it becomes easier for us to find it and access it.

Similarly, in C language, when we want to use some data value in our program, we can store it in a
memory space and name the memory space so that it becomes easier to access it.

The naming of an address is known as variable. Variable is the name of memory location. Unlike
constant, variables are changeable, we can change value of a variable during execution of a program. A
programmer can choose a meaningful variable name. Example: average, height, age, total etc.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 3


Module 1 – Constants, Variables & Data Types

Datatype of Variable

A variable in C language must be given a type, which defines what type of data the variable will hold.
It can be:
i) char: Can hold/store a character in it.
ii) int: Used to hold an integer.
iii) float: Used to hold a float value.
iv) double: Used to hold a double value.

Rules to name a Variable


1. Variable name must not start with a digit.
2. Variable name can consist of alphabets, digits and special symbols like underscore _.
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.
5. Upper and lower case names are treated as different, as C is case-sensitive, so it is suggested to
keep the variable names in lower case.

Declaring, Defining and initializing a variable

Declaration of variables must be done before they are used in the program. Declaration does the
following things.
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. Until the variable is defined the compiler doesn't have to worry about allocating memory space
to the variable.
4. Declaration is more like informing the compiler that there exist a variable with following
datatype which is used in the program.
5. A variable is declared using the extern keyword, outside the main() function.

Defining a variable means the compiler has to now assign a storage to the variable because it will be
used in the program. It is not necessary to declare a variable using extern keyword, if you want to use
it in your program. You can directly define a variable inside the main() function and use it.

To define a function we must provide the data-type and the variable name. We can even define
multiple variables of same data-type in a single line by using comma to separate them.
i) int a;
ii) float b, c;

Initializing a variable means to provide it with a value. A variable can be initialized and defined in a
single statement, like:
int a = 10;

DATATYPES

Each variable in C has an associated data type. Each data type requires different amounts of memory
and has some specific operations which can be performed over it. C supports three types of data
i) Primary data types
ii) Derived data types
iii) User defined data types

Primary datatype: These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 4


Module 1 – Constants, Variables & Data Types

Integer type: Integers are used to store whole numbers.

Size and range of Integer type on 16-bit machine:

Type Size (bytes) Range


int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295

Floating point type: Floating types are used to store real numbers.

Size and range of Integer type on 16-bit machine

Type Size (bytes) Range


Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

Character type: Character types are used to store characters value.

Size and range of Integer type on 16-bit machine

Type Size (bytes) Range


char or signed char 1 -128 to 127
unsigned char 1 0 to 255

Type Conversions:

Type casting is a way to convert a variable from one data type to another data type

Implicit Conversions:

C can perform conversions between different data type. The following rules apply when objects of
different types appear:

Operand 1 Operand 2 Result


float int Converts int to floats. Returns float
char int Treats both as int and returns int. This proves to be dangerous.
float double Converts float to double and returns double
int short Converts short to int
int long Converts int to long
unsigned Int converts int to unsigned if no sign is present

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 5


Module 1 – Constants, Variables & Data Types

Examples:

1) float=int -> converts int to float


float a;
a=5;
print a will give 5.000000

2) int=float -> truncates the fractional part of float


int a;
a=25.47;
print a will give 25

EXPLICIT Conversions: (casting)

You can convert explicitly by type casting.

Syntax : data_type expression

Where data_type  any valid data type like int, float etc.
expression  includes, constants, variable or expression itself.

Ex : int x;
...
...
(float)x;

Derived Data Type:


These data types are formed by a combination of two or more primary data types. They have extended
the scope of C language. The most common are pointers, arrays, union and structures.

Pointers: Pointers are very powerful features of the C language. The basic concept of a pointer is that
it provides the mechanism for determining the address of data. It can reference any data type – basic
or derived. However, overuse of pointers affects performance.

Arrays: An array is a container used to store several values in one variable and data type. It is defined
using square brackets. An integer comes in between the brackets, which defines the array’s size.

Structures: C allows you to declare variables that can hold various types of data items into one. This is
called a structure in C. The “struct” keyword is used to define the structure. It defines new data types
with several members.

Unions: A union stores different data types in the same memory location. It consists of many members
but only one member can contain the value at any given time. It provides an efficient way of using the
same memory location for various purposes.

We will be dealing with these derived data types as separate topic later.

User-Defined Data Types:

C supports the features “typedef” that allows users to define the identifier which would represent an
existing data type. This defined data type can then be used to declare variables:

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 6


Module 1 – Constants, Variables & Data Types

Syntax:
typedef int numbers;

numbers num1,num2;

In this example, num1 and num2 are declared as int variables. The main advantage of user defined
data type is that it increases the program’s readability.

Another type is enumerated type. This is also a user defined data type

Syntax: enum identifier {value1,value2, value 3,…}

“Enum” is the keyword and “identifier” is the user defined data type that is used to declare the
variables. It can have any value enclosed within the curly braces. For example:

enum day {January, February,March,April,..};

enum day month_st,month_end;

The compiler automatically assigns integer digits beginning from 0 to all the enumeration constants.
For example, “January ” will have value 0 assigned, “February” value 2 assigned and so on. You can
also explicitly assign the enumeration constants.

Dr. N. Guruprasad – Professor in CSE, DBIT, Bengaluru Page 7


MODULE-1 contd
2.1 Operators and Expressions
✓ Operator: Operator is a symbol (or token) that specifies the operation to be performed on
various types of data.
✓ Operand: A constant or variable or function which returns a value is an operand.
✓ Expression: A sequence of operands and operators that reduces to a single value is an
expression.
Operands

a + b Expression

a _ b

Operators

2.1.1 Classification of operators


The operators in C can be classified based on:
• The number of operands an operator has.
• The type of operation being performed.

1. Classification of operators based on the number of operands


Unary operators Ex: ++,-- etc.

Operators Binary operators Ex: +,-,*,/ etc.

Ternary operators Ex: ? and :

i) Unary operator: An operator which acts on only one operand to produce the result is
called Unary operator.
Ex: -10, -a, *b, ++a, a++, b-- etc.

ii) Binary operator: An operator which acts on two operands to produce the result is called
Binary operator.
Ex: a+b, a*b, 10/5 etc

iii) Ternary operator: An operator which acts on three operands to produce the result is
called Ternary operator.
Ex: a ? b : c;

DBIT 1
2. Classification of operators based on type of operation
Arithmetic Operators Ex: +, - , * etc.

Assignment Operators Ex: =, +=

Increment/Decrement Operators Ex: ++, --

Relational Operators Ex: <, >, <=, >=

Types of Operators Logical Operators Ex: &&, ||

Conditional Operators Ex: ?:

Bitwise Operators Ex: &, ^

Special Operators Ex: ,, . ,[ ] , ( )

i) Arithmetic Operators
✓ The operators that are used to perform arithmetic operations such as addition,
subtraction, multiplication, division and modulus are called arithmetic operators.
✓ These operators perform operations on two operands and hence they are called binary
operators.

✓ % (modulus operator) divides the first operand by second and returns the remainder.
✓ % (modulus operator) cannot be applied to floating or double.
✓ % operator returns remaining value(remainder) of an integer division.

✓ *, / and % operators are having higher precedence than +, - operators.

DBIT 2
Arithmetic Operator’s Precedence (Precedence of operators)
✓ The Arithmetic Expressions are evaluated based on “BODMAS” Rule. (Brackets of Operator
(x(2),[ ]), Order or Power (xy,23 etc.), Division, Multiplication, Addition, Subtraction).

ii) Assignment Operators


✓ An operator which is used to assign the data or result of an expression into a variable (also
called memory location) is called an assignment operator.
✓ Assignment operator is denoted by ‘=’ sign.
Ex: a=b; //value of b is copied into variable a

Types of Assignment statements:


a). Simple Assignment Statement

variable= expression;

Ex: a=10;
a=b;
a=a+b;
Area= l*b; //Result of Expression l*b is copied into variable area.

b). Shorthand Assignment Statement


✓ The operators such as +=, -=, *=, /= and %= are called shorthand assignment operators.
Ex 1: a=a+10; // simple assignment
a+=10; // shorthand assignment
Ex 2: i=i+2;
i+=2;
✓ If expr1 and expr2 are expressions then
expr1op = expr2 ;
is equivalent to
expr1 = (expr1) op (expr2) ;
i.e., x*=y+1 means x=x*(y+1) ;

DBIT 3
c). Multiple Assignment Statement
✓ Assigning a value or a set of values to different variables in one statement is called multiple
assignment statement.
✓ The multiple assignments are used whenever same value has to be copied into various memory
locations.
Ex: int i=10; //simple assignment
int j=10;
int k=10;
int i=j=k=10; //multiple assignment

iii) Increment and Decrement Operators


Increment Operator
✓ ‘++’ is an increment operator. This is unary operator. It increments the value of a variable
by one.
Post Increment Ex: a++
Increment
Operator Pre Increment Ex: ++a

1. Post Increment
✓ It increments the value after (post) the operand value is used. i.e., operand value is used
first and then the operand value is incremented by 1.
Ex: void main()
{
int a=20,b; // a=20, b?
b=a++; // b=a=20, a=a+1= 20+1
printf(“%d”,a); // a=21
printf(“%d”,b); // b=20
}

2. Pre Increment
✓ It increments before (pre) the operand value is used. The operand value is incremented by
1 and this incremented value is used.

4
Ex: void main()
{
int a=20,b; // a=20, b?
b=++a; // a=++a=a+1= 20+1, b=a=21
printf(“%d”,a); // a=21
printf(“%d”,b); // b=21
}

Decrement Operator
✓ '--' is a decrement operator. This is a unary operator. It decrements the value of a variable
by one.
Post Decrement Ex: a--
Decrement
Operator Pre Decrement Ex: --a

1. Post Decrement
✓ It decrements the value after (post) the operand value is used. i.e., operand value is used
first and then the operand value is decremented by 1.
Ex: void main()
{
int a=20,b; // a=20, b?
b=a--; // b=a=20, a=a-1= 20-1
printf(“%d”,a); // a=19
printf(“%d”,b); // b=20
}

2. Pre Decrement
✓ It decrements before (pre) the operand value is used. The operand value is decremented by
1 and this decremented value is used.
Ex: void main()
{
int a=20,b; // a=20, b?
b=--a; // a=--a=a-1= 20-1, b=a=19
printf(“%d”,a);// a=19
printf(“%d”,b); // b=19
}

iv) Relational operators


✓ The operators that are used to find the relationship between two operands are called
relational operators.
✓ The relationship between the two operand values results in true (always 1) or false (always
0).

5
Relational operators available in C are:

✓ All the relational operators are having a same priority and left to right associativity.
✓ The relational operators have lower precedence than arithmetic operators.

Equality operators
✓ C supports two kinds of equality operators to compare their operands for strict equality or
inequality.
equal ==
not equal ! =
✓ Equality operators have lower precedence than the relational operators.

v) Logical operators
✓ The operators that are used to combine two or more relational expressions are called
logical operators.
✓ The output of relational expression is true or false, the output of logical expression is also
true or false.

Logical operators available in C:

Description Operators Priority Associativity


not ! 1 Left to Right
and && 2 Left to Right
or !! 3 Left to Right

Operand1 Operand2 AND(&&) OR(||) NOT(!) (Operand1)


True(1) True(1) True(1) True(1) False(0)
True(1) False(0) False(0) True(1) False(0)
False(0) True(1) False(0) True(1) True(1)
False(0) False(0) False(0) False(0) True(1)

Logical NOT: The logical NOT operator is denoted by ‘!’. The output of not operator can be true or
false. The result is true if the operand value is false and the result is false if the operand is true.

Logical AND: The logical AND operator is denoted by ‘&&’. The output of and operator is true if
both the operands are evaluated to true. If one of the operand is evaluated false, the result is false.

6
Logical OR: The logical OR operator is denoted by ‘||’. The output of or operator is true if and only if
at least one of the operands is evaluated to true. If both the operands are evaluated to false, the result
is false.

Ex: 1. If a, b, c are 3 sides of a triangle, then if a==b && b==c && c==a then triangle is equilateral
otherwise not an equilateral triangle.
2. If a, b, c are 3 sides of a triangle then if a==b || b==c || c==a then triangle is isosceles triangle
otherwise not a isosceles triangle.
3. int a=10, b:
b =!a ;
Output: value of b=0, because a = 10 then !a=0 and !a value assigned to b.

vi) Conditional Operator


✓ The conditional operator is also called as 'ternary operator'.
✓ An operator that operates on the three operands is called ternary operator.
Syntax:
(expr1)? expr2: expr3;

Where,
- expr1 is evaluated first.
- If expr1 is evaluated to true, then expr2is evaluated.
- If expr1 is evaluated to false, then expr3is evaluated.
Example:
1. Write a C program to find the biggest of two numbers using conditional operator.
#include<stdio.h>
void main()
{
int a,b,big;
printf(“Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
big=(a>b)?a:b;
printf(“Big=%d”,big);
}

2. Write a C program to find the smallest of two numbers using conditional operator.
#include<stdio.h>
void main()
{
int a,b,small;
printf(“Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
small=(a<b)?a:b;
printf(“Small=%d”,big);
}

7
vii) Bitwise Operators
✓ The operators that are used to manipulate the bits of given data are called bitwise
operators.

Bitwise operators available in C are:

✓ These may only be applied to integral operand. i.e., char, short, int and long whether signed or
unsigned.

a. One’s Complement(~)
✓ The operator that is used to change every bit from 0 to 1 and 1 to 0 in the specified operand
is called One’s complement operator.
Truth table of One’s Complement(~):
Op1 ~Op1
0 1
1 0

✓ One’s complement operator is denoted by ‘~(tilde)’ symbol.

Ex: Write a C program to show the usage of Bitwise Negate operator.


#include<stdio.h>
void main()
{
int a=10,b;
b=~a;
printf(“~%d=%d”,a,b);
getch();
}

Output: ~10=245
Binary Representation:
10 = 0 0 0 0 1 0 1 0
245= 1 1 1 1 0 1 0 1

8
b. Left shift operator (<<)
✓ The operator that is used to shift the data by a specified number of bit positions towards
left is called ‘left shift operator’.
Syntax:
b=a<<num;
Ex: Write a C program to show the usage of Left Shift operator.
#include<stdio.h>
void main()
{
int a=5,b;
b=a<<1;
printf(“%d<<1=%d”,a,b);
}
Output: 5<<1=10
MSB is discarded

0 0 0 0 0 1 0 1 a=5

0 0 0 0 1 0 1 0 b=10

0 is appended at LSB

c. Right shift operator (>>)


✓ The operator that is used to shift the data by a specified number of bit positions towards
right is called ‘right shift operator’.
Syntax:
b=a>>num;
Ex: Write a C program to show the usage of Right Shift operator.
#include<stdio.h>
void main()
{
int a=10,b;
b=a>>1;
printf(“%d>>1=%d”,a,b);
}
Output: 10>>1=5
LSB is discarded

0 0 0 0 1 0 1 0 a=10

0 0 0 0 0 1 0 1 b=5
0 is appended at MSB

9
d. Bit-wise AND (&)
✓ If the corresponding bit positions in both the operands are 1, then AND operation results in
1, otherwise AND operation results in 0.
Truth table of Bit-wise AND (&):
Op1 Op2 Op1&Op2
0 0 0
0 1 0
1 0 0
1 1 1
Ex: Write a C program to show the usage of ‘&’ operator.
#include<stdio.h>
void main()
{
int a=10,b=6;
c=a&b;
printf(“%d&%d=%d”,a,b,c);
}
Output: 10&6=2

Binary Representation:
10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
02 = 0 0 0 0 0 0 1 0

e. Bit-wise OR (|)
✓ If the corresponding bit positions in both the operands are 0, then OR operation results in
0, otherwise OR operation results in 1.

Truth table of Bit-wise OR (|):


Op1 Op2 Op1|Op2
0 0 0
0 1 1
1 0 1
1 1 1

Ex: Write a C program to show the usage of ‘|’ operator.


#include<stdio.h>
void main()
{
int a=10,b=6;
c=a|b;
printf(“%d|%d=%d”,a,b,c);
}
Output: 10|6=14
Binary Representation: 10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
14 = 0 0 0 0 1 1 1 0

10
f. Bit-wise XOR (^)
✓ If the corresponding bit positions in both the operands are different, then XOR operation
results in 1, otherwise XOR operation results in 0.
0^0=0
0^1=1
1^0=1
1^1=0
Ex: Write a C program to show the usage of ‘^’ operator.
#include<stdio.h>
void main()
{
int a=10,b=6;
c=a^b;
printf(“%d^%d=%d”,a,b,c);
}

Output: 10^6=12
Binary Representation:
10 = 0 0 0 0 1 0 1 0
06 = 0 0 0 0 0 1 1 0
12 = 0 0 0 0 1 1 0 0

viii) Special Operators


✓ Comma operator, size of operator and [ ], ->, Indirection operator, *, dot operator etc.

1. Comma operator
✓ Comma Operator has the least precedence among all the operators and it is left associative
operator.
✓ Comma Operator is used in the declaration to separate the variables.
Ex: int a,b,c;
✓ It can be used to separate the items in the list.
Ex: a=12,345,678;
✓ It can be used to combine two or more statements into a single statement.
Ex: sum=a+b,sub=a-b,mul=a*b,div=a/b,mod=a%b;

2. sizeof()
✓ ‘sizeof()’ operator is used to determine the number of bytes occupied by a variable or a constant
in the memory.
✓ Ex: sizeof(char) 1 byte
sizeof(int) 2 bytes
sizeof(float) 4 bytes
Example program: Write a C program that computes the size of int, float, char and double
variables.
#include<stdio.h>
void main()
{

11
char ch;
int x;
float y;
double z;
clrscr();
printf(“Number of bytes occupied by character variable=%d”,sizeof(ch));
printf(“Number of bytes occupied by integer variable=%d”,sizeof(x));
printf(“Number of bytes occupied by floating-point variable=%d”,sizeof(y));
printf(“Number of bytes occupied by double variable=%d”,sizeof(z));
}

2.1.2 Arithmetic Expressions


✓ The expression consisting of only arithmetic operators such as +, -, *, / and % are called
arithmetic expressions.

Example: Write the equivalent C expression for the Mathematical expressions.


Mathematical Expression C Equivalent Expression
𝑎+𝑏+𝑐 S=(a + b +c) /2
𝑆=
2
𝑎𝑟𝑒𝑎 = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐) area=sqrt(s*(s-a)*(s-b)*(s-c))

𝑥 = √2𝜋𝑛 x=sqrt(2*3.142*n)
a a/b
b
𝑏 x=-b/(2*a)
𝑥=−
2𝑎
𝑎𝑥2 + bx + c a*x*x+b*x+c

12
2.1.3 Associativity of operators
✓ When two or more operators have the same precedence, then precedence rules are not
applicable.
✓ Associativity determines how the operators with the same precedence are evaluated in an
expression.
The two types of operators Associativity are:
1. Left Associativity
2. Right Associativity

1. Left Associativity
✓ In an expression, if two or more operators having the same priority are evaluated from
left-to-right, then the operators are called Left to Right associative operators.
✓ We normally denote it using L R.

2. Right Associativity
✓ In an expression, if two or more operators having the same priority are evaluated from
right-to-left, then the operators are called Left to Right associative operators.
✓ We normally denote it using R L.
Ex: i=j=k=10.

2.1.4 Precedence and order of Evaluation


✓ In C language, each operator is associated with priority value.
✓ Based on the priority the expressions are evaluated. The priority of each operator is pre-defined
in C language.
✓ The order in which the different operators are used to evaluate an expression is called
Precedence or hierarchy of operators
✓ The pre-defined priority or precedence order given to each of the operator is called precedence of
operator.

13
✓ Unary +, - and * have higher precedence than the binary forms.

2.2 Problems on Expression Evaluation

14
15
16
2.3 Type Conversion and Typecasting
✓ The process of converting the data or variable from one data type to another data type is called
Type Conversion or Typecasting.
✓ Type conversion is done implicitly by the compiler, whereas typecasting has to be done
explicitly by the programmer.

2.3.1 Type Conversion


✓ Type conversion is done when the expression has variables of different data types.
✓ To evaluate the expression, the data type is promoted from lower to higher level where the
hierarchy of data types (from higher to lower level) can be given as: double, float, long, int,
short and char.
char short int int unsigned int long int float double
Lower Rank Higher Rank
Data types Data types

17
✓ C compiler converts the data type with lower rank to the data type with higher rank. This process of
conversion of data from lower rank to higher rank automatically by the C compiler is called “Implicit
type Conversion”.

✓ If one operand type is same as that of other operand type, no conversion takes place. Ex: int
+ int = int, float + float = float
✓ If one operand type is ‘int’ and other operand type is ‘float’, then the operand with type int is promoted
to ‘float’ (because float is up in ladder compared with int).
✓ Type conversion is automatically done when we assign an integer value to floating point variable. Consider
the code given below in which an integer data type is promoted to float. This is known as promotion (where
the lower level data type is promoted to higher type).
float x; int y=3;
x=y;
Now, x=3.0, as automatically integer value is converted into its equivalent floating point representation.

2.3.2 Typecasting
✓ Typecasting is also known as forced conversion.
✓ It is done when the value of a higher data type has to be converted into a value of a lower data type.
✓ But this casting is done under the programmer’s control and not under the compiler’s control.
✓ The programmer can instruct the compiler to change the type of the operand or variable from one
data type to another data type. This forcible conversion from one data type to another data type is
called “Explicit type Conversion” (Type Casting).
Syntax:
(type) Expression

Ex: (int) 9.43


i= (int) 5.99 / (int) 2.4, now it becomes 5/2 = 2, i=2 (float) (3/10)
= 3.0 / 10.0 = 0.3

You might also like