0% found this document useful (0 votes)
14 views33 pages

PPS Unit-1 Notes

The document provides an introduction to computers, detailing their characteristics, components, and the distinction between hardware and software. It explains the roles of the Central Processing Unit (CPU), memory types, and the software development process, including program creation, compilation, linking, and execution. Additionally, it outlines various computing environments such as personal computing, mobile computing, client-server computing, and distributed systems.

Uploaded by

mitrasri37
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)
14 views33 pages

PPS Unit-1 Notes

The document provides an introduction to computers, detailing their characteristics, components, and the distinction between hardware and software. It explains the roles of the Central Processing Unit (CPU), memory types, and the software development process, including program creation, compilation, linking, and execution. Additionally, it outlines various computing environments such as personal computing, mobile computing, client-server computing, and distributed systems.

Uploaded by

mitrasri37
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
You are on page 1/ 33

KMEC/I/PPS/Unit-1

UNIT-I
INTRODUCTION TO COMPUTERS
A computer is an electronic machine that takes input from the user, processes the given input
and generates output in the form of useful information
 A computer accepts input in different forms such as data, programs and user reply.
 Programs refer to the set of instructions that can be executed by the computer in a
sequential or non-sequential manner.

Characteristics of Modern Computer:


 Speed: Computer is a fast electronic device that can solve large and complex problems in
few seconds. The speed of a computer depends upon its hardware configuration.
 Storage capacity: A computer can store huge amount of data in many different formats.
Computer storage is divided into 2 categories: Main memory and Secondary storage.
 Accuracy: A computer carries out calculations with great accuracy. The accuracy achieved
by a computer depends upon its hardware configuration and the specified instructions.
 Reliability: A computer produces results with no error. Most of the computer-generated
errors are in actuality human errors that are instigated by the user itself. Therefore,
computers are regarded as quite trustworthy machines.
 Versatility: Computers are versatile machines. They can perform varied tasks and can be
used for many different purposes.
 Diligence: Computers can perform repetitive calculations any number of times with the
same level of accuracy.
COMPONENTS OF COMPUTER
A computer is a system made of two major components: Hardware and Software.
 The computer hardware is the physical equipment.
 Computer software is the collection of programs that allows hardware to do its job.
Hardware component of the computer system consists of five components:
1. Input devices
2. Output devices
3. Central Processing Unit (CPU)
4. Primary storage devices
5. Auxiliary storage devices

Input device
It is a device where the programs and data
are entered into the computer.
Example: Keyboard, Mouse, Scanner.

Output device
It is a device to show output. The data
processed by the CPU, is made available to
the end user by the output devices.
Example: Monitor, Printer, Speaker.

1
KMEC/I/PPS/Unit-1

Central Processing Unit (CPU)


It is called as the brain of the computer. It is the processor of the computer that is responsible
for controlling and executing instructions such as arithmetic calculations, comparisons among
the data, and movement of data inside the system.
Three components of CPU: Arithmetic and Logic Unit, Control Unit, Registers.
Arithmetic and Logic Unit (ALU)
ALU is a part of the CPU that performs arithmetic and logical operations on the data.
It performs arithmetic operations such as addition, subtraction, multiplication, division etc.
It performs logical operations such as greater than, less than, equal to, not equal to, left shift,
right shift etc.
 ALU takes input as an instruction that contains Opcode, Operands & Format code.
 The output of ALU contains the result of the operation & the status of the result, whether
it is final or not.
 ALU stores the output in the CPU register.

Control Unit (CU)


Control Unit controls the flow of data and information.
 It maintains the sequence of operations being performed by the CPU.
 Control Unit guides the ALU about the operations that are to be performed.
 Control unit suggests the I/O devices to which the data is to be communicated.
 It uses a program counter register for retrieving the next instruction that is to be executed.
Registers
CPU Registers are high-speed memory locations used for holding instructions, data and
intermediate results that are currently being processed.
A processor can have different types of registers to hold different types of information.
 Program Counter (PC) to keep track of the next instruction to be executed.
 Accumulator (ACC) for storing the results produced by arithmetic and logic units.
 Memory Data Register (MDR) for storing operands and data.
 Memory Address Register (MAR) to hold the address of the next location in the memory
to be accessed.
Note: Buses are electrical pathways that transfer data and instructions among different parts of
the computer. (i.e) transfers data among the processor to main memory devices and
input/output devices connected to the computer.

Memory Unit
The memory unit of a computer is used to store data, instructions.
The memory units of a computer are classified as primary memory and secondary memory.

Main memory or Primary storage


 It is a place where the programs and data are stored temporarily during processing.
 The data in primary storage are erased when we turn off a personal computer or when we
log off from a time-sharing system.
 Examples: Random Access Memory (RAM), Read-Only Memory (ROM).

2
KMEC/I/PPS/Unit-1

Secondary Memory or Auxiliary storage


 It is used store the programs and data permanently.
 That means, even after we turn off the computer, the programs and data remain in the
secondary storage, ready for the next time we need them.
 Ex: Hard disk drives, solid state disks CD-ROM. DVD-ROM USB drives, pen drives etc.
Note: USB devices and memory cards are considered as tertiary storage devices. They also
store the data permanently.

Random Access Memory (RAM)


 It is a Volatile Memory storage. ROM stores information temporarily.
 The information inside the RAM is deleted when even we switch off the computer.
 It is the internal memory of the CPU for storing data, program, and program result.
 RAM’s are categorized into two types: Static RAM and Dynamic RAM.

Read-Only Memory (ROM)


 It is a Non-Volatile Memory storage. ROM stores information permanently.
 ROM stores such instructions that are required to start a computer such as bootstrap
program and Basic Input/Output System (BIOS) programs.
 We cannot change the data very often in ROM.
 ROM stores static programs, which can’t be changed frequently by end user.
 EPROM and EEPROM are examples of different types of ROM.
Difference between RAM & ROM
Random Access Memory (RAM) Read-Only Memory (ROM)
It is a read/write memory. It is a read only memory.
It is volatile storage device. It is a permanent storage device.
Data is erased when power supply is turned off. Data remains stored permanently.
It is used as the main memory. It is used to store BIOS.

Cache memory
 It is used to store the data and the related application that was last processed by the CPU.
 Cache memory is placed in between CPU and the main memory of the computer system.
 When the processor performs processing, it first searches for the instruction in the the cache
memory and then it searches in the RAM.

COMPUTER SOFTWARE
Software is divided in to two broad categories: System software & Application software.
 System software manages the computer resources .It provides the interface between the
hardware and the users. Example: Operating System
 Application software is directly responsible for helping users solve their problems.
Example: Notepad, MS Word, MS Excel etc.

Operating System (OS)


It is a system software. It acts as an intermediary between the user of a computer and the
computer hardware.

3
KMEC/I/PPS/Unit-1

The purpose of an operating system is to provide an environment in which a user can execute
programs in a convenient and efficient manner.
 The operating system manages the resources such as CPU time, memory space, file-storage
space, I/O devices and so on.
 An operating system is a control program that manages the execution of user programs to
prevent errors and improper use of the computer.
Compilers
 The process of converting high-level language code into machine language code is known
as compilation.
 A compiler is a software program that transforms high-level language source code into a
low level object code (binary code) in machine language.
 Machine language code is understood by the processor.
 High level language code understood by user.

COMPUTER LANGUAGES
Computer Languages are categorized into 3 levels:
1. Low level language or Machine language
2. Symbolic language or Assembly language
3. High level language or Procedural oriented language

Machine Language
 Computers only understands machine code or machine language.
 Machine code consists of combination of 0's and 1's called binary data.
 All instructions and data should be written using binary codes 1 and 0.
 Machine language is difficult to understand and remember the various combinations of 1’s
and 0’s representing numerous data and instructions.
 Machine languages are usually referred to as the first generation languages.

Assembly Language
 The Assembly languages are introduced in 1950s.
 They reduce programming complexity.
 The assembly languages second-generation programming languages.
 An assembly language program consists of a series of instructions and mnemonics that
correspond to a stream of executable instructions.
 Assembly instructions consists of an opcode followed by zero or more operands.
 Opcode specifies the operation to be performed on the given arguments.
Example: mov AL, 061h.
 Opcode “mov” is used to move the hexadecimal value 61 into the processor register ‘AL’.
 Note: During the execution, all the assembly language statements are converted to machine
language statements by using Assembler program.

High-Level Languages
In High level language, the programs are written in human understandable languages like
English. Example: C, C++, JAVA, PYTHON, FORTRAN, COBAL etc.

4
KMEC/I/PPS/Unit-1

 Compilers are used to convert the high level language code to machine code. That means
it converts alphabets and digits and other special characters to 0's and 1's.
 Some programming languages uses interpreter to convert to machine code.
Let the instruction: C=A+B
 A, B, C are memory locations and the values of A and B are added and stored in C.
 Programmers don’t need to manage memory addresses, CPU registers, or binary code
directly.
 Debugging is easy in high level languages.
CREATING AND RUNNING PROGRAMS
It is the job of a programmer to write and run the program.
This process involves four steps.
1. Creating and Editing program
2. Compiling the program
3. Linking the program
4. Executing the program

Creating a program
 The program must be written into a file using "Text Editor" software.
 The file name must ends with ".c" extension. Ex: welcome.c
 A text editor helps us to write, modify and store character data.
 After we complete the program, we save the file to disk. This file is called "Source File"
(welcome.c).
 The source file is given as an input to the compiler.

5
KMEC/I/PPS/Unit-1

Compiling the program


 The compiler takes the source file an input.
 The compiler is used to convert source file code (high level language code) to machine
level language code and creates an object file with .o extension (Ex: welcome.o)
 That means, the source code contains english alphabets are converted to 0's and 1's and
stored in a file called object file.
 After compiling the program if everything is correct then only object file is created
otherwise it raises the error and we need to goto text editor and correct the errors and
compile again.

Linking the program


 The object file will be linked to the necessary library files such as input/output processes
and mathematical library functions etc,and must be attached to our program.
 Linker is a program that takes the responsibility of linking library files with source file and
creates a new file called "Executable file".
 The executable file has .exe extension. Example: welcome.exe
 The executable file is stored in hard disk.

Executing program
 Loader program is used to load an executable file from hard disk to main memory for
execution.
 It locates the executable program and reads it into memory.
 When everything is loaded, the program takes control and begins execution.
 After the program processes the data, it prepares the output.
 Data output can be to the user’s monitor or to a file.
 When the program has finished its job, it tells the operating system, which then removes
the program from memory.
SOFTWARE DEVELOPMENT METHOD
The following steps to be followed during the development of software
1. Analyzing the Requirements
2. Feasibility Analysis
3. Creating the Design
4. Developing the Code
5. Testing the Software
6. Deploying the Software
7. Maintaining the Software
Note: Each successive step is dependent on the outcome of the previous step.

Analyzing the Requirements


It is the first step towards development of a software.
 Here we need to understand what are the requirements related to the software, which is to
be developed.
 If the requirements of the user are not properly understood, then the software is bound to
fall short of the end user’s expectations.

6
KMEC/I/PPS/Unit-1

 Hence, there should be continuous interaction between the software development team and
the end users.
 Proper analysis of user requirements is quite essential for developing the software within a
given timeframe.
 It is used to control the software development cost.
 It lead to faster and accurate development of a software.

Feasibility Analysis
Here, we will check whether the proposed software project is practical to implement or not.
 In order to determine the feasibility of software development, the existing system of the
user is analyzed properly.
 Here we can understand requirements from user, collects background information,
analyzing technical , economical, time schedule feasibility, and identify any risks or
limitations in of the software project.
 The analysis done in this step is documented as a report called feasibility report.

Creating the Design


This step involves developing a logical model or basic structure of the new software.
 This step involves documenting the various specifications related to database and data
structure design using UML diagrams.
 The software design should be flexible and extensible.
 Software should be modular in nature, so we can develop multiple module at the same time.
 Software should run correctly in the existing system with an older version or with other
software.
 Software design must ensure secure and fault tolerant.

Developing the Code


According to the design specifications, the code for the different modules are developed.
 The code can be written using programming languages such as C, C++ or Java.
 The code must follow Proper naming conventions, proper indentation, and write proper
comments,.
 The code must be easily understood and logically correct.
 The programmers use debugging tools to find errors in the code.
 The programmers use compilers, interpreters to convert the code into machine language for
its execution.

Testing the Software


Testing is used to detect any errors in the new software and rectify those errors.
 verifi cation and validation activities will be performed during testing.
 Verifi cation is the process of checking the software based on some predefined specifi
cations.
 Validation involves testing the product to ascertain whether it meets the user’s requirements
so that we willg get correct output.

7
KMEC/I/PPS/Unit-1

 We use various testing such as unit testing, integration testing, black box testing,white box
testing etc.

Deploying the Software


In this step, we deliver the software to the end user.
 That means software is installed in its target environment.
 Software documentation is handed over to the users.
 Some initial data are entered in the software to make it operational.
 The users are also given training on the software’s interface and its other functions.

Maintaining the Software


It ensures that the software continues to run smoothly after its deployment.
 During this phase, developers fix bugs reported by users, update the software to enhance
security and improve performance, and add new features when required.
 The outcome of this phase is an updated and improved version of the software that meets
evolving user needs and technological requirements.

COMPUTING ENVIRONMENTS
There are several computing environment are built for different computing purposes:
1. Personal computing
2. Mobile computing
3. Client server computing
4. Distributed computing
Personal computing
It refers to the use of a single computer or workstation by an individual.
 This setup is typically designed for personal tasks such as document creation, web
browsing, gaming, and personal software development.
 Example: Desktop PCs & laptops running operating systems like Windows, Mac, or Linux.

Mobile Computing
Mobile computing refers to computing on handheld smartphones and tablet computers.
 Mobile devices are portable and lightweight.
 As compared with desktop and laptop computers, mobile systems have small screen size,
less memory capacity, less processing speed and also consumes less power consumption.
 Operating systems like Apple iOS and Google Android are used in mobile devices.
 Mobile systems are most widely used for taking photos & videos, e-mail and web browsing,
Global positioning system (GPS), accelerometers and gyroscopes, etc.

Client–Server Computing
Client –Server computing is a Centralized system in which Server systems are used to service
the requests generated by client systems.
PC’s and mobile devices are connected to the Centralized system through internet connection.
Example: A web browser (client) in a mobile devices requesting web pages to web server
(Google server).

8
KMEC/I/PPS/Unit-1

Distributed Systems
 It is a collection of different interconnected computers (servers) that work together to finish
a task.
 Computer servers are connected through internet and communicated using internet
protocols.
 Distributed systems shares resources of one system with others and the workload is shared
among the systems.
 Each node processes its assigned portion of the task independently and communicates with
other nodes.
 Example: Apache Hadoop, Google Map Reduce.
ALGORITHM
 Algorithm is a step-by-step procedure for solving a problem or doing a task.
 Algorithms help a programmer in breaking down the solution of a problem into a number
of sequential steps.
 The algorithm can be written human understandable language like English.
 Every algorithm must start with Start/ Begin statement and ends with Stop/ End statement.
Characteristics of Algorithms
 The instructions must be in an ordered form.
 The instructions must be simple and concise.
 They must not be ambiguous.
 The algorithm must completely and definitely solve the given problem statement.

Advantages of Algorithm
 Algorithms are written in a step-by-step manner, making them easy to understand, follow,
and implement.
 Algorithms provide a systematic approach to solving problems, ensuring no important step
is missed.
 Algorithms are conceptual and can be implemented in any programming language.
 Since each step is clearly defined, errors can be identified and corrected easily.
 A well-designed algorithm can be reused for similar problems without starting from
scratch.

Disadvantages of Algorithm
 In large algorithms, the flow of program control becomes difficult to track.
 An algorithm itself doesn’t handle unexpected inputs unless explicitly designed to do so.
 Some problems are too complex to express easily as a simple, step-by-step algorithm.

9
KMEC/I/PPS/Unit-1

FLOW CHARTS
A Flow chart is a pictorial representation of an Algorithm.
 The diagrammatic representation to solve the given problem is called Flow chart.
 The flow of information is represented inside the flowchart in a step-by-step form.
 Flowchart uses different symbols for depicting different activities.
Name Representation Description
Start and End Starting and Ending of a process is represented by an oval
or a rounded rectangle.
Every flow chart must have start and end symbols.
Input / Output It is represented by a parallelogram.
All Input and output statements of process are written
inside parallelogram.
Action / process It is represented by a rectangle.
/ calculations All the statements related to calculations, actions, logics are
written inside rectangle.
Decision/ All the conditional statements are written inside a rhombus.
condition Ex: if a>0.
The result is either true or false. Each of these values takes
the flow of the program to a different direction.
Arrow Arrow represents the flow of process and the sequence of
steps in a flowchart.
Connector It is represented by a circle in a flowchart.
It represents the continuation of the flow of steps when a
flowchart continues to the next page.
A character such as an alphabet (a-z or A-Z) can be placed
in the circle at the position where the flow is broken and the
same character is also placed in the circle at the position
from where the flowchart continues.
Rules for Designing a Flowchart
 It must begin with a “Start” and end with a “Stop” symbol.
 The standard process flow should be either from top to bottom or from left to right.
 The instructions specified in the flowchart must be simple and concise.
 The arrows must be aligned properly so as to clearly depict the flow of program control.
 A process or action flowchart symbol must have only one input arrow and one output arrow.
 Use of connectors should be generally avoided as they make the program more complex.

Advantages of Flowcharts
 Visual representations gives better understanding of problem statement.
 It helps to understand the flow of program control in an easy way.
 It is easy to develop program code using flow charts.
 It helps in avoiding semantic errors.
 The use of flowcharts works well for small program design.

10
KMEC/I/PPS/Unit-1

Disadvantages of Flowcharts
 For a large program, the flow chart might become very complex and confusing.
 Modification of a flowchart is difficult and requires lot of rework.
 It takes a lot of time to create a flowchart.
 Excessive use of connectors in a flowchart may confuse the programmers.

PSUDO CODE
Pseudo code only focuses on the logic of the program.
 Pseudo code does not have any specific syntax, we can write it in general English language.
 Pseudo code helps the programmer understand the basic logic of the program.
 Once we write a pseudo code, a programmer can select any programming language to write
the source code of program.

Rules for writing Pseudo code


 Instruction or operation code in a pseudo code statement must be kept all capitalized;
 Example: READ (specifying input operation), PRINT (specifying print command) etc.
 The ending of looping and decision-making constructs must be labelled appropriately with
corresponding “END” keywords.
 The pseudo code instructions must be properly indented just like the statements are
indented in a computer program.
 Convoluted programming instructions must be avoided by writing simple and clear
instructions.

Advantages of Pseudo code


 It is easy to understand as it uses English phrases for writing program instructions.
 Developing program code using pseudo code is also easier in comparison to flowcharts.
 Modifying the pseudo code instructions are easier.
 The use of pseudo code works well for large program design.

Disadvantages of Pseudo code


 There is no standard format for developing a pseudo code. Therefore, it may become a
challenge to use the same pseudo code by different programmers.
 Since pseudo code does not use any kind of pictorial representations for program elements,
sometimes, it may become difficult to understand the program logic.
 Pseudo codes are at a disadvantage in comparison to flowcharts when it comes to
understanding the flow of program control.

Write an algorithm to find the average of marks obtained by a student in three subjects.
1. Start
2. Read the marks of three subjects from the user into marks1, marks2, marks3.
3. Calculate average = (marks1 + marks2 + marks3)/3
4. Display average marks
5. Stop

11
KMEC/I/PPS/Unit-1

Draw a flowchart to find the average of marks obtained by a student in three subjects.

Write an algorithm to find out whether a given number is even or odd.


1. Start
2. Read a number (num) from the user.
3. Check, if num%2==0
a. if True, then goto step 4.
b. if False, then goto step 5.
4. Display “num is an even number” and goto Step 6
5. Display “num is an odd number”
6. Stop
Draw a flowchart to find out whether a given number is even or odd.

Write an algorithm to find out whether a given number is prime or not.


1. Start
2. Read a number from the user (num)
3. Initialize looping counter i = 2
4. Repeat Step 5 while i < num
5. If remainder of num divided by i (num%i) is Zero then goto Step 6 else goto Step 4
6. Display “num is not a prime number” and break from the loop
7. If i = num then goto Step 8 Else goto Step 9
8. Display “num is a prime number”
9. Stop

12
KMEC/I/PPS/Unit-1

Draw a flowchart to find out whether a given number is prime or not.

13
KMEC/I/PPS/Unit-1

NUMBER SYSTEMS
There are four types of Number systems are used by computers:
1. Decimal system
2. Binary system
3. Octal system
4. Hexadecimal system

Decimal System
 It is base 10 number system, represented as (X)10.
 There are total of 10 symbols (0-9) used 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
 Each digit’s position represents a power of 10.
 The decimal system can be used to represent both the integer and floating point values.
 Floating point values are represented by using a dot (.) called decimal point.
Binary system
 The binary system is base 2, represented as (X)2.
 There are total of 2 symbols used in Binary system 0 &1.
 It is used by computers to represent data.
 Each digit’s position represents a power of 2.

Octal system
 The Octal system is base 8, represented as (X)8.
 Total of 8 symbols (0-7) are used in octal system 0, 1, 2, 3, 4, 5, 6, 7.
 Each digit’s position represents a power of 8.

Hexa Decimal system


 The Hexa Decimal system is base 16, represented as (X)16.
 Total of 16symbols used 0-9 and A-F. (i.e.) 0, 1, 2, 3, 4, 5, 6, 7,8,9,A,B,C,D,E,F.
 Here A-10, B-11, C-12, D-13, E-14, F-15.
 Each digit’s position represents a power of 16.

NUMBER SYSTEM CONVERSION


The following conversions can be done:
1. Decimal to Binary
2. Decimal to Octal
3. Decimal to Hexa Decimal
4. Binary to Decimal
5. Binary to Octal
6. Binary to Hexa Decimal
7. Octal to Decimal
8. Octal to Binary
9. Octal to Hexa Decimal
10. Hexa Decimal to Decimal
11. Hexa Decimal to Binary
12. Hexa Decimal to octal

14
KMEC/I/PPS/Unit-1

Decimal to Binary
Here we need to divide the decimal number with 2 continuously until, the quotient reaches to
0 and record the remainder every time we divide it.
Example: Convert the Decimal value 37 to Binary value.
2 37 Remainder We need to write the remainders from bottom to top.
2 18 1 (37)10=(100101)2
2 9 0
2 4 1
2 2 0
2 1 0
0 1
Decimal to Octal
Here we need to divide the decimal number with 8 continuously until, the quotient reaches to
0 and record the remainder every time we divide it.
Example: Convert the Decimal value 37 to Octal value.
8 37 Remainder We need to write the remainders from bottom to top.
8 4 5 (37)10=(45)8
0 4
Decimal to Hexa Decimal
Here we need to divide the decimal number with 8 continuously until, the quotient reaches to
0 and record the remainder every time we divide it.
Example: Convert the Decimal value 92 to Binary value.
16 92 Remainder We need to write the remainders from bottom to top.
16 5 12 Note: Here the remainders are 12 and 5.
0 5 But in Hexa decimal 12 can be represented as C.
Hence (92)10=(5C)16
Binary to Decimal Conversion
Convert the binary value (110) to Decimal value.
=(1*22) + (1*21) + (0*20)
=(1*4) + (1*2) + (0*1)
=4 + 2 + 0
=6.
110 in binary represent to 6 in decimal.
Binary to Octal conversion
To convert a binary number to octal number we need to group of 3 bits from the right side.
Hence, a group of 3 bits ranges from 000 to 111 represents 0-7 as shown below.
0 - 000 2 - 010 4 - 100 6 - 110
1 - 001 3 - 011 5 - 101 7 - 111
Example_1: 110001
We can group 3 bits from right, hence we divide them into (110) (001).
1106 and 0011.
Hence , (110)2 = (61)8

15
KMEC/I/PPS/Unit-1

Note: If the left most group does not have 3 bits then we prefix 0’s to the left over bits in that
group so that it will become a group of 3.
Example_2: Convert the binary number (1101101)2 to Octal number.
Group 3 bits from the right side: (1) (101)(101).
The left most group has only one bit, hence we need to prefix 2 bits of 0’s, to make it a group
of 3-bits.
Therefore, (001) (101) (101) hence, 0011, 1015, 1015
Hence (1101101)2 = (155)8

Binary to Hexa-Decimal conversion


To convert a binary number to Hexa-Decimal number we need to group of 4 bits from the
right side. The Hexa-Decimal values are ranging from 0-9 and A-F.
Hence, a group of 4 bits ranges from 0000 to 1111 represents 0-F as shown below.
0 - 0000 4 - 0100 8-1000 C-1100
1 - 0001 5 - 0101 9-1001 D-1101
2 - 0010 6 - 0110 A-1010 E-1110
3 - 0011 7 - 0111 B-1011 F-1111
Example_1: 10110001
We can group 4 bits from right, hence we divide them into (1011) (0001).
1011B and 00011.
Hence , (10110001)2 = (B1)16

Note: If the left most group does not have 4 bits then we prefix 0’s to the left over bits in that
group so that it will become a group of 4.
Example_2: Convert the binary number (1101101)2 to Hexa-Decimal number.
Group 4 bits from the right side: (110)(1101).
The left most group has only 3 bits, hence we need to prefix 1 bit of 0’s, to make it a group of
4-bits.
Therefore, (0110)(1101) Hence 01106, 1101D
Hence (1101101)2 = (6D)16
Octal to Decimal Conversion
To convert from octal to decimal system, we need to multiply each digit with powers of 8.
Example: Let the octal number be (354)8.
=(3*82) + (5*81) + (4*80)
=(3*64) + (5*40) + (4*1)
=192 + 200 + 4
=396.
Answer: (354)8 = (396)10

Octal to Binary conversion


To convert from octal to binary, we need to write the 3-bit binary value for each octal digit.
Example: Convert (354)8 to binary value.
(3)8 – 011 (5)8 101 (4)8 100
Answer: (354)8 = (011101100)2

16
KMEC/I/PPS/Unit-1

Hexa Decimal to Decimal conversion


To convert from octal to decimal system, we need to multiply each digit with powers of 16.
Example: Let the hexa decimal value be (45F) 16
=(4*162) + (5*161) + (F*160)
=(4*256) + (5*16) + (15*1)
=1024 + 80 + 15
=1119.
Answer: (45F)16 =(1119)10.

Hexa Decimal to Binary conversion


To convert from octal to binary, we need to write the 3-bit binary value for each octal digit.
Example: Convert (35F)16 to binary value.
(3)16  0011 (5)16  0101 (F)16  1111
Hence (35F)16 = (001101011111)2
Octal to Hexa Decimal conversion
We need to follow two steps to convert from octal to hexa decimal:
1. Convert Octal to Binary
2. Convert Binary to Hexa decimal
Example: Convert octal value (354)8 to Hexa Decimal.
Step_1: Convert (354)8 to binary value.
(3)8  011 (5)8  101 (4)8  100
(354)8 = (011101100)2
Note: We can delete the leading 0’s, hence the answer is: (354)8 = (11101100)2
Step_2: Convert (1110 1100)2 to Hexa decimal.
Group 4 bits from the right side: (1110)(1100).
Therefore, (0110)(1101) hence 1110 E & 1100  C
Hence (11101100)2 = (EC)16
Final answer: (354)8 = (EC)16

Hexa Decimal to Octal conversion


We need to follow two steps to convert from octal to hexa decimal:
1. Convert Hexa decimal to Binary
2. Convert Binary to octal decimal
Example: Convert Hexa Decimal value (EC)16 to Octal.
Step_1: Convert (EC)16 to binary value.
(E)16  1110 (C)16  1100
(EC)16 = (11101100)2
Step_2: Convert (11101100)2 to Octal.
Group 3 bits from the right side: (11) (101) (100).
Add a 0 bit to the leftmost group to make it group of 3 bits.
Therefore, (011) (101) (100)
011- 3, 101-5, 100-4 Hence (11101100)2= (354)8
Final answer: (EC)16 = (354)8

17
KMEC/I/PPS/Unit-1

INTRODUCTION TO C LANGUAGE
C Language is one of the most popular computer languages.
It is a structured, high-level, machine independent language.
It allows software developers to develop programs without worrying about the hardware
platforms where they will be implemented.
HISTORY OF C LANGUAGE
 In the early 1960s ALGOL language was introduced. ALGOL was the first computer
language to use a block structured programming.
 In 1967, BCPL (Basic Combined Programming Language) was developed by Martin
Richards for writing system software.
 In 1970, B language was created by Ken Thompson using many features of BCPL. B was
used to create early versions of UNIX operating system.
 Both BCPL and B were “typeless” system programming languages.
 C Language was developed by Dennis Ritchie at the Bell Laboratories in 1972, evolving
from the features of ALGOL, BCPL and B.
 C also introduces many new powerful concepts such as data types.
 C was developed along with UNIX operating system in Bell Laboratories and almost entire
code of UNIX OS written in C. Today UNIX is the most popular network operating system.
 In 1978, Brian Kerningham and Dennis Ritchie published the book ‘The C Programming
Language’.
 In 1989, ANSI committee approved a version of C, called ANSI C.
 In 1990, International Standards Organization (ISO) approved A version of C called C89.
 In 1999, the C99 standard was released.
Note:
1. C++ language developed fully based on C.
2. Java language created by Sun Microsystems and it modeled on C and C++.

STRUCTURE OF C PROGRAMS
A C program may contain following sections:
1. Documentation section
2. Link section
3. Definition section
4. Global declaration section
5. main() function section
6. Sub program section
 Documentation section consists of a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to use later.
 Link section provides instructions to the compiler to link functions from the system library.
 Definition section defines all symbolic constants.
 Global Declaration Section we declare global variables that are used in more than one
function. This section also declares all the user-defined functions.

18
KMEC/I/PPS/Unit-1

 main() section: Every C program must have one main() function. main() contains two
parts, variable declaration part and executable part. Declaration part declares all the
variables used in the executable part. Opening and the closing braces { } are used to define
the scope of main( ). The program execution begins at the opening brace and ends at the
closing brace. All statements in declaration and executable parts end with a semicolon (;).
 Subprogram section contains all the user-defined functions that are called in the main().
Note: main( ) section is mandatory and all remaining sections are optional.

CHARACTER SET
The characters in C are grouped into the four categories:
1. Letters: Upper case (A-Z) , Lower case (a-z)
2. Digits: 0-9 (0,1,2,3,4,5,6,7,8,9)
3. Special characters: & ! @ # $ % ^ * ( ) + - / * . etc.
4. White spaces: Blank space, horizontal tab, new line etc.

C TOKENS
In a C program the smallest individual units are known as tokens. C has six types of tokens:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators

KEYWORDS
A keyword in C language have fixed meaning. There are 32 keywords in C language.
 Keywords serve as basic building blocks for program statements.
 All keywords must be written in lowercase.
 We cannot use keywords for variable names.
auto const double float int short struct unsigned
break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while
IDENTIFIERS
Identifiers refer to the names of variables, functions and arrays.
These are user-defined names and consist of a sequence of letters, digits, underscore symbol.
Rules for defining an identifier:
1. First character must be an alphabet (or underscore).
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. We cannot use a keyword as identifier.
5. Identifier must not contain white space.
6. The underscore character is used to connect to words to make it a single name. Example:
first_name, last_name. Date_of_birth, string_length() etc.

19
KMEC/I/PPS/Unit-1

CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a program.
1. Integer constants
2. Real constants
3. Single character constants
4. String constants

Integer constants
An integer constant refers to a sequence of digits.
There are three types of integers constants: Decimal, Octal, Hexadecimal integer.
 Decimal: 0,1,2,-15,17,-324,65535 etc.
 Octal: An octal integer constant consists of any combination of digits from the set 0 through
7, with a leading 0. Example: 037,0, 0435, 0551, etc.
 Hexadecimal: A sequence of digits preceded by 0x or 0X is considered as hexadecimal
integer. 0X2, 0x9F, 0Xbcd, 0x, etc.

Real constants
These are the numbers with a decimal point or in exponential form.
 They are also called as Floating point constants.
 Example: 0.0083, –0.75, 435.36, +247.0 etc.
 A real number can be expressed in exponential (or scientific) notation.
 Example: 3.14, -1.05, 2.5e3 (which means 2.5 × 10³).
 Note: In 2.5e3, 2.5 is called mantissa and 3 is called exponent.

Single Character Constants


It contains a single character enclosed within a pair of single quote marks.
 Example: ‘5’ ‘X’ ‘;’ ‘ ’
 Note: Anything that are enclosed with in a single quote becomes a character, hence '5' is
not a number it is an ascii character.
 Each character constant is associated with an ASCII value.

String constants
A string constant is a sequence of characters enclosed in double quotes.
 The characters may be letters, numbers, special characters and blank space.
 Example: “Hello!” “2025” “Good Morning” “What is your name?” “5+3” “X”
 String constants may contain one more characters inside double quotes.
 Hence "X" is a string constant, not single character constant.

Backslash Character Constants


Backslash character constants are used in output functions.
 Backslash constants also called Escape sequences.
 Each character is preceded by backslash( \ )
 Example: '\n' : New line, '\t : horizontal tab, ‘\v’ : vertical tab, ‘\0’ : null etc.

20
KMEC/I/PPS/Unit-1

DATA TYPES
C language is rich in its data types.
Data types in C is divided into 3 categories:
1. Primary data types
2. Derived data types
3. User-defined data types

Primary data types


C compilers support five fundamental data types:
1. int
2. float
3. char
4. double
5. void
Note:
1. C also supperts extension to fundamental datatypes such as long int and long double.
2. int, float, char, double, void are keywords in C.

int datatype
int represents integers (i.e. whole numbers) that consists of positive, negative numbers & 0.
 Memory size of int type is either 16 bits or 32 bits depends upon the computer word length.
 Values range in 16 bit word machine : –32768 to +32767 (–215 to +215–1)
 Values range in 32 bit word machine : -2,147,483,648 to 2,147,483,647 (–231 to +231–1)
 C has divided int datatype to three classes based on size: short, int, long int.
 We can take above datatype values as both signed and unsigned values.
Note: Unsigned values are starts from 0, where signed values have both positive and negative
and zero.
int type and their range of values are in 16 bit computer is given below:
Type Size (bits) Range in numbers Range in 2x
int or signed int 16 –32,768 to 32,767 –215 to 215–1
unsigned int 16 0 to 65535 0 to 216–1
short int or signed short int 8 –128 to 127 –27 to 27–1
unsigned short int 8 0 to 255 0 to 28–1
long int or signed long int 32 –2,147,483,648 to 2,147,483,647 –231 to +231–1
unsigned long int 32 0 to 4,294,967,295 0 to +232–1

float datatype
float datatype or floating point datatype consisits of real numbers.
 Memory size of float values 32 bits.
 Floating point numbers have 6 digits of precision. Ex: 65.547814
 Floating point numbers are categorized into 3 types: float, double and long double.
 C has divided float datatype to three classes based on size: float, double, long double.
 double is an extension of float type, takes memory size of 64 bits with 14 digit precision.
 long double is an extension of double, takes memory size of 80 bits.

21
KMEC/I/PPS/Unit-1

Type Size (bits) Range in numbers Range in 2x


float 32 3.4E–38 to 3.4E+38 –215 to 215–1
double 64 1.7E–308 to 1.7E+308 0 to 216–1
long double 80 3.4E–4932 to 1.1E+4932

char datatype
char datatype is used to represent a single characters.
 char values are enclosed with a single quote (' '). Ex: 'a', 'Z', '1', '$'.
 char data takes 8 bits to store the data. signed or unsigned are also applied to char.
Type Size (bits) Range in numbers Range in 2x
char or signed char 8 -128 to 127 –27 to 27–1
unsigned char 8 0 to 255 0 to 28–1
void datatype
The void type has no values. This is used to specify the type of functions.
 The type of a function is said to be void when it does not return any value to the calling
function.
 void type is also called as a generic type, meaning that it can represent any of the other
standard types.

VARIABLES
 Variable is a name of memory location used to store a data.
 Variable values can be changed during execution of a program.
 Variable names may consist of letters, digits, and the underscore(_) character.
Example: age=18, ch = 'A', PRICE=10.25.
Rules for defining a variable name:
1. Variable name must begin with a alphabet or underscore.
2. The maximum length of variable is 31 characters.
3. Variable name should not be a keyword.
4. White space is not allowed.
5. C is a case sensitive language, Uppercase and lowercase are considered as different
characters.(i.e) The variable Total is not the same as total or TOTAL.
6. Except underscore (_) no special character is allowed in the variable name.

Example_1: ch='A', stock_price=27.50, marks1=85, are valid varible names.


Example_2: 1stmarks=56, 1a=78.5 are not valid varible names.

Variable Declaration
A variable must be declarated before they are used in the program.
variable declartion tells the compiler about the variable name and specifies its datatype.
Syntax: datatype variable_names;
Example: int i;
int count,age;
float price, height, weight;
char ch;
While declaring multiple variables we need to seperate them by commas.

22
KMEC/I/PPS/Unit-1

Defining a Variable or Variable Initialization


Assigning a value to a variable is called defining a variable.
The memory is allocated to variable only after we assign a value to a variable.
Syntax: datatype variable_name=value;
Ex: int a=10;
The value 10 is stored in the variable a, and the memory size of 16 bits (2Bytes) is allocated to
the variable.
We can define multiple variables by separating them by commas.
Example: int x=10, y=20, z=30;

INPUT / OUTPUT STATEMENTS


scanf() and print() are used for input and output statements respectively.
 They are formatted input / output functions we arrange the data in a particular format.
 print() and scanf() are defined in stdio.h file, hence we need write #include<stdio.h> to
use the functions.

scanf()
It is an input function used to take input data from the user.
Syntax: scanf("format string", &variable1,&variable2,...);
Example: scanf("%d%f",&count,&price);
 scanf() used & operator called address operator.
 & operator is prefixed with variable_name, so that the value can be stored at the variable’s
memory location.
 Format string consists of symbols prefixed with %, that specifies the data type of variable.
The format specifiers for different datatypes are given below:
Format specifier Datatype
%d int
%f float
%c char
%s string
%i decimal, octal, hexa decimal
%u unsigned integer
Example: scanf("%d%f",&count,&price);
 In the above statement %d represents count is an int value, %f represents price is an float
value.
 The memory is allocated after we assign the values to count and price.
 We can assign 5 and 90.50 as count and price values.
Note: The number of format specifiers must match with the variable names.

printf()
It is an output function used to display output on the screen.
print() is used to display the values inside the variables and also used to print a message on the
output screen.
Syntax: printf("format string", variable1,variable2,...);

23
KMEC/I/PPS/Unit-1

Example: printf("%d%f",count,price);
 The format string consists of symbols prefixed with %, that specifies the data type of
variable.
 The format specifiers and variable names are separated by commas.
 The number of format specifiers and variable names should be matched.
Example: printf("%d%f", count, price);
The above statement prints the values of count and price on the output screen.
We can print a messages on the output screen using print( ).
Example: printf("Programming for Problem Solving")
Output: Programming for Problem Solving

We can also print the message as well as display the variable name combined in the print
statement.
Example: printf("Total products=%d Total price=%f", count, price);
Output: Total products=5 Total price=90.50

COMMENTS
Comments are used in a program to enhance its readability and understanding.
 Comment lines are not executable statements.
 Comments are used to describe the statements.
Types of comments:
1. Single line comments
2. Multi line comments

Single line comment


Before writing a single line comment, we need to use two double slashes (//) and write the
comment.
Example: i=10 //i is a variable stores the value 10.

Multi line comments


When we want to write comments more than one line then we need to write the comments in
between /* ... */.
Anything that written between /* and */ is ignored by the compiler and treated as comment.
Multi line comments are used to explain the logic of the code.
Example:
/*
if n%2 is equal to zero, then compiler prints "Even"
or else Compiler prints "Odd"
*/

OPERATORS AND EXPRESSIONS


An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Operators are used in programs to manipulate data and variables.
They usually form a part of the mathematical or logical expressions.

24
KMEC/I/PPS/Unit-1

Expressions consist of values and operators, and they can always evaluate down to a single
value.
C operators can be classified into a following categories:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Increment and decrement operators
7. Conditional operators
Arithmetic Operators
Arithmetic operators are used for performing mathematical calculations.
Example: The operations are performed between operands 10 & 3.
Operator Name Example Description
+ Addition 10+3 13 It adds two operands
- Subtraction 10-3 7 It subtracts two operands
* Multiplication 10*3 30 It multiplies two operands
/ Division 10/3 3 It return quotient value after division
% Modulus 10%3 1 It return the remainder of division
Note:
1. For integer value division, / operator returns quotient value. Example: 10/3=3
2. For floating point values division, then / operator returns the floating value after division.
Example: 7.0/2.0=3.5
3. In division operation, if the denominator is 0, then we will get division by zero error.
4. % operator cannot be used with real values. Ex: 9.5%2  Error.

Relational operators
Relational operators also called as comparison operators.
They are used to compare values and returns either True or False based on the comparison.
Note: The output of relational operator is either 0 or 1. 1 means True and 0 means False.
Operator Name Example Description
> Greater than 10>7 Returns True if a>b else returns False
< Less than 10<7 Returns True if a<b else returns False
>= Greater than or 10>=7 Returns True if a>=b else returns False
equal to
<= Less than or 10<=7 Returns True if a<=b else returns False
equal to
== Equals to 10==10 Returns True if a is equals to b else returns False
!= Not equals to 10!=7 Returns True if a is not equals to b else returns False

Logical Operators
Logical operators are used to combine logical expressions and evaluate complex conditions.
There are 3 main logical operators: logical and ( && ), logical or ( || ), logical not( ! ).

25
KMEC/I/PPS/Unit-1

 The logical operators && and || are used when we want to test more than one condition and
make decisions.
 The output of logical expression is 0 or 1. 1 means True and 0 means False.
&& : It returns True only if all expressions are true. Otherwise, it returns False.
Example: a=10 b=20 c=15
a>b && a<c  0 && 1 returns 0 (i.e. False)
a<b && a<c  1 && 1 returns 1 (i.e. True)
|| : It returns True if atleast one of the expressions is true. Returns False only if all expressions
are false.
a>b || a<c  0 || 1 returns 1
a>b || a>c  0 || 0  returns 0
! : used to negate a logical expression. It reverses the value of the expression. If the expression
is True (i.e. 1), the not operator returns False (i.e. 0).
If the expression is False (i.e. 0) , the not operator returns True (i.e. 1).
Example: 10
!0 1
Bitwise operators
Bitwise operations performed on integer values only. We cannot apply bitwise operators to
float and double values.
At first the integer values will be converted into binary value and then apply bitwise operators
on each bit of a binary value. Finally we get the output result in the form of integer only.
There are 6 bitwise operators in python:

Operator Name Example Description


& Bitwise And 4&5 It return 1 when both bits are 1 else 0.
| Bitwise Or 4|5 It return 1 when at least one bit is 1 else 0.
^ Bitwise XOR 4^5 It returns 1 if the bits are different, if bits are same
then return 0.
>> Bitwise Right 10 >> 1 Shifts the bits of the number to the left and fills 0 on
Shift voids right as a result.
<< Bitwise Left 10 << 1 Shifts the bits of the number to the right and fills 0
Shift on voids left.

Assignment Operators
The assignment operator (=) is used to assign value to the variable or we can assign the result
of expression to a variable.
Example_1: a=10
Example: a=(10*3)+5.
The following is the list of all possible compound assignment operators in C.
+= -= *= /= %=
Consider a = 10 then observe the result of following operations:
Operator Statement Meaning Result
+= a+=2 a=a+2 a=12

26
KMEC/I/PPS/Unit-1

-= a-=2 a=a-2 a=8


*- a*=2 a=a*2 a=20
/= a/=2 a=a/2 a=5
%= a%=2 a=a%2 a=0

Increment and Decrement Operators


C allows increment (++) and decrement (--) operators.
Increment and decrement operators are unary operators and they require variable as their
operands.
++ adds 1 to the operand whereas – subtract 1 from the operand.
Example_1: a++  a=a+1
Example_2: a--  a=a-1
We can use ++ and -- operators before and after an operand.
If we use a++ and ++a, the result is same. Simillarlly, a-- and --a will get same value.

Operator Statement Name Meaning Let a=10


++ a++ Post increment a=a+1 a=11
-- a-- Post decrement a=a-1 a=9
++ ++a Pre increment a=a+1 a=11
-- --a Pre decrement a=a-1 a=9

We need to observe that pre-increment and post increment is not same when we use different
variables in the left side and right side of an expression.
Let a=10 and b is a variable. Consider the following cases.
Case_1: b=a++
The above statement using post increment of a.
In post increment, first the actual value a is stored into b, then increment of a is done.
Step_1: b=a  b=10
Step_2: a=a+1  a=11
Hence the new values are: a=11 and b=10.

Case_2: b=++a
The above statement using pre increment of a.
In pre increment, first we increment the value of a (i.e. a+1) then the incremented value is
stored into b.
Step_1: a=a+1  a=11
Step_2: b=a  b=11
Hence the new values are: a=11 and b=11.

Case_3: b=a--
The above statement using post decrement of a.
In post decrement, first the actual value a is stored into b, then decrement of a is done.
Step_1: b=a  b=10
Step_2: a=a-1  a=9

27
KMEC/I/PPS/Unit-1

Hence the new values are: a=9 and b=10.

Case_4: b= --a
The above statement using pre decrement of a.
In pre decrement, first we decrement the value of a (i.e. a-1) then the decremented value is
stored into b.
Step_1: a=a-1  a=9
Step_2: b=a  b=9
Hence the new values are: a=9 and b=9.
Summary above cases are given in the table: a=10 and b
Operator Statement Name a b
++ b=a++ Post increment a=11 b=10
-- b=a-- Post decrement a=9 b=10
++ b=++a Pre increment a=11 b=11
-- b=--a Pre decrement a=9 b=9

Conditional Operator or Ternary operator (?:)


A ternary operator is a pair of “?" and ":”.
It is used as alternative to if-else construct.
Syntax: variable=exp1 ? exp2 : exp3
where exp1, exp2, and exp3 are expressions.
Example: x = (a > b) ? a : b;
In the above example:
a>b is exp1
a is exp2
b is exp3
 If exp1 (i.e. a>b) is true, then exp2 (i.e. a) is evaluated and it is stored into variable (x=a).
 If exp1 (i.e. a>b) is false, then exp3 (i.e. b) is evaluated and it is stored into variable (x=b).

x = (a > b) ? a : b; can be written alternatively as:


if (a > b)
x = a;
else
x = b;
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
Operator precedence decide which operator is evaluated first when multiple operators are
present in a single line of expression.
Operators with higher precedence are evaluated before those with lower precedence.
When operators have the same precedence, their associativity dictates the order of evaluation,
most operators have left-to-right associativity, except for a few like conditional and assignment
operators have right-to-left associativity.
Precedence rules decides the order in which different operators are applied.
Associativity rule decides the order in which multiple occurrences of the same level operator
are applied.

28
KMEC/I/PPS/Unit-1

Precedence
Operators Description Associativity
Level
() Function call
[] Array subscript
-> Structure access
1 Left to Right
. Structure access
++ Postfix increment
-- Postfix decrement
++ Prefix increment
-- Prefix decrement
+ (unary) Unary Plus
- (unary) Unary Minus
! Logical Not
2 ~ Bitwise Not Right to Left
*
Pointer Dereference
(dereference)
& (address) Address Of
sizeof Size Of Operator
(type) Type casting Ex: (int)6.5.
* Multiplication
3 / Division Left to Right
% Modulus
+ Addition
4 Left to Right
- Subtraction
<< Bitwise Shift Left
5 Left to Right
>> Bitwise Shift Right
< Less than
<= Less than or equal to
6 Left to Right
> Greater than
>= Greater than or equal to
== Equals to
7 Left to Right
!= Not equals to
8 & Bitwise AND Left to Right
9 ^ Bitwise XOR Left to Right
10 | Bitwise OR Left to Right
11 && Logical AND Left to Right
12 || Logical OR Left to Right
13 ?: Ternary (conditional) Right to Left
=, +=, -=, *=,
/=, %= , <<=,
14 Assignment operators Right to Left
>>=, &=, ^=,
|=
15 , Comma operator Left to Right

29
KMEC/I/PPS/Unit-1

Examples on Arithmetic Operator Precedence


Example_1: 3+4*5
Answer: 3+4*5
3+20
23
 Here * is executed first because it has higher precedence than +.
 First, 4*5=20 is executed, followed by 3+20=23 is executed.
Example_2: (3+4)*5
Answer: (3+4)*5
7*5
35
 Here () having higher precedence than *.
 Hence first expression inside paranthesis (3+4) is executed first, then * is executed.
Example_3: 6*4/2
Answer: 6*4/2
24/2
12
 Here both * and / have same precedence level, so we check the associativity.
 Arithmetic operations have left to right associativity, hence the operator which comes on
the left will be evaluated first.
 Therefore * operation (6*4) is evaluated then / operation (24/2) is evaluated.

Example_4: 6/4*2
Answer: 6/4*2
1*2
2
 Here both * and / have same precedence level, so we check the associativity.
 Arithmetic operations have left to right associativity, hence the operator which comes on
the left will be evaluated first.
 Therefore / operation (6/4) is evaluated then * operation (1*2) is evaluated.

Example_5: 2+6/3*4
Answer: 2+6/3*4
2+2*4
2+8
10
 Here / and * have higher precedence than +. Hence / and * operations will be evaluated
before +.
 / and * have same precedence level, hence left to right associativity is applied.
 Hence first (6/3=2) is evaluated, then (2*4=8) is evaluated, finally 2+8=10 is evaluated.

Example_6: (2+6)/3*4
Answer: 2+6/3*4
2+2*4
2+8
10

30
KMEC/I/PPS/Unit-1

 Here / and * have higher precedence than +. Hence / and * operations will be evaluated
before +.
 / and * have same precedence level, hence left to right associativity is applied.
 Hence first (6/3=2) is evaluated, then (2*4=8) is evaluated, finally 2+8=10 is evaluated.

Example_6: (2+6)/3*4
Answer: (2+6)/3*4
8/3*4
2*4
8
Explanation:
 Here () will have higher precedence than / and *.The operations inside () is executed first.
 / and * have same precedence level, hence left to right associativity is applied.
 Hence first (2+6=8) is evaluated, then (8/3=2) is evaluated, finally 2*4=8 is evaluated.
TYPE CASTING OR TYPE CONVERSION
Changing the data type of a variable or expression from one type to another is called Type
Casting.
There are two types of Type casting:
1. Implicit Type Casting
2. Explicit Type Casting

Implicit Type Casting


 If the operands are of different types, then the ‘lower’ datatype is automatically converted
to the ‘higher’ data type is called implicit type casting.
 This type casting is done by compiler.
The hierarchy of datatypes are given below:
long double > double > float > unsigned long int > long int > unsigned int > int > short >
char.
Example:
1. If one operand is short or char and other int then compiler automatically converts to int.
2. If one of the operands is double, the other will be converted to double and the result will be
double.
Note:
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long int to int causes dropping of the excess higher order bits.
Explicit Type Casting
The programmer manually changes the datatype of a variable or expression is called explicit
type casting.
Syntax: (datatype) expression
Example: (int) 5.2*2 = 10
The expression may be a variable name.
Example: f=1.5
(int)f--> 1
Examples:
Operation Result
x = (int) 9.8 X=9, it deletes fractional part ( .8)

31
KMEC/I/PPS/Unit-1

a = (int) 9.3/(int)3.6 A=3, it performs 9/3 by deleting .3 and .6.


Z=(int)x + y X value is converted to int and added to y

BASIC C PROGRAMS
Write a program to display the variable values on the output screen.
#include<stdio.h>
int main()
{
int a=10,b=20;
printf("a=%d b=%d",a,b);
}
output: a=10 b=20

Write a program to take input values from user and display them on the output screen.
#include<stdio.h>
int main()
{
int a,b;
printf("Enter a,,b values:");
scanf("%d%d",&a,&b);
printf("a=%d b=%d",a,b);
}
output:
Enter a,,b values:10
20
a=10 b=20
Write a program to find the area of Rectangle.
#include<stdio.h>
int main()
{
int length=5,breadth=3;
int area=length*breadth;
printf("Rectangle_Area:%d",area);
}
output: Rectangle_Area:15

Write a C program to find area of Rectangle. Take length & breadth input values from
user.
#include<stdio.h>
int main()
{
int length=5,breadth=3;
printf("Enter length and breadth values:")
scanf("%d%d",&length,&breadth);
int area=length*breadth;
printf("Rectangle_Area:%d",area);
}
output:
Enter length and breadth values:5
3

32
KMEC/I/PPS/Unit-1

Rectangle_Area:15

Write a C program to find perimeter of rectangle. Take length & breadth values from
user.
#include<stdio.h>
int main()
{
int l=5,b=3;
printf("Enter length and breadth values:");
scanf("%d%d",&l,&b);
int perimeter=2*(l+b);
printf("Rectangle_Perimeter:%d",perimeter);
}
output:
Enter length and breadth values:5
3
Rectangle_Perimeter:16

Write a C program to print the average of 3 marks.


(Note: This program needs Type casting)
#include<stdio.h>
int main()
{
int m1,m2,m3;
printf("Enter 3 subject marks:");
scanf("%d%d%d",&m1,&m2,&m3);
float avg; avg=(float)(m1+m2+m3)/3;
printf("Average:%f",avg);

}
output:
Enter 3 subject marks:6
4
4
Average:4.666667

Write a C program to find the area of circle.


#include<stdio.h>
int main()
{
int r;
printf("Enter radius of circle:");
scanf("%d",&r);
float area=3.1415*r*r;
printf("area=%f",area);
}
output:
Enter radius of circle:5
area=78.537498

33

You might also like