PPS Complete Notes
PPS Complete Notes
PPS Complete Notes
What is Computer?
Computer is an advanced electronic device that takes raw data as input from the user and processes these
data under the control of set of instructions (called program) and gives the result (output) and saves output
for the future use. It can process both numerical and non-numerical (arithmetic and logical) calculations.
A computer has four functions: Input
a. accepts data
b. processes data Processing
c. produces output Output
d. stores results Storage
Input (Data):
Input is the raw information entered into a computer from the input devices. It is the collection of letters,
numbers, images etc.
Process:
Process is the operation of data as per given instruction. It is totally internal process of the computer
system.
Output:
Output is the processed data given by computer after data processing. Output is also called as Result. We
can save these results in the storage devices for the future use.
Santosh kumar 1
Computer System
All of the components of a computer system can be summarized with the simple equations.
COMPUTER SYSTEM = HARDWARE + SOFTWARE+ USER
Generation of computer:
ARCHITECTURE OF COMPUTER
Santosh kumar 2
Input Devices: Those devices which help to enter data into computer system. Eg. Keyboad, Mouse,
Touchscreen, Barcode Reader, Scanner, MICR, OMR etc.
Bar code Reader MICR used in Bank OMR(Used for answer sheet evaluation)
Output Devices: Those devices which help to display the processed information. Eg. Monitor, Printer,
Plotter, Projector
Santosh kumar 3
Processor
Memory: It facilitates the remembrance power to computer system. It refers to the physical devices used to
store programs (sequences of instructions) or data (e.g. program state information) on a temporary or
permanent basis for use in a computer or other digital electronic device. The term primary memory is used
for the information in physical systems which are fast (i.e. RAM), as a distinction from secondary memory,
which are physical devices for program and data storage which are slow to access but offer higher memory
capacity. Primary memory stored on secondary memory is called virtual memory. Primary Memory can be
categorized as Volatile Memory & Non-Volatile Memory.
Volatile memory(RAM)
Volatile memory is computer memory that requires power to maintain the stored information. Most modern
semiconductor volatile memory is either Static RAM or dynamic RAM.
SRAM retains its contents as long as the power is connected and is easy to interface to but uses six
transistors per bit.
Dynamic RAM is more complicated to interface to and control and needs regular refresh cycles to prevent
its contents being lost. However, DRAM uses only one transistor and a capacitor per bit, allowing it to reach
much higher densities and, with more bits on a memory chip, be much cheaper per bit. SRAM is not
worthwhile for desktop system memory, where DRAM dominates, but is used for their cache memories..
Santosh kumar 4
Examples of non-volatile memory are flash memory and ROM/PROM/EPROM/EEPROM memory (used for
firmware such as boot programs).
Cache Memory:
Cache memory is random access memory (RAM) that a computer microprocessor can access more quickly
than it can access regular RAM. As the microprocessor processes data, it looks first in the cache memory
and if it finds the data there (from a previous reading of data), it does not have to do the more
timeconsuming reading of data from larger memory. It is of two types- L1 cache is on the same chip as the
microprocessor. L2 is usually a separate static RAM (SRAM) chip.
Secondary Memory:
A. Hard Disk (Local Disk)
B. Optical Disks: CD-R, CD-RW, DVD-R, DVD-RW
C. Pen Drive
D. Floppy Disks
F. Memory Cards
G. External Hard Disk
H. Blu Ray Disk
Blu-Ray Disk:
Blu-ray (not Blue-ray) also known as Blu-ray Disc (BD), is the name of a new optical disc format.
The format offers more than five times the storage capacity of traditional DVDs and can hold up to 25GB on
a single-layer disc and 50GB on a dual-layer disc. While current optical disc technologies such as DVD,
DVD±R, DVD±RW, and DVD-RAM rely on a red laser to read and write data, the new format uses a
blueviolet laser instead, hence the name Blu-ray.
Units of Memory:
Santosh kumar 5
1 Gega Byte = 1024 MB= 210 MB
1 Tera Byte = 1024 GB= 210 GB
1 Peta Byte =1024 TB= 210 TB
1 Exa Byte =1024 PB= 210 PB
1 Zetta Byte = 1024 EB= 210 EB
1 Yotta Byte = 1024 ZB= 210 ZB
Booting
The process of loading the system files of the operating system from the disk into the computer memory to
complete the circuitry requirement of the computer system is called booting. Types of Booting:
There are two types of booting:
• Cold Booting: If the computer is in off state and we boot the computer by pressing the power switch
‘ON’ from the CPU box then it is called as cold booting.
• Warm Booting: If the computer is already ‘ON’ and we restart it by pressing the ‘RESET’ button from
the CPU box or CTRL, ALT and DEL key simultaneously from the keyboard then it is called warm booting.
Types of Computer
On the basis of working principle
a) Analog Computer
An analog computer is a form of computer that uses continuous physical phenomena such as electrical,
mechanical, or hydraulic quantities to model the problem being solved.
Eg: Thermometer, Speedometer, Petrol pump indicator, Multimeter
b) Digital Computer
A computer that performs calculations and logical operations with quantities represented as digits, usually
in the binary number system.
Santosh kumar 6
On the basis of Size
a) Super Computer
The fastest type of computer. Supercomputers are very expensive and are employed for specialized
applications that require immense amounts of mathematical calculations. For example, weather
forecasting requires a supercomputer. Other uses of supercomputers include animated graphics, fluid
dynamic calculations, nuclear energy research, and petroleum exploration. PARAM, Pace & Flosolver
are the supercomputer made in india.
b) Mainframe Computer
A very large and expensive computer capable of supporting hundreds, or even thousands, of users
simultaneously. In the hierarchy that starts with a simple microprocessor (in watches, for example) at
the bottom and moves to supercomputers at the top, mainframes are just below supercomputers. In
some ways, mainframes are more powerful than supercomputers because they support more
simultaneous programs. But supercomputers can execute a single program faster than a mainframe.
c)
Mini Computer
A midsized computer. In size and power, minicomputers lie between workstations and mainframes. In
the past decade, the distinction between large minicomputers and small mainframes has blurred,
however, as has the distinction between small minicomputers and workstations. But in general, a
minicomputer is a multiprocessing system capable of supporting from 4 to about 200 users
simultaneously. Generally, servers are comes in this category.
d) Micro Computer
i. Desktop Computer: a personal or micro-mini computer sufficient to fit on a desk.
ii. Laptop Computer: a portable computer complete with an integrated screen and keyboard. It is
generally smaller in size than a desktop computer and larger than a notebook computer.
iii. Palmtop Computer/Digital Diary /Notebook /PDAs: a hand-sized computer. Palmtops have no
keyboard but the screen serves both as an input and output device. e) Workstations
Santosh kumar 7
A terminal or desktop computer in a network. In this context, workstation is just a generic term for a user's
machine (client machine) in contrast to a "server" or "mainframe."
Software
Software, simply are the computer programs. The instructions given to the computer in the form of a
program is called Software. Software is the set of programs, which are used for different purposes. All the
programs used in computer to perform specific task is called Software. Types of software
1. System software:
a) Operating System Software
DOS, Windows XP, Windows Vista, Unix/Linux, MAC/OS X etc.
b) Utility Software
Windows Explorer (File/Folder Management), Compression Tool, Anti-Virus Utilities, Disk
Defragmentation, Disk Clean, BackUp, WinZip, WinRAR etc…
c) Language Processors
Compiler, Interpreter and Assembler
2. Application software:
a) Package Software
Ms. Office 2003, Ms. Office 2007, Macromedia (Dreamweaver, Flash, Freehand), Adobe
(PageMaker,
PhotoShop)
b) Tailored or Custom Software
School Management system, Inventory Management System, Payroll system, financial system etc.
Operating system
Operating system is a platform between hardware and user which is responsible for the management and
coordination of activities and the sharing of the resources of a computer. It hosts the several applications
that run on a computer and handles the operations of computer hardware.
Santosh kumar 8
• Single User Systems: Provides a platform for only one user at a time. They are popularly
associated with Desk Top operating system which run on standalone systems where no user
accounts are required. Example: DOS.
• Multi User Systems:Provides regulated access for a number of users by maintaining a database of
known users.Refers to computer systems that support two or more simultaneous users. Another
term for multi-user is time sharing. Ex: All mainframes are multi-user systems. Example: Unix
• Multi-tasking and Single-tasking Operating Systems: When a single program is allowed to run at
a time, the system is grouped under the single-tasking system category, while in case the operating
system allows for execution of multiple tasks at a time, it is classified as a multi-tasking operating
system.
• Distributed Operating System: An operating system that manages a group of independent
computers and makes them appear to be a single computer is known as a distributed operating
system. Distributed computations are carried out on more than one machine. When computers in a
group work in cooperation, they make a distributed system.
UNIX: Pronounced yoo-niks, a popular multi-user, multitasking operating system developed at Bell Labs in
the early 1970s. UNIX was one of the first operating systems to be written in a high-level programming
language, namely C. This meant that it could be installed on virtually any computer for which a C compiler
existed.
LINUX: Pronounced lee-nucks or lih-nucks. A freely-distributable open source operating system that runs
on a number of hardware platforms. The Linux kernel was developed mainly by Linus Torvalds and it is
based on Unix. Because it's free, and because it runs on many platforms, including PCs and Macintoshes,
Linux has become an extremely popular alternative to proprietary operating systems.
Windows: Microsoft Windows is a series of graphical interface operating systems developed, marketed,
and sold by Microsoft.Microsoft introduced an operating environment named Windows on November 20,
1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces (GUIs).[2]
Microsoft Windows came to dominate the world's personal computer market with over 90% market share,
overtaking Mac OS, which had been introduced in 1984.The most recent client version of Windows is
Windows 7; the most recent server version is Windows Server 2008 R2; the most recent mobile version is
Windows Phone 7.5.
SOLARIS: Solaris is a Unix operating system originally developed by Sun Microsystems. It superseded
their earlier SunOS in 1993. Oracle Solaris, as it is now known, has been owned by Oracle Corporation
since Oracle's acquisition of Sun in January 2010.
BOSS: BOSS (Bharat Operating System Solutions) GNU/Linux distribution developed by C-DAC (Centre
for
Development of Advanced Computing) derived from Debian for enhancing the use of Free/ Open Source
Software throughout India. This release aims more at the security part and comes with an easy to use
application to harden your Desktop.
Mobile OS: A mobile operating system, also called a mobile OS, is an operating system that is specifically
designed to run on mobile devices such as mobile phones, smartphones, PDAs, tablet computers and other
handheld devices. The mobile operating system is the software platform on top of which other programs,
called application programs, can run on mobile devices.
Santosh kumar 9
• Android: Android is a Linux-based mobile phone operating system developed by Google. Android is
unique because Google is actively developing the platform but giving it away for free to hardware
manufacturers and phone carriers who want to use Android on their devices.
• Symbian: Symbian is a mobile operating system (OS) targeted at mobile phones that offers a
highlevel of integration with communication and personal information management (PIM)
functionality. Symbian OS combines middleware with wireless communications through an integrated
mailbox and the integration of Java and PIM functionality (agenda and contacts). The Symbian OS is
open for third-party development by independent software vendors, enterprise IT departments,
network operators and Symbian OS licensees.
LANGUAGE PROCESSORS: Since a computer hardware is capable of understanding only machine level
instructions, So it is necessary to convert the HLL into Machine Level Language. There are three Language
processors:
A. Compiler: It is translator which coverts the HLL language into machine language in one go. A Source
program in High Level Language get converted into Object Program in Machine Level Language.
B. Interpreter: It is a translator which converts the HLL language into machine language line by line. It
takes one statement of HLL and converts it into machine code which is immediately executed. It
eliminate the need of separate compilation/run. However, It is slow in processing as compare to
compiler.
C. Assembler: It translate the assembly language into machine code.
Microprocessor:
A microprocessor is a semiconductor chip, which is manufactured using the Large Scale integration (LSI) or
Very Large Scale Integration (VLSI), which comprises Arithmetic Logic Unit, Control unit and Central
Processing Unit (CPU) fabricated on a single chip.
Terminologies:
Registers: A register is a very small amount of very fast memory that is built into the CPU (central processing
unit) in order to speed up its operations by providing quick access to commonly used values. All data must be
represented in a register before it can be processed. For example, if two numbers are to be multiplied, both
numbers must be in registers, and the result is also placed in a register.
Bus:
A collection of wires through which data is transmitted from one part of a computer to another. You can think
of a bus as a highway on which data travels within a computer. When used in reference to personal
computers, the term bus usually refers to internal bus. This is a bus that connects all the internal computer
components to the CPU and main memory. All buses consist of two parts -- an address bus and a data bus.
The data bus transfers actual data whereas the address bus transfers information about where the data
should go. The control bus is used by the CPU to direct and monitor the actions of the other functional areas
of the computer. It is used to transmit a variety of individual signals (read, write, interrupt, acknowledge, and
so forth) necessary to control and coordinate the operations of the computer.
The size of a bus, known as its width, is important because it determines how much data can be transmitted
at one time. For example, a 16-bit bus can transmit 16 bits of data, whereas a 32-bit bus can transmit 32 bits
Santosh kumar 10
Clock speed: Also called clock rate, the speed at which a microprocessor executes instructions. Every
computer contains an internal clock that regulates the rate at which instructions are executed and
synchronizes all the various computer components. The CPU requires a fixed number of clock ticks (or clock
cycles) to execute each instruction. The faster the clock, the more instructions the CPU can execute per
second.
16 bit Microprocessor: It indicates the width of the registers. A 16-bit microprocessor can process data
and memory addresses that are represented by 16 bits. Eg. 8086 processor
32 bit Microprocessor: It indicates the width of the registers. A 32-bit microprocessor can process data
and memory addresses that are represented by 32 bits. Eg. Intel 80386 processor, Intel 80486
64 bit Microprocessor: It indicates the width of the registers; a special high-speed storage area within the
CPU. A 32-bit microprocessor can process data and memory addresses that are represented by 32 bits.
Eg.
Pentium dual core, core 2 duo.
128 bit Microprocessor: It indicates the width of the registers. A 128-bit microprocessor can process data
and memory addresses that are represented by 128 bits. Eg. Intel core i7
It is a 64-bit microprocessor instruction set, jointly defined and designed by Hewlett Packard and Intel, that
provides up to 128 general and floating point unit registers and uses speculative loading, predication, and
explicit parallelism to accomplish its computing tasks. By comparison, current 32-bit CISC and RISC
microprocessor architectures depend on 32-bit registers, branch prediction, memory latency, and implicit
parallelism, which are considered a less efficient approach in microarchitecture design.
Santosh kumar 11
PORTS: A port is an interface between the motherboard and an external device. Different types of port are
available on motherboard as serial port, parallel port, PS/2 port, USB port, SCSI port etc.
Serial port(COM Port): A serial port transmit data one bit at a time. Typically on older PCs, a modem,
mouse, or keyboard would be connected via serial ports. Serial cables are cheaper to make than parallel
cables and easier to shield from interference. Also called communication port.
Parallel Port (LPT ports): It supports parallel communication i.e. it can send several bits simultaneously.It
provides much higher data transfer speed in comparison with serial port. Also called Line Printer Port.
USB (Universal Serial Bus): It is a newer type of serial connection that is much faster than the old serial
ports. USB is also much smarter and more versatile since it allows the "daisy chaining" of up to 127 USB
peripherals connected to one port. It provides plug & play communication.
PS/2 Port : PS/2 ports are special ports for connecting the keyboard and mouse to some PC systems. This
type of port was invented by IBM
FireWire Port : The IEEE 1394 interface, developed in late 1980s and early 1990s by Apple as FireWire, is
a serial bus interface standard for high-speed communications and isochronous real-time data transfer. The
1394 interface is comparable with USB and often those two technologies are considered together, though
USB has more market share.
Infrared Port: An IR port is a port which sends and receives infrared signals from other devices. It is a
wireless type port with a limited range of 5-10ft.
Bluetooth: Bluetooth uses short-range radio frequencies to transmit information from fixed and mobile
devices. These devices must be within the range of 32 feet, or 10 meters for Bluetooth to effectively work. A
Bluetooth port enables connections for Bluetooth-enabled devices for synchronizing. Typically there are two
types of ports: incoming and outgoing. The incoming port enables the device to receive connections from
Bluetooth devices while the outgoing port makes connections to Bluetooth devices.
ASCII( American standard code for information interchange): ASCII code is most widely used
alphanumeric code used in computers. It is a 7- bit code, and so it has 27 =128 possible code groups. It
represents all of the standard keyboard characters as well as control functions such as Return & Linefeed
functions.
ISCII(American standard code for information interchange) : To use the Indian language on computers,
ISCII codes are used. It is an 8-bit code capable of coding 256 characters. ISCII code retains all ASCII
characters and offers coding for Indian scripts also.
Unicode: It is a universal coding standard which provides a unique number for every character, no matter
what the platform, no matter what the program, no matter what the language. Unicode version 3.1
represented 94,140 characters.
NUMBER SYSTEM:
Santosh kumar 12
These digits can represent any value, for example: 754.
The value is formed by the sum of each digit, multiplied by the base (in this case it is 10 because there are
10 digits in decimal system) in power of digit position (counting from zero):
Integer
45(10)->Χ(2)
45 / 2 22 1 1
22 / 2 11 0 01
11 / 2 5 1 101
5/2 2 1 1101
2/2 1 0 01101
1/2 0 1 101101
45(10)->101101(2)
Fractional Part
0.182(10)->Χ(2)
Santosh kumar 13
0.182 * 2 0.364 0 0.0
101101.0010111(2)->Χ(10) Index
150413120110.0-10-21-30-41-51-61-7
= 45.179688(10)
Santosh kumar 14
Table to remember
Decimal Binary Hexadecimal Octal
0 0 0 0
1 1 1 1
2 10 2 2
3 11 3 3
4 100 4 4
5 101 5 5
6 110 6 6
7 111 7 7
8 1000 8 10
9 1001 9 11
10 1010 A 12
11 1011 B 13
12 1100 C 14
13 1101 D 15
14 1110 E 16
15 1111 F 17
16 10000 10 20
Convert from decimal to octal Χ(10)->Χ(8)
Integer
45(10)->X(8)
45 / 8 5 5 55
/8 0 5 55
45(10)->55(8)
15
Fractional Part
0.182(10)->Χ(8)
Integer
45(10)->X(16)
16
Div Quotient Remainder Hex Number (Χ)
45(10)->2D(16)
Fractional Number
0.182(10)->Χ(16)
55.135136(8)->Χ(10)
5150.1-13-25-31-43-56-6
= 45.1663829(10)
2D.2E978D(16)->Χ(10)
21130.2-114-29-37-48-513-6
17
We multiply each digit
= 45.18199997(10)
Convert from binary to octal: For this conversion make the group of three digits from right to left before
decimal & left to right after decimal then assign the specific octal value. (Given in the table above)
110101000.101010(2)->X(8)
|| || || || ||
\/ \/ \/ \/ \/
110101000.101010(2)->650.52(8)
Convert from binary to hexadecimal: This conversion make the group of four digits from right to left
before decimal & left to right after decimal then assign the specific Hexadecimal value. (Given in the table
above) 110101000.101010(2)->X(16)
|4 | | 4| | 4| | 4| | 4|
|| || || || ||
\/ \/ \/ \/ \/
1 Α 8 . Α 8
110101000(2)->1Α8.Α8(16)
Convert from hexadecimal to octal and binary: In this conversion write the binary of specific digit. For
Octal three digit binary & for Hexadecimal four digit binary.
650.52(8)->X(2)
6 5 0 . 5 2
18
|| || || || ||
\/ \/ \/ \/ \/
650.52(8)->110101000.101010(2)
1Α8.Α8(16)->X(2)
1 Α 8 . Α 8
|| || || || ||
\/ \/ \/ \/ \/
Practice Session:
1. Which electronic device invention brought revolution in earlier computers?
Ans. Microprocessor
Ans. ROM
Ans. Software (programs or data) that has been written onto read-only memory (ROM). Firmware is a
combination of software and hardware. ROMs, PROMs and EPROMs that have data or programs
recorded on them are Firmware.
5. What do you mean by language processors? Why we need it? (Do yourself)
6. Give any example of hybrid computer in daily life.
Ans. In medical science- To measure the heart beat, blood pressure etc.
7. Can we think of a computer system without operating system? Justify your answer. (Do yourself)
8. Fifth generation of computer is a symbol of intelligence. Why?
Ans. Due to invention of robotics
9. Which is better for translator & why? Compiler or Interpreter. (Do yourself)
10. What do you mean by Defragmentation? (Do yourself) 11. What do you mean by RISC & CISC?
(Do yourself)
12. Which port a mouse should be connected?
19
Ans. PS/2 port
15. What is cache memory? (Do yourself) 16. Convert the followings:
i. 101001.0101 to decimal ii.
(236)8 to Binary iii.
(266)10 to Hexadecimal iv.
(AF2)16 to Binary
v. 0101110.1010110 to Hexadecimal
PROGRAMMING METHODOLOGY
Stylistic Guidelines:
Writing good program is a skill. This can be developed by using the following guidelines .
1. Meaningful Names for identifiers: A programmer to give the meaningful names to each section
of the program so that it can help him to identify the variable used for specific purpose. This
helps him to execute the right elements during the complex run of a program.
2. Ensure clarity of expression: Expression carry out the specified action. Thus they must be
clearly understood by the users. There should not be any compromise with the clarity of
expression.
3. Use of comments and indentations: Comments generally are used as the internal
documentation of a program . if comments are used in the program they will guide the program
while debugging and checking. While indentation is the proper way of writing to avoid the
confusion regarding the flow of program. These highlights nesting of groups of control
statements.
4. Insert blank lines and blank spaces: Blank lines should be used to separate long, logically
related blocks of code. Specifically Normally in programming the standard for the use of spaces
is to follow normal English rules. This means that: Most basic symbols in C++ (e.g., “=”, “+”,
etc.) should have at least one space before and one space after them.
5. Statements :Each statement should appear on a separate line. The opening brace following a
control statement such as if or while should appear on the line after the if or while, lined up with
the left of the control statement, and the closing brace should appear on its own line, lined up
with the left of the control statement. As an example, see the for loop in Figure 1. The opening
and closing braces for a function should be lined up in the same way. The statements within a
{_____} pair are indented relative to the braces.
20
Characteristics of a Good Program:
Following are the characteristics of a good program.
1. Effective and efficient: The program produces correct results and is faster, taking into account
the memory constraints.
2. User friendly: The program should be user friendly. the user should not be confused during the
program execution . The user should get correct direction and alerts when he is going through
the program.
3. Self documenting code: A good program must have self documenting code. This code will
help the programmer to identify the part of the source code and clarify their meaning in the
program.
4. Reliable: The good program should be able to cope up from any unexpected situations like
wrong data or no data.
5. Portable: The program should be able to run on any platform, this property eases the use of
program in different situations.
2. Design : In this phase of design a Model is developed which I look a like of a program . this
phase gives the face to the program. Outputs are designed in this phase.
3. Coding : In this stage the algorithm is translated into the program called source code using
some programming language.
4. Compile the program: Issue a compile command against source, and fix any compile errors
that arise.
5. Execute the program: An error free program after compilation is put to run to produce the
output. This phase is called run-time, the phase of program execution during which program
instructions are carried out.
Robustness:
Robustness is the ability of the program to bounce back an error and to continue operating within its
environment.
21
2. This is very useful for upkeep and maintenance.
2. Analyze the program. : analyzing the problem involves identifying the program specification
and defining each program’s minimum number of inputs required for output and processing
components.
3. Code program : This step is the actual implementation of the program. In this program
algorithm is translated into programming language. in this it is essential to decide which
technique or logical will be more appropriate for coding.
4. Test and Debug program.: Once the solution algorithm is coded the next step is to test and
debug the program. Testing is the process of finding errors in a program and debugging is
of correcting the errors. The developed program is put to test in different conditions and
verified at different level for its proper and efficient working.
************************
22
Introduction:
C is a general-purpose, high-level language that was originally developed by Dennis M.
Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the
DEC PDP-11 computer in 1972.
C is a general-purpose programming language used for wide range of applications from
Operating systems like Windows and iOS to software that is used for creating 3D movies programming is
highly efficient.
C Programming Data Types:
Data types simply refers to the type and size of data associated with variables and functions.
Structure of c program:
Example 1: C Output
#include <stdio.h> //This is needed to run printf() function. int
main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
• All valid C program must contain the main() function. The code execution begins from the start of
main() function.
• The printf() is a library function to send formatted output to the screen. The printf()function is
declared in "stdio.h" header file.
• Here, stdio.h is a header file (standard input output header file) and #include is a preprocessor
directive to paste the code from the header file.
• The return 0; statement is the "Exit status" of the program. In simple terms, program ends.
Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format string
matches the argument (test in this case), it is displayed on the screen.
Example 3: C Integer Input/Output
#include <stdio.h> int
main()
{
int test;
printf("Enter an integer: ");
scanf("%d",&test); printf("Number
= %d",test);
return 0;
}
Output:
The scanf() function reads formatted input from the keyboard. When user enters an integer, it is stored in
variable test. Note the '&' sign before test; & test gets the address of test and the value is stored in that
address.
When a character is entered in the above program, the character itself is not stored. Instead a numeric
value(ASCII value) is stored. And when we displayed that value using "%c" text format, the entered
character is displayed.
Example 5: C ASCII Code
25
Relational Operators ==, > , <, >=, <=, !=
Logical Operators &&, ||, !
Decision Statements:
Decision making is used to specify the order in which statements are executed.
Types:
1. if
2. if..Else
3. Nested if...else statement.
1. if statement:
if (test Expression)
{
// statements
}
If test expression is evaluated to true (nonzero), statements inside the body of if is executed.
If test expression is evaluated to false (0), statements inside the body of if are skipped.
Flowchart of if statement:
Example 1: C if statement
27
// Program to display a number if user enters negative
number
#include <stdio.h>
int main()
{
int number;
return 0;
}
Output :
Enter an integer: -2
You entered -2.
The if statement is easy.
When user enters -2, the test expression (number < 0) becomes true. Hence, You entered -2 is displayed on
the screen.
When user enters 5, the test expression (number < 0) becomes false and the statement inside the body ofif is
skipped.
2. if...else statement:
The if...else statement executes some code if the test expression is true (nonzero) and some other code if the
test expression is false (0).
Syntax of if...else:
if (testExpression)
{
// codes inside the body of if
}
else {
// codes inside the body of else
}
28
If test expression is true, code inside the body of if statement is executed; and code inside the body
of else statement is skipped.
If test expression is false, code inside the body of else statement is executed; and code inside the body
of if statement is skipped.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
29
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and
testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
30
Example 3: C nested if...else statement
// Program to relate two integers using =, > or <
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
23
Result: 12 < 23
Loops are used in programming to repeat a specific block until some end
condition is met. There are three loops in C programming:
31
1. for loop
2. while loop
3. do...while loop for Loop:
The syntax of a for loop is:
// codes
32
#include <stdio.h>
int main ()
{
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
Output:-
value of a: 10 value
of a: 11 value of a:
12 value of a: 13
value of a: 14 value
of a: 15 value of a:
16 value of a: 17
value of a: 18 value
of a: 19
{ //codes
}
33
Example 1: while loop
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++; }
return 0;
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop:
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed once, before checking the test expression. Hence, the
do...while loop is executed at least once.
do...while loop Syntax
do{
// codes
}while (testExpression);
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0 (false).
34
When the test expression is false (nonzero), the do...while loop is terminated.
Example #2: do...while loop
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do { printf("value of a:
%d\n", a); a = a + 1;
}while( a < 20 );
return 0;
}
Output:
value of a: 10 value
of a: 11 value of a:
12 value of a: 13
value of a: 14 value
of a: 15 value of a:
16 value of a: 17
value of a: 18 value
of a:19
35
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue
statements are used.
break Statement
The break statement terminates the loop immediately when it is encountered. The break
statement is used with decision making statement such as if...else.
Syntax of break statement
Break;
36
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
}
Output
01234
continue Statement:
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
continue;
37
Example : continue statement
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf("\nSkipping %d from display using " \
"continue statement \n",i);
continue;
}
printf("%d ",i);
}
}
Output
01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement 7
89
The switch statement is often faster than nested if...else (not always). Also, the syntax of
switch statement is cleaner and easy to understand.
Syntax of switch...case:
38
switch (n)
{
case constant1:
// code to be executed if n is equal to
constant1; break; case constant2:
// code to be executed if n is equal to constant2; break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}
switch Statement Flowchart
39
Example: switch Statement
#include <stdio.h>
int main ()
{ int value =
3;
switch(value)
{ case 1:
printf(“Value is 1 \n” );
break;
case 2:
printf(“Value is 2 \n” );
break; case 3:
printf(“Value is 3 \n” );
break; case 4:
printf(“Value is 4 \n” );
break;
default :
printf(“Value is other than 1,2,3,4 \n” );
}
return 0;
}
Output:
Value is 3
C Programming go to Statement
goto label;
... .. ...
... .. ...
statement;
The label is an identifier. When goto statement is encountered, control of the program
jumps tolabel: and starts executing the code.
41
Output
01234
The use of goto statement may lead to code that is buggy and hard to follow. For example:
one:
for (i = 0; i < number; ++i)
{ test
+= i;
goto two;
} two: if
(test > 5) {
goto three;
}
... .. ...
Also, goto statement allows you to do bad stuff such as jump out of scope.
C Programming Functions:
These functions are defined in the header file. When you include the header file, these
functions are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display
output on the screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(),getchar() etc. Once you include "stdio.h" in your program, all these
functions are available for use.
Visit this page to learn more about standard library functions in C programming.
43
User-defined functions
The function define by User Such functions created by the user are called user-defined
functions.Depending upon the complexity and requirement of the program, you can create
as many user-defined functions as you want.
#include <stdio.h>
void functionName()
... .. ...
... .. ...
} int
main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
When the compiler encounters functionName(); inside the main function, control of the
program jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes
inside the function definition are executed.
45
Example: User-defined function
Here is a example to add two integers. To perform this task, a user-defined function
addNumbers() is defined.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype int
main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a,int b) // function definition
{ int result;
result = a+b;
return result; // return statement }
Function prototype
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used
in the program.
Syntax of function prototype
In the above example, int addNumbers(int a, int b); is the function prototype which
provides following information to the compiler:
46
The function prototype is not needed if the user-defined function is defined before
In the above example, function call is made using addNumbers(n1,n2); statement from
inside the main().
Function definition
Function definition contains the block of code to perform a specific task.
Syntax of function definition
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
The parameters a and b accepts the passed arguments in the function definition. These
arguments are called formal parameters of the function.
47
The type of arguments passed to a function and the formal parameters must match,
otherwise the compiler throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also
should be of float type.
Return Statement
The return statement terminates the execution of a function and returns a value to the
calling function. The program control is transferred to the calling function after return
statement.
In the above example, the value of variable result is returned to the variable sum in the
main()function.
Syntax of return statement
example, return a;
return (a+b);
The type of value returned from the function and the return type specified in function
prototype and function definition must match.
Types of User-defined Functions in C Programming
For better understanding of arguments and return value from the function, user-defined
functions can be categorized as:
49
The following programs below write a program to print an sum of two numbers. And, all
these programs generate the same output.
The empty parentheses in sum(); statement inside the main() function indicates that no
argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
The sum() function takes input from the user, print the addition of two numbers.
Here, the getInteger() function takes input from the user and returns it. The code to
check whether a number is prime or not is inside the main() function.
Here, the sum() function checks whether the argument passed is a prime number or not
and displays the appropriate message.
65
66
The recursion continues until some condition is met to prevent it. To prevent infinite
recursion,if...else statement (or similar approach) can be used where one branch makes
the recursive call and other doesn't.
Output
Initially, the sum() is called from the main() function with number passed as an
argument.
Suppose, the value of n is 3 initially. During next function call, 2 is passed to the
sum() function. In next function call, 1 is passed to the function. This process
continues until n is equal to 0.
67
When n is equal to 0, there is no recursive call and the sum of integers is returned to the
main()function.
Advantages and Disadvantages of Recursion
Recursion makes program elegant and cleaner. All algorithms can be defined recursively
which makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion. Recursions use
more memory and are generally slow.
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope and
lifetime of a variable.
54
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Local Variable
The variables declared inside the function are automatic or local variables.
The local variables exist only inside the function in which it is declared. When the function
exits, the local variables are destroyed.
main() function
... .. ...
Global Variable:
Variables that are declared outside of all functions are known as external variables.
External or global variables are accessible to any function.
Example 1: External Variable
#include <stdio.h> void
display(); int n = 5; //
global variable int main() {
++n; // variable n is not declared in the main() function
display(); return 0;
}
void display()
{
55
Suppose, a global variable is declared in file1. If you try to use that variable in a different
filefile2, the compiler will complain. To solve this problem, keyword extern is used in file2
to indicate that the external variable is declared in another file.
Register Variable:
The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables.
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}
Output:
n=7
However, modern compilers are very good at code optimization and there is a rare chance
that using register variables will make your program faster.
Unless you are working on embedded system where you know how to optimize code for
the given application, there is no use of register variables.
Static Variable
A static variable is declared by using keyword static. For example;
static int i;
The value of a static variable persists until the end of the program.
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It's because c is a
static variable. So, 5 is displayed on the screen.
C Programming Arrays:
1. One-dimensional arrays
2. Multidimensional arrays( will be discussed in next chapter )
data_type array_name[array_size];
For example:
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of
arrayage. All element in an array are of the same type (int, in this case).
Array elements:
Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program. For example:
int age[5];
73
Here, the size of array age is 5 times the size of int because there are 5 elements.
Suppose, the starting address of age[0] is 2120d and the size of int be 4 bytes. Then, the
next address (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.
int age[5]={2,4,34,3,4};
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of
elements of an array.
Output
74
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45
Suppose, you declared the array of 10 students. For example: arr[10]. You can use array
members from arr[0] to arr[9]. But, what if you want to use element arr[10], arr[13] etc.
Compiler may not show error using these elements but, may cause fatal error during
program execution.
float a[2][6];
For better understanding of multidimensional arrays, array elements of above example can
be thinked of as below:
75
};
Write a C program to find sum of two matrix of order 2*2 using multidimensional arrays
where, elements of matrix are entered by user.
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
Ouput:
76
C Programming Arrays and Functions
In C programming, a single array element or an entire array can be passed to a function.
Also, both one-dimensional and multi-dimensional array can be passed to function as
argument.
#include <stdio.h>
void display(int a)
{
printf("%d",a);
} int main(){ int c[]={2,3,4};
display(c[2]); //Passing array element c[2] only.
return 0;
}
Output
While passing arrays to the argument, the name of the array is passed as an
argument(,i.e, starting address of memory area is passed as argument).
#include<stdio.h>
#include<conio.h>
//--------------------------------- void
fun(int arr[])
{
int i;
for(i=0;i< 5;i++)
arr[i] = arr[i] + 10;
}
//-------------------------------- void
main()
{ int
arr[5],i;
clrscr();
printf("\nEnter the array elements :
"); for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
61
getch();
}
78
Output
Enter the array elements : 1 2 3 4 5 Passing
entire array .....
After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
After Function call a[4] : 15
79
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
String:
In C programming, array of character are called strings. A string is terminated by null
character/0. For example:
When, compiler encounters strings, it appends null character at the end of string.
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are
of chartype.
char s[5];
char *p
Initialization of strings
In C, string can be initialized in different number of ways.
80
char c[]="abcd";
OR,
char c[5]="abcd";
OR, char
c[]={'a','b','c','d','\0'};
OR; char
c[5]={'a','b','c','d','\0'};
char c[20];
scanf("%s",c);
String variable c can only take a word. It is beacause when white space is encountered,
the scanf() function terminates.
Output:
Enter name: Dennis Ritchie
81
82
Function Work of Function
Strings handling functions are defined under "string.h" header file, i.e, you have to include
the code below to run string handling functions.
#include <string.h>
Structure:
Structure is the collection of variables of different types under a single name for
better handling.
For example: You want to store the information about person about his/her name,
citizenship number and salary. You can create these information separately but, better
approach will be collection of these information under single name because all these
information are related to person. Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{ data_type
member1; data_type
member2;
83
.
data_type memeber;
};
p2.salary
Scanf(“%d%s%f”,&record.id,record.name,&
record.percentage);
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n",
record.percentage);
return 0;
}
Output:
Enter id ane name ane per:
1
Raju
86.5
Id is: 1
Name is: Raju
Percentage is: 86.500000
Suppose you want to access imag_value for n2 structure variable then, structure
membern1.c1.imag_value is used.
struct name {
member1; member2;
};
name *ptr;
In this example, the pointer variable of type struct name is referenced to the address of p.
Then, only the structure member through pointer can can accessed.
Write a C program to create a structure student, containing name and roll. Ask user the
name and roll of a student in main function. Pass this structure to a function and display
the information in that function.
#include <stdio.h> struct
student{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure
declaration otherwise compiler shows error */ int
main(){ struct student s1; printf("Enter student's
name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
70
Display(s1); // passing structure variable s1 as
argument
return 0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll); }
Output
Enter student's name: Akshay jadhv
Enter roll number: 149
Output
Name: Akshay jadhv
Roll: 149
Unions:
Unions are quite similar to the structures in C. Union is also a derived type as structure.
Union can be defined in same manner as structures just the keyword used in defining
union in union where keyword used in defining structure was strut.
name[50];
int price;};
71
union car{ char
name[50];
int price;
OR;
name[50];
int price;
};
In both cases, union variables c1, c2 and union pointer variable c3 of type union car is
created.
72
#include <stdio.h>
union job { //defining a union
char name[32];
float salary; int
worker_no;
}u; struct job1 {
char name[32];
float salary; int
worker_no;
}s; int
main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}
Output
size of union = 32 size
of structure = 40
73
#include <stdio.h>
union job { char
name[32]; float
salary; int
worker_no;
}u; int main(){ printf("Enter name:\n");
scanf("%s",&u.name); printf("Enter salary:
\n"); scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
return 0;
}
Output
Enter name
Hillary
Enter salary
1234.23
Displaying
Name: f%Bary
Salary: 1234.2
Initially, Hillary will be stored in u.name and other members of union will contain garbage
value. But when user enters value of salary, 1234.23 will be stored in u.salary and other
members will contain garbage value. Thus in output, salary is printed accurately but, name
displays some random string.
74
It will contain the data even after program exit. Normally we use variable or array to
store data, but data is lost after program exit. Variables and arrays are non-permanent
storage medium whereas file is permanent storage medium.
File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
FILE *ptr;
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in
standard I/O is:
ptr=fopen("fileopen","mode")
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
75
Opening Modes in Standard I/O
Open for both reading and If the file does not exist, fopen() returns
r+
writing. NULL.
Open for both reading and If the file exists, its contents are overwritten.
w+
writing. If the file does not exist, it will be created.
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().
The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only
difference while using fprintf() and fscanf() is that, the first argument is a pointer to the
structure FILE
Writing to a file
76
#include <stdio.h>
int main()
{ int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){ printf("Error!");
exit(1);
} printf("Enter n:
"); scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr); return
0;
}
This program takes the number from user and stores in file. After you compile and run this
program, you can see a text file program.txt created in C drive of your computer. When
you open that file, you can see the integer you entered.
If you have run program above to write in file successfully, you can get the integer back
entered in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Write a C program to read name and marks of n number of students from user
and store them in a file. If the file previously exits, add the information of n
students.
#include <stdio.h> int main(){ char
name[50]; int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){ printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name); printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d
\n",name,marks);
78
}
fclose(fptr);
return 0;
}
C Programming Enumeration
An enumeration is a user-defined data type consists of integral constants and each integral
constant is give a name. Keyword enum is used to defined enumerated data type.
enum type_name{ value1, value2,...,valueN };
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can
change the default value.
// Changing the default value of enum elements
enum suit{
club=0;
diamonds=10;
hearts=20;
spades=3;
};
enum boolean{
false;
true;
};
enum boolean check;
79
Output
4day
You can write any program in C language without the help of enumerations but,
enumerations helps in writing clear codes and simplify programming.
#include <stdio.h>
Here, "stdio.h" is a header file and the preprocessor replace the above line with the
contents of header file.
Use of #define
Preprocessing directive #define has two forms. The first form is:
#define identifier token_string
token_string part is optional but, are used almost every time in program.
80
C is a general-purpose programming language used for wide range of applications
from
Operating systems like Windows and iOS to software that is used for creating 3D movies programming is
highly efficient.
82