Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PPS Complete Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

1FY3-06 /2FY3-06

Programming for Problem Solving


B. Tech I year (I&II Semester)
Computer Fundamentals

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

• Hardware = Internal Devices + Peripheral Devices


All physical parts of the computer (or everything that we can touch) are known as Hardware.
• Software = Programs
Software gives "intelligence" to the computer.
• USER = Person, who operates computer.

Generation of computer:

First Generation (1940-56):


The first generation computers used vaccum tubes & machine language was used for giving the
instructions. These computer were large in size & their programming was difficult task. The electricity
consumption was very high. Some computers of this generation are ENIAC, EDVAC, EDSAC & UNIVAC-1.
Second Generation(1956-63):
In 2nd generation computers, vaccum tubes were replaced by transistors. They required only 1/10 of power
required by tubes. This generation computers generated less heat & were reliable. The first operating
system developed in this generation. The Third Generation(1964-71):
The 3rd generation computers replaced transistors with Integrated circuit known as chip. From Small scale
integrated circuits which had 10 transistors per chip, technology developed to MSI circuits with 100
transistors per chip. These computers were smaller, faster & more reliable. High level languages invented
in this generation.
The fourth Generation(1972- present):
LSI & VLSI were used in this generation. As a result microprocessors came into existence. The computers
using this technology known to be Micro Computers. High capacity hard disk were invented. There is great
development in data communication.

The Fifth Generation (Present & Beyond):


Fifth generation computing devices, based on artificial intelligence, are still in development, though there
are some applications, such as voice recognition, that are being used today. The use of parallel processing
and superconductors is helping to make artificial intelligence a reality. Quantum computation and molecular
and nanotechnology will radically change the face of computers in years to come.

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

Printer Plotter Projector

CENTRAL PROCESSING UNIT (CPU)


The main component to make a computer operate is the computer chip or microprocessor. This is referred
to as the Central Processing Unit (CPU) and is housed in the computer case. Together, they are also called
the CPU. It performs arithmetic and logic operations. The CPU (Central Processing Unit) is the device that
interprets and executes instructions.

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..

Non Volatile Memory (ROM)


Non-volatile memory is computer memory that can retain the stored information even when not powered.

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:

The smallest unit is bit, which mean either 0 or 1.


1 bit = 0 or 1
1 Byte = 8 bit
1 Nibble = 4 bit
1 Kilo Byte = 1024 Byte= 210 Byte
1 Mega Byte = 1024 KB= 210 KB

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.

c) Hybrid Computer (Analog + Digital)


A combination of computers those are capable of inputting and outputting in both digital and analog signals.
A hybrid computer system setup offers a cost effective method of performing complex simulations. The
instruments used in medical science lies in this category.

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.

Functions of operating System:


Processor Management
• Memory Management
• File Management
• Device Management

Types of Operating System:


• Real-time Operating System: It is a multitasking operating system that aims at executing real-time
applications. Example of Use: e.g. control of nuclear power plants, oil refining, chemical processing
and traffic control systems, air

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.

Commonly used operating 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.

Clock speeds are expressed in megahertz (MHz) or gigahertz ((GHz).

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

Difference between RISC & CISC architecture

RISC (Reduced Instruction Set Computing):


1. RISC sytem has reduced number of instructions.
2. Performs only basic functions.
3. All HLL support is done in software.
4. All operations are register to register.

CISC (Complex Instruction Set Computing):


1. A large and varied instruction set.
2. Performs basic as well as complex functions.
3. All HLL support is done in Hardware.
4. Memory to memory addressing mode

EPIC (Explicitly Parallel Instruction Computing):

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.

Internal Storage encoding of Characters:

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:

A. Decimal Number System:


Decimal Number system composed of 10 numerals or symbols. These numerals are 0 to 9. Using these
symbols as digits we can express any quantity. It is also called base-10 system. It is a positional value
system in which the value of a digit depends on its position.

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):

Decimal numbers would be written like this:


12710 1110 567310

B. Binary Number System:


In Binary Number system there are only two digits i.e. 0 or 1. It is base-2 system. It can be used to
represent any quantity that can be represented in decimal or other number system. It is a positional
value system, where each binary digit has its own value or weight expressed as power of 2.

The following are some examples of binary numbers:


1011012 112 101102

Conversion from Decimal to Binary or Binary to Decimal

Convert from decimal to binary Χ(10)->Χ(2)

Integer

45(10)->Χ(2)

Div Quotient Remainder Binary Number (Χ)

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)

Div Product Integer value Binary Number (Χ)

Santosh kumar 13
0.182 * 2 0.364 0 0.0

0.364 * 2 0.728 0 0.00

0.728 * 2 1.456 1 0.001

0.456 * 2 0.912 0 0.0010

0.912 * 2 1.824 1 0.00101

0.824 * 2 1.648 1 0.001011

0.648 * 2 1.296 1 0.0010111 0.182(10)->0.0010111(2)

(After we round and cut the number)

Conversion from Binary to Decimal

Convert from binary to decimal Χ(2)->Χ(10)

101101.0010111(2)->Χ(10) Index

the digits of the number

150413120110.0-10-21-30-41-51-61-7

Multiply each digit

1 * 25 + 0 * 24 + 1 * 23 + 1 * 22 + 0 * 21 + 1 * 20 + 0 * 2-1 + 0 * 2-2 + 1 * 2-3 + 0 * 2-4 + 1 * 2-5 + 1 * 2-6 + 1 * 2-7 =

32 + 0 + 8 + 4 + 0 + 1 + 0 + 0 + 0.125 + 0 + 0.03125 + 0.015625 + 0.007813

= 45.179688(10)

C. Octal Number System:


It has eight unique symbols i.e. 0 to 7. It has base of 8. Each octal digit has its own value or weight
expressed as a power of 8.

D. Hexadecimal Number System:


The hexadecimal system uses base 16. It has 16 possible digit symbols. It uses the digits 0 through 9 plus
the letters A,B,C,D,E,F as 16 digit symbols. Each hexadecimal digit has its own value or weight expressed
as a power of 16.

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)

Div Quotient Remainder Octal Number (Χ)

45 / 8 5 5 55

/8 0 5 55

45(10)->55(8)

15
Fractional Part

0.182(10)->Χ(8)

Mul Product Integer Binary Number (Χ)

0.182 * 8 1.456 1 0.1

0.456 * 8 3.648 3 0.13

0.648 * 8 5.184 5 0.135

0.184 * 8 1.472 1 0.1351

0.472 * 8 3.776 3 0.13513

0.776 * 8 6.208 6 0.135136

0.182(10)->0.135136(8) (After we round and cut the number)

Convert from decimal to hexadecimal Χ(10)->Χ(16)

Integer

45(10)->X(16)

16
Div Quotient Remainder Hex Number (Χ)

45 / 16 2 13 D (Since 13 decimal is D in hexadecimal)

2 / 16 0 2 2D (See the table)

45(10)->2D(16)

Fractional Number

0.182(10)->Χ(16)

Mul Product Integer Binary Number (Χ)

0.182 * 16 2.912 2 0.2

0.912 * 16 14.592 14 0.2Ε

0.592 * 16 9.472 9 0.2Ε9

0.472 * 16 7.552 7 0.2Ε97

0.552 * 16 8.832 8 0.2Ε978

0.832 * 16 13.312 13 0.2Ε978D

0.182(10)->0.2E978D(16) (After we round and cut the number)


Convert from octal to decimal Χ(8)->Χ(10)

55.135136(8)->Χ(10)

Index the digits of the number

5150.1-13-25-31-43-56-6

We multiply each digit

5 * 81 + 5 * 80 + 1 * 8-1 + 3 * 8-2 + 5 * 8-3 + 1 * 8-4 + 3 * 8-5 + 6 * 8-6 =

40 + 5 + 0.125 + 0.03125 + 0.009766 + 0.000244 + 0.0001 + 0.0000229

= 45.1663829(10)

Convert from hexadecimal to decimal Χ(16)->Χ(10)

2D.2E978D(16)->Χ(10)

Index the digits of the number

21130.2-114-29-37-48-513-6

17
We multiply each digit

2 * 161 + 13 * 160 + 2 * 16-1 + 14 * 16-2 + 9 * 16-3 + 7 * 16-4 + 8 * 16-5 + 13 * 16-6 =

32 + 13 + 0.125 + 0.0546875 + 0.00219727 + 0.00010681 + 0.00000762 + 0.00000077

= 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)

|3| |3||3| |3| |3|

110 101 000 .101 010

|| || || || ||

\/ \/ \/ \/ \/

6 5 0 . 5 2 (See that in the array 110(2) corresponds to 6(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|

0001 1010 1000 .1010 1000

|| || || || ||

\/ \/ \/ \/ \/

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.

Convert from octal to binary

650.52(8)->X(2)

6 5 0 . 5 2

18
|| || || || ||

\/ \/ \/ \/ \/

110 101 000 . 101 010

650.52(8)->110101000.101010(2)

Convert from hexadecimal to binary

1Α8.Α8(16)->X(2)

1 Α 8 . Α 8

|| || || || ||

\/ \/ \/ \/ \/

0001 1010 1000 .1010 1000

Practice Session:
1. Which electronic device invention brought revolution in earlier computers?

Ans. Microprocessor

2. Which memory is responsible for booting of system.

Ans. ROM

3. Where do you find analog computers in daily life?


Ans. In Bike-speedometer, voltmeter

4. What do you mean by term firmware?

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

13. What do you mean by LPT port?


Ans. Line Print Terminal

14. What is difference between USB & Firewire Port?


Ans. USB is host based, mean device must connect to computer while Firewire is peer-to-peer. Firewire
is sought for high speed devices with more data like camcorders.

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.

Stages of Program Development Process:


A program development process is the step by step process in converting the inputs into
outputs.
1. Analysis: this is the important phase where all the requirements of the program are gathered
and the problem is cracked downed. An algorithm is formulated which gives the solution for
the problem.

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.

Documentation: Documentation referrers to written descriptions specification, design code and


comments , internal and external to program which makes more readable and understandable.
Uses of documentation:
1. This becomes an useful interface between a technical personnel and non technical personnel.

21
2. This is very useful for upkeep and maintenance.

3. Documentation makes ease for any technical emergencies.

4. Very useful in operating for learners and trainers.

5. Enables trouble shooting when the application system breaks down.

PROBLEM SOLVING METHODOLOGY AND TECHNIQUES:


To develop an efficient and effective programs we should adopt a proper problem solving
methodology and use appropriate techniques. Following are some of the methods and
techniques to develop a good program.
1. Understand the problem well : for a good program one should understand the problem well
.
one should know what exactly is expected from the problem. Knowing the problem well is the
half way done.

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.

datatype Storage Size Value range Example The


Following diagram shows types c Data types.
char 1 byte -128 to 127 Char test=’h’;

Unsigned Char 1 byte 0 to 255


Signed char 1 byte -128 to 127
Int 2 byte -32,768 to 32,767 Int no=10;

Short int 2 byte -32,768 to 32,767

Long int 2 byte -2,147,483,648 to


2,147,483,647

Float 4 byte 1.2E-38 to 3.4E+38 float no=3.14;

Double 8 byte 2.3E-308 to 1.7E+308


Keywords:
Keywords are the words whose meaning is already define in c compiler. Keywords
are also called as reserved words which have special meaning .There are 32 keywords in c.

Auto double Int Struct


23

Break Else Long Switch


Case Enum Register Typedef
Char Extern Return union
Const Float Short unsigned
Continue For Signed void
Default Goto Sizeof volitle
Do If Static while

Structure of c program:

C Programming Input Output (I/O):


C programming has several in-build library functions to perform input and output tasks.
The scanf() function reads formatted input from standard input (keyboard) whereas the printf()function
sends formatted output to the standard output (screen).The following example define the how to work
printf and scanf functions.

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;
}

How this program works?


24

• 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.

Example 2: C Integer Output


#include <stdio.h> int
main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
Output:
Number = 5

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:

Enter an integer: 4 Number


=4

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.

Little bit on ASCII code:

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 &&, ||, !

Bitwise operator &, !


Comma Operator ,
Conditional Operator ?:

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;

printf("Enter an integer: ");


scanf("%d", &number);

// Test expression is true if number is less than 0


if (number < 0)
{
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

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.

Flowchart of if...else statement


Example 2: C if...else statement
// Program to check whether an integer entered by the user is odd or even

#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

4.Nested if...else statement (if...else if....else Statement):


The if...else statement executes two different codes depending upon whether the test expression is true or
false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute different codes
for more than two conditions.
Syntax of nested if...else statement.

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);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}

return 0;
}
Output

Enter two integers: 12

23
Result: 12 < 23

C Programming for Loop


Loops are used in programming to repeat a specific block of code.

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:

for (initializationStatement; testExpression; updateStatement)

// codes

for loop Flowchart


Example: for loop

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

while loop: Syntax


while (testExpression)

{ //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);

How do...while loop works?

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

C Programming break and continue Statement

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;

How break statement works?

Example : break statement

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

Coming out of for loop when i = 5

In C programming, break statement is also used with switch...case statement.

continue Statement:
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.

Syntax of continue Statement:

continue;

How continue statement works?

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

C Programming switch...case Statement


The nested if...else statement allows you to execute a block code among many
alternatives. If you are checking on the value of a single variable in nested if...else
statement, it is better to use switch statement.

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

The goto statement is used to alter the normal sequence of a C program.

Syntax of goto statement:

goto label;

... .. ...

... .. ...

... .. ... label:

statement;

The label is an identifier. When goto statement is encountered, control of the program
jumps tolabel: and starts executing the code.
41

Example: goto Statement


#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nWe are using goto statement when i =
5");
goto HAI;
}
printf("%d ",i);
}
HAI : printf("\nNow, we are inside label name \"hai\"
\n");
}

Output

01234

We are using goto statement when i = 5

Now, we are inside label name “hai”

Reasons to avoid goto statement

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:

A function is a block of code that performs a specific task.

Types of functions in C programming

Depending on whether a function is defined by the user or already included in C compilers,


there are two types of functions in C programming

There are two types of functions in C programming:

• Standard library functions


• User defined functions
Standard library functions:
The standard library functions are in-built functions in C programming to handle tasks such
as mathematical computations, I/O processing, string handling etc.

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.

How user-defined function works?

#include <stdio.h>

void functionName()

... .. ...

... .. ...

} int

main()

{
... .. ...

... .. ...

functionName();

... .. ...

... .. ...

The execution of a C program begins from the main() function.

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.

Remember, function name is an identifier and should be unique.

Advantages of user-defined function


1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.

C Programming User-defined functions


C allows programmer to define functions according to their need. These functions are
known as user-defined functions.

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

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which
provides following information to the compiler:

1. name of the function is add()


2. return type of the function is int

46

3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before

the main()function. Calling a function


Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

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

returnType functionName(type1 argument1, type2 argument2, ...) {

//body of the function

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.

Passing arguments to a function


In programming, argument refers to the variable passed to the function. In the above
example, two variables n1 and n2 are passed during function call.

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.

A function can also be called without passing an argument.

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

return (expression); For

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

• Function with no arguments and no return value


• Function with no arguments and a return value Function with
arguments and no return value Function with arguments and a
return value.

The following programs below write a program to print an sum of two numbers. And, all
these programs generate the same output.

Example 1: No arguments passed and no return Value


#include <stdio.h>
void sum(); int
main()
{
sum(); // no argument is passed to sum()
return 0; }
// return type of the function is void becuase no value is returned
from the function void sum()
{
int a, b, sum;
printf("Enter a first no: ");
scanf("%d",&a); printf("Enter
a second no: ");
scanf("%d",&b); sum=a+b;
printf(“Sum=%d”,sum);
}

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.

Example 2: No arguments passed but a return value


#include <stdio.h>
int getInteger(); int
main()
{
int n, i, flag = 0;

// no argument is passed to the function


// the value returned from the function is assigned to n
n = getInteger();
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1;
break;
}
}
if (flag == 1) printf("%d is not a
prime number.", n); else printf("%d
is a prime number.", n); return 0;
}
// getInteger() function returns integer entered by the user int
getInteger()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
return n;
}

The empty parentheses in n = getInteger(); statement indicates that no argument is


passed to the function. And, the value returned from the function is assigned to n.

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.

Example3: Argument passed but no return value


#include <stdio.h> void
sum(int a,int b); int
main()
{ int a, b; printf("Enter a
first no: "); scanf("%d",&a);
printf("Enter a second no: ");
scanf("%d",&b);
sum(a,b); return
0;
}
void sum(int a,int b)
{
int res;
res=a+b; printf("Sum=%d",res);
}

The integer value entered by the user is passed to sum() 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.

Example: Sum of Natural Numbers Using Recursion


#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int n)
{
if (n!=0)
return n + sum(n-1); // sum() function calls itself
else
return n;
}

Output

Enter a positive integer:


3
6

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.

Scope and Lifetime of a variable

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.

int main() { int n; // n is a local varible to

main() function

... .. ...

void func() { int n1; // n1 is local to


func() fucntion }

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.

Example 2: Static Variable


#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
c += 5;
}

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:

An array is a sequence of data item of homogeneous value(same type).

Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays( will be discussed in next chapter )

Declaration of one-dimensional array

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];

Note that, the first element is numbered 0 and so on.

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.

Initialization of one-dimensional array:

Arrays can be initialized at declaration time in this source code as:

int age[5]={2,4,34,3,4};

It is not necessary to define the size of arrays during initialization.

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.

Accessing array elements:


In C programming, arrays can be accessed and treated like variables in C.

Example of array in C programming


/* C program to find the sum marks of n students using arrays
*/
#include <stdio.h> int
main(){
int marks[10],i,n,sum=0; printf("Enter
number of students: "); scanf("%d",&n);
for(i=0;i<n;++i){ printf("Enter marks of
student%d: ",i+1);
scanf("%d",&marks[i]); sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}

Output

74
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45

Important thing to remember in C arrays

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.

C Programming Multidimensional Arrays

C programming language allows programmer to create arrays of arrays known as


multidimensional arrays. For example:

float a[2][6];

Here, a is an array of two dimension, which is an example of multidimensional array.

For better understanding of multidimensional arrays, array elements of above example can
be thinked of as below:

Initialization of Multidimensional Arrays:


In C, multidimensional arrays can be initialized in different number of ways.

int c[2][3]={{1,3,0}, {-1,5,9}};


OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};

75
};

Example of Multidimensional Array In C

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];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");

for (c = 0; c < m; c++) {


for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}

Ouput:

Enter the number of rows and columns of matrix


2
2
First Matrix :-
12
34
Second matrix :-
45
-1 5
sum of entered matrix is:
57
29

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.

Passing One-dimensional Array In Function

C program to pass a single element of an array to function

#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

Single element of an array can be passed in similar manner as passing variable to a


function.

Passing entire one-dimensional array to a function

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

printf("\nPassing entire array .....");


fun(arr); // Pass only name of array

for(i=0;i< 5;i++) printf("\nAfter Function call


a[%d] : %d",i,arr[i]);

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

Passing Multi-dimensional Arrays to Function


To pass two-dimensional array to a function as an argument, starting address of memory
area reserved is passed as in one dimensional array

Example to pass two-dimensional arrays to function


#include<stdio.h> void
Function(int c[2][2]); int
main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to
function */ return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is
also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}

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:

"c string tutorial"

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];

Strings can also be declared using pointer.

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'};

Reading Strings from user.

Reading words from user.

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.

Write a C program to illustrate how to read string from terminal.


#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}

Output:
Enter name: Dennis Ritchie

Your name is Dennis.

81
82
Function Work of Function

strlen() Calculates the length of string

strcpy() Copies a string to another string

strcat() Concatenates(joins) two strings

strcmp() Compares two string

strlwr() Converts string to lowercase

strupr() Converts string to uppercase

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;

};

We can create the structure for a person as mentioned above as:


struct person
{ char
name[50]; int
cit_no; float
salary;
};
This declaration above creates the derived data type struct person.

Structure variable declaration:


When a structure is defined, it creates a user-defined type but, no storage is allocated. For
the above structure of person, variable can be declared as:
struct person
{ char
name[50]; int
cit_no; float
salary;
};
Inside main function:
struct person p1, p2, p[20];
Another way of creating sturcture variable is:
struct person
{
char name[50];
int cit_no;
float salary; }p1
,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct
person are created.

Accessing members of a structure


There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->) (will be discussed in structure and pointers chapter)

Any member of a structure can be accessed as: structure_variable_name.member_name


67
Suppose, we want to access salary for variable p2. Then, it can be accessed as:

p2.salary

typedef struct complex{


int imag;
float real;
}comp;
Inside main:
comp c1,c2;
Example of structure
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record; //Initializing to
null
Printf(“Enter id ane name ane per”);

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

Keyword typedef while using structure:


Programmer generally use typedef while using structure in C language. For example:
Here, typedef keyword is used in creating a type comp(which is of type as struct
complex). Then, two structure variables c1 and c2 are created by this comp type.

Structures within structures


Structures can be nested within other structures in C programming.
struct complex
{ int
imag_value;
float real_value;
}; struct number{
struct complex c1;
int real;
}n1,n2;

Suppose you want to access imag_value for n2 structure variable then, structure
membern1.c1.imag_value is used.

C Programming Structure and Pointer


Pointers can be accessed along with structures. A pointer variable of structure can be
created as below:

struct name {

member1; member2;

};

-------- Inside function ------- struct

name *ptr;

Here, the pointer variable of type struct name is created.

Structure's member through pointer can be used in two ways:

1. Referencing pointer to another address to access memory


2. Using dynamic memory allocation

Consider an example to access structure's member through pointer.


#include <stdio.h> struct
name{
69
int a;
float b; };
int main(){
struct name *ptr,p;
ptr=&p; /* Referencing pointer to memory
address of p */ printf("Enter integer: ");
scanf("%d",&(*ptr).a); printf("Enter number: ");
scanf("%f",&(*ptr).b); printf("Displaying: ");
printf("%d%f",(*ptr).a,(*ptr).b); return 0;
}

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.

C Programming Structure and Function


In C, structure can be passed to functions by two methods:

1. Passing by value (passing actual value as argument)


2. Passing by reference (passing address of an argument)

Passing structure by value


A structure variable can be passed to the function as an argument as normal variable. If
structure is passed by value, change made in structure variable in function definition does
not reflect in original structure variable in calling function.

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.

union car{ char

name[50];

int price;};

Union variables can be created in similar manner as structure variable.

71
union car{ char

name[50];

int price;

}c1, c2, *c3;

OR;

union car{ char

name[50];

int price;

};

-------Inside Function----------- union

car c1, c2, *c3;

In both cases, union variables c1, c2 and union pointer variable c3 of type union car is
created.

Accessing members of an union


The member of unions can be accessed in similar manner as that structure. Suppose,
we you want to access price for union variable c1 in above example, it can be accessed
as c1.price. If you want to access price for union pointer variable c3, it can be accessed
as (*c3).price or asc3->price.

Difference between union and structure


Though unions are similar to structure in so many ways, the difference between them is
crucial to understand. This can be demonstrated by this example:

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

There is difference in memory allocation between union and structure as suggested in


above example. The amount of memory required to store a structure variables is the sum
of memory size of all members.

What difference does it make between structure and union?


As you know, all members of structure can be accessed at any time. But, only one
member of union can be accessed at a time in case of union and other members will
contain garbage value.

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

Note: You may get different garbage value of name.

Why this output?

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.

C Programming Files I/O


In C programming, file is a place on disk where a group of related data is stored.

Why files are needed?


When the program is terminated, the entire data is lost in C programming. If you want to
keep large volume of data, it is time consuming to enter the entire data. But, if file is created,
these information can be accessed using few commands. There are large numbers of
functions to handle file I/O in C language. Advantage of File:

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

Working with file


While working with file, you need to declare a pointer of type file. This declaration is
needed for communication between file and program

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")

For Example: fopen("E:\\cprogram\program.txt","w");

/* --------------------------------------------------------- */

E:\\cprogram\program.txt is the location to create file.

"w" represents the mode for writing.

/* --------------------------------------------------------- */

Opening Modes in Standard I/O


Here, the

File Mode Meaning of Mode During Inexistence of file

program.txt file is opened for writing mode.

75
Opening Modes in Standard I/O

File Mode Meaning of Mode During Inexistence of file

If the file does not exist, fopen() returns


r Open for reading.
NULL.

If the file exists, its contents are overwritten.


w Open for writing.
If the file does not exist, it will be created.

Open for append. i.e, Data


a If the file does not exists, it will be created.
is added to end of file.

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.

Open for both reading and


a+ If the file does not exists, it will be created.
appending.

Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().

fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions

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.

Similarly, fscanf() can be used to read data from file.

Reading from file


#include <stdio.h>
int main()
{ int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file"); exit(1); /* Program
exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}

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.

C Programming File Examples


77
Write a C program to read name and marks of n number of students from user
and store them in a file
#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","w"));
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);
}
fclose(fptr);
return 0;
}

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 };

Here, type_name is the name of enumerated data type or tag.


And value1, value2,....,valueNare values of type type_name.

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;
};

Declaration of enumerated variable


Above code defines the type of the data but, no any variable is created. Variable of
type enumcan be created as:

enum boolean{
false;
true;
};
enum boolean check;

Here, a variable check is declared which is of type enum boolean.

Example of enumerated type


#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday,
friday, saturday};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}

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.

C Programming Preprocessor and Macros


Preprocessor extends the power of C programming language. Line that begin with # are
called preprocessing directives. The C preprocessor is a micro processor that is used by
compiler to transform your code before compilation. It is called micro preprocessor
because it allows us to add macros. Use of #include
Let us consider very common preprocessing directive as below:

#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.

C Program to find area of a cricle. [Area of circle=πr2


]

#include <stdio.h> #define


PI 3.1415 int main(){ int
radius; float area;
printf("Enter the radius: ");
scanf("%d",&radius);
area=PI*radius*radius;
printf("Area=%.2f",area);
return 0;
}

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

You might also like