Вы находитесь на странице: 1из 67

C NOTES

Unit I
Definition of a computer
Computer Definition
 Computer is an electronic device that takes data and instructions as input from the user and
processes the data as per set of instructions (called program) and gives the result as output and
saves it for the future use.
 It can compute arithmetic and logical operations.
Characteristics of a computer
 Speed : Very high speed measured in milli,micro and nano seconds
 Accuracy : 100% accurate
 Diligence : No tiredness, no lack of concentration, no fatigue etc.
 Versatility : It can perform variety of processes
 Memory : Can store large amount of data in memory
 No IQ : No intelligence. Cannot take decisions on its own.
 No Feeling : No feelings, emotions, knowledge, and learning.

Generation of computers:In the history of computers, generation term is used in the different
advancements of new computer technology. As a result of the miniaturization, speed, power,
and computer memory has proportionally increased. Each generation of computers is characterized by
major technological development that fundamentally changed the way computers operate, resulting in
increasingly smaller, cheaper, more powerful and more efficient and reliable devices.

First Generation - 1940-1956: Vacuum Tubes


 Vacuum tube technology, The first electronic computer ENIAC invented in 1946 by an English
mathematician “Charles Babbage”, occupied large space, generated heat, unreliable, slow
speed, less memory

Second Generation - 1956-1963: Transistors


 Transistors were use in place of vacuum tube, size, cost, heat generation & power consumption
decreased, use of low-level language, puch cards as input devices.

Third Generation - 1964-1971: Integrated Circuits


 Compact Integrated Circuit of silicon chips,
size, cost, heat generation & power consumption further decreased, use of high level language,
use of translators, magnetic tapes as storage device, invention of operating system, inputs thru
keyboard & mouse,SSI & LSI technology, e.g.IBM 370,PDP-11 etc.

Fourth Generation - 1971-Present: Microprocessors


thousands of integrated circuits were built onto a single silicon chip.
LSI & VLSI techniques were used. Invention of floppy disk, OS like MS-DOS, Xenix, UNIX,
GUI, Word processors, spread sheets etc.. Networking allowed sharing of resources.
Three basic characteristics differentiate microprocessors:

 Instruction Set: The set of instructions that the microprocessor can execute.
 Bandwidth: The number of bits processed in a single instruction.
 Clock Speed: Given in megahertz (MHz), the clock speed determines how many instructions
per second the processor can execute.

Fifth Generation - Present and Beyond: Artificial Intelligence


 5th generation (present and future):- Artificial Intelligence
ULSI (Ultra LSI), Parallel processing & super conductor technology, Aim to develop devices
that respond to natural language, voice recognition, gaming, expert system, Neutral n/w,
Robotics etc..

Classification of Computers: Computers differ based on their data processing abilities. They are
classified on the basis of 1. Purpose 2. Data handling, and 3. Functionality

Genral Purpose Computer : A general-purpose computer is able to perform most common computing
tasks. Personal computers, including desktops, notebooks, smart phones and tablets, are all examples of
general-purpose computers.

Special-Purpose Computer: They are designed for a specific task and most of the times their job is to
solve one particular problem. They are also known as dedicated computers, because they are dedicated to
perform a single task over and over again. E.g. traffic lights control system, navigational system in an
aircraft, weather forecasting, satellite launch / tracking etc.

Analog computers: are used to process analog data. Analog data is of continuous nature and which is
not discrete or separate. Such type of data includes temperature, pressure, speed weight, voltage, depth
etc.

Digital Computer: as its name implies, works on inputs which are ON-OFF type and its output is also
in the form of ON-OFF signal. Normally, an ON is represented by a 1 and an OFF is represented by a
0. So we can say that digital computers process information which is based on the presence or the
absence of an electrical charge or we prefer to say a binary 1 or 0.
Hybrid computer: is a combination of digital and analog computers. It combines the best features of
both types of computers, i-e. It has the speed of analog computer and the memory and accuracy of
digital computer. Hybrid computers are used mainly in specialized applications where both kinds of
data need to be processed. Hybrid computers for example are used for scientific calculations, in defense
and radar systems.

Supercomputers: The most powerful computers in terms of performance and data processing are the
supercomputers. These are specialized and task specific computers used by large organizations. These
computers are used for research and exploration purposes, like NASA uses supercomputers for launching
space shuttles, controlling them and for space exploration purpose, weather forecasting, Earthquake
studies, nuclear weapon testing.
The supercomputers are very expensive and very large in size. It can be accommodated in large air-
conditioned rooms; some super computers can span an entire building.

In 1964, Seymour cray designed the first supercomptuer CDC 6600. Indian supercomputers are Prithvi,

PARAM Yuva, SAGA, EKA etc.

Mainframe Computer: A very large and expensive computer capable of supporting hundreds, or even
thousands, of users simultaneously. Mainframes are not as powerful as supercomputers, but certainly they
are quite expensive nonetheless, and many large firms & government organizations uses Mainframes to run
their business operations. Mainframes can also process & store large amount of data. Banks educational
institutions & insurance companies use mainframe computers to store data about their customers, students
& insurance policy holders. E.g. IBM S/360, S/370

Mini Computer: A midsized computer. In the past decade, the distinction between large minicomputers
and small mainframes has blurred. But in general, a minicomputer is a multiprocessing system capable
of supporting from 4 to about 200 users simultaneously. E.g. HP 3000 and HP e3000 mini-
computers

Micro/Personal Computer: These are –

o Desktop Computer: a personal or micro-mini computer sufficient to fit on a desk.

o Laptop Computer: a portable computer complete with a screen and keyboard. It is generally
smaller in size than a desktop computer and larger than a notebook computer.

o 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.
Describe the basic functions ( operations) performed by a computer system, with the help of a
suitable diagram.
Or
Explain the basic components of a digital computer with its block diagram.
Or
Explain Functional components of digital computer.

Answer:
Input Devices : Keyboard, Mouse, Scanner, Bar code reader, OCR, OMR, MICR, Voice input devices,
digital camera etc.

Output Devices: Monitor, Printer, Plotter, Projector, Speakers etc.

Storage Unit: The storage unit is used for storing data and instructions before and after processing.

Central Processing Unit (CPU):


The CPU is called brain of the computer The Central Processing Unit (CPU) takes data and
instructions from the storage unit and makes all sorts of calculations based on the instructions given
and the type of data provided. It is then sent back to the storage unit. CPU includes Arithmetic logic
unit (ALU) and control unit (CU)
e.g A PC may have CPU such as Pentium, Pentium Pro, Pentium II,III,IV, Dual Core, quad core and
AMD etc.

Memory
Computer’s memory can be classified into two types; primary memory and secondary memory.
Primary Memory: It is directly accessible by the CPU and it is the working memory. It stores The
program being currently executed, the data received from the input unit, and intermediate and final
results of the program.
The primary memory is mainly volatile or temporary in nature for the user. It is faster and costlier than
secondary storage devices.
The primary memory is of three types:
a) ROM memory (Read Only Memory)
b) RAM or Read /Write memory or Random Access Memory
c) Cache Memory.

RAM (Random Access Memory): RAM is the Read and write (R/W) memory and is called main
memory of a computer. RAM is a volatile memory. It means information written to it can be accessed
as long as power is on. RAM holds data and processing instructions temporarily until the CPU needs it.
RAM is considered “random access” because you can access any memory cell directly if you know the
row and column that intersect at that cell.
There are two basic types of RAM:

(i) Dynamic Ram (ii) Static RAM

Dynamic RAM: loses its stored information in a very short time (for milli sec.) even when power
supply is on. D-RAM’s are cheaper & lower speed. Dynamic RAM has to be dynamically refreshed all
of the time or it forgets what it is holding. The downside of all of this refreshing is that it takes time and
slows down the memory.

Static RAM: S-RAM retains stored information only as long as the power supply is on. Static RAM’s
are costlier and consume more power. They have higher speed than D-RAMs.

Read Only Moemory (ROM): It is non volatile memory, also known as firmware (software
embedded in hardware). ROM is an integrated circuit programmed with specific data when it is
manufactured. The instructions (BIOS) for starting (booting) the computers are stored on ROM chip.
As the name suggests, the computer system can only read data from the ROM but cannot write onto it.
ROM chips are used not only in computers, but in most other electronic items as well. ROM Types :
1. PROM (programmable read-only memory)
2. EPROM (erasable programmable read-only memory)
3. EEPROM (electrically erasable programmable read-only memory)

Secondary Memory: It is not directly accessible by the CPU. It is a permanent storage and is non-
volatile. E.g. Hard disk, CD, pendrives, etc. It stores the data and results permanently, various
softwares e.g. operating system, device drivers, gaming softwares etc., and Several programs,
documents, data bases etc. The secondary memory is slower and cheaper than the primary
memory.

Operating System
An operating system, also commonly called OS is a set of programs that coordinates all the activities
among computer hardware devices. It also supports the application software that we run.
It is designed to work with a specific type of computer such as a PC or a Macintosh. Examples of
popular Operating Systems are:-
•Disk Operating System (DOS)
•Linux
•Mac OS X
•Unix
•Windows XP

FUNCTIONS OF OPERATING SYSTEM


Most operating systems perform the following important functions:
1. Process management: that is, assignment of processor to different tasks being performed by the
computer system.
2. File management: It is responsible to create and maintain files using file editors, and to store and
retrieve files in various storage devices.
3. Memory management: allocation of main memory and other storage areas to the system programs
as well as user programs and data.
4. I/O management: co-ordination and assignment of the different output and input devices while one
or more programs are being executed.
5. Command interpreter: Interpretation of commands and instructions.
6. Data security & Integrity
7. Networking and Communications.

Types of OS
Batch OS : Several programs and data that need to be processed are collected together as a Job or
Batch and executed together.
Disadvantages: Lack of interaction between the user and job, CPU is often idle, because the speeds of the mechanical I/O
devices is slower than CPU, Difficult to provide the desired priority.

Single User OS: are usable by a single user at a time. E.g. DOS,Windows 3.x
Multi User OS: are usable by multiple users at a time. E.g. LINUX, UNIX, Windows NT
Multi tasking OS: The operating system that allows the execution of multiple tasks at a time is
classified as a multi-tasking operating system. E.g. Windows OS
Multi Programming OS: It is the technique of running several programs at one time in the computer
using timesharing. E.g. LINUX, UNIX, Windows NT, Google chrome OS, Chromium OS, Android
for mobies.
Time Sharing OS: Time sharing is a technique which enables many people, located at various
terminals, to use a particular computer system at the same time. Time-sharing or multitasking is a
logical extension of multiprogramming. Processor's time which is shared among multiple users
simultaneously is termed as time-sharing.
The main difference between Multiprogrammed Batch Systems and Time-Sharing Systems is that in
case of Multiprogrammed batch systems, objective is to maximize processor use, whereas in Time-
Sharing Systems objective is to minimize response time.
Advantages: quick response, Avoids duplication of software, Reduces CPU idle time
Disadvantages: Problem of reliability, security and integrity of user programs and data, Problem of data communication
Real Time OS: Real time system is defines as a data processing system in which the time interval
required to process and respond to inputs is so small that it controls the environment. Real time
processing is always on line whereas on line system need not be real time.
Real-time operating system has well-defined, fixed time constraints otherwise system will fail.For
example Scientific experiments, medical imaging systems, industrial control systems, weapon systems,
robots, and home-applicance controllers, Air traffic control system etc. E.g. ERIKA, EROS, Nucleous
OS etc.
Embedded OS: The operating systems designed for being used in embedded computer systems are
known as embedded operating systems. They are designed to operate on small machines like PDAs.
E.g Embedded Linux : on Android, Maemo based on Debian deployed on Nokia's Nokia
770, N800 and N810 Internet Tablets, i-Pod OS, NetBSD,Airport Exteme
Multi processing OS: Multiprocessing is the coordinated processing of programs by more than one
computer processor. The processors share memory and the I/O bus or data path. A single copy of
the operating system is in charge of all the processors. Symmetric Multi Proccessing (SMP), also
known as a "shared everything" system, does not usually exceed 16 processors. In massively parallel
processing (MPP), up to 200 or more processors can work on the same application. Each processor has
its own operating system and memory, but an "interconnect" arrangement of data paths allows
messages to be sent between processors.
Distributed OS :- An operating system that manages a group of different independent computers
which are linked with each other and communicate with each other through various communication
lines (such as high-speed buses or telephone lines). Distributed systems use multiple central processors
to serve multiple real time application and multiple users. Data processing jobs are distributed among
the processors accordingly to which one can perform each job most efficiently.
The advantages of distributed systems are following.
 With resource sharing facility user at one site may be able to use the resources available at another.
 Speedup the exchange of data with one another via electronic mail.
 If one site fails in a distributed system, the remaining sites can potentially continue operating.

Q Write down a short note on MS DOS. Describe its five commands.


Answer: Microsoft Disk operating system, MS-DOS is a non-graphical command line operating
system. MS-DOS allows the user to navigate, open, and otherwise manipulate files on their computer
from a command line instead of a GUI like Windows.
Disk operating system , originally developed by microsoft for IBM.
DOS is still a 16-bit operating system and does not support multiple users or multitasking.
DOS Commands are divided into 2 types:

1.Internal Commands: An Internal command, which is a command embedded into the


command.com file. These are for performing basic operations on files and directories and
they do not need any external file support.

2. External Commands: An external command, which is not embedded into command.com and
therefore requires a separate file to be used. For example, if your computer does not have the
fdisk.exe file and you try using the fdisk command, you would receive an error "Bad command
or file name" error message. Fdisk is an external command that only works if fdisk.exe, or in
some cases, fdisk.com, is present.
These external commands are for performing advanced tasks and they do need some external
file.
Most Commonly Used Internal DOS Command
 DATE
This command is used to display the system current date setting and prompt you to enter a new
date. The syntax is: DATE[/T | date]
If you type DATE without parameters then it displays current date and prompts to enter new
date. We should give new date in mm-dd-yy format. If you want to keep the same date just
Press ENTER. DATE command with /T switch tells the command to just output the current
system date, without prompting for a new date.

2. TIME
This command is used to displays or set the system time.
The syntax is: TIME[/T | time]

Same as DATE command, typing TIME with no parameters displays the current time and a
prompt for a new one. Press ENTER to keep the same time. TIME command used with /T
switch tells the command to just output the current system time, without prompting for a new
time.

3. COPY CON
It is used to create a file in the existing directory. Here CON is a DOS reserved word which
stands for console.
Syntax is: COPY CON filename after that press Enter and start typing your text and after

you're done typing your text, to save and exit hit F6 key.

4. REN: This command is used to change/modify the name of a file or files.


Syntax is: REN[drive:][path]filename1 filename2.

Here, filename1 is source file for which you wanted to change the name, and filename2 will obviously
becomes your new file name. Also note that you cannot specify a new drive or path for your destination
file.
5. TYPE : This command is used to display the contents of a text file or files. The syntax is: TYPE
[drive:][path]filename.
6. CLS: It is used to clear the screen. Syntax is CLS

Q Explain the architecture of Linux operating system.


Answer:
Linux System Architecture is consists of following layers
 Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
 Kernel - The kernel is the central module of an operating system (OS). It is the part of the
operating system that loads first, and it remains in main memory. Because it stays in memory, it
is important for the kernel to be as small as possible while still providing all the essential
services required by other parts of the operating system and applications. The kernel code is
usually loaded into a protected area of memory to prevent it from being overwritten by
programs or other parts of the operating system.

Typically, the kernel is responsible for memory management, process and task management, and
disk management. The kernel connects the system hardware to the application software. Every
operating system has a kernel. For example the Linux kernel

 Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes
commands from user and executes kernel's functions.
 Utilities - Utility programs giving user most of the functionalities of an operating systems.

Q Explain important features of linux operating system.

Answer: Following are some of the important features of Linux Operating System.
 Portable - Portability means softwares can works on different types of hardwares in same
way.Linux kernel and application programs supports their installation on any kind of hardware
platform.
 Open Source - Linux source code is freely available and it is community based development
project. Multiple team works in collaboration to enhance the capability of Linux operating
system and it is continuously evolving.
 Multi-User - Linux is a multiuser system means multiple users can access system resources like
memory/ ram/ application programs at same time.
 Multiprogramming - Linux is a multiprogramming system means multiple applications can
run at same time.
 Hierarchical File System - Linux provides a standard file structure in which system files/ user
files are arranged.
 Shell - Linux provides a special interpreter program which can be used to execute commands of
the operating system. It can be used to do various types of operations, call application programs
etc.
 Security - Linux provides user security using authentication features like password protection/
controlled access to specific files/ encryption of data.
Short Notes on windows
Microsoft Windows is a popular operating system software for computers. Windows is made by
the Microsoft company. Almost 90% of desktop and laptop computers have Windows installed
(included). The newest version of Windows is Windows 8.1, though Windows 10 is currently being
developed and will come out later in 2015.

Windows makes it easier to run programs (applications) than DOS did. It also helps people keep their
files safe and in order.
Some programs are included with Windows. Some examples are:

 Wordpad – to write simple documents.


 Photo viewer – to look at pictures.
 Paint – to make simple drawings.
 Internet Explorer web browser – to use the Internet to look at web pages and download files.
 Windows Media Player – to listen to music and watch videos.

Short notes on Android Operating system


Android is a mobile operating system developed by Google. It is used by several smartphones, such as
the Motorola Droid, the Samsung Galaxy, and Google's own Nexus One.
The Android operating system (OS) is based on the open Linux kernel. Unlike the iPhone OS, Android
is open source, meaning developers can modify and customize the OS for each phone. Therefore,
different Android-based phones may have different graphical user interfaces GUIs even though they
use the same OS.
Android phones typically come with several built-inapplications and also support third-party programs.
Developers can create programs for Android using the free Android SDK (Software Developer Kit).
Android programs are written in Java and run through Google's "Davlik" virtual machine, which is
optimized for mobile devices. Users can downloadAndroid "apps" from the online Android Market.
Definitions hardware, software, Assembler, Compiler, Interpreter
Main parts of digital computer are:
Hardware
Software

Computer hardware is the collection of physical elements that constitutes a computer system.
Computer hardware refers to the physical parts or components of a computer such as the monitor,
mouse, keyboard, computer data storage, hard drive disk (HDD), system unit (graphic cards, sound
cards, memory, motherboard and chips), etc. all of which are physical objects that can be touched
(known as tangible). In contrast, software is instructions that can be stored and run by hardware.

Computer Software: Instruction is a single word or expression that represents one operation. Program
is a relevant set of instructions to perform a well defined task. Software is a set of programs related to
one particular application. Software is the interface between the user and the hardware. Users mainly
interact with the computer through the software.

1. System Software: System software is responsible for managing the various independent hardware
components enabling them to coordinate their work. . It controls the execution of the application
programs as well. System s/w is written in low level language. System software comprises of the
following.

(i) Operating system: It helps different parts of a computer to work together along with providing a
platform to run different high-level system software.

(ii) Language Translator: Language translators are used to convert source code into machine codes.
Source codes are written in assembly or high level languages. These are language translators: (a)
Assembler, (b) Interpreter, and (c) Compilers

(iii) Simulators: Simulators are large System Software used to simulate execution of program of other
computer. A flight simulation program mimics flying airplane.

(iv) Emulators: It is used to mimics functionality of other program, computer, modem, printer etc. It is
also used to convert program written in one language into other language.

(v) Utility Software: The commons purpose small program is called Utilities Software used in file
management, Memory management, mail-merging, virus scanning, and disk repairing and backup
programs.
2. Application software: Application software is developed for a specific user application. There are
two categories of application softwares:

(i) Customized/Tailor-made Application software: These software are developed according to the need
of a particular user/organization. They are not available ready-made in the market.. Example: Software
for Payroll for Specific organization, Software for specific Bank, Software for Railway Reservation,
Hotel Reservation etc.

(ii) Packaged/Off-the-shelf Application software: Packaged Software is readymade, bug free, advance
and standard software for special work. These software are ready-made software developed by software
development companies and can be purchased and used. E.g. (a)Database Management Software: MS-
Access, dBase-IV, Clippers, Oracle, OMNIS, Ingress, Integra, FoxPro, FQXBASE, SQL, etc.

(b) Word Processing Software –: MS-Word, Word Perfect, Word Star, etc.

(c) Spreadsheet software – This is generally used for business applications as the software helps to
record transactions and execute financial calculations. E.g. MS-Excel, Lotus-123, QuattroPro, etc.

(d) Graphics and Presentation: MS-Paint, MS PowerPoint, CorelDraw, Adobe Photoshop, Adobe
Illustrator

(e) Animation: Macromedia Director, Macromedia Flash, Adobe Image Ready, Adobe Premiere,
Adobe After Effect

(f) Web Designing: Macromedia Dreamweaver, Microsoft FrontPage Express

Assembler

An assembler translates assembly language into machine code. Assembly language consists of
mnemonics for machine opcodes so assemblers perform a 1:1 translation from mnemonic to a direct
instruction. For example:

LDA #4 converts to 0001001000100100

Conversely, one instruction in a high level language will translate to one or more instructions at
machine level.

Advantages of using an Assembler:


1. Very fast in translating assembly language to machine code as 1 to 1 relationship
2. Assembly code is often very efficient (and therefore fast) because it is a low level language
3. Assembly code is fairly easy to understand due to the use of English-like mnemonics

Disadvantages of using Assembler:


1. Assembly language is written for a certain instruction set and/or processor
2. Assembly tends to be optimised for the hardware it's designed for, meaning it is often incompatible
with different hardware
3. Lots of assembly code is needed to do relatively simple tasks, and complex programs require lots of
programming time
Linker

A linker is a program that combines object modules to form an executable program. In addition to
combining modules, a linker also replaces symbolic addresses with real addresses. Link editors are
commonly known as linkers. The compiler automatically invokes the linker as the last step in
compiling a program. The linker inserts code (or maps in shared libraries) to resolve program library
references, and/or combines object modules into an executable image suitable for loading
into memory.
Two types of linking is available:
Dynamic linking
In dynamic linking , actual linking with the library routines does not occur until the image is run, when
both the executable and the library are placed in memory. An advantage of dynamic linking is that
multiple programs can share a single copy of the library.
In short, dynamic linker postpones the linking function until execution time.
Static linking
In static linking, linker copies all library routines used in the program into the executable image. This
may require more disk space and memory than dynamic linking, but is both faster and more portable,
since it does not require the presence of the library on the system where it is run.
Loader
When the user is ready to run the linked program, a simple relocating loader can be used to load the
program into memory.
A loader is a system program that performs the loading function. It brings object program into memory

and starts its execution.


Fig. 2 Role of Loader
Type of Loaders
The different types of loaders are, absolute loader, bootstrap loader, relocating loader (relative loader),
and, direct linking loader.
Bootstrap Loader
When a computer is first turned on or restarted, a special type of absolute loader, called bootstrap
loader is executed. This bootstrap loads the first program to be run by the computer - usually an
operating system. The bootstrap itself begins at address 0.

Absolute Loader
The operation of absolute loader is very simple. The object code is loaded to specified locations in the
memory.
Disadvantage of absolute loaders
One of the most disadvantage is that programmer has to specify the actual starting address, from where
the program to be loaded. This does not create difficulty, if one program to run, but not for several
programs.

Relocatable loaders
The concept of program relocation is, the execution of the object program using any part of the
available and sufficient memory. The object program is loaded into memory wherever there is room for
it. The actual starting address of the object program is not known until load time. Relocation provides
the efficient sharing of the machine with larger memory and when several independent programs are to
be run together. It also supports the use of subroutine libraries efficiently. Loaders that allow for
program relocation are called reallocating loaders or relative loaders.

Algorithm- An algorithm is a set of instructions designed to perform a specific task. It is the analytical
way of solving a problem. Algorithm is done step by step and in any case First step is named as start
and last as stop.

Characteristics of algorithm
1) Finiteness: - an algorithm terminates after a finite numbers of steps.

2) Definite: - each step in algorithm is unambiguous. This means that the action specified by the step cannot be
interpreted (explain the meaning of) in multiple ways & can be performed without any confusion.

3)Input:-an algorithm accepts zero or more inputs

4) Output:- it produces at least one output.

5) Effectiveness:- it consists of basic instructions that are realizable. This means that the instructions can be
performed by using the given inputs in a finite amount of time.
Q1.Write an algorithm to add two numbers.

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2
Step 5: Display sum

Step 6: Stop

Q2.Write an algorithm to find out number is odd or even

Ans. step 1 : start

step 2 : input number

step 3 : rem←number mod 2

step 4 : if rem=0 then

print "number even"

else

print "number odd"

endif

step 5 : stop

Q3.Write an algorithm to find the largest among three different numbers entered by user.

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a>b

If a>c

Display a is the largest number.

Else

Display c is the largest number.

Else

If b>c

Display b is the largest number.


Else

Display c is the greatest number.

Step 5: Stop

Q4.Write an algorithm to find the factorial of a number entered by user.

Step 1: Start

Step 2: Declare variables n,factorial and i.

Step 3: Initialize variables

factorial←1

i←1

Step 4: Read value of n

Step 5: Repeats the steps until i=n

5.1: factorial←factorial*i

5.2: i←i+1

Step 6: Display factorial

Step 7: Stop

Q5. Write an algorithm to check whether a number entered by user is prime or not.

Step 1: Start

Step 2: Declare variables n,i,flag.

Step 3: Initialize variables

flag←1

i←2

Step 4: Read n from user.

Step 5: Repeats the steps until i<(n/2)

5.1 If remainder of n÷i equals 0


flag←0

Go to step 6

5.2 i←i+1

Step 6: If flag=0

Display n is not prime

else

Display n is prime

Step 7: Stop

Q6. Write an algorithm to find the Fibonacci series till term≤1000.

Step 1: Start

Step 2: Declare variables first_term,second_term and temp.

Step 3: Initialize variables first_term←0 second_term←1

Step 4: Display first_term and second_term

Step 5: Repeats the steps until second_term≤1000

5.1: temp←second_term

5.2: second_term←second_term+first term

5.3: first_term←temp

5.4: Display second_term

Step 6: Stop

Q7. Write an algorithm to find all roots of a quadratic equation ax2+bx+c=0.

Step 1: Start

Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;

Step 3: Calculate discriminant

D←b2-4ac
Step 4: If D≥0

r1←(-b+√D)/2a

r2←(-b-√D)/2a

Display r1 and r2 as roots.

Else

Calculate real part and imaginary part

rp←b/2a

ip←√(-D)/2a

Display rp+j(ip) and rp-j(ip) as roots

Step 5: Stop

Flowchart

A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the steps
as boxes of various kinds, and their order by connecting them with arrows. Symbols Used In Flowchart

More symbols

Connector Symbol Indicates that the flow continues where a matching


symbol (containing the same letter) has been placed.
Q1. Draw a flowchart to add two numbers entered by user.

Q2. Draw flowchart to find the largest among three different numbers entered by user.

Q3. Draw flowchart to find


all the roots of a quadratic
equation ax2+bx+c=0
Q4. Draw a flowchart to find the Fibonacci series till term≤1000.

Definition of Editor: an editor is a software program that allows users to create or manipulate plain
text computer files.
Or
Editor of any language is a software which provide environment to develop any program in that
particular language.
There are several kinds of editors.

Examples of text editors

Notepad, WordPad, = Microsoft Windows included text editors.


TextEdit = Apple computer text editor.
Emacs = Text editor for all platforms that is a very powerful text editor once you've learned all of its
commands and options.

Programming Languages
We need to write instructions and programs to solve a problem by the computer. For writing programs
we need a formal language, which is called a programming language.
There are two types of programming languages
 Low-level language
o Machine language
o Assembley language
 High- level language
o BASIC, COBOL, FORTRAN, PASCAL, C, C++, JAVA etc.
We have generations of programming languages. These ranges from machine level languages (1GL) to
languages necessary for AI & Neural Networks (5GL).

Machine language is lower level language which uses a combination of binary digits( 0 & 1) to write
code.
o These languages can directly communicate to hardware.
o This language is machine dependent. Programmer has to understand the internal architecture of
the computer system to write a program.
o The programs are not portable.
o , it is difficult to read, write and modify these programs.
o These programs are very efficient in terms of speed.

Assembly language is second generation of language which is also low level language.
o It is also known as symbolic language.
o Instead of strings of 0 and 1, they use symbols called as mnemonics.
o But these programs cannot be directly understood by the computer.
o Each instruction written in assembly language needs to be converted to machine language using
a translator called as assembler.
o Easier to understand, read, write and modify by the programmer.
o Assembly language is also machine dependent and not portable.

Assembly Machine
Language ASSEMBLER Language
Program Program

One-to-One
(source program) (object program)
correspondence
High level Programming languages : 3rd generation languages
These languages enable the programmer to write a program in simple English and familiar
mathematical symbols.
 The program written in high level language needs to be converted to machine language using
compiler/interpreter (translator). Translators in themselves are software that resides on
secondary storage.
 These languages are architecture independent and portable.
 Unlike assembly language (1-to-1 correspondence with machine language), one high level
language instruction is generally converted into many machine level instructions.
 These languages are easy to learn, read, write and modify.
 These programs are less efficient in terms of speed and require more memory storage.
 Third generation programming languages are called as procedural languages as a programmer
needs to define each step to get the task done.

High-level COMPILER/ Machine


Language INTERPRETER Language
Program Program

One-to-Many
(source program) (object program)
correspondence
Fourth Generation Programming Language: These are similar or closer to human languages.
General characteristics of 4GL are:
 Portable
 Database supportive
 Non procedural
Different types of 4 GL are: Query language,Report generator,Form Generator,GUI Generator,
Relational Database Manager

Fifth Generation Programming Language


Languages used for writing programs for Artificial Intelligence, Neural Network, Plasma Computing
etc. come under 5GL. This is the future of programming language. Eg. LISP, PROLOG

Compiler : A compiler is a system software that translates the high level language into machine
language. When a user writes a code in a high level language such as C,Java and wants it to execute, a
specific compiler which is designed for C or Java is used before it will be executed.
Interpreters: Interpreters are not much different than compilers. They also convert the high level
language into machine readable binary equivalents. Each time when an interpreter gets a high level
language code to be executed, it converts the code into an intermediate code before converting it into
the machine code. Each part of the code is interpreted and then execute separately in a sequence and an
error is found in a part of the code it will stop the interpretation of the code without translating the next
set of the codes.

Difference b/w Compiler and Interpreter

COMPILER INTERPRETER
1. Compiler translates the entire program 1. Translates the program statement by
from high level language to machine statement.
language in one go.
2. All the syntax errors are reported after 2. The syntax errors are reported after
translation and the program can be translating each statement and when the
executed only after all the error are errors are removed that statement is
removed. executed before translating the next
statement.
3. Object code is generated and saved. 3. Object code not saved.
There is no need to translate the program
again if the source code is not changed.
4. Faster then interpreter. 4. Comparatively slower.
5. example: C, C++ etc. 5. example: BASIC, Visual basic, etc.

Q. What do you understand by memory hierarchy? Name the general classes of storage media
that might make up a memory hierarchy.

Ans: There is a trade-off to be made while designing the systems architecture in the context of
computer memory, among the three key characteristics of memory, namely cost, capacity
and access time. The plan is not to rely on a single memory component to technology, but to
employ a memory hierarchy, as shown below. Going down the hierarchy, the following
thing occurs:
• Decreasing cost per bit
• Increasing Capacity
• Increasing access time i.e. slower memory
• Decreasing frequency of access of the memory by the CPU
Following is a traditional memory hierarchy.

REGISTERS
CACHE
MAIN MEMORY
MAGNETIC DISKS
MAGNETIC TAPE

Q. Distinguish between the following:


(i) Syntactic error and semantic error
(ii) Run time error and logical error
Ans:(i)Syntactic error and semantic error
Syntactic errors also known as compilation errors are caused by violation of the grammar rules of the language.
The compiler detects, isolate these errors and give terminate the source program after listing the errors. Some of
the common syntactic errors are:
• missing or misplaced ; or }
• missing return type for a procedure
• missing or duplicate variable declaration
Semantic errors are logical errors. If there is a semantic error in a program, it will run successfully, in the sense
that the computer will not generate any error messages, but it will not do the right thing. The problem is that the
meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires
working backward by looking at the output of the program and trying to figure out what it is doing.
(ii) Run time error and logical error
Run-time errors: Errors such as mismatch of data types or array out of bound error are known as runtime errors.
These errors are generally go undetected by the compiler so programs with run-time error will run but produce
erroneous results.
Logical errors: These are the errors related with the logic of the program execution. These errors are not
detected by the compiler and are primarily due to a poor understanding of the problem or a lack of clarity of
hierarchy of operators. Such errors cause incorrect result.

Unit II
C FundamentalS:
Data Types: DATA TYPES
Primitive or fundamental data type
void – used to denote the type with no values
int – used to denote an integer type
char – used to denote a character type
float, double – used to denote a floating point type
Derived Data Types
Array – a finite sequence (or table) of variables of the same data type
Pointer - int *, float *, char * – used to denote a pointer type, which is a memory address type.
Function-- Set of statements grouped together into single logical unit is refered to as function.

various data types used in c

We can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator
Types Session.

Here is an example to check size of memory taken by various datatypes.

int
main()
{
printf("sizeof(char) == %d\n", sizeof(char));
printf("sizeof(short) == %d\n", sizeof(short));
printf("sizeof(int) == %d\n", sizeof(int));
printf("sizeof(long) == %d\n", sizeof(long));
printf("sizeof(float) == %d\n", sizeof(float));
printf("sizeof(double) == %d\n", sizeof(double));
printf("sizeof(long double) == %d\n", sizeof(long double));
printf("sizeof(long long) == %d\n", sizeof(long long));

return 0;
}
DATA TYPE QUALIFIERS
Each of these data type has got qualifiers. The purpose of a qualifier is to manipulate the range of a particular
data type or its size.
Size qualifier
Size qualifiers alter the size of basic data type. The keywords long and short are two size qualifiers.
Example: Integer data type int is normally 2 byte. If you declare it as long int – then its size will increase from 2
bytes to 4 bytes. Similarly if you declare it as short int – its size will reduce from 2 bytes to 1 byte.
Sign qualifier
Whether a variable can hold only positive value or both values is specified by sign qualifiers. Keywords signed
and unsigned are used for sign qualifiers.
Example: int – when declared normally is of 2 bytes. If it is declared as unsigned int – then its range is from 0
to 65535. In other case, if it is declared as signed int – then its range is from (-32767 to 32768). In the case of
signed int, one bit (MSB) is used to store the sign of the integer +/-. This basically means the programmer will
not be able to display/store a number higher than 65535 using unsigned int. Similarly it is not possible to
manipulate a number beyond -32767 or +327678 using signed int.
The table below describes all data types and the most commonly used qualifier combinations – with its size,
range and format specifier.
Keyword Format Specifier Size Date Range
char %c 1 byte -128 to +127
int %d 2 bytes 0 to 255
float %f 4 bytes -3.4e38 to +3.4e38
double %lf 8 bytes -1.7e38 to +1.7e38
long int %ld 4 bytes -231 to +231
unsigned int %u 2 bytes 0 to 65535
long double %Lf 16 bytes -3.4e38 to +3.4e38
Unsigned char %c 1 byte 0 to 255

Constant qualifiers
Constant qualifiers can be declared with keyword const. An object declared by const cannot be modified.

const int p=20;


The value of p cannot be changed in the program.
Volatile qualifiers:
A variable should be declared volatile whenever its value can be changed by some external sources outside
program. Keyword volatile is used to indicate volatile variable.

TYPES OF VARIABLES DEPENDING UPON PLACE OF DECLARATION


A. Global Variables/External Variables B. Local Variables/Internal Variables

B. Local Variables: or Internal Variables


1. These variables are declared inside a function.
2. Only the function which has the variable declaration can access the local variables.
3. Every function can access only its own local variable, but cann’t access the local variables of other functions.
i.e., variables are protected within function.
4. The local variables are created when the function is invoked and is destroyed when the function is exited.

For example:--

main()

{ int i=4;
int j=10;

i++;

if (j > 0)

{ /* i defined in 'main' can be seen */

printf("i is %d\n",i);

if (j > 0)

/* 'i' is defined and so local to this block */

int i=100;

printf("i is %d\n",i);

}/* 'i' (value 100) dies here */

printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/

This will generate following output

i is 5

i is 100

i is 5

Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is
equivalent to i = i + 1;

You will see -- operator also which is called decremental operator and it idecrease the value of any integer variable
by 1. Thus i-- is equivalent to i = i - 1;

A. Global Variables: also called External Variables


1. The variables that are declared outside all functions are called global variables.
2. Lifetime of these variables is throughout the program.
3. Scope is from the point of declaration to the end of the program.
4. Global variables are automatically initialised to zero, when they are declared.
5. They are allocated space in the global memory section.
6. All the functions can access the global variables after declaration.
7. Global variables can be accessed by other programs e.g. in multifile programs
8. In case a local variable and a global variable, the local variable will have precedence over global variable.
int i=4; /* Global definition */

main()
{
i++; /* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}

func()
{
int i=10; /* Local definition */
i++; /* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}

This will produce following result


Value of i = 11 -- func() function
Value of i = 5 -- main function

i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When
control returns to main the internal variable will die and and any reference to i will be to the global.

Format Specifiers :-- Special codes which starts with % and used format the data for input and ouput
o %d decimal
o %o Octal
o %x or %X Hexa Decimal
o %i Integer
o %f Fixed Float
o %e or %E Scientific Float
o %g or %G General Float
o %lf double and long double
o %c Char
o %s String (Do not accept space in input)
o %[^\n] String (Allows to read any data including spaces till Enter key is
 pressed)
o %u Unsigned
o %ld long int
o %p Show to addresses in Hexa Decimal
 Escape-sequence: Character combinations consisting of a backslash (\) followed by a letter or
by a combination of digits are called "escape sequences."
 Escape sequences are typically used to specify actions such as carriage returns and tab
movements on terminals and printers. They are also used to provide literal representations of
nonprinting characters and characters that usually have special meanings, such as the double
quotation mark (").
Escape Sequence Represents
\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\\ Backslash

Case 1
void main()
{
printf("Pakistan\rIndia");
getch();
}

Output
Indiatan
Case 2
WAP to print the following
He said, “\n” is made for new line
void main()
{
printf("He said,\"\\n\" is made for new line");
getch();
}
String LiteralsStrings are enclosed in double quotes. Each string is terminated by a NULL character.
char name[]=”Vikas”; //6 bytes
Case 1
What is the output of the following?
void main()
{
char str[]="vikas\007\a";
printf("%d",sizeof(str));
getch();
}

Operators
1. Arithmetic Operators
2. Type Cast Operator
3. Relational or Conditional Operators
4. Logical Operators
5. Bitwise operators
6. Assignment operators
Arithmetic Operators
+
-
*
/ (5/2=2) (5.0/2 or 5/2.0 = 2.5)
%
Note: use math.h header file for other mathematical functions
What is the output of the following?
#include<stdio.h>
void main()
{
int a=5,b=2;
float c=a/b;
printf("Division of %d and %d is %f",a,b,c);
getch();
}

Type Cast Operator


An operator used to convert one kind of data to another kind of data is called as type cast operator.
Enclose the data type inside the brackets to make the type cast operator.
#include<stdio.h>
void main()
{
int a,b;
float c;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
c=(float)a/b; //type cast operator
printf("Division of %d and %d is %f",a,b,c);
getch();
}
Relational Operators
Used to compare two values and return the result as 0 or 1
If the condition is true then returns 1
If the condition is false then returns 0

There are six relational operators


== equals to
!= not equals to
> Greater than
>= Greater than or equals to
< Less than
<= Less than or equals to
Example
void main()
{
int n=5 + 7 > 6; //12 > 6 = 1
printf("%d",n);
getch();
}
Example
void main()
{
int n=5 + (7 > 6); //5 + 1 = 6
printf("%d",n);
getch();
}
void main()
{
int n=12 - 2 > 6; //10 > 6 = 1
printf("%d",n);
getch();
}

Logical Operators
Operators used to combine two conditions are called as logical operators
&& Logical And
|| Logical Or
! Logical Not
Truth Tables
For &&
F F  F
F T  F
T F  F
T T  T
For ||
F F  F
F T  T
T F  T
T T  T

For !
T  F
F  T
Notes
1. In case of &&, if first condition is false then second is not checked
2. In case of ||, if first condition is true then second is not checked
3. All values other than 0 are treated as true
What is the output of the following?
int n=6 && printf(“%d”,printf(“%d”,printf(“Hello”)));
printf(“%d”,n);
Output
Hello511

What is the output of the following?


int n=6 || printf(“%d”,printf(“%d”,printf(“Hello”)));
printf(“%d”,n);
Output
1
Bitwise Operators
The operators which first convert a number into bits then operate.
& Bitwise And
| Bitwise Or
^ Bitwise XOR
~ Bitwise Not
<< Left Shift
>> Right Shift
Example
int n=6 & printf(“Hello”);
printf(“%d”,n);
Output
Hello4
Example
int n=6 | printf(“Hello”);
printf(“%d”,n);
Output
Hello7
Example
int n = 6 << 3;
printf(“%d”,n);

Output
48
1. WAP to input a number and check it to be divisible by 7 and 9.
2. WAP to input and check its right most digit to be greater than second rightmost digit
3. WAP to input an alphabet and check it to be vowel or consonant

a=567;
ld=a%10; //ld is 7 and a is 567
a=a/10; // 56
sld=a%10; //6

STORAGE CLASSES:
There are 4 storage classes. A variable in ‘C’ can have any one of the 4 storage classes.
1. Automatic Variables or Local Variables
2. External Variables or Global Variables
3. Static Variables
4. Register Variables

Scope of Variables or Visibility: This refers to those parts of the program where the variable is accessible or
active or visible for use ( e.g. for calculations etc.)

Lifetime of Variable: It refers to the period during which the variable retains the memory location or retains a
given value during execution of a program (i.e. it is alive). Here, the variable can be active or dormant but it is
alive not destroyed.
Storage class tells us: 1) Where the variable is stored. 2) Initial value of the variable. 3) Scope of the
variable. Scope specifies the part of the program which a variable is accessed. 4) Life of the variable.
Keyword Declaration Declaration Accessibility Existence/ Place of Default
Statement Or Scope Lifetime Storage value

AUTOMATIC STORAGE CLASS: In this automatic storage class, Variable is stored in memory. Default
value is garbage value Scope is local to the block Life is, with in the block in which the variable is defined
REGISTER STORAGE CLASS: Variable is stored in CPU registers. Default value is garbage value.
Scope is local to the block. Life is,with in the block in which the variable is defined. We can not use register
storage class for all types of variables. For example: register float f;
STATIC STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local to the block.
Life is,value of the variable persists between different function calls. Example :
main()
{
add();
add();
}
add()
{
static int i=10;
printf(“ %d”,i);
i+=1;
}
Output:
10 11
EXTERNAL STORAGE CLASS: Variable is stored in memory. Default value is zero. Scope is local to the
block. Life is,as long as the program execution doesn’t come to an end.

Summary of the Main Features of the various Storage Classes


auto auto datatype Within Accessible within the Exists from the time of Primary Garbage
var_name; function or function or block invocation of function memory value
block where it is declared to its return to the
calling function OR
from the time of entry
into the block to the end
of the block.
extern extern datatype Outside all Accessible within the Exists as long as the full Primary Zero
var_name; functions or combination of program is in execution. memory
within program modules that
This var has function form the full program.
been declared
somewhere else
as a global or
external variable.
register register datatype Within a Accessible within the Exists from the time of CPU Garbage
var_name; function or function or block invocation of function register value
block where it is declared to its return to the
calling function OR
from the time of entry
into the block to the end
of the block
static static datatype Within a Internal static: Internal static: Primary zero
var_name; function or Accessible within the Preserves the value memory
block function or block between the function
where it is declared calls or block entries.
static datatype Outside all External static: External static: Primary zero
var_name; functions Accessible within the Preserves the value in memory
program file where it the program file.
is declared and not
other files.

Unit-III
Control Statements:

Program Blocks and Loops:

A program block is a group of statements that have the following two characteristics: They have a
single entry point and a single exit point. A loop has a program block at its heart. A loop is used to
repeatedly perform an operation or a block of code through the use of a conditional expression.

Control Structures:

The C language control statements include the if/else, the do/while, the while, the for loop, and the
switch/case. The nature of the loop or control structure used determines the number of times the
statements (or code block) are executed, if executed at all. Nesting of control structures also allows for
more detailed and complex software.

Structured programming is a technique for organizing and coding programs that reduces complexity,
improves clarity, and facilitates debugging and modifying. The benefits are listed below:
1. Operation is simple to trace
2. Structures are self-documenting
3. Structures are easy to define in flowcharts
4. Structured programming increases programmer productivity
5. Structures lead to functions

IF STATEMENT
• If statement is the simplest form of decision control statements that is frequently used in
decision making. The general form of a simple if statement is shown in the figure.
• First the test expression is evaluated. If the test expression is true, the statement of if block
(statement 1 to n) are executed otherwise these statements will be skipped and the execution
will jump to statement x.
FALSE
Test
Expression

TRUE

Statement Block 1

Statement x

SYNTAX OF IF STATEMENT

if (test expression)
{
statement 1;
..............
statement n;
}
statement x;

© Oxford University Press 2012. All rights reserved.

IF ELSE STATEMENT
• In the if-else construct, first the test expression is evaluated. If the expression is true, statement
block 1 is executed and statement block 2 is skipped. Otherwise, if the expression is false,
statement block 2 is executed and statement block 1 is ignored. In any case after the statement
block 1 or 2 gets executed the control will pass to statement x. Therefore, statement x is
executed in every case.

FALSE

Test
Expression
SYNTAX OF IF STATEMENT TRUE

if (test expression)
Statement Block 1 Statement Block 2
{
statement_block 1;
}
else
{
statement_block 2; Statement x
}
statement x;

© Oxford University Press 2012. All rights reserved.


ITERATIVE STATEMENTS
• Iterative statements are used to repeat the execution of a list of statements, depending on the
value of an integer expression. In this section, we will discuss all these statements.
While loop
Do-while loop
For loop

WHILE LOOP
• The while loop is used to repeat one or more statements while a particular condition is true.
• In the while loop, the condition is tested before any of the statements in the statement block is
executed.
• If the condition is true, only then the statements will be executed otherwise the control will jump
to the immediate statement outside the while loop block.
• We must constantly update the condition of the while loop. Statement x

Update the
condition TRUE Condition
expression
while (condition)
{ FALSE
statement_block; Statement Block
} Statement y
statement x; © Oxford University Press 2012. All rights reserved.

DO WHILE LOOP
• The do-while loop is similar to the while loop. The only difference is that in a do-while loop, the
test condition is tested at the end of the loop.
• The body of the loop gets executed at least one time (even if the condition is false).
• The do while loop continues to execute whilst a condition is true. There is no choice whether to
execute the loop or not. Hence, entry in the loop is automatic there is only a choice to continue
it further or not.
• The major disadvantage of using a do while loop is that it always executes at least once, so
even if the user enters some invalid data, the loop will execute.
• Do-while loops are widely used to print a list of options for a menu driven program.

Statement x

Statement x; Statement Block


do
{
Update the condition expression
statement_block;
} while (condition); TRUE
statement y;
Condition

FALSE
Statement y
© Oxford University Press 2012. All rights reserved.

Program to demonstrate the use of while loop and do while loop

// PROGRAM TO PRINT NUMBERS FROM 0 TO 10 USING WHILE LOOP


#include<stdio.h>
int main()
{
int i = 0;
while(i<=10)
{
printf(“\n %d”, i);
i = i + 1; // condition updated
}
return 0;
}

// PROGRAM TO PRINT NUMBERS FROM 0-10 USING DO-WHILE LOOP


#include<stdio.h>
int main()
{
int i = 0;
do
{
printf(“\n %d”, i);
i = i + 1;
} while(i<=10);
return 0;
}

FOR LOOP

• For loop is used to repeat a task until a particular condition is true.


• The syntax of a for loop

for (initialization; condition; increment/decrement/update)


{
statement block;
}
Statement Y;

• When a for loop is used, the loop variable is initialized only once.
• With every iteration of the loop, the value of the loop variable is updated and the condition is checked. If
the condition is true, the statement block of the loop is executed else, the statements comprising the
statement block of the for loop are skipped and the control jumps to the immediate statement following
the for loop body.
• Updating the loop variable may include incrementing the loop variable, decrementing the loop variable
or setting it to some other value like, i +=2, where i is the loop variable.

Look at the code given below which print first n numbers using a for loop.
#include<stdio.h>
int main()
{
int i, n;
printf(“\n Enter the value of n :”);
scanf(“%d”, &n);
for(i=0; i<= n; i++)
printf(“\n %d”, i);
return 0;
}
SWITCH CASE
• A switch case statement is a multi-way decision statement. Switch statements are used:
When there is only one variable to evaluate in the expression
When many conditions are being tested for
• Switch case statement advantages include:
Easy to debug, read, understand and maintain,
Execute faster than its equivalent if-else construct
switch(grade)
{
case 'A': printf("\n Excellent");
break;
case 'B': printf("\n Good");
break;
case 'C': printf("\n Fair");
break;
default: printf("\n Invalid Grade");
break;
}
// PROGRAM TO PRINT THE DAY OF THE WEEK

#include<stdio.h>
int main()
{
int day;
printf(“\n Enter any number from 1 to 7 : “);
scanf(“%d”,&day);
switch(day)
{
case 1: printf(“\n SUNDAY”); break;
case 2 : printf(“\n MONDAY”); break;
case 3 : printf(“\n TUESDAY”); break;
case 4 : printf(“\n WEDNESDAY”); break;
case 5 : printf(“\n THURSDAY”); break;
case 6 : printf(“\n FRIDAY”); break;
case 7 : printf(“\n SATURDAY”); break;
default: printf(“\n Wrong Number”);
}
return 0;
}

/* WAP to get an alphabet and check it to be vowel or consonant */


void main()
{
char ch;
printf("Enter an alphabet : ");
ch=getchar();
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
{
switch(ch)
{
case 'a' : case 'A' :
case 'e' : case 'E' :
case 'o' : case 'O' :
case 'i' : case 'I' :
case 'u' : case 'U' :
printf("%c is a vowel",ch);
break;
default: printf("%c is a consonent",ch);
}
}
else
printf("Sorry! %c is not an alphabet",ch);
getch();
}
/*WAP to get two numbers and print the bigger one */
void main()
{ int a,b;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
printf("Greater is %d",a>b?a:b);
getch();
}
/*WAP to get three numbers and print the biggest one */
void main()
{
int a,b,c,g;
printf("Enter three numbers : ");
scanf("%d%d%d",&a,&b,&c);
g=a>b? (a>c?a:c) : (b>c?b:c);
printf("Greatest is %d",g);
getch();
}
Example 1
/* WAP to input a number and print table of it */
/* Using while loop */
void main()
{
int n,i;
printf("Enter the number : ");
scanf("%d",&n);
i=1;
while(i<=10)
{
printf("%3d x %3d = %3d\n",n,i,n*i);
i++;
}
getch();
}
Example 2
/* WAP to input a number and print table of it */
/* Using for loop */
void main()
{
int n,i;
printf("Enter the number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d x %3d = %3d\n",n,i,n*i);
getch();
}
Example 3
/* WAP to input a number and print table of it */
/* Using do-while loop */
#include<stdio.h>
void main()
{
int n,i;
char ans;
do
{
printf("Enter the number : ");
scanf("%d",&n);
for(i=1;i<=10;i++)
printf("%3d x %3d = %3d\n",n,i,n*i);
printf("\n\nMore Tables [Y/N] ? ");
fflush(stdin); ans=getchar();
}while(ans=='y' || ans=='Y');
}
Example 4
/* WAP to input a number and print table of it */
/* Using goto statement */
#include<stdio.h>
void main()
{
int n,i=1;
printf("Enter the number : ");
scanf("%d",&n);
top:
printf("%3d x %3d = %3d\n",n,i,n*i);
i++;
if(i<=10) goto top;
getch();

Assignment
1. WAP to print all even numbers between 1 and 20
2. WAP to input two numbers and print sum of all numbers in range e.g. 2 and 5 means
2+3+4+5

Solution 2
/* WAP to input two numbers and print sum of numbers in range */
void main()
{
int a,b,n,sum=0;
printf("Enter two numbers : ");
scanf("%d%d",&a,&b);
n=a;
while(n<=b)
{
sum=sum+n;
n++;
}
printf("Sum is %d",sum);
getch();
}
/* WAP to input a number and print factorial of it */
int main()
{
int n,i;
unsigned long f=1;
printf("Enter the number : ");
scanf("%d",&n);

for(i=n;i>=1;i--)
f=f*i;

printf("Factorial of %d is %lu",n,f);
getch();
}

/*WAP to input a number and print sum of five digits */


int main()
{
int n,temp,d,sum=0;
printf("Enter a number : ");
scanf("%5d",&n);

temp=n;
while(temp)
{
d=temp%10;
sum=sum+d;
temp=temp/10;
}
printf("Sum of digits of %d is %d",n,sum);
getch();
}
/* WAP to get a number and check it to be prime number */
void main()
{
int n,d,cut=0;
printf("Enter a number : ");
scanf("%d",&n);
d=2;
while(d<=n/2)
{
if(n%d==0)
{
cut=1;
break;
}
d++;
}
if(cut)
printf("%d is not a prime",n);
else
printf("%d is a prime number",n);
getch();
}

What is a function: --
A set of statements clubbed together to perform some action is called as function. Functions can be of
three types
1. Library Functions
2. User Defined Functions
Library Functions

Library function
Library functions are the in-built function in C programming system. For example:

1. stdio.h
a. printf()
b. cprintf()
c. scanf()
d. gets()
e. puts()
f. getchar()
g. putchar()
2. conio.h
a. getch()
b. getche()
c. clrscr()
3. ctype.h (Character Related Function)
a. toupper(ch) – Convert the character in capital
b. tolower(ch) – Convert the character in small letter
c. isalpha(ch) – returns true if alphabet
d. isupper(ch)
e. islower(ch)
f. isdigit(ch)
4. string.h (String Related Functions)
a. strupr(s)
i. Convert to upper case
b. strlwr(s)
i. Convert to lower case
c. strlen(s)
i. return the length of string
d. strrev(s)
i. Reverse the string
e. strcpy(target, source)
i. To copy a string from source to target
f. strcmp(s1,s2)
i. Compare two strings and return a number as case sensitive
1. s1==s2 returns 0
2. s1>s2 returns > 0
3. s1<s2 return s<0
g. strcmpi(s1,s2)
i. to check two string as case insensitive
h. strcat(s1,s2)
i. To concatenate two strings
5. stdlib.h (Standard Library)
a. atoi(s)
i. String to integer conversion
b. atof(s)
i. String to float conversion
6. math.h
a. log(n)
b. pow(n,p)
c. abs(n)

User defined function

A set of statements grouped together into single logical unit is referred to as function.

C provides programmer to define their own function according to their requirement known as user defined
functions.

Suppose, a programmer wants to find factorial of a number and check whether it is prime or not in same
program. Then, he/she can create two separate user-defined functions in that program: one for finding factorial
and other for checking whether it is prime or not.
Creating User Defined Functions
A function has three components
1. Function Declaration/Prototype
2. Function Definition
3. Function Call

Function prototype (declaration):

 Every function in C programming should be declared before they are used.


 Function declaration is a declaration statement that identifies a function with its name, a list of
arguments that it accepts and the type of data it returns.
 The general format for declaring a function that accepts some arguments and returns some value as
result can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..);

 No function can be declared within the body of another function.

Example, float avg ( int a, int b);

 Function prototype are not needed if user-definition function is written before main() function.

Function call

• The function call statement invokes the function.

• When a function is invoked the compiler jumps to the called function to execute the statements
that are a part of that function.

• Once the called function is executed, the program control passes back to the calling function.

• Function call statement has the following syntax.

function_name(variable1, variable2, …);

variable_name = function_name(variable1, variable2, …);

Function Definition

 Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function
 When a function defined, space is allocated for that function in the memory.
 The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..)

{
………….
statements
………….
return( variable);
}

 The no. and the order of arguments in the function header must be same as that given in function
declaration statement.

Example program of user defined function


/* Source code to find factorial of a number. */

#include<stdio.h>
int factorial(int n); // function prototype
int main()
{
int n,f=0;
printf("Enter an positive integer: ");
scanf("%d",&n);
f= factorial(n); //function call
printf("Factorial of %d = %ld", n,f);
return 0;
}

int factorial(int n) //function Definition


{
int count;
if ( n< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else
{
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
factorial*=count; /* factorial=factorial*count */
}
printf("Factorial = %lu",factorial);

Output

Enter an positive integer: 6


Factorial of 6 = 720

Based on return type, functions can be of two types


1. void functions
2. non-void functions
void functions do not return any value
non-void functions return some value.
If no return type is specified then default type is int.

Note: A function can return only one value and void function do not return any value.

Examples
1. Declare a function to get a character and return its ASCII value
2. Declare a function to get a year and check it to be leap year
3. Declare a function which takes a number as argument and returns its factorial
4. Declare a function which takes length and width of a rectangle and prints area of the rectangle

[1]
int toascii(char);
or
int toascii(char ch);

[2]
int isleapyear(int);
or
int isleapyear(int year);

[3]
long factorial(int num);

[4]
void area(int length, int width);
Function Definition
Used to provide the real functioning to the method
int toascii(char ch)
{
return ch;
}
int isleapyear(int y)
{
if((y%4==0 && y%100!=0) || y%400==0)
return 1;
else
return 0;}

long factorial(int num)


{
long f=1;
int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
void area(int length, int width)
{
printf("Area is %d",length*width);
}

Note: If definition is provided above main() then declaration is not required


Solution 2
int toascii(char ch)
{
return ch;
}
int isleapyear(int y)
{
if((y%4==0 && y%100!=0) || y%400==0)
return 1;
else
return 0;
}
long factorial(int num)
{
long f=1;
int i;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
void area(int length, int width)
{
printf("Area is %d",length*width);
}

Passing Arguments to the functions


C allows to pass arguments using two ways
1. Pass by value
2. Pass by address
C++ allows to pass arguments using three ways
1. Pass by value
2. Pass by address
3. Pass by reference
Passing arguments by value
When passing arguments by value, value of actual arguments get copied to formal arguments.
Duplicate variables get created as formal argument. If we make any changes to formal arguments they
will not be reflected in actual arguments. It gives data safety to our arguments.
//Using Pass by value
void update(int a) //formal argument
{
a=a+7;
printf("After update data is %d\n",a);
}
void main()
{
int a=5;
printf("Actual data is %d\n",a);
update(a);//actual argument
printf("Data after udpation %d",a);

getch();}
Pass by address
When passing as argument by address, address of actual argument get passed to formal argument. If we
make any changes to formal arguments, they will be reflected in actual arguments.
//Using Pass by address
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int x=5,y=6;
swap(&x,&y); //passing address
printf("x=%d and y=%d",x,y);
getch();
}
//Using pointers
void manyresults(int n, int *sq, int *cb)
{
*sq=n*n;
*cb=n*n*n;
}
int main()
{
int x=6,y,z;

manyresults(x,&y,&z);
printf("Square of %d is %d and cube is %d",x,y,z);
getch();
}

Unit-IV
Arrays:

An array is a finite set of variables of the same basic type. Instead of giving each variable a name, we
use enumeration and group all of them in an array The enumeration of elements within an array
always starts with 0. If the array has N elements, the last element is in position N-1 The C compiler
does not check the array boundaries "this is a very typical error that it is very difficult to find (usually
happens inside loops that traverse the array) "always check the array boundaries before accessing a
variable in an array. For example:

#include <stdio.h>
float data[5]; /* data to average and total */
float total; /* the total of the data items */
float average; /* average of the items */
main() {
data[0] = 34.0;
data[1] = 27.0;
data[2] = 45.0;
data[3] = 82.0;
data[4] = 22.0;
total = data[0] + data[1] + data[2] + data[3] + data[4];
average = total / 5.0;
printf("Total %f Average %f\n", total, average);
return (0);
}
Structures and Unions
1. Introduction

As we know array is a collection of elements of the same data type under a common name. However, there may
be a requirement to represent a collection of data elements belonging to different data types under a common
name. For this purpose, C supportsstructure. A structure consists of packing elements of different data types as
a single unit under the same name. A structure may consist of elements of the type float, int and char. Pointers,
arrays and other structures can also be included as elements within a structure.
Closely associated with the structure is another user defined data type called the union which also contains
elements of different data types under a common name. However, a union differs from a structure in the manner
in which the member elements are allocated memory and its usage.
2. Defining a Structure

A structure is a user defined data type that is defined in terms of its individual elements. Subsequently, the
variables of this data type can be declared and used.
The definition of a structure consists of defining the elements of the structure and their data types. The elements
of the structure are also called its members. The definition of a structure takes the following general form:
structstructure_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_typemember_n;
};

In the above definition, struct is the keyword and structure_name is the name that will be given to the structure
data type; member_1, member_2 ,………, member_n are the elements or members of the structure data type that
may be of different data types.

For example, we declare the structure type student as follows:

struct student
{
int roll_no;
char name[20];
float marks;
};

The structure definition is only a template that can be used to declare variables of its type; the definition itself
does not declare any variable. Thus there is a clear distinction between the structure definition and declaration of
variables of the structure type.

3. Declaring Structure Variables

Once the structure data type has been defined, the individual variables of the structure type can be declared as
follows:

structstructure_name var_1, var_2,……………var_m;

where struct is the keyword, structure_name is the name of the structure type and var_1, var_2……… var_m are
the variables of the structure type.

For example, we can declare the variables of the structure type student, declared earlier, as follows :

struct student, s1, s2, s3;

where s1, s2 and s3 are the variables of the structure type student.

It is important to note that the members of a structure type are not variables themselves and do not occupy any
memory space. It is only the structure variables that occupy memory space.

Another important point to be taken care of is that a member of the structure cannot be initialized within the
structure definition.

For example, the structure definition

struct student
{
int roll_no =20; /* invalid */
char name[20];
float marks;
};

is invalid because of the initialization of the member roll_no because this would mean that the member roll_no
will have a value 20 in all the variables of the structure which may not be possible in the real world.

It is also permitted to combine the structure definition and the declaration of its variables in a single statement in
the form shown:

structstructure_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_typemember_n;
} var_, var_2, ……….,var_m;

For example,

struct student
{
int roll_no;
char name[20];
float marks;
}s1, s2,s3;

The structure_name is optional in this case as follows:

struct
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_type member_n;
} var_, var_2, ……….,var_m;

For example,

struct
{
int roll_no;
char name[20];
float marks;
}s1, s2,s3;

4. Structure Variable As Member of Another Structure

A structure variable can be defined as a member of another structure as follows:

struct date
{
int dd;
int mm;
int yy;
}

struct student
{
int roll_no;
char name[20];
float marks;
struct date dob;
};

The variable dob of the structure type date is a member of the structure student.

In such a case where a structure variable is member of another structure, the definition of the embedded structure
must appear before the definition of the outer structure. In the example, the definition of the structure date
appears before the definition of the structure student in which the variable dob of the type date is embedded.

5. Initialization of Structure Variables

The members of a structure variable can be initialized in the same way as the variables of any other data type.
The general form is:

structstructure_name variable_name = {value_1, value_2, ………., value_n);

The initial values must appear in an order in which they will be assigned to the members of the structure
variable.

For example,

struct student
{
int roll_no;
char name[20];
float marks;
};

struct student s1={127, “Amit”,67};


struct student s2={134, “Vijay”, 98};

In the first initialization, 127 will be assigned to the member roll_no of student s1, “Amit” will be assigned to the
member name of students1 and 67 will be assigned to the member marks of student s1. Similarly the values will
be assigned to the members of variable s2.

Another way of writing the same initialization is:

struct student
{
int roll_no;
char name[20];
float marks;
} s1={127, “Amit”,67};

6. Accessing the Structure Members

The structure members are processed individually as separate entities. However, as they are not variables
themselves, they are required to be linked to the corresponding structure variables at the time of usage such as
accessing, assigning the values and computations etc. The individual structure members can be used as follows
structure_variable.member

The period or dot (.) that separates the structure variable and the member is an operator called the dot operator
or member operator or period operator.

For example,

s1.marks refers to the member marks of the variable s1 of type student.

The members associated with the structure variables can be used just like ordinary variables in C. For example,

s1.marks /*valid*/
scanf(“%d”, &s1.roll_no); /*valid*/
s1.marks = s1.marks + 5; /*valid*/
printf(“%d %s %f”, s1.roll_no, s1.name, s1.marks); /*valid*/

are all valid C statements/expressions.

Illustration 1 : Write a program to illustrate the use of members of a structure variable using the member
operator.

struct complex /* Structure Definition */


{
int real;
int imag;
};

void main()
{
struct complex c1, c2, sum; /* Declaration of variables of the type complex */
printf("Enter the real and imaginary parts of the first number:");
scanf("%d %d", &c1.real, &c1.imag); /*Use of member operator in reading members of variable c1*/
printf("\nEnter the real and imaginary parts of the second number:");
scanf("%d %d", &c2.real, &c2.imag); /*Use of member operator in reading members of variable c2*/
sum.real = c1.real + c2.real; /*Use of member operator in processing members of variables c1
and c2*/
sum.imag = c1.imag + c2.imag; /*Use of member operator in processing members of variables c1
and c2*/
/*Use of member operator in printing members of variable sum*/
printf("\nThe new number is Real Part :%d Imaginary Part : %d", sum.real, sum.imag);
}

Test Run:
Enter the real and imaginary parts of the first number: 3 2
Enter the real and imaginary parts of the second number: 5 1
The new number is Real Part :8 Imaginary Part : 3

More complex expressions involving the repeated use of the dot operator can also be written in the form

structure_variable.member.sub_member
where member refers to a member of the structure variable and sub_member refers to the member of an
embedded structure variable.

Illustration 2 : Write a program to illustrate the use of member operator in embedded structures.

struct date
{
int dd;
int mm;
int yy;
};

struct student
{
int roll_no;
float marks;
struct date dob; /* dob is variable of the embedded structure date*/
/*structure date must be defined before structure student */
};

void main()
{
struct student s;
printf("Enter the details of the student");
printf("\n Roll_no");
scanf("%d", &s.roll_no);
printf("\nMarks");
scanf("%f", &s.marks);
printf("\n Date of Birth in dd mm yy format");
scanf("%d %d %d", &s.dob.dd, &s.dob.mm, &s.dob.yy);
printf("\n The student details are :");
printf("\n Roll_no : %d", s.roll_no);
printf("\n Marks : %0.2f", s.marks);
printf("\n Date of Birth :%d/%d/%d", s.dob.dd, s.dob.mm, s.dob.yy);
}

Test Run :

Enter the details of the student


Roll_no 34
Marks 56.5
Date of Birth in dd mm yy format 3 6 90
The student details are
Roll_no :34
Marks :56.50
Date of Birth :3/6/90

If the member of a structure is an array, then the individual array elements are used as

structure_variable.member[index];
For example, s1.name[3];

Illustration 3 : Write a program to illustrate the use of array as structure member.

struct student
{
int roll_no;
int marks[3];
};

void main()
{
struct student sx;
int i, sum = 0;
float avg;
printf("Enter the roll_no of the student:");
scanf("%d", &sx.roll_no); /* Use of array member */

printf("\nEnter the marks of the student");


for(i=1; i<=3; i++)
{
printf("\nMarks%d : ", i);
scanf("%d", &sx.marks[i]); /* Use of array member */
}

for(i=1; i<=3; i++)


sum = sum + sx.marks[i]; /* Use of array member */
avg = (float)sum/3;
printf("\n Average Marks = %0.2f", avg);
}

Test Run :

Enter the roll_no of the student:23


Enter the marks of the student
Marks1: 23
Marks2: 45
Marks3: 56
Average Marks = 41.33

7. Operations on Structures

Most operations – arithmetic, relational and logical – can be carried out only on the individual structure members
and not on the structure variable as a whole. The only operation that can be performed on the structure variable
is the assignment operation.

For example, if s1 and s2 are two variables of the structure student (defined earlier in this chapter), then the
statements
s1 = s2; /*valid statement */
s2 = s1; /*valid statement */

are valid.
When the statement
s1=s2;
is processed, it is equivalent to
s1.roll_no = s2.roll_no;
s1.marks = s2.marks;
strcpy(s1.name, s2.name);

i.e. the values of the individual members of s1 are assigned to those of s2.

However, the statements or expressions such as

s3 = s1 + s2; /*invalid statement */


s1 == s2; /*invalid expression */
s1 != s2; /*invalid expression */
s1 > s2; /*invalid expression */

are not valid. Such operations can be performed only on the individual structure members.

Illustration 4: Create the structure point with data members x and y. Create two variables p1 and p2 of
the type point and find if p1 and p2 represent the same points.

struct point
{int x;
int y;
};

void main()
{
struct point p1, p2;
printf("Enter point p1:");
scanf("%d %d", &p1.x, &p1.y);
printf("\nEnter point p2:");
scanf("%d %d", &p2.x, &p2.y);
if((p1.x ==p2.x) && (p1.y == p2.y)) /*Comparison of individual structure members */
printf("\nThe points are the same");
else
printf("\nThe points are not the same");
}

Test Run 1:

Enter point p1: 2 3


Enter point p2: 2 3
The points are the same

Test Run 2:

Enter point p1: 2 3


Enter point p2: 4 5
The points are not the same
Illustration 5: Use the structure point to create two variables p1 and p2 and assign the value of p1 to p2.

struct point
{
int x;
int y;
};

void main()
{
struct point p1={3,4} , p2;
printf("Point p1 is x=%d y=%d", p1.x, p1.y);

p2.x = p1.x; /* Assignment of member x of p1 to p2 */


p2.y = p1.y; /* Assignment of member y of p1 to p2 */
printf("\nPoint p2 is x=%d y=%d", p2.x, p2.y);
}

Test Run :
Point p1 is x=3 y=4
Point p2 is x=3 y=4
8. Arrays of Structures

Just like the arrays of ordinary variables, we can also declare and use arrays of structure variables. The general
form is

structstructure_name array_name[index];

For example

struct student S[3];

declares an array S of the type student and having 3 elements.


The following code shows the initialization of an array of structures
struct point
{
int x;
int y;
};
struct point p[3] = {{1,2},{3,4},{6,7}};

Illustration 6 : Write a program to define a structure named student with members roll_no and marks. Use
the structure to create an array of students. Input data and find the average marks of the students.
struct student
{
int roll_no;
int marks; };
void main()
{
struct student s[3]; /* Array s of type student */
int i, sum = 0;
float avg;
printf(“Enter the student details”);
for(i=0; i<3; i++)
{
printf(“\n Student %d: ”, i);
scanf("%d %d", &s[i].roll_no, &s[i].marks); /* Input the structure members */
}
printf(“\n The student details are :”);

for(i=0; i<3; i++)


{
printf(“\n Student %d:”, i);
printf("%d %d", s[i].roll_no, s[i].marks);/* Access the structure members */
}
for(i=0;i<3;i++)
sum = sum + s[i].marks;
avg = (float)sum/3;
printf("\nAverage Marks = %0.2f", avg);
}
Test Run:
Enter the student details
Student0: 3 45
Student1: 4 65
Student2: 5 89
The student details are :
Student0: 3 45
Student1: 4 65
Student2: 5 89
Average Marks = 66.33

In the above program, s[i].roll_no and s[i].marks are used to access the members of the structure variables s[i]
as the value of i varies from 0 to 2.

9. Size of Structures

The sizeof operator can be used to find the size of a structure or a structure variable. The general form is
sizeof(structure_name);
or
sizeof(variable_name);

For example,
If we have a structure

struct point
{
int x;
int y;
};

then the expression

sizeof(point);
will return the number of bytes (4 in this case) required to hold all the members of the structure point.

If p is a variable of the type point, then the expression

sizeof(p);

will return the number of bytes required to hold the members of the variable p. The expression will return 4.

If px is an array of the type point, then

sizeof(px);

will return the total number of bytes that the array p requires.

Illustration 7 : Write a program to illustrate the use of pointers to structures.


struct point
{
int x;
int y;
};

void main()
{
struct point p1={3,4};
struct point *ptr; /* ptr is a pointer of the type point */
struct point new_point;
ptr = &p1; /* ptr stores the address of the variable p1 of type point */
new_point.x = ptr-> x+3;
new_point.y = ptr-> y+3;
printf("\nThe original point is %d,%d", ptr->x, ptr->y);
ptr = &new_point; /* Now ptr points to variable new_point */
printf("\nThe new point is %d,%d", ptr->x, ptr->y);
}
Test Run:
The original point is 3,4
The original point is 6,7

In illustration 7, the statement

struct point *ptr;

creates a pointer variable of the type point i.e. the pointer ptr can point to structure type point
The statement

ptr = &p1;

assigns the address of the variable p1 of type point to the pointer variable ptr.

The statements
new_point.x = ptr-> x+3;
new_point.y = ptr-> y+3;
access the members of point p1 using the pointer ptr.

The statement

ptr = &new_point;

points the pointer ptr to the structure variable new_point.

The members of new_point are accessed through the pointer ptr in the statement

printf("\nThe new point is %d,%d", ptr->x, ptr->y);

Defining Structures with typedef


We have already studied the typedef feature in C. This feature allows users to define new data types that are
equivalent to existing data types.
The typedef feature is particularly convenient in defining structures as it eliminates the need to repeatedly use
the keyword struct whenever a structure is referenced. The general form is
typedefstructstructure_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_typemember_n;
};

For example,
typedef struct student
{
int roll_no;
char name[20];
float marks;
};

The variable declaration for the structure student is


student s1, s2;
Unions
Unions, like structures, are composition of members of different data types. However, all the members within a
union share the same memory space whereas each member within a structure is assigned its unique storage area.
Thus, though a union may consist of several members it can handle only one member at a time.
Thus unions are used to conserve memory and are used in applications involving multiple members but the
values need not be assigned to all the members at the same time.
A union is declared using the keyword union in the following general form

unionunion_name
{
data_type member_1;
data_type member_2;
…………………………………
…………………………………
data_type member_n;
};

For example

union test
{
int x;
float y;
char z;
};

test is a union with three data members of different data types. A variable temp of the union data type test can be
declared as

union test temp;

The memory allocated to the variable of a union is the memory required to hold the data member with the largest
memory requirement. This memory is shared by all the data members and only one member can use the memory
at a time. The memory allocated to the variable temp is 4 bytes which is the memory required by the member y
of the union variable.

The union members can be accessed using the dot or member operator. For example
temp.x
temp.y
temp.z

are all valid members.

Since the memory allocated to a union is shared by all the members and only one member can use this memory
at a time, when a member is assigned a new value, the new value overwrites the value of the previous member in
the shared memory.

For example,

temp.x = 3;

allocates the memory to the member x and hence the memory contains the value 3.

The statement

printf(“%d”, temp.x);

will display 3.

Now the statement

temp.y = 67.3;

overwrites the value in the memory to 67.3. The statement

printf(“%d”, temp.y);
will display 67.3

While accessing the member of a union, we must take care that we access only that member whose value is
currently stored in the memory.

For example, the code

temp.z = ‘y’;
printf(“%f”, temp.z);

will produce an erroneous output as the value in the memory is of char type whereas we are attempting to access
a float type value.

Only one member of the union variable can be initialized and most compilers will accept the initial value only
for the first member of the union. For example,

union temp1 = {3};

is a valid initialization whereas the initializations

union temp1 = {5.6};

and

union temp1 = {‘g’};

are invalid.

Enumeration

Enumeration type allows programmer to define their own data type . Keyword enum is used to define
enumerated data type.

enum type_name(value1, value2,……….valueN);

Here, type_name is the name of enumerated data type or tag. And value1, value2,....,valueN are 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 as below:

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

Output

4 day

You can write any program in C language without the help of enumerations but, enumerations helps in
writing clear codes and simplify programming.

Command line argument:


It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your program
specially when you want to control your program from outside instead of hard coding those values inside
the code.

The command line arguments are handled using main() function arguments where argcrefers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly:

#include<stdio.h>
int main( int argc, char *argv[ ] )
{ if (argc==2)
Printf(“ The argument supplied is %s\n”, argv[1]);
else if (argc>2)
Printf(“ Too many arguments supplied.\n”);
else
printf("One argument expected.\n");
}
Unit-V
PointersA variable that can hold address of another variable of its data type. To declare a pointer type
variable use indirection operator *
int *p; // p is a pointer variable that can hold address of some other int type variable
double *k;
char *ch;
void *ptr; // ptr can hold address of any data type also called as Generic Pointer
Example
void main()
{ char *x;
int *y;
double *z;
void *p;
printf("%d %d %d %d",sizeof(x),sizeof(y),sizeof(z),sizeof(p));
getch(); }

Pointers are used for


1. Indirect Memory Referencing
2. Dynamic Memory Allocation

Indirect Memory Referencing


int a=6;
int *p; // p is a pointer type variable to hold address of int type variable
p=&a; //referencing
*p=55; // value at the address in p (de-referencing) i.e. a is now 55
Example
//Indirect memory referncing
void main()
{
int a=5,b=6;
int *p;
p=&a;
*p=33;
p=&b;
*p=44; //value at the address
printf("%d %d",a,b);//33 44
getch();
}
Dynamic Memory Allocation
We can allocate the memory on demand using functions of malloc.h and calloc.h like malloc() and
calloc().
datatype *ptr=(dataype *)malloc(items * sizeof(datatype));
datatype *ptr=(dataype *)calloc(items, sizeof(datatype));

Example
WAP to ask the number of items, input that much of numbers and show sum of all those
numbers.
#include<malloc.h>
void main()
{
int *p;
int n,i=0,s=0;
printf("No of elements : ");
scanf("%d",&n);
p=(int *) malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter data %d : ",i+1);
scanf("%d",p+i);
s=s+*(p+i);
}
printf("Sum is %d",s);
getch();
}
Pointer as Array
#include<malloc.h>
void main()
{
int *p;
int n,i=0,s=0;
printf("No of elements : ");
scanf("%d",&n);

p=(int *) malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter data %d : ",i+1);
scanf("%d",&p[i]);
s=s+p[i];
}
printf("Sum is %d",s);
getch();
}

File Handling
A system to manage data on disc permanently. We can create files on disc and manage the record in
that files with different operations
 Open a file
 Close a file
 Save new record
 Search a record
 Update a record
 Delete a record
C provides a built-in structure called FILE which is used to manage the files.
C provides functions inside stdio.h header file
 fopen()
o To open a file
 fclose()
o To close a file
 fwrite()
o To write a record in file
 fread()
o To read a record from file
 fseek()
o To lookup a file position
 rewind()
o To go back to start of the file
 fputc()
o To a character to the file
 fgetc()
o To get a character from file
 fputs()
o To write a string into file
 fgets()
o To read a string from file

 fprintf()
o To write formatted data to a file
 fscanf()
o To read formatted data from file

File Types
1. Text File (default)
2. Binary File – Use b for binary file

File Opening Mode Purpose


“r”  Open an existing file for read only
 If file does not exist, an error is generated
 The file pointer points to the beginning of the file
“w”  Open a new file for writing only
 If a file with the specified filename currently exists, it will be deleted and
a new file will be created in its place
 The file pointer points to the beginning of the file
“a”  Open an existing file for appending (i.e. for adding new information at the
end of the file)
 A new file will be created if the file with the specified filename does not
exist
 The file pointer points to the position where the data is to be appended
“r+”  Open an existing file for both reading and writing
 If file does not exist, an error is generated
 The file pointer points to the beginning of the file
“w+”  Open a new file for both reading and writing
 If a file with the specified filename currently exists, it will be deleted and
a new file will be created in its place
 The file pointer points to the beginning of the file
“a+”  Open an existing file for both reading and appending.
 A new file will be created with a file with the specified filename does not
exist
 The file pointer points to the position where the data is to be appended

Difference between r+ and w+?


In case of r+, the file must exist. If file does not exits returns NULL
In case of w+, if the file exists, overwrites it contents and if not found, creates a new file
How to open a file?
- Use fopen() function
o FILE *fopen(“filename”,”mode / purpose”)
FILE *fp=fopen("book.dat","rb+");
if(fp==NULL)
fp=fopen("book.dat","wb+");
Closing a file
fclose(fp);

Macros:-- A replaceable code which get replaced at the time compilation. Use #define pre-processor
directive to create the macros
#define P printf
#define S scanf
#define go(r,c) gotoxy(c,r)
#define cl() clreol()
Example
#include<stdio>
#include<conio>
#define P printf
#define S scanf

Example
#include<conio.h>
#define p(a,b) a*b //6+4*10+7 = 53
void main()
{
int n=p(6+4,10+7);
printf("%d",n);
getch();
}

Вам также может понравиться