0% found this document useful (0 votes)
1 views

3. Programming Languages and Computer

The document discusses language design techniques essential for programming languages, covering topics such as programming language concepts, paradigms, and translation processes. It details various programming languages, including low-level languages like machine and assembly languages, high-level languages like FORTRAN and COBOL, and object-oriented languages like C++ and Java. Additionally, it explores different programming paradigms such as imperative, object-oriented, and declarative programming, highlighting their advantages and disadvantages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

3. Programming Languages and Computer

The document discusses language design techniques essential for programming languages, covering topics such as programming language concepts, paradigms, and translation processes. It details various programming languages, including low-level languages like machine and assembly languages, high-level languages like FORTRAN and COBOL, and object-oriented languages like C++ and Java. Additionally, it explores different programming paradigms such as imperative, object-oriented, and declarative programming, highlighting their advantages and disadvantages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 268

Language Design

Language design techniques are the most important topic to design the Programming Language
and to solve various types of problems in the discipline of Comp. Science and IT. The following are
the major topics covered in Language Design.
1. Programming Language Concepts
2. PL-Paradigms and Models
3. Programming Environments
4. Translation process

Programming Language Concepts


Computer programming language, any of various languages for expressing a setof detailed
instructions for a digital computer. Such instructions can be executed directly when they are in the
computer manufacturer-specific numerical form known as machine language, after a simple
substitution process when expressed in a corresponding assembly language, or after translation
from some “higher- level” language. Although there are many computer languages, relatively few
are widely used.

Machine and assembly languages are “low-level,” requiring a programmer tomanage explicitly all
of a computer’s idiosyncratic features of data storage and operation. In contrast, high-level
languages shield a programmer from worrying about such considerations and provide a notation
that is more easily written and read by programmers.

Language Types
Machine and assembly languages
A machine language consists of the numeric codes for the operations that a particular computer
can execute directly. The codes are strings of 0s and 1s, or binary digits (“bits”), which are
frequently converted both from and to hexadecimal (base 16) for human viewing and modification.
Machine language instructions typically use some bits to represent operations, such as addition,
and some to represent operands, or perhaps the location of the next instruction. Machine language
is difficult to read and write, since it does not resemble conventional mathematical notation or
human language, and its codes vary from computer to computer.

Assembly language is one level above machine language. It uses short mnemonic codes for
instructions and allows the programmer to introduce names for blocks of memory that hold data.
One might thus write “add pay, total”instead of “0110101100101000” for an instruction that adds
two numbers.

Assembly language is designed to be easily translated into machine language. Although blocks of
data may be referred to by name instead of by their machine addresses, assembly language does
not provide more sophisticated means of organizing complex information. Like machine language,
assembly language requires detailed knowledge of internal computer architecture. It is useful when
such details are important, as in programming a computer to interact with input/output devices
(printers, scanners, storage devices, and so forth).

The built-in competence and defects of the various programming languages like FORTRAN, ALGOL,
COBOL, C, C++, and JAVA. List of Differences between higher and lower/machine level languages.
Basic theories like abstract syntax, interpretation, stack, heap organization, compilation
techniques, different types of 'type checking' and 'error checking' various for each Programming
420
language

Algorithmic languages
Algorithmic languages are designed to express mathematical or symbolic computations. They can
express algebraic operations in notation similar to mathematics and allow the use of subprograms
that package commonly usedoperations for reuse. They were the first high-level languages.

FORTRAN
The first important algorithmic language was FORTRAN (formula translation), designed in 1957 by
an IBM team led by John Backus. It was intended for scientificcomputations with real numbers and
collections of them organized as one- or multidimensional arrays. Its control structures included
conditional IF statements,repetitive loops (so-called DO loops), and a GOTO statement that allowed
nonsequential execution of program code. FORTRAN made it convenient to have subprograms for
common mathematical operations, and built libraries of them.

FORTRAN was also designed to translate into efficient machine language. It was immediately
successful and continues to evolve.

ALGOL
ALGOL (algorithmic language) was designed by a committee of American and European computer
scientists during 1958–60 for publishing algorithms, as well asfor doing computations. Like LISP
(described in the next section), ALGOL had recursive subprograms—procedures that could invoke
themselves to solve a problem by reducing it to a smaller problem of the same kind. ALGOL
introduced block structure, in which a program is composed of blocks that mightcontain both data
and instructions and have the same structure as an entire program. Block structure became a
powerful tool for building large programs outof small components.

ALGOL contributed a notation for describing the structure of a programming language, Backus–
Naur Form, which in some variation became the standard toolfor stating the syntax (grammar) of
programming languages. ALGOL was widely used in Europe, and for many years it remained the
language in which computeralgorithms were published. Many important languages, such as Pascal
and Ada (both described later), are its descendants.

421
LISP
LISP (list processing) was developed about 1960 by John McCarthy at
the Massachusetts Institute of Technology (MIT) and was founded on the mathematical theory of
recursive functions (in which a function appears in its owndefinition). A LISP program is a function
applied to data, rather than being a sequence of procedural steps as in FORTRAN and ALGOL. LISP
uses a very simple notation in which operations and their operands are given in a parenthesized
list. For example, (+ a (* b c)) stands for a + b*c. Although this appears awkward, the notation works
well for computers. LISP also uses the list structure to represent data, and, because programs and
data use the same structure, it is easy for a LISP program to operate on other programs as data.

LISP became a common language for artificial intelligence (AI) programming, partly owing to the
confluence of LISP and AI work at MIT and partly because AIprograms capable of “learning” could
be written in LISP as self-modifying programs. LISP has evolved through numerous dialects, such
as Scheme and Common LISP.
The C programming language was developed in 1972 by Dennis Ritchie and Brian Kernighan at the
AT&T Corporation for programming computer operating systems. Its capacity to structure data and
programs through the composition of smaller units is comparable to that of ALGOL. It uses a
compact notation and provides the programmer with the ability to operate with the addresses of
data aswell as with their values. This ability is important in systems programming, and C shares
with assembly language the power to exploit all the features of a
computer’s internal architecture. C, along with its descendant C++, remains one of the most
common languages.

Business-oriented languages
COBOL
COBOL (common business-oriented language) has been heavily used by businesses since its
inception in 1959. A committee of computer manufacturers and users and U.S. government
organizations established CODASYL (Committee on Data Systems and Languages) to develop and
oversee the language standard inorder to ensure its portability across diverse systems.

COBOL uses an English-like notation—novel when introduced. Business computations organize and
manipulate large quantities of data, and COBOLintroduced the record data structure for such tasks.
A record
clusters heterogeneous data such as a name, ID number, age, and address into a single unit. This
contrasts with scientific languages, in which homogeneous arrays of numbers are common.
Records are an important example of “chunking” data into a single object, and they appear in nearly
all modern languages.

SQL
SQL (structured query language) is a language for specifying the organization of databases
(collections of records). Databases organized with SQL are called relational because SQL provides
the ability to query a database for information
that falls in a given relation. For example, a query might be “find all records withboth last_name
Smith and city New York.” Commercial database programs commonly use a SQL-like language for
their queries.

Education-oriented languages

422
BASIC
BASIC (beginner’s all-purpose symbolic instruction code) was designed
at Dartmouth College in the mid-1960s by John Kemeny and Thomas Kurtz. It wasintended to be
easy to learn by novices, particularly non-computer science majors, and to run well on a time-
sharing computer with many users. It had simple data structures and notation and it was
interpreted: a BASIC program wastranslated line-by-line and executed as it was translated, which
made it easy to locate programming errors.

Its small size and simplicity also made BASIC a popular language for early personalcomputers. Its
recent forms have adopted many of the data and control structures of other contemporary
languages, which makes it more powerful but less convenient for beginners.

Pascal
About 1970 Niklaus Wirth of Switzerland designed Pascal to teach structured programming, which
emphasized the orderly use of conditional and loop controlstructures without GOTO statements.
Although Pascal resembled ALGOL in notation, it provided the ability to define data types with
which to organize complex information, a feature beyond the capabilities of ALGOL as well
as FORTRAN and COBOL. User-defined data types allowed the programmer tointroduce names for
complex data, which the language translator could then check for correct usage before running a
program.

During the late 1970s and ’80s, Pascal was one of the most widely used languagesfor programming
instruction. It was available on nearly all computers, and, because of its familiarity, clarity, and
security, it was used for
production software as well as for education.

Logo
Logo originated in the late 1960s as a
simplified LISP dialect for education; Seymour Papert and others used it at MIT to teach
mathematical thinking to schoolchildren. It had a more
conventional syntax than LISP and featured “turtle graphics,” a simple method for generating
computer graphics. (The name came from an early project to programa turtlelike robot.) Turtle
graphics used body-centred instructions, in which an object was moved around a screen by
commands, such as “left 90” and “forward,” that specified actions relative to the current position
and orientation of the object rather than in terms of a fixed framework. Together with recursive
routines, this technique made it easy to program intricate and attractive patterns.

Hyper talk
Hyper talk was designed as “programming for the rest of us” by Bill Atkinson for Apple’s Macintosh.
Using a simple English-like syntax, Hypertalk enabledanyone to combine text, graphics, and audio
quickly into “linked stacks” that
could be navigated by clicking with a mouse on standard buttons supplied by the program.
Hypertalk was particularly popular among educators in the 1980s and early ’90s for classroom
multimedia presentations. Although Hypertalk had many features of object-oriented languages
(described in the next section), Apple did
not develop it for other computer platforms and let it languish; as Apple’s marketshare declined in
the 1990s, a new cross-platform way of displaying multimedia left Hypertalk all but obsolete (see
the section World Wide Web display languages).
423
Object-oriented languages
Object-oriented languages help to manage complexity in large programs. Objectspackage data and
the operations on them so that only the operations are publiclyaccessible and internal details of the
data structures are hidden. This information hiding made large-scale programming easier by
allowing a programmer to think about each part of the program in isolation. In addition, objects
may be derived from more general ones, “inheriting” their capabilities. Such an
object hierarchy made it possible to define specialized objects without repeatingall that is in the
more general ones.

Object-oriented programming began with the Simula language (1967), which added information
hiding to ALGOL. Another influential object-oriented language was Smalltalk (1980), in which a
program was a set of objects that interacted by sending messages to one another.

C++
The C++ language, developed by Bjarne Stroustrup at AT&T in the mid-1980s, extended C by adding
objects to it while preserving the efficiency of C programs.It has been one of the most important
languages for both education and industrial programming. Large parts of many operating systems,
such as
the Microsoft Corporation’s Windows 98, were written in C++.

Ada
Ada was named for Augusta Ada King, countess of Lovelace, who was an assistantto the 19th-
century English inventor Charles Babbage, and is sometimes called the first computer programmer.
Ada, the language, was developed in the early 1980s for the U.S. Department of Defense for large-
scale programming. It combined Pascal-like notation with the ability to package operations and
data into independent modules. Its first form, Ada 83, was not fully object-oriented, but the
subsequent Ada 95 provided objects and the ability to
construct hierarchies of them. While no longer mandated for use in work for theDepartment of
Defense, Ada remains an effective language for engineering largeprograms.

Java
In the early 1990s, Java was designed by Sun Microsystems, Inc., as a programming language for
the World Wide Web (WWW). Although it resembled C++ in appearance, it was fully object-oriented.
In particular, Java dispensed with lower-level features, including the ability to manipulate data
addresses, a capability that is neither desirable nor useful in programs for distributed systems.In
order to be portable, Java programs are translated by a Java Virtual Machine specific to each
computer platform, which then executes the Java program. In addition to adding interactive
capabilities to the Internet through Web “applets,”Java has been widely used for programming
small and portable devices, such as mobile telephones.

PL-Paradigms and Models


A programming paradigm is a various system design of ideas that have been used to
guide/implement the programming.
Paradigm can also be termed as method to solve some problem or do some task. Programming
paradigm is an approach to solve problem using some programminglanguage or also we can say
it is a method to solve a problem using tools and techniques that are available to us following some
approach. There are lots for programming language that are known but all of them need to follow
some strategy when they are implemented and this methodology/strategy is paradigms. Apart
424
from varieties of programming language there are lots of paradigms to fulfil each and every
demand.

Following list of paradigms


Imperative: Explicit sequence [such as assignment statements] of statements thatchange the state
of the computer.

It is one of the oldest programming paradigm. It features close relation relation to machine
architecture. It is based on Von Neumann architecture. It works by changing the program state
through assignment statements. It performs step by step task by changing state. The main focus
is on how to achieve the goal. The paradigm consist of several statements and after execution of
all the result is stored.

Advantage:

1. Very simple to implement


2. It contains loops, variables etc.

Disadvantage
1. Complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible

vdc
This paradigm emphasizes on procedure in terms of under lying machine model.
There is no difference in between procedural and imperative approach. It has the ability to reuse
the code and it was boon at that time when it was in use because of its reusability.
Object-Oriented: By defining the objects that transfers messages to each objects or program.
Objects have their own internal state with public interface calls[encapsulation].

The program is written as a collection of classes and object which are meant for communication.
The smallest and basic entity is object and all kind of computation is performed on the objects
only. More emphasis is on data rather procedure. It can handle almost all kind of real life problems
which are today in scenario.

Advantages:
1. Data security
2. Inheritance
3. Code reusability
4. Flexible and abstraction is also present

Parallel processing: It is a type of processing that works like a divide and conquer technique by
dividing the task into multiple small processes and processing them parallel to run a program in
the least time.

Parallel processing is the processing of program instructions by dividing them among multiple
425
processors. A parallel processing system posses many numbers ofprocessor with the objective of
running a program in less time by dividing them. This approach seems to be like divide and conquer.
Examples are NESL (one of the oldest one) and C/C++ also supports because of some library
function.

Declarative
Programming by mentioning/specifying the value/result that what we need andmentioning how to
get the result.

It is divided as Logic, Functional, Database. In computer science the declarative programming is a


style of building programs that expresses logic of computation without talking about its control
flow. It often considers programs as theories of some logic.It may simplify writing parallel
programs. The focus is on what needs to be done rather how it should be done basically
emphasize on what code codeis actually doing. It just declare the result we want rather how it has
be produced. This is the only difference between imperative (how to do) and declarative (what to
do) programming paradigms. Getting into deeper we would see logic, functional and database.

Logic (as per defined rules): Specifying a set of rules/business logic in theprogramming. It is
used to solve logic problems.
It can be termed as abstract model of computation. It would solve logical problems like puzzles,
series etc. In logic programming we have a knowledge basewhich we know before and along with
the question and knowledge base, which is given to machine, it produces result. In normal
programming languages, such concept of knowledge base is not available but while using the
concept of artificial intelligence, machine learning we have some models like Perception model
which is using the same mechanism.
In logical programming the main emphasize is on knowledge base and theproblem.

sum of two number in prolog:


predicates
sumoftwonumber(integer, integer)
clauses
sum (0, 0).
sum(n, r):-/

n1=n-1,
sum (n1,
r1),r=r1+n

Functional (Application-oriented): Expressing the calculations as evaluation ofmath-function,


Function call programming with to avoid any global state change.

426
The functional programming paradigms has its roots in mathematics, and it is language
independent. The key principle of this paradigms is the execution of series of mathematical
functions. The central model for the abstraction is the function which are meant for some specific
computation and not the data structure. Data are loosely coupled to functions. The function hide
their implementation. Function can be replaced with their values without changing the meaning of
the program. Some of the languages like Perl, JavaScript mostly uses this paradigm.

Examples of Functional programming paradigm:

JavaScript: developed by Brendan Eich


Haskwell : developed by Lennart Augustsson, Dave Barton
Scala: developed by Martin Odersky
Erlang: developed by Joe Armstrong, Robert Virding
Lisp : developed by John Mccarthy
ML : developed by Robin Milner
Clojure : developed by Rich Hickey

Structured: Clean programming like goto-free, with proper nested control structures.
This programming methodology is based on data and its movement. Program statements are
defined by data rather than hard-coding a series of steps. A database program is the heart of a
business information system and provides file creation, data entry, update, query and reporting
functions. There are several programming languages that are developed mostly for database
application. For example, SQL. It is applied to streams of structured data, for filtering, transforming,
aggregating (such as computing statistics), or calling other programs. So it has its own wide
application.

To execute a program written in any kind of language, it has to be translated to machine level
language first. The source code will be translated to Machine level language / Object code by a
translator.
There are three types of translators available

Assembles: Assemblers convert the assembly language mnemonics codes to themachine code.
427
Compilers: Compiler converts the full source code program to machine level code.Hence it will run
in the machine without any further translation process. But, the error correction process is tough in
the compilers.

Interpreters: Interpreters converts each instruction line by line into the objectcode [like Java].

Virtual Machine
A virtual machine (or "VM") is an emulated computer system created
using software. It uses physical system resources, such as the CPU, RAM, and diskstorage, but is
isolated from other software on the computer. It can easily be created, modified, or destroyed
without affecting the host computer.

Virtual machines provide similar functionality to physical machines, but they do not run directly on
the hardware. Instead, a software layer exists between the hardware and the virtual machine. The
software that manages one or more VMs is called a "hypervisor" and the VMs are called "guests"
or virtualized instances. Each guest can interact with the hardware, but the hypervisor controls
them. Thehypervisor can start up and shut down virtual machines and also allocate a specific
amount of system resources to each one.
virtual machine can be created using virtualization software. Examples includeMicrosoft Hyper-V
Manager, VMware Workstation Pro, and Parallels Desktop. These applications allow us to run
multiple VMs on a single computer. For example, Parallels Desktop for Mac allows us to run
Windows, Linux, and macOS virtual machines on our Mac.
VMs are ideal for testing software since developers can install one or more applications and revert
to a saved state (or "snapshot") whenever needed. Testingsoftware on a regular operating system
can cause unexpected crashes and may leave some files lingering behind after the software is
uninstalled. It is safer to test software on a virtual machine that is isolated from the operating
system and can be fully reset as needed.

Binding Time
As we have just seen, operating systems use various kinds of names to refer to objects. Sometimes
the mapping between a name and an object is fixed, but sometimes it is not. In the latter case, it
may matter when the name is bound tothe object. In general, early binding is simple, but is not
flexible, whereas late binding is more complicated but often more flexible.
To clarify the concept of binding time, look at some real-world examples. An example of early
binding is the practice of some colleges to allow parents to enrolla baby at birth and prepay the
current tuition. When the student shows up 18years later, the tuition is fully paid up, no matter how
high it may be at thatmoment.

In manufacturing, ordering parts in advance and maintaining an inventory of themis early binding.
In contrast, just-in-time manufacturing requires suppliers to be able to provide parts on the spot,
with no advance notice required. This is late binding.
Programming languages often support multiple binding times for variables. Globalvariables are
bound to a particular virtual address by the compiler. This exemplifies early binding. Variables local
428
to a procedure are assigned a virtual address (on the stack) at the time the procedure is invoked.
This is intermediate binding. Varables stored on the heap (those allocated by malloc in C or new in
Java) are assigned virtual addresses only at the time they are actually used. Here we have late
binding.

Operating systems often use early binding for most data structures, but occasionally use late
binding for flexibility. Memory allocation is a case in point. Early multiprogramming systems on
machines lacking address relocation hardware had to load a program at some memory address
and relocate it to runthere. If it was ever swapped out, it had to be brought back at the same memory
address or it would fail. In contrast, paged virtual memory is a form of late binding. The actual
physical address corresponding to a given virtual address is not known until the page is touched
and actually brought into memory.

Another example of late binding is window placement in a GUI. In contrast to theearly graphical
systems, in which the programmer had to specify the absolute screen coordinates for all images
on the screen, in modern GUIs, the software uses coordinates relative to the window's origin, but
that is not determined untilthe window is put on the screen, and it may even be changed later.
Binding refers to the process of converting identifiers (such as variable andperformance names)
into addresses. Binding is done for each variable andfunctions. For functions, it means that
matching the call with the right functiondefinition by the compiler. It takes place either at compile
time or at runtime.

Early Binding (compile-time time polymorphism) As the name indicates, compiler(or linker) directly
associate an address to the function call. It replaces the call with a machine language instruction
that tells the mainframe to leap to the address of the function.
By default early binding happens in C++. Late binding is achieved with the helpof virtual keyword)

429
// CPP Program to illustrate early binding.

// Any normal function call (without virtual)

// is binded early. Here we have taken base

// and derived class example so that readers

// can easily compare and see difference in

// outputs. #include<iostream>

using namespace std;

class Base

public:

void show() { cout<<" In Base \n"; }

};

class Derived: public Base

public:

void show() { cout<<"In Derived \n"; }

};

int main(void)

Output:

430
In Base
Late Binding : (Run time polymorphism) In this, the compiler adds code thatidentifies the kid of
object at runtime then matches the call with the right function definition. This can be achieved by
declaring a virtual function.

// CPP Program to illustrate late binding#include<iostream>using namespace std;class Base

public:

virtual void show() { cout<<" In Base \n"; }

};

class Derived: public Base{public:void show() { cout<<"In Derived \n"; }};int main(void){Base
*bp = new Derived;bp->show(); // RUN-TIME POLYMORPHISM return 0;

Output:

In Derived

Syntax in Programming
Syntax is the set of rules that define what the various combinations of symbols mean. This tells
the computer how to read the code. Syntax refers to a concept inwriting code dealing with a very
specific set of words and a very specific order to those words when we give the computer
instructions. This order and this strict structure is what enables us to communicate effectively with
a computer. Syntax is to code, like grammar is to English or any other language. A big difference
though is that computers are really exacting in how we structure that grammar orour syntax.
This syntax is why we call programming coding. Even amongst all the different languages that are
out there. Each programming language uses different words ina different structure in how we give
it information to get the computer to follow our instructions.
Web developers primarily focus on HTML, CSS, and JavaScript. That is what we’regoing to focus
on in this course as well. By focusing on these languages and mastering them, We’ll be able to write
websites that can be opened by any browser in the world.
Syntax in computer programming means the rules that control the structure of the symbols,
punctuation, and words of a programming language.
Without syntax, the meaning or semantics of a language is nearly impossible tounderstand.

For example, a series of English words, such as — subject a need and doessentence a verb — has
little meaning without syntax.
Applying basic syntax results in the sentence — Does a sentence need a subjectand verb?

431
Programming languages function on the same principles.
If the syntax of a language is not followed, the code will not be understood by a compiler or
interpreter.
Compilers convert programming languages like Java or C++ into binary code thatcomputers can
understand. If the syntax is incorrect, the code will not compile.
Interpreters execute programming languages such as JavaScript or Python at runtime. The
incorrect syntax will cause the code to fail.
That’s why it is crucial that a programmer pays close attention to a language’s syntax. No
programmer likes to get a syntax error.

Basic Syntax
Basic syntax represents the fundamental rules of a programming language.Without these rules, it
is impossible to write functioning code.
Every language has its own set of rules that make up its basic syntax. Naming conventions are a
primary component of basic syntax conventions and vary bylanguage.
1. Case Sensitive. Java, C++, and Python are examples of languages that are case-
sensitive. Identifiers such as world and World have different meanings in these languages.
Languages such as Basic and SQL are insensitive, meaning world and World have the same
meaning.
2. Class Names. Java requires the first letter of each word in class names beupper
case. For example, class FirstJavaClass. Languages such as C or C++use an underscore to
separate words. In C, the class name would befirst_java_class.
3. Program Filenames. The name of a Java program file must match the classname
with the extension ‘*.java” added to the name. For
4. example, FirstJavaClass.java would be the name of the program file for the class
FirstJavaClass. C and C++ files require a “*.c” or “*.cpp” extension buthave no other stipulations.
5. Different languages may have rules for adding comments, using white space, ordeclaring
variables.
6. Object-oriented languages such as Java and C use methods that have different syntax
requirements.
The first step in learning any programming language is to understand the basicssuch as phrase
structure, proper syntax and correctly structured code.

Understanding Syntax
Human languages have syntax. These rules stipulate word order, punctuation and sentence
structure.
Without these rules, it would be impossible to communicate in a given language.When learning a
foreign language, one of the first steps is learning its syntax.
Writing code requires the same focus on syntax. Once the code is written, it isread multiple times
by different people.
Sometimes the code may be read years after it is written, making coding standards necessary.
Coding standards can make the code easy to understand.

432
C Syntax
look at a C program that prints the sentence — My first line of code. All Cinstructions are written in
lower case.

#include
int main() {
printf( “My first line of code” );}
For this example, ignore the include statement at the start of the program. All Cprograms must
begin with main () followed by a left curly bracket ( { ).
This convention indicates the start of the program. A right curly bracket ( } )indicates the end.
The print function (printf) is called, followed by what is to print. The text to printmust be surrounded
by quotation marks and enclosed in parentheses.
All statements must end with a semicolon ( ; ). For example, to print a secondsentence add the
following statement before the right curly bracket:
printf( “just printed!” );}
The executed program would display: My first line of code just printed!

Why Is Syntax Important in Programming?


Syntax improves code readability. It ensures that the four C’s of coding aremaintained:
1. Communication
2. Code integration
3. Consistency
4. Clarity

The concept behind conventions is to make the code explain itself. If the code is self-explanatory,
the focus can be on design and program improvements and noton what does this mean?
Using consistent standards means that code is predictable and discoverable whenread by other
programmers.
When code does not follow conventions, it becomes disorganized and difficult toread. It becomes
what is known as spaghetti code.
The term has a negative connotation indicating that the programmer did not have the skills or
experience needed to write readable code.

The Translation Process.


A computer system can only understand machine code. A program written for example in a high
level language such as Java cannot be run directly. To execute acomputer program written in any
programming language, it must first be translated.

The source code which is written by the programmer needs to be translated. When translated, the
source code becomes object code which is understandableby the computer system. This process
can be seen in the following diagram;

433
There are three main types of translators; Assemblers, Compilers and Interpreters.A description of
each of these types of translators is given in the following table.
The three main types of translators

Type Description

Assembler Assemblers convert assembly language mnemonics

into machine code.


Interpreters convert each instruction of the source code into
Interpreters the object code as the program is being run. This gives a
better interactive environment butis slower.
A compiler converts the entire source code into machine code
Compilers so that it can be run on the machinewithout further translation.
However, error correction is tedious.

Stages in Translating a Program Lexical analysis (Scanner): Breaking a program into primitive
components, calledtokens (identifiers, numbers, keywords, …)
Syntactic analysis (Parsing): Creating a syntax tree of the program.
Symbol table: Storing information about declared objects (identifiers, procedurenames, …)
Semantic analysis: Understanding the relationship among the tokens in theprogram.
Optimization: Rewriting the syntax tree to create a more efficient program.

Code generation: Converting the parsed program into an executable form.

Elementary Data Types

Variables and Constants


Variables: A variable is it Quadruple which is composed of a name, a set ofattributes, a reference
and a value.
A simple variable is an elementary data object with a name and binding of dataobject to value may
change during its lifetime. This data objects are basically defined and named by programmer
explicitly.

Attribute of a variable:
example of variable in "ALGOL Language"y:=9;

434
We can say that it has four attributes

1) the name of the box:y

2) The name of description of a current content.i.e. 9 we can also say that square of 3.

3) the box or storage location(s) which holds(s) the value.

4) the content of the box or 9.

The name of the box and its storage location are fixed, but the contents and itname may vary
over time.

Another example in C language:


• int N;- It declares a simple data object N of type integer.
• N=27; beta value 27 is assigned to variable N.
o declare the variable name N of type integer.
o lifetime of N is execution end.
o data object bound to N during end of execution time.
o value 27 is assigned and may be changed during life of N.
o hidden from the programmer are other binding made by virtual computer
like creating Activation Record, Storage for this activationrecord in Run-TimeStack etc.
Data Object:
Definition: A Data object represents a container for data values, a place wheredata values may be
stored and later retrieved.
Definition: A runtime grouping of one or more pieces of data in a virtualcomputer.
Definition: A Location in memory with an assignment name in the actualcomputer.

Data objects can be:

1) at program execution- Programmer-defined -(example variables, constant,arrays, files etc)


2) not directly accessible to programmer- system defined- run time storage,stacks, file buffers, free
space lists.

435
Data values can be:
• Single number
• Pointer to other objects and characters.

Data object is usually represented as storage in Computer memory and a datavalue is represented
by a pattern of bits. So we can represent the relation between Data Object and Data value.

436
A Data Object is elementary if it contains a data value that is always manipulatedas a unit.
A Data Object is an Data Structure if it is an aggregate of the data object
Binding and Attributes of Data Object:

Binding is an association of data values and entity.


Type: This associates the data object with the set of data values that the objectmay take.
1. location: This associate the binding of a storage location in memory where thedata object is
represented. Only storage management routines can only change add data object in the virtual
computer.
2. Value: This binding is usually the result of an assignment operation.
3. Name: The binding to one or more names by which the object maybe referenced
during program execution is usually set up by declaration andmodified by subprogram calls the
returns.

437
Component: The binding of a data object to one or more data object of which it is a component is
often represented by a pointer value. And may be modified bya change in pointer.

In ALGOL68 we can define constant by

real root2=1.4142135;
That was much acceptable that time.

In Ada, provides a uniform notation for setting constants to initial values and for initializing
variables.

X: Constant INTEGER:=17;
In C language: const is used to initialise the constant value

Const int MAX=80;


The constant MAX is a programmer defined constant because the programmerexplicitly defines
the name for the value 30.
In C, there is micro definition which is used for control the execution of programand can be used
for declaring constant.
Example #define MAX30
It is a compile-time operation that causes all references to MAX in program to bechanged to the
constant 30.
In this 30 has two names, the programmer defined MAX and literal name 30. Bothof which may be
used to refer to a data object containing the value 30.
# Define MAX 30 is a command, which the translator used to equate "MAX" withthe value "30",
whereas the const attribute in C is a translator directive startingthat MAX will always contain the
value 30.

Specification of Elementary Data Types


An elementary data object contains a single data values and class of such data objects over which
various operations are defined is termed as elementary datatype.
Some elementary data types: Integer, real, character, Boolean, enumeration and pointer and
specification may differ significantly between two languages.

Attributes: Basic attributes of any data object, such as data type and name areusually invariant
during its lifetime.

Some attributes may be stored in a descriptor as a part of the data object dailyprogram execution.
Others may be used only to determine the storage representation of the data object.
The value of an attribute of a data object is different from the value that the dataobject contains.
Values: The type of a data object determines the set of possible values that it maycontain.

For Example: C defines the following four classes of integer typesint, short, long and char

438
because most hardware implements multiple Precision integer arithmetic(example 16 bit and 32
bit integers or 32 bit and 64 integers) We can use' short'for shortest value of the integer word length.
long uses the longest value implemented by the hardware.
int uses the most efficient value that the hardware implements.
In C, Characters are stored as 8 bit integers in the type char, which is subtype ofinteger.
Operations:- The set of operations Defined by language is basically refers thathow data object of
that data type may be manipulated.
If the operations are primitive operation, means specified as part of language.

Programmer defined operations, in the form of subprograms or methoddeclarations as part of


class definitions.

Example
Integer* integer-> integer
a) integer addition is an operation that take to integer data objects as anarguments and produces
an integer data object as a result.

b) SQRT: real-> real


A Square-root operation, SQRT,on real number data object is specified.
(Port of operation)
An algorithm that specifies how to compute the results for any given set ofarguments is a common
method for specifying the action of an operation.
In C, we have concept a function prototype which signature of an operation, the number, order and
data types of the arguments in the domain of an operation aregiven as well as the order and the
data type of the resulting range.

Binary operation: Two arguments with single result Monolic operation: Single argument with single
result. Implementation of Elementary Data Types:" Implementation of Elementary data type
consists of
1. Storage representation for data objects
2. Values of that type
3. Set of algorithms or procedures that define the operations of thetype in
terms of manipulations of the storage representation.

Storage representation of Elementary data type:


1) Hardware Influence: Computer hardware influence the storage of elementarydata type.
In this case computer hardware executes the program. If the hardware storage representation are
used, then the basic operations on data of that data type notimplemented using hardware provided
operations.
2) Software influenced: If we do not use hardware storage representation, thenthe operation must
be software simulated and some operation will execute muchless efficient.

Two methods to treat Attributes:


It has to be determined by the compiler and not stored in discriptors during execution or not stored
439
in runtime storage representation. It is usually a methodin C language.
It is stored in a descriptor as part of the data object at runtime in LISP, Prologlanguage .
The storage representation is usually described in terms of

1. Size of the block of memory required (the number of memory wordsbytes, ot


bits needed)
2. Layout of attributes and data values within the block.

Implementation of operations:
Each operation defined for data objects of a given type may be implemented inone of three main
ways: -
1) Directly as a hardware operation: If simple data types are stored using the hardware
representation, when the primitive operations are implemented usingthe arithmetic operations built
in to hardware.
2) As a Subprogram or procedure: A square root for an example, this operation isnot provided
directly as a hardware operation. So it is software simulated implemented as a procedure or
function.
3) as an inline code sequence: It is software implementation of the code and itsoperation. Instead
of using a subprogram, operation in the subprogram are copied into the program at the point where
the subprogram would otherwise have been invoked.

For Example:
The absolute value of function on numbers abs(x)= if x<0 then -x else x
is usually implemented as an inline code sequence.

1. fetch value of x from memory


2. if x >0, skip the next instruction
3. set x=-x
4. store new value of x in memory
Here each line is implemented by a single hardware operation.

Scalar Data Types


Scalar data types represent a single object, i.e. only one value can be derived. In general, scalar
objects follow the hardware architecture of a computer.Numeric Data Types
Integers Sub -ranges

Floating-point real numbers Fixed-point real numbers Other Data Types - Complex numbers
Rational numbers Enumerations Booleans Characters
Integers Specification Maximal and minimal valuesOperations:

Arithmetic Relational Assignment Bit operations


Implementation - hardware defined

Sub-ranges Specification:
subtype of integer
a sequence of integer values within some restricted range Example:
440
Pascal declaration A: 1..10 means that the variable A may be assigned integer values from 1
through 10.
Implementation
smaller storage requirements, better type checking

Floating-point real numbers Specification:


Minimum and maximal value
Round-off issues - the check for equality may fail due to round -off

Implementation
Mantissa - exponent model. Example: 10.5 = 0.105 x 102,Mantissa: 105, Exponent: 2

Fixed-point real numbers Specification:


real numbers with predefined decimal places

Implementation:
Directly supported by hardware or simulated by software

Other scalar data types


Complex numbers: software simulated with two storage locations one the realportion and one for
the imaginary portion.

Rational numbers: the quotient of two integers. Enumerations: Ordered list of different values
Booleans
Characters

Scalar Data Type Enumeration


An Enumerated data type is a data type whose domain values are given in a list orordered list and
who's only operations are equality and assignment. or
An Enumeration is an ordered list of distinct values.or
An Enumeration is a complete ordered listing of all items in a collection.
Pascal was first language which introduced enumeration. To make enumeration facility useful, a
programming language must provide a mechanism for declaring and defining the new data type
and for declaring variables whose value will comefrom the element of type.

It is assumed that this literals are distinct and does equality can be directlydefined.
"Before an era of enumeration what we had ?"
For example: A variable student class might have only 4 possible values representing fresher,
sophomore, junior and senior. Similarly, a variableStudents might have only two values representing
Male and Female. Before the contact of enumeration, the language like

Fortran or Cobol such variables is declared as integer type and distinct values areassigned. like
fresher=1 , sophomore=2, and so onand male=0, female =1

441
Then translator manipulate values as integers.
That creates big problem likeSophomore =1 and female=1
As both have some values can we apply integer-based operation on it. As a point of view of
programmer, it should not be but according to translator it can apply asthey are of integer types.
Then languages such as C, article Pascal and Ada includes an Enumeration datatype that allows
the programmer to define and manipulate such variables directly.

Specification of Enumeration
The programmers defined both the literal name to be used for the values andtheir ordering using a
declaration such as in pascal.

Type months=(jan,feb, mar, apr, june, jul, aug, sep, oct,nov,dec); In C


Enum student class{ fresh, soph, junior, senior};enum studentsex {male, female};
In Pascal, C example can be written as type class =(fresh, soph, junior, senior}; Followed by
declaration for variables such asStudent class: Class;
Studentsex class: Class.
Here type definition introduces the type name class, which may be used whereverthe primitive type
name such as integer might be used time.
It also introduces the literals of fresh, soph, junior, senior which may be used

wherever a language- defined literal such as "27" might be used. Thus we canwrite.
if studentclass= junior then.....
Instead of the less understandable
if studentclass= 3 then ...........
Which would be required if integer variables were used. Static compiler can finderror such as if
student class= Male then

As Male is part of student class. Operations which we can perform-


• Relational operations (equal, less-than, greater-than,etc)
• Assignment
• Successor and Predecessor

Implementation of Enumeration
• Each value in the enumeration sequence is represented at run-time by one ofthe integers 0,1,2,
as only a small set of values is involved and the values are
• never negative.
• In this integer representation is often shortened to omit the sign bit and use only enough bits for
the range of values required, as with the sub-range values.
• Only and maximum 2 bits are required to represent the senior=3 in memory because
3=11(binary)/ 2 bits only
• In C, the programmer main override default and set any values desired for enumeration
values for example.
• Enum class{ fresh=74, soph=89, junio=7, senior=28}

442
• With this storage representation for enumeration types. Relational operationssuch as =,>,
and < may be implemented.

Scalar Data Types: Booleans

The Boolean data type is a data type, having two values(usually denoted true orfalse), intended to
represent the truth values of logic and Boolean algebra.

Specification: In Pascal and Ada, the Boolean data type is considered simply alanguage - defined
enumeration, viz;
type Boolean=(false, true);

Which both defines the names true and false for the values of the types and define ordering
false<true
Common Operations in boolean are
and: Boolean*Boolean->Boolean(conjunction)
or: Boolean*Boolean->Boolean(inclusive disjunction ) not : Boolean ->Boolean(negative or
complement)

Implementation of boolean data type:


Single bit of storage is provided, no descriptor designated the data type is needed. Because single
bit may not be separately addressable in memory whichoften takes a byte or word to represent it if
extended. Then the value true and false might be represented in two ways within the storage unit:
• a particular bit is used for the value(often the sign bit of the number
representation), with '0= false', '1=true', and the rest of the byte or wordignored, or
• A zero value in the entire storage unit represent False, and any other nonzero value
represents true

Scalar Data Types: CharactersSpecification of Characters


443
A character data type provides data objects that have a single character as their value. Set of values
in character data type depends upon "Hardware and Operating System" like ASCII character set.
and ordering of the characters in thischaracter set is called Collecting Sequence And ordering given
by the 'RelationalOperations'.

Character set includes


• Spaces
• Digits
• Special character @,#,$,& etc.

Operations on character data include only

• Relational operations
• Assignment and
• To test character for- Letter, Digit, Special Character

Implementation of Character Data Type


Character data values are almost directly supported by the underlying hardware and operating
system because their use in input-output.

In C Character is declared

ASCII value of character data type in C are


0 to 9 is 48 to 57/ ASCII value
A to z is 65 to 90
a to z is 97 to 122
And all remaining for special characters.char a ; //declaration
a='A'; // initializing character data object with AWhere= A=65=1000001

444
Composite Data Types
Unbounded length: storage allocation at run time. String can be any length

Character Strings - operations


Concatenation – appending two strings
➢ Relational operations – equal, less than, greater than
• Substring selection using positioning subscripts
• Substring selection using pattern matching
• Input / output formatting
• Dynamic strings - the string is evaluated at run time.

implementation
445
• Fixed declared length: A packed vector of characters
• Variable length to a declared bound: a descriptor that contains the maximum length and
the current
Length
• Unbounded length: Either a linked storage of fixed-length data objects or acontiguous
array of characters with dynamic run-time storage allocation

Pointers and Programmer- Constructed Objects

Objects
Specification:
Reference data objects only of a single type – C, Pascal, Ada.Reference data objects of any type –
Smalltalk C, C++: pointers are data objects and can be manipulated by the program Java: pointers
are hidden data structures, managed by the languageimplementation

Pointers - implementation
Absolute addresses stored in the pointer. Allows for storing the new objectanywhere in the memory
Relative addresses: offset with respect to some base address.
Advantages: the entire block can be moved to another location without invalidating the addresses
in the pointers, since they are relative, not absolute.

Pointers – implementation problems

• Management of a general heap storage area: to create objects of differentsize


• Garbage - the contents of pointer is destroyed, and the object still exists
• Dangling references: the object is destroyed however the pointer still contains the
address of the used location, and can be wrongly used by theprogram.

Characteristics:
• Usually resideon secondary storage devicesas disks, tapes.
• Lifetime is greater than the lifetime of the program that hascreated the files.

Implementation – as part of the operating system

Types of Files
Sequential file: a data structure composed of a linear sequence ofcomponents of the same type.
Interactive Input-Output: sequential files used in interactive mode.

Direct Access Files: Any single component can be accessed at random just as in anarray.
Key: the subscript to access a component.

Implementation: a key table is kept in main memory


Indexed Sequential Files: Similar to direct access files using a key combined withbeing able to
sequentially process the file. The file must be ordered by the key

446
C programming
C programming is a general-purpose, procedural, imperative computer programming language
developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX
operating system. C is the most widely used computer language. It keeps fluctuating at number
one scale of popularity along with Java programming language, which is also equally popularand
most widely used among modern software programmers.
Why to Learn C Programming?

C programming language is a MUST for students and working professionals to become a great
Software Engineer specially when they are working in SoftwareDevelopment Domain. I will list down
some of the key advantages of learning CProgramming:
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
• Facts about C

• C was invented to write an operating system called UNIX.


• C is a successor of B language which was introduced around the early1970s.
• The language was formalized in 1988 by the American NationalStandard Institute (ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System ProgrammingLanguage.
• Most of the state-of-the-art software have been implemented usingC.

1. Today's most popular Linux OS and RDBMS MySQL have been writtenin C.
2. Hello World using C Programming.

#include <stdio.h

int main() {

/* my first program in C */

printf("Hello, World! \n");

return 0;

Applications of C Programming
C was initially used for system development work, particularly the programs that make-up the
447
operating system. C was adopted as a system development languagebecause it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use of C
are -
1. Operating Systems
2. Language Compilers
3. Assemblers
4. Text Editors
5. Print Spoolers
6. Network Drivers
7. Modern Programs
8. Databases
9. Language Interpreters
10. Utilities

Token
Tokens are the smallest elements of a program, which are meaningful to thecompiler.
The following are the types of tokens: Keywords, Identifiers, Constant, Strings,Operators, etc.

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

Identifiers
Each program element in C programming is known as an identifier. They are usedfor naming of
variables, functions, array etc. These are user-defined names whichconsist of alphabets, number,
underscore ‘_’. Identifier’s name should not be same or same as keywords. Keywords are not used
as identifiers.
448
Rules for naming C identifiers −
• It must begin with alphabets or underscore.
• Only alphabets, numbers, underscore can be used, no other special
characters, punctuations are allowed.
• It must not contain white space.
• It should not be a keyword.
• It should be up to 31 characters long.
Rules for constructing C identifiers
• The first character of an identifier should be either an alphabet or an underscore,
and then it can be followed by any of the character, digit, orunderscore.
• It should not begin with any numerical digit.
• In identifiers, both uppercase and lowercase letters are distinct. Therefore,we can
say that identifiers are case sensitive.
• Commas or blank spaces cannot be specified within an identifier.
• Keywords cannot be represented as an identifier.
• The length of the identifiers should not be more than 31 characters.
• Identifiers should be written in such a way that it is meaningful, short, andeasy to
read.

Example of valid identifiers


total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers


2sum (starts with a numerical digit)
• int (reserved word)
• char (reserved word)
• m+n (special character, i.e., '+')

• Types of identifiers
• Internal identifier
• External identifier

Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internalidentifier. The
internal identifiers can be local variables.

External Identifier
If the identifier is used in the external linkage, then it is known as an externalidentifier. The external
identifiers can be function names, global variables.

Differences between Keyword and Identifier

449
Keyword Identifier

Keyword is a pre-defined word. The identifier is a user-defined word

It can be written in both lowercase anduppercase


It must be written in a lowercaseletter.
letters.

Its meaning is pre-defined in the ccompiler. Its meaning is not defined in the c compiler.

It is a combination of alphabetical
It is a combination of alphanumericcharacters.
characters.
It does not contain the underscore
It can contain the underscore character.
character.

int main()

int a=10;

int A=20;

printf("Value of a is : %d",a);

printf("\nValue of A is :%d",A);return

0;

}
The above output shows that the values of both the variables, 'a' and 'A' aredifferent. Therefore, we
conclude that the identifiers are case sensitive.

Strings
A string is an array of characters ended with a null character (\0). This null character indicates that
string has ended. Strings are always enclosed with doublequotes (“ “).
how to declare String in C language –
Example:

450
1) char string[20] = {‘s’,’t’,’u’,’d’,’y’, ‘\0’};

2) char string[20] = “demo”;

char string [] = “demo”;Here is an example of tokens in C language,


#include >stdio.h>int main() {

// using keyword charchar a1 = 'H';

int b = 8; float d 5.6.

// declaration of string

char string[200] = "demodotcom";if(b<10)

printf("Character Value : %c\n",a1);else

printf("Float value : %f\n",d);

printf("String Value : %s\n", string);

return 0;

Output
Character Value: H
String Value: demo dot com

Data Types in C
A data type specifies the type of data that a variable can store such as integer,floating,
character, etc.

451
There are the following data types in C language

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

452
signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

453
Subprogram
A Subprogram is a program inside any larger program that can be reused anynumber of times.
ontrol at the subprogram level is concerned with subprogram invocation and the relationship
between the calling module and the called module. What follows is alist of possible ways the caller
and the callee are related.

Characteristics of a Subprogram:

(1) A Subprogram is implemented using the Call & Return instructions inAssembly Language.
(2) The Call Instruction is present in the Main Program and the Return(Ret)Instruction is present in
the subprogram itself.
(3) It is important to note that the Main Program is suspended during the execution of any
subprogram. Moreover, after the completion of the subprogramthe main program executes from
the next sequential address present in the Program Counter .
(4) For the implementation of any subprogram, a “Stack” is used to store
the “Return Address” to the Main Program . Here, Return Address means the immediately next
instruction address after the Call Instruction in the Main program. This Return Address is present
inside the Program Counter . Thus duringthe execution of the Call Instruction, the Program Counter
value is first pushed tothe Stack as the Return Address and then the Program Counter value is
updated to the given address in the Call Instruction. Similarly, during the execution of Return(Ret)
Instruction, the value present in the stack is popped and the ProgramCounter value is restored for
further execution of the Main Program .
(5) The Main advantage of Subprogram is that it avoids repetition of Code andallows us to reuse
the same code again and again.

454
ARRAY

Introduction
• Arrays are also known as subscript variable.
• Array is a collection of similar elements
• Whatever may the size of array, it always consumed memory in a contiguousmanner

• Need of array
• Till now we have been designing solution to small problems that require less number of
variables to handle program data. Think about a scenario where Weneed to handle hundreds of
variables or even more than that.
• In such scenario, We might be thinking about what variable names should beused, how to
reduce redundant code, etc.
• Assume We have to store marks of 100 students and then think about thefollowing:
455
• What could be our variable naming convention?
• How We efficiently write input instruction to store 100data.
• How could We easily manipulate data like adding all ofthem
in a less complex style?
• The answer to all these questions is subscript notation also known as arrays.

Array Declaration

• When We want to create large number of variables We need not to think about 100s of
names. Assume that We want to create 100 variables to store marks of 100 students.
• Here is the way:

int marks [100];


• Notice square brackets after array name marks. This pair of square bracketsis
used to depict array usage.Number mention in the square bracket is size of array. In our example
we wrote 100, so size of the array is 100. Thus we have declared 100 variablesin one go.
• These 100 variables are all of type int. Since array is a collection of similar
elements, data type for all 100 variables is int.
• Name of the first variable is marks[0], second variable is marks[1], and so on.
Therefore the last variable is marks[99]. Here it is important to note that in C language array
indexing starts with 0 and not from 1.
• Example: Program to calculate average of 10 marks#include<stdio.h>

• #include<conio.h>main()

• {
• int i, marks[10], sum=0;float avg;

clrscr(); print(“Enter 10 numbers”);for(i=0;i<=9;i++)


scanf(“%d”,&marks[i]); for(i=0;i<=9;i++)

sum=sum+marks[i]; avg=sum/10.0;

printf(“Average is %f”,avg);
getch();

}Explanation:

• Total numbers of variables in this program are 13. Their namesare i,


sum, avg, marks[0], marks[1],…marks[9].
• Notice the input statement, scanf() is repeated 10 times, this is possible
as we can access array index with the help of variable. Observe &marks[i] in scanf(), here i is used
for indexing. As the loop proceed value of i changes from 0 to 9. In this way wee neednot to write
scanf() 10 times.
• Data manipulation becomes also easy, we added all 10 values stored in
an array putting statement sum=sum+marks[i] in theloop.
456
• Since we have an array of size 10 and each of these blocks are oftype
int, to tal memory consumed for this array is 20 bytes (2 bytes for each).

One dimension array


To use an array variable in a program, it must be declared. When defining anarray in a program,
three things need to be specified.
• What kind of data it can hold, i.e., int, char, double, string, etc.
• How many values it can hold, i.e., the maximum number it can hold
• A name
In the previous example the array declared known as one dimensional array.
Note: According to our previous example marks is not a variable name but marks[0] is a variable.
Thus we can not assign anything to marks like marks=5;

Two-dimension array
C language supports multidimensional arrays also. The simplest form of a multidimensional array
is the two-dimensional array. Both the row's and column'sindex begin from 0.
Two dimensional arrays is actually array of arrays. So here we are creating an array of several
identical arrays.
Consider the following declaration style

int a [2][3];

• this declaration means, we have an array of 2 arrays containing 3 int blocks each.
o Total numbers of blocks are 6, they are all of type int. Memory
allocation done is always sequential, but we canassume it as two arrays each of size 3.
o Logically we can see it as a row column structure. Firstrow is
our 0th array and second row is 1st array.
o Two dimensional arrays are used to handle data which is
logically two dimensional like matrix.
• Example: Program to add two matrix of order 3 x 3.#include<conio.h>

#include<stdio.h> main(){int a[3][3],b[3][3],c[3][3];int i,j; clrscr();printf("Enter 9 numbers for first

matrix\n");for(i=0;i<3;i++)for(j=0;j<3;j++) scanf("%d",&a[i][j]); printf("Enter 9 numbers for second

matrix\n");

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

scanf("%d",&b[i][j]);

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

c[i][j]=a[i][j]+b[i][j];printf("\nSum of matrix is: \n");


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

for(j=0;j<3;j++)
printf("%d ",c[i][j]);printf("\n");

}
getch();

}
Explanation:

1. Notice the declaration of arrays. We have declared three two dimensionalarrays.


2. Observe the style of input. scanf() is repeated with nested loop.

3. Lastly sum of corresponding elements of two matrices are added and storedin third
array.
4. Finally sum is displayed on the screen Initialization of array at the time of

declarationInitializing one dimension array

int a[5]={ 23,45,11,67,55};


int a[ ]= { 23,45,11,67,55};int a[5]= {22,45};

int a[5]= {12,23,76,85,43,33};

In the first style we declared an array with size 5 and assign 5 values to them, Firstvalue is stored
in a[0] and last in a[4].
Second style is also valid. When We initialize array at the time of declaration it isnot necessary to
mention size of array, otherwise it is compulsory. Compiler assumes the size of array by counting
number of values assigned to it.
Third notation style is also valid as two variables a[0] and a[1] initializes with 22and 45, remaining
variables are initialized to 0.
Fourth style leads to compilation error. an array can not be intialized with datamore than the size of
array.
Initialization of two dimension array
int b[2] [3] = {12,65,78,45,33,21};
int b[ ] [3] = {12,65,78,45,33,21};
int b[2] [ ] = {12,65,78,45,33,21};
int b[ ] [ ] = {12,65,78,45,33,21};

Last two styles are invalid and lead to compile time error.

C Structures
Structure is a user-defined datatype in C language which allows us to combine data of different
types together. Structure helps to construct a complex data typewhich is more meaningful. It is

458
somewhat similar to an Array, but an array holds data of similar type only. But structure on the other
hand, can store data of any type, which is practical more useful.
For example: If I have to write a program to store Student information, which willhave Student's
name, age, branch, permanent address, father's name etc, which included string values, integer
values etc, how can I use arrays for this problem, I will require something which can hold data of
different types together.
In structure, data is stored in form of records.

Defining a structure

struct keyword is used to define a structure. struct defines a new data type whichis a collection of
primary and derived datatypes.

Syntax:

struct [structure_tag]

//member variable 1

//member variable 2

//member variable 3

...

}[structure_variables];

As We can see in the syntax above, we start with the struct keyword, then it's optional to provide
our structure a name, we suggest giving it a name, then inside the curly braces, we have to mention
all the member variables, which are nothing but normal C language variables of different types like
int, float, array etc.
After the closing curly brace, we can specify one or more structure variables,again this is optional.
Note: The closing curly brace in the structure type declaration must be followedby a semicolon (;).

Example of Structure

459
struct Student

char name[25];

int age;

char branch[10];

// F for female and M for male

char gender;

};

Here struct Student declares a structure to hold the details of a student which consists of 4 data
fields, namely name, age, branch and gender. These fields are called structure elements or
members.
Each member can have different datatype, like in this case, name is an array
of char type and age is of int type etc. Student is the name of the structure and iscalled as the
structure tag.

Declaring Structure Variables


It is possible to declare variables of a structure, either along with structure definition or after the
structure is defined. Structure variable declaration is similar to the declaration of any normal
variable of any other datatype. Structure variables can be declared in following two ways:

1) Declaring Structure variables separately

460
struct Student

char name[25];

int age;

char branch[10];

//F for female and M for male

char gender;

};

struct Student S1, S2; //declaring variables of struct Student

2) Declaring Structure variables with structure definition

struct Student

char name[25];

int age;

char branch[10];

//F for female and M for male

char gender;

}S1, S2;

Here S1 and S2 are variables of structure Student. However, this approach is not much
recommended.

Accessing Structure Members


Structure members can be accessed and assigned values in a number of ways. Structure members

461
have no meaning individually without the structure. In order to assign a value to any structure
member, the member name must be linked withthe structure variable using a dot . operator also
called period or member
access operator.
For example:

#include<stdio.h>

#include<string.h>

struct Student

char name[25];

int age;

char branch[10];

//F for female and M for male

char gender;

};

int main()

struct Student s1;

/*

s1 is a variable of Student type andage is a member of Student

*/

s1.age = 18;

/*

using string function to add name

*/
462
strcpy(s1.name, "Viraaj");

/*

displaying the stored values

*/

printf("Name of Student 1: %s\n", s1.name);printf("Age of Student 1: %d\n", s1.age);

return 0;

}
Name of Student 1: ViraajAge of Student 1: 18
We can also use scanf() to give values to structure members through terminal.

scanf(" %s ", s1.name);


scanf(" %d ", &s1.age);

Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized atcompile time.

or,

struct Patient p1;

p1.height = 180.75; //initialization of each member separately

p1.weight = 73;

p1.age = 23;

C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using the
structure as given below.
#include<stdio.h>
struct student

char name[20];
463
int id;

float marks;

};

void main()

struct student s1,s2,s3;

int dummy;

printf("Enter the name, id, and marks of student 1 ");

scanf("%s %d %f",s1.name,&s1.id,&s1.marks);

scanf("%c",&dummy);

printf("Enter the name, id, and marks of student 2 ");

scanf("%s %d %f",s2.name,&s2.id,&s2.marks);

scanf("%c",&dummy);

printf("Enter the name, id, and marks of student 3 ");

scanf("%s %d %f",s3.name,&s3.id,&s3.marks);

scanf("%c",&dummy);

printf("Printing the details \n");

printf("%s %d %f\n",s1.name,s1.id,s1.marks);

printf("%s %d %f\n",s2.name,s2.id,s2.marks);

printf("%s %d %f\n",s3.name,s3.id,s3.marks);

Output

464
Enter the name, id, and marks of student 1 James 90 90

Enter the name, id, and marks of student 2 Adoms 90 90

Enter the name, id, and marks of student 3 Nick 90 90

Printing the details....

James 90 90.000000

Adoms 90 90.000000

Nick 90 90.000000

In the above program, we have stored data of 3 students in the structure. However, the complexity
of the program will be increased if there are 20 students. In that case, we will have to declare 20
different structure variables andstore them one by one. This will always be tough since we will have
to declare a variable every time we add a student. Remembering the name of all the variablesis
also a very tricky task. However, c enables us to declare an array of structures by using which, we
can avoid declaring the different structure variables; instead we can make a collection containing
all the structures that store the information of different entities.

Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used to
store information about multiple entities ofdifferent data types. The array of structures is also
known as the collection of structures.

465
#include<stdio.h> #include <string.h>struct student{

int rollno;

char name[10];

};

int main(){

int i;

struct student st[5];

printf("Enter Records of 5 students");

for(i=0;i<5;i++){ printf("\nEnter Rollno:");scanf("%d",&st[i].rollno);printf("\nEnter Name:");

scanf("%s",&st[i].name);

printf("\nStudent Information List:");

for(i=0;i<5;i++){

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);

return 0;

}
Output:

Enter Records of 5 students

Enter Rollno:1

Enter Name:Sonoo Enter Rollno:2 Enter Name:Ratan Enter Rollno:3 Enter Name:Vimal

Enter Rollno:4 Enter Name:James Enter Rollno:5 Enter Name:Sarfraz

466
Student Information List:Rollno:1, Name:Sonoo Rollno:2, Name:Ratan Rollno:3,

Name:Vimal Rollno:4, Name:James

Rollno:5, Name:Sarfraz that one structure has another stucture as member variable.
C provides us the feature of nesting one structure within another structure by using which, complex
data types are created. For example, we may need to storethe address of an entity employee in a
structure. The attribute address may also have the subparts as street number, city, state, and pin
code. Hence, to store theaddress of the employee, we need to store the address of the employee
into a separate structure and nest the structure address into the structure employee.
Consider the following program.

#include<stdio.h>

struct address

char city[20];

int pin;

char phone[14];

};

struct employee

char name[20];

struct address add; 467

};
printf("Printing the employee information.........\n");

printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.


city,emp.add.pin,emp.add.phone);

o By Embedded structure

1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main
structure as a member. Consider the following example.

468
struct Date

int dd;

int mm;

int yyyy;

};

struct Employee

int id;

char name[20];

struct Date doj;

}emp1;

As We can see, doj (date of joining) is the variable of type Date. Here doj is usedas a member in
Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure

The embedded structure enables us to declare the structure inside the structure.Hence, it requires
less line of codes but it can not be used in multiple data structures. Consider the following example.
o struct Employee
o {
o int id;
o char name[20];
o struct Date
o {
o int dd;
o int mm;
o int yyyy;
o }doj;
o } emp1;

Accessing Nested Structure

469
We can access the member of the nested structure by Outer_Structure.Nested_Structure.member
as given below:

e1.doj.dd

e1.doj.mm

e1.doj.yyyy

C Nested Structure example

a simple example of the nested structure in C language.

#include <stdio.h>

#include <string.h>

struct Employee

int id;

char name[20];

struct Date

int dd;

int mm;

int yyyy;

}doj;

}e1;

int main( )

//storing employee information

470
e1.id=101;

strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array

e1.doj.dd=10;

e1.doj.mm=11;

e1.doj.yyyy=2014;

//printing first employee information

printf( "employee id : %d\n", e1.id);

printf( "employee name : %s\n", e1.name);

printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e


1.doj.mm,e1.doj.yyyy);

return 0;
char name[20];

struct address add;

};

void display(struct employee);

void main ()

struct employee emp;

printf("Enter employee information?\n");

scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);

display(emp);

void display(struct employee emp)

471
printf("Printing the details ...... \n");

printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);

We can pass a structure as a function argument just like we pass any othervariable or an array as
a function argument.
Example:
int roll;};

void show(struct Student st);void main()

struct Student std;

printf("\nEnter Student record:\n");printf("\nStudent name:\t"); scanf("%s", std.name);

printf("\nEnter Student rollno.:\t"); scanf("%d", &std.roll);

show(std);

void show(struct Student st)

#include<stdio.h>

struct Student

char name[10];

printf("\nstudent name is %s", st.name);

printf("\nroll is %d", st.roll);

C Unions

472

int roll;};
Unions are conceptually similar to structures. The syntax to declare/define a union is also similar
to that of a structure. The only differences is in terms of storage. In structure each member has its
own storage location, whereas all members of union uses a single shared memory location which
is equal to the sizeof its largest data member.

union item

int m;

float x;

char c;

}It1;
This implies that although a union may contain many members of different types, it cannot handle
all the members at the same time. A union is declaredusing the union keyword.

This declares a variable It1 of type union item. This union contains three memberseach with a
different data type. However only one of them can be used at a time. This is due to the fact that
only one location is allocated for allthe union variables, irrespective of their size. The compiler
allocates the storagethat is large enough to hold the largest variable type in the union.
In the union declared above the member x requires 4 bytes which is largest amongst the members
for a 16-bit machine. Other members of union will sharethe same memory address.

Accessing a Union Member in C


Syntax for accessing any union member is similar to accessing structure members,

473
union test

int a;

float b;

char c;

}t;

t.a; //to access members of union t

t.b;

t.c;

Time for an Example

#include <stdio.h>

union item

int a;

float b;

char ch;

};

int main( )

union item it;it.a = 12;

it.b = 20.2;it.ch = 'z'

printf("%d\n", it.a);

474
printf("%f\n", it.b);

printf("%c\n", it.ch);return 0;

the expected result. This is because in union, the memory is shared among
different data types. Hence, the only member whose value is currently stored willhave the memory.
In the above example, value of the variable c was stored at last, hence the valueof other variables
is lost.

Advantage of union over structure


It occupies less memory because it occupies the size of the largest member only.

Disadvantage of union over structure


Only the last entered data can be stored in the union. It overwrites the datapreviously stored in the
union.

String
String is nothing but a collection of characters in a linear sequence. 'C' alwaystreats a string a
single data even though it contains whitespaces. A single character is defined using single quote
representation. A string is representedusing double quote marks.
Example, "Welcome to the world of programming!"

'C' provides standard library <string.h> that contains many functions which can beused to perform
complicated string operations easily.
Declare and initialize a String

A string is a simple array with char as a data type. 'C' language does not directlysupport string as a
data type. Hence, to display a string in 'C', We need to makeuse of a character array.
The general syntax for declaring a variable as a string is as follows,

char string_variable_name [array_size];

The classic string declaration can be done as follow:


char string name[string_length] = "string";

The size of an array must be defined while declaring a string variable because itused to calculate
how many characters are going to be stored inside the string variable. Some valid examples of
string declaration are as follows,

475
char first_name[15]; //declaration of a string variable

char last_name[15];

The above example represents string variables with an array size of 15. This means that the given
character array is capable of holding 15 characters at most.The indexing of array begins from 0
hence it will store characters from a 0-14 position. The C compiler automatically adds a NULL
character '\0' to the character array created.
The initialization of a string variable. Following example demonstrates theinitialization of a string
variable,

char first_name[15] = "ANTHONY";

char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0' is


required at end in this declaration

char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */

char string2 [ ] = "world"; /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */

char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size
6*/

In string3, the NULL character must be added explicitly, and the characters areenclosed in single
quotation marks.
'C' also allows us to initialize a string variable without defining the size of thecharacter array. It can
be done in the following way,

char first_name[ ] = "NATHAN";

The name of a string acts as a pointer because it is basically an array.


String Input: Read a String
When writing interactive programs which ask the user for input, C provides thescanf(), gets(), and
fgets() functions to find a line of text entered from the user.
When we use scanf() to read, we use the "%s" format specifier without using the"&" to access the
variable address because an array name acts as a pointer. For example:

476
#include <stdio.h>

int main() {

char name[10];

int age;

printf("Enter your first name and age: \n");

scanf("%s %d", name, &age);

printf("You entered: %s %d",name,age);

Output:

Enter your first name and age:

John_Smith 48

The problem with the scanf function is that it never reads an entire string. It will halt the reading
process as soon as whitespace, form feed, vertical tab, newline ora carriage return occurs. Suppose
we give input as "Guru99 Tutorials" then the scanf function will never read an entire string as a
whitespace character occurs between the two names. The scanf function will only read Guru99.
In order to read a string contains spaces, we use the gets() function. Gets ignoresthe whitespaces.

477
#include <stdio.h>

int main() {

char full_name[25];

printf("Enter your full name: ");

gets(full_name);

printf("My full name is %s ",full_name);

return 0;

Output:

Enter your full name: Dennis Ritchie

My full name is Dennis Ritchie

Another safer alternative to gets() is fgets() function which reads a specified


number of characters. For example:

#include <stdio.h>

int main() {

char name[10];

printf("Enter your name plz: ");

fgets(name, 10, stdin);

printf("My name is %s ",name);


It stops reading when a newline is reached (the Enter key is pressed).For example:

return 0;}

Output:

478
Enter your name plz: Carlos

My name is Carlos

The fgets() arguments are :

• the string name,

• the number of characters to read,

• stdin means to read from the standard input which is the keyboard.


String Output: Print/Display a String
The standard printf function is used for printing or displaying a string on an outputdevice. The
format specifier used is %s

Example,

printf("%s", name);

String output is done with the fputs() and printf() functions.


fputs() function

The fputs() needs the name of the string and a pointer to where We want to display the text. We
use
printf("Enter your town: ");gets(town);

fputs(town, stdout);
return 0;}
#include <stdio.h>int main()

{char town[40];

stdout which refers to the standard output in order toprint to the screen. For example:

479
The standard 'C' library provides various functions to manipulate the strings within a program.
These functions are also called as string handlers. All thesehandlers are present inside <string.h>
header file.

Output:

Enter your town: New York

New York

puts function

The puts function prints the string on an output device and moves the cursor back
to the first position. A puts function can be used in the following way,

#include <stdio.h>
int main() {

char name[15];

gets(name); //reads a string

puts(name); //displays a string

return 0;}

The syntax of this function is comparatively simple than other functions.

The string library

Function Purpose

This function is used for finding a length of a string. It returns


strlen() how manycharacters are present in a string excluding the
NULL character.

480
This function is used for combining twostrings together to
strcat(str1, str2) form a single string.It Appends or concatenates str2 to the
end of str1 and returns a pointer to str1.

This function is used to compare two strings with each other.


strcmp(str1, str2) It returns 0 if str1 is equal to str2, less than 0 if str1 <str2, and
greater than 0 if str1 > str2.

int val;

//string comparison

val= strcmp(string1,string2); if(val==0){

printf("Strings are equal\n");

else{

printf("Strings are not equal\n");

//string concatenation

printf("Concatenated string:%s",strcat(string1,string2)); //string1 contains helloworld!

//string length

printf("\nLength of first string:%d",strlen(string1)); printf("\nLength of second

string:%d",strlen(string2));

//string copy

printf("\nCopied string is:%s\n",strcpy(string3,string1)); //string1 is copied intostring3

return 0;}

481
Strings are not equal
Output:

Concatenated string:Hello World!

Length of first string:12

Length of second string:7

Copied string is:Hello World!

Other important library functions are:


• strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal tothe first
n characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
• strncpy(str1, str2, n) This function is used to copy a string from anotherstring.
Copies the first n characters of str2 to str1
• strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, orNULL
if character not found.
• strrchr(str1, c): it searches str1 in reverse and returns a pointer to theposition of
char c in str1, or NULL if character not found.
• strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, orNULL
if str2 not found.
• strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to theend
of str1 and returns a pointer to str1.
• strlwr() :to convert string to lower case
• strupr() :to convert string to upper case
• strrev() : to reverse string

Converting a String to a Number


In C programming, we can convert a string of numeric characters to a numericvalue to prevent a
run-time error. The stdio.h library contains the following functions for converting a string to a
number:
int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the
first character is not a number or no numbers areencountered.
double atof(str) Stands for ASCII to float, it converts str to the equivalent double value. 0.0 is
returned if the first character is not a number or numbers are encountered.
long int atol(str) Stands for ASCII to long int, Converts str to the equivalentlong integer value.
0 is returned if the first character is not a number or nonumbers are encountered.

The following program demonstrates atom() function:


482
#include <stdio.h>int main()

{char *string_id[10];int ID;

printf("Enter a number: ");gets(string_id);

ID = atoi(string_id); print("you enter %d ",ID);

return 0;}

Output:

Enter a number: 221348

you enter 221348

➢ A string pointer declaration such as char *string = "language" is a constantand


cannot be modified.

Summary
• A string is a sequence of characters stored in a character array.
• A string is a text enclosed in double quotation marks.
• A character such as 'd' is not a string and it is indicated by single quotation marks.
• 'C' provides standard library functions to manipulate strings in a program. String
manipulators are stored in <string.h> header file.
• A string must be declared or initialized before using into a program.
• There are different input and output string functions, each one among them has itsfeatures.
• Don't forget to include the string library to work with its functions
• We can convert string to number through the atoi(), atof() and atol() which are veryuseful
for coding and decoding processes.
• We can manipulate different strings by defining a string array.

Pointer?

POINTER is a variable that stores address of another variable. A pointer can alsobe used to refer
to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/
previous memory location.The purpose of pointer is to save memory space and achieve faster
execution time.

How does Pointer Work?


If we declare a variable v of type int, v will actually store a value.
v is equal to zero now.

483
However, each variable, apart from value, also has its address (or, simply put, where it is located in
the memory). The address can be retrieved by putting anampersand (&) before the variable name.

If We print the address of a variable on the screen, it will look like a totally
random number (moreover, it can be different from run to run).

The output of this program is -480613588.

Now, what is a pointer? Instead of storing a value, a pointer will y store the
address of a variable.

Int *y = &v;

VARIABLE POINTER

A variable that points to thestorage/memory


A value stored in
address
a named storage/memory address
of another variable

Declaring a pointer
Like variables, pointers have to be declared before they can be used in our program. Pointers can
be named anything We want as long as they obey C'snaming rules. A pointer declaration has the
following form.

484
data_type * pointer_variable_name;

Here,
• data_type is the pointer's base type of C's variable types and indicates thetype of
the variable that the pointer points to.
• The asterisk (*: the same asterisk used for multiplication) which is indirection
operator, declares a pointer.
• Some valid pointer declarations
• int *ptr_thing; /* pointer to an integer */
• int *ptr1,thing;/* ptr1 is a pointer to type integer and thing is an integer variable
• */
• double *ptr2; /* pointer to a double */float *ptr3; /* pointer to a float */

• char *ch1 ; /* pointer to a character */


• float *ptr, variable;/*ptr is a pointer to type float and variable is an ordinary floatvariable */

Initialize a pointer
After declaring a pointer, we initialize it like standard variables with a variable address. If pointers
are not uninitialized and used in the program, the results are unpredictable and potentially
disastrous.
To get the address of a variable, we use the ampersand (&)operator, placed before the name of a
variable whose address we need. Pointer initialization isdone with the following syntax.pointer =
&variable.

A simple program for pointer illustration is given below:


Address stored in a variable p is:60ff08

Value stored in a variable p is10


#include <stdio.h>

int main()

{
int a=10; //variable declaration

int *p; //pointer variable declaration

p=&a; //store address of variable a in pointer p printf("Address stored in a variable p


is:%x\n",p); //accessing the address

printf("Value stored in a variable p is:%d\n",*p); //accessing the valuereturn 0;


Output:
485
Operator Meaning

Serves 2 purpose

* • Declaration of a pointer
• Returns the value of thereferenced
variable

Serves only 1 purpose


&
➢ Returns the address of avariable

Types of a pointer

Null pointer
We can create a null pointer by assigning null value during the pointer declaration. This
method is useful when We do not have any address assigned tothe pointer. A null pointer
always contains value 0.
Following program illustrates the use of a null pointer:
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf (“The value inside variable p is:\n%x”,p);

return 0;
Output:
The value inside variable p is:
0

Void Pointer
In C programming, a void pointer is also called as a generic pointer. It does not have any standard
data type. A void pointer is created by using the keyword void.It can be used to store an address of
any variable.

Following program illustrates the use of a void pointer: #include <stdio.h>int main()
486
{

void *p = NULL; //void pointer

printf("The size of pointer is:%d\n",sizeof(p));return 0;

}
Output: The size of pointer is:4

Wild pointer
A pointer is said to be a wild pointer if it is not being initialized to anything. Thesetypes of
pointers are not efficient because they may point to some unknown memory location
which may cause problems in our program and it may lead to crashing of the program. One
should always be careful while working with wild pointers.
Following program illustrates the use of wild pointer: #include <stdio.h>int main()
{ int *p; //wild pointer printf("\n%d",*p);

return 0;

}
Output:
timeout: the monitored command dumped core sh: line 1: 95298 Segmentation fault
timeout 10s main

Other types of pointers in 'c' are as follows:


• Dangling pointer
• Complex pointer
• Near pointer
• Far pointer
• Huge pointer

Direct and Indirect Access Pointers


In C, there are two equivalent ways to access and manipulate a variable content
• Direct access: we use directly the variable name
• Indirect access: we use a pointer to the variableunderstand this with the help

of program below

• #include <stdio.h>

• /* Declare and initialize an int variable */int var = 1;


/* Declare a pointer to int */int *ptr;int main( void )

Indirect access, var = 1

487
The address of var = 4202496

The address of var = 4202496

Indirect access, var = 48

Pointers Arithmetic
The pointer operations are summarized in the following figure

Pointer Operations
Priority operation (precedence)

When working with pointers, we must observe the following priority rules:

o The operators * and & have the same priority as the unary operators (the
negation!, the incrementation++, decrement--).
o In the same expression, the unary operators *, &,!, ++, - are evaluatedfrom right
to left.
488
• If a P pointer points to an X variable, then * P can be used wherever X can bewritten.
• The following expressions are equivalent:

int X =10 int *P = &Y;

For the above code, below expressions are true

Expression Equivalent Expression

Y=*P+1
Y=X+1 X=X+10X+=2
*P=*P+10
++X
*P+=2
X++
++*P (*P)++

In the latter case, parentheses are needed: as the unary operators * and ++ areevaluated from right
to left, without the parentheses the pointer P would be incremented, not the object on which P
points.

Below table shows the arithmetic and basic operation that can be used whendealing with pointers

Operation Explanation

int *P1,*P2 P1=P2; P1 and P2 point tothe same


Assignment
integer variable

Incrementation and decrementation Int *P1; P1++;P1-- ;

489
This allows the pointer to move N elements in a
table. The pointer will beincreased or decreased
Adding an offset (Constant) by N times the number of byte (s) of the type of
the
variable. P1+5;

Pointers and Arrays


Traditionally, we access the array elements using its index, but this method can beeliminated by
using pointers. Pointers make it easy to access each array element.

#include <stdio.h>

int main()

int a[5]={1,2,3,4,5}; //array initialization

int *p; //pointer declaration

/*the ptr points to the first element of the array*/

p=a; /*We can also type simply ptr==&a[0] */


printf("Printing the array elements using pointer\n"); for(int i=0;i<5;i++)//loop for

traversing array elements

{
printf("\n%x",*p); //printing array elements

p++; //incrementing to the next element, you can also write p=p+1

return 0;

then it will execute in this manner:

490
Pointer Addition/Increment

Since p currently points to the location 0 after adding 1, the value will become 1,and hence
the pointer will point to the memory location 1.

Pointers and Strings


A string is an array of char objects, ending with a null character '\ 0'. We can manipulate
strings using pointers. Here is an example that explains this section #include <stdio.h>
#include <string.h>int main()
{

char str[]="Hello Manish99";char *p;

p=str;

printf("First character is:%c\n",*p);p =p+1;

printf("Next character is:%c\n",*p); printf("Printing all the characters in a string\n");p=str;

//reset the pointer

for(int i=0;i<strlen(str);i++)

Outpu
t

Adding a particular number to a pointer will move the pointer location to the
value obtained by an addition operation. Suppose p is a pointer that currently
points to the memory location 0 if we perform following addition operation, p+1

491
p++;

return 0;

Output

First character is:H

Next character is:e

Printing all the characters in a string

e
l
l
o

a
n
i
s
h
9

Another way to deal strings is with an array of pointers like in the following
program:

#include <stdio.h>

492
int main(){

char *materials[ ] = { "iron", "copper", "gold"};

printf("Please remember these materials :\n");

int i ;

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

printf("%s\n", materials[ i ]);}

return 0;}

Output:

Please remember these materials:

iron

copper

gold

Advantages of Pointers

Pointers are useful for accessing memory locations.


Pointers provide an efficient way for accessing the elements of an array
structure.
Pointers are used for dynamic memory allocation as well as
deallocation.
Pointers are used to form complex data structures such as linked list,
graph, tree, etc.

Disadvantages of Pointers
1. Pointers are a little complex to understand.
2. Pointers can lead to various errors such as segmentation faults or canaccess a
memory location which is not required at all.

3. If an incorrect value is provided to a pointer, it may cause memorycorruption.

493
4. Pointers are also responsible for memory leakage.
5. Pointers are comparatively slower than that of the variables.
6. Programmers find it very difficult to work with the pointers; therefore it is
programmer's responsibility to manipulate a pointer carefully.
Summary
o A pointer is nothing but a memory location where data is stored.
o A pointer is used to access the memory location.
o There are various types of pointers such as a null pointer, wild pointer, voidpointer
and other types of pointers.
o Pointers can be used with array and string to access elements moreefficiently.
o We can create function pointers to invoke a function dynamically.
o Arithmetic operations can be done on a pointer which is known as pointer
arithmetic.
o Pointers can also point to function which make it easy to call differentfunctions in
the case of defining an array of pointers.
o When We want to deal different variable data type, We can use a typecastvoid
pointer.
Functions in C

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

There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C language provides anapproach in which We can declare and define a group of
statements once in theform of a function and it can be called and used whenever required.
These functions defined by the user are also know as User-defined Functions

C functions can be classified into two categories,


➢ Library functions
➢ User-defined functions

494
Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. We just need to include appropriate header
files to use these functions. These are already declared and defined in C libraries.

A User-defined functions on the other hand, are those functions which are
defined by the user at the time of writing program. These functions are made for
code reusability and for saving time and space.

Benefits of Using Functions

1. It provides modularity to Wer program's structure.

2. It makes our code reusable. We just have to call the function by its name to
use it, wherever required.

3. In case of large programs with thousands of code lines, debugging andediting


becomes easier if We use functions.

4. It makes the program more readable and easy to understand.


Function Declaration

General syntax for function declaration is,

returntype functionName(type1 parameter1, type2 parameter2,...);

495
Like any variable or an array, a function must also be declared before its used. Function declaration
informs the compiler about the function name, parametersis accept, and its return type. The actual
body of the function can be defined separately. It's also called as Function Prototyping. Function
declaration consistsof 4 parts.
1. returntype
2. function name
3. parameter list
4. terminating semicolon

returntype
When a function is declared to perform some sort of calculation or any operationand is expected
to provide with some result at the end, in such cases,
a return statement is added at the end of function body. Return type specifies thetype of value(int,
float, char, double) that function is expected to return to the program which called the function.
Note: In case our function doesn't return any value, the return type wouldbe void.
functionName
Function name is an identifier and it specifies the name of the function. Thefunction name is any
valid C identifier and therefore must follow the same naming rules like other variables in C
language.
parameter list

The parameter list declares the type and number of arguments that the functionexpects when it is
called. Also, the parameters in the parameter list receives theargument values when the function
is called. They are often referred as formal parameters.
An Example
a simple program with a main() function, and a user defined function to multiplytwo numbers, which
will be called from the main() function.

#include<stdio.h>

int multiply(int a, int b); // function declaration

int main()
}

intdefinition
Function i, j, result;Syntax
Just like in the example above, the general syntax of function definition is,
printf("Please enter 2 numbers you want to multiply...");
496
scanf("%d%d", &i, &j);
returntype functionName(type1 parameter1, type2 parameter2,...)

// function body goes here

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as


function header and the statement(s) within curlybraces is called function body.
Note: While defining a function, there is no semicolon(;) after the parenthesis inthe function header,
unlike while declaring the function or calling the function.

functionbody
The function body contains the declarations and the statements(algorithm) necessary for
performing the required task. The body is enclosed within curlybraces { ... } and consists of three
parts.
a) local variable declaration(if required).
b) function statements to perform the task inside the function.
c) a return statement to return the result evaluated by the function(if returntype is
void, then no return statement is required).

Calling a function
When a function is called, control of the program gets transferred to the function.

functionName(argument1, argument2,...);

In the example above, the statement multiply(i, j); inside the main() function isfunction call.

Passing Arguments to a function


Arguments are the values specified during the function call, for which the formal

parameters are declared while defining the function: It is possible to have a function with
parameters but no return type. It is not necessary, that if a function accepts parameter(s),
it must return a result too.

497
While declaring the function, we have declared two parameters a and b of
type int. Therefore, while calling that function, we need to pass two arguments, else we will get
compilation error. And the two arguments passed should be received in the function definition,
which means that the function header in the function definition should have the two parameters to
hold the argument values. These received arguments are also known as formal parameters. The
name of thevariables while declaring, calling and defining a function can be different.

Returning a value from function


A function may or may not return a result. But if it does, we must use
the return statement to output the result. return statement also ends the function execution, hence
it must be the last statement of any function. If Wewrite any statement after the return statement,

498
it won't be executed.

The datatype of the value returned using the return statement should be same asthe
return type mentioned at function declaration and definition. If any of it mismatches, We
will get compilation error.In the next tutorial, we will learn about the different types of
user defined functions in C language and the concept of Nesting of functions which is used
inrecursion.

Type of User-defined Functions in C


There can be 4 different types of user-defined functions, they are:

• Function with no arguments and no return value


• Function with no arguments and a return value
• Function with arguments and no return valueFunction with arguments and a return value
• Below, about all these types, along with program examples.

Function with no arguments and no return value


Such functions can either be used to display information or they are completelydependent on user
inputs.
Below is an example of a function, which takes 2 numbers as input from user, anddisplay which is
the greater number. #include<stdio.h>

void greatNum(); // function declarationint main()

greatNum();{

// function call
499
return 0;

void greatNum()

// function definition
int i, j;

printf("Enter 2 numbers that you want to compare...");scanf("%d%d", &i, &j);

if(i > j) {

printf("The greater number is: %d", i);

}
else {

printf("The greater number is: %d", j);

}}

Function with no arguments and a return value


We have modified the above example to make the function greatNum() returnthe number which is
greater amongst the 2 input numbers.

if(i > j) {

greaterNum = i;

else {

greaterNum = j;

// returning the result

return greaterNum;

Function with arguments and no return value

500
We are using the same function as example again and again, to demonstrate thatto solve a problem
there can be many different ways.
This time, we have modified the above example to make the
function greatNum() take two int values as arguments, but it will not be returninganything.

greatNum(i, j); // function call

return 0;

void greatNum(int x, int y) // function definition

if(x > y) {

printf("The greater number is: %d", x);

else {

printf("The greater number is: %d", y);

#include<stdio.h>

int greatNum(int a, int b); // function declaration

int main()

int i, j, result;

printf("Enter 2 numbers that you want to compare...");

501
Function with arguments and a return value
This is the best type, as this makes the function completely independent of inputsand outputs, and
only the logic is defined inside the function body.

scanf("%d%d", &i, &j);


result = greatNum(i, j); // function call

printf("The greater number is: %d", result);

return 0;

int greatNum(int x, int y) // function definition

if(x > y) {

return x;

else {

return y;

Nesting of Functions
C language also allows nesting of functions i.e to use/call one function insideanother function's
body. We must be careful while using nested functions, because it may lead to infinite nesting.

502
function1()

// function1 body here

function2();

// function1 body here

If function2() also has a call for function1() inside it, then in that case, it will lead to an infinite
nesting. They will keep calling each other and the program will neverterminate.
consider that inside the main() function, function1() is called and its execution starts, then inside
function1(), we have a call for function2(), so the control of program will go to the function2(). But
as function2() also has a call to function1()in its body, it will call function1(), which will again call
function2(), and this will goon for infinite times, until We forcefully exit from program execution.

Recursion
Recursion is a special way of nesting functions, where a function calls itself insideit. We must have
certain conditions in the function to break out of the recursion,otherwise recursion will occur infinite
times.

function1()

// function1 body

function1();

// function1 body

Example: Factorial of a number using Recursion

503
#include<stdio.h>

int factorial (int //declaring the function


x);

void main()

int a, b;

printf("Enter a number...");

scanf("%d", &a);

b = factorial(a); //calling the function named factorial

printf("%d", b);

int factorial(int x) //defining the function

int r = 1;

if(x == 1)

return 1;

else

r = x*factorial(x-1); //recursion, since the function calls itself

return r;

Similarly, there are many more applications of recursion in C language. Go to theprograms section,
to find out more programs using recursion.

504
File Handling in C
In programming, we may require some specific input data to be generated severalnumbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may
be very large, and only a limited amount ofdata can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data again and
again.
However, if we need to do so, we may store it onto the local file system which isvolatile and can be
accessed every time. Here, comes the need of file handling inC.
File handling in C enables us to create, update, read, and delete the files stored onthe local file
system through our C program. The following operations can be performed on a file.
• Creation of the new file
• Opening an existing file
• Reading from the file
• Writing to the file
• Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and closethe file. A list of file
functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

505
8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

name can be like "c://some_folder/some_file.ext".

• The mode in which the file is to be opened. It is a string.We can use one of the

following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

506
rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.


• Firstly, It searches the file to be opened.
• Then, it loads the file from the disk and place it into the buffer. The buffer isused
to provide efficiency for the read operations.
• It sets up a character pointer which points to the first character of the file.

Consider the following example which opens a file in write mode.

Output

The content of the file will be printed.

#include<stdio.h>

void main( )

FILE *fp ;

char ch ;

fp = fopen("file_handle.c","r") ;

while ( 1 )

ch = fgetc ( fp ) ;

if ( ch == EOF )

break ;

printf("%c",ch) ;

fclose (fp ) ; 507

}
#include; void main( )

FILE *fp; // file pointerchar ch;

fp = fopen("file_handle.c","r");while ( 1 )

ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.if ( ch ==

EOF )

break; printf("%c",ch);

fclose (fp );

Closing File: fclose()

C fprintf() and fscanf()

C fprintf() and fscanf() example


1. int fclose(FILE *fp );

C fputc() and fgetc()

C fputc() and fgetc() example

508
C fputs() and fgets()

C fputs() and fgets() example

C fseek()

C fseek() example

C fprintf() and fscanf()


Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formattedoutput to a
stream.
Syntax:

int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

#include <stdio.h>

main(){

FILE *fp;

fp = fopen("file.txt", "w");//opening file

fprintf(fp, "Hello file by fprintf...\n");//writing data into file

fclose(fp);//closing file

Reading File: fscanf() function#include <stdio.h>\


void main()

FILE *fptr;
509
int id;

char name[30];
float salary;

fptr = fopen("emp.txt", "w+");/* open for writing */

if (fptr == NULL)

{
printf("File does not exists \n");

return;

}
printf("Enter the id\n"); scanf("%d", &id); fprintf(fptr, "Id= %d\n", id); printf("Enter the

name \n");scanf("%s", name);

fprintf(fptr, "Name= %s\n", name);

The fscanf() function is used to read set of characters from file. It reads a word
from the file and returns EOF at the end of file.

Syntax: int fscanf(FILE *stream, const char *format [, argument, ...])


Example: #include <stdio.h>main (){

FILE *fp;

char buff[255];//creating char array to store data of filefp = fopen("file.txt", "r");

while(fscanf(fp, "%s", buff)!=EOF){printf("%s ", buff );

fclose(fp);

}
Output:

Hello file by fprintf...

C File Example: Storing employee information

510
A file handling example to store employee information as entered by user fromconsole. We are
going to store id, name and salary of the employee.
printf("Enter the salary\n");

scanf("%f", &salary);

fprintf(fptr, "Salary= %.2f\n", salary);

fclose(fptr);

Output:

Enter the id

Enter the name

sonoo

Enter the salary

120000

Now open file from current directory. For windows operating system, go to TC\bindirectory, We will
see emp.txt file. It will have following information.
emp.txt
Id= 1
Name= sonoo Salary= 120000

Command Line Arguments in C


The arguments passed from command line are called command line arguments.These arguments
are handled by main() function.
To support command line argument, We need to change the structure of main()function as given
below.

int main(int argc, char *argv[] )

Here, argc counts the number of arguments. It counts the file name as the first
argument.
The argv[] contains the total number of arguments. The first argument is the filename
always.

511
#include <stdio.h>

void main(int argc, char *argv[] ) {

printf("Program name is: %s\n", argv[0]);


if(argc < 2){
printf("No argument passed through command line.\n");

}
else{

printf("First argument is: %s\n", argv[1]);

}
Example
the example of command line arguments where we are passing one argumentwith file
name.

Run this program as follows in Linux:

./program hello

Run this program as follows in Windows from command line:

program.exe hello

Output:

Program name is: program

First argument is: hello

If we pass many arguments, it will print only one.

./program hello c how r u

Output:

512
Program name is: program

First argument is: hello

./program "hello c how r u"


But if we pass many arguments within double quote, all arguments will be treated as a single
argument only.

Output:

Program name is: program

First argument is: hello c how r u

We can write our program to print all the arguments. In this program, we areprinting only argv[1],
that is why it is printing only one argument.

C - Preprocessors
The C Preprocessor is not a part of the compiler but is a separate step in the compilation process.
In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character,
and for readability, a preprocessor directive should begin in the first column. The following section
lists down all the important preprocessor directives −

Sr.No. Directive & Description

#define
1
Substitutes a preprocessor macro.

#include
2
Inserts a particular header from another file.

#undef
3
Undefines a preprocessor macro.

513
#ifdef
4
Returns true if this macro is defined.

#ifndef
5
Returns true if this macro is not defined.

#if
6
Tests if a compile time condition is true.

#else
7
The alternative for #if.

#elif
8
#else and #if in one statement.

#endif
9
Ends preprocessor conditional.

#error
10
Prints error message on stderr.

#pragma
11
Issues special commands to the compiler, using a standardized method.

Preprocessors Examples
Analyze the following examples to understand various directives.#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
#include <stdio.h>
#include "myheader.h"
Use #define for constants to increase readability.

514
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current
source file. The next line tells CPP to get myheader.h from thelocal directory and add the content
to the current source file.

#undef FILE_SIZE
#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif

It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

#ifdef DEBUG
/* Your debugging statements here */
#endif

It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if We pass
the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so We can
turn debugging on and off on thefly during compilation.
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in programming, the
predefined macros should not be directly modified.

Sr.No. Macro & Description

DATE
1
The current date as a character literal in "MMM DD YYYY" format.

TIME
2
The current time as a character literal in "HH:MM:SS" format.

FILE
3
This contains the current filename as a string literal.

515
LINE
4
This contains the current line number as a decimal constant.

#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")

5 STDC
Defined as 1 when the compiler complies with the ANSI standard.

try the following example −

#include <stdio.h>

int main() {

printf("File :%s\n", FILE );


printf("Date :%s\n", DATE );
printf("Time :%s\n", TIME );
printf("Line :%d\n", LINE );
printf("ANSI :%d\n", STDC );

When the above code in a file test.c is compiled and executed, it produces thefollowing result −
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1

Preprocessor Operators
The C preprocessor offers the following operators to help create macros −The Macro Continuation

(\) Operator

A macro is normally confined to a single line. The macro continuation operator(\) is used to
continue a macro that is too long for a single line. For example −
516
The Stringize (#) Operator

The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro
parameter into a string constant. This operator may be used only in a macro having a specified
argument or parameter list. For example −

#include <stdio.h>

#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")

int main(void) {
message_for(Carole, Debra);
return 0;
}
When the above code is compiled and executed, it produces the following result
−Carole and Debra: We love you! The Token Pasting (##) Operator
The token-pasting operator (##) within a macro definition combines two arguments. It permits two
separate tokens in the macro definition to be joined into a single token. For example −

#include <stdio.h>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}

When the above code is compiled and executed, it produces the following result
−token34 = 40
It happened so because this example results in the following actual output fromthe preprocessor

printf ("token34 = %d", token34);

This example shows the concatenation of token##n into token34 and here we have used both
stringize and token-pasting.
The Defined() Operator
The preprocessor defined operator is used in constant expressions to determine if an identifier is
defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol
517
is not defined, the value is false (zero). The defined operator is specified as follows −

#include <stdio.h>

#if !defined (MESSAGE)


#define MESSAGE "You wish!"
#endif

int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}

When the above code is compiled and executed, it produces the following result
−Here is the message: You wish!Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square anumber as follows −

int square(int x) {
return x * x;
}

We can rewrite above the code using a macro as follows −

#Define square(x) ((x) * (x))

Macros with arguments must be defined using the #define directive before they can be used. The
argument list is enclosed in parentheses and must immediately follow the macro name. Spaces
are not allowed between the macro name and open parenthesis. For example −

#include <stdio.h>

#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}

When the above code is compiled and executed, it produces the following result
−Max between 20 and 10 is 20

Object-oriented programming (OOP)


518
Object-oriented programming (OOP) is a computer programming model thatorganizes software
design around data, or objects, rather than functions andlogic. An object can be defined as a data
field that has unique attributes and behavior.
OOP focuses on the objects that developers want to manipulate rather than thelogic required to
manipulate them. This approach to programming is well-suitedfor programs that are large, complex
and actively updated or maintained.

The organization of an object-oriented program also makes the method beneficialto collaborative
development, where projects are divided into groups.
Additional benefits of OOP include code reusability, scalability and efficiency. Even when using
microservices, developers should continue to apply the principles of OOP.
The first step in OOP is to collect all of the objects a programmer wants to manipulate and identify
how they relate to each other -- an exercise often knownas data modeling.
Examples of an object can range from physical entities, such as a human being who is described
by properties like name and address, down to small computerprograms, such as widgets.
Once an object is known, it is labeled with a class of objects that defines the kindof data it contains
and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method.
Objects can communicate with well- defined interfaces called messages.

Principles of OOP
Object-oriented programming is based on the following principles:

Encapsulation. The implementation and state of each object are privately held inside a defined
boundary, or class. Other objects do not have access to this class or the authority to make changes
but are only able to call a list of public functions, or methods. This characteristic of data hiding
provides greater program security and avoids unintended data corruption.
Hiding the implementation details of the class from the user through an object’s methods is known
as data encapsulation. In object oriented programming, it binds the code and the data together and
keeps them safefrom outside interference.Abstraction. Objects only reveal internal mechanisms
that are relevant for theuse of other objects, hiding any unnecessary implementation code. This
concept helps developers more easily make changes and additions over time.

Inheritance. Relationships and subclasses between objects can be assigned, allowing developers
to reuse a common logic while still maintaining a unique hierarchy. This property of OOP forces a
more thorough data analysis, reducesdevelopment time and ensures a higher level of accuracy.
Inheritance as in general terms is the process of acquiring properties. In OOPone object inherit the
properties of another object.

Polymorphism. Objects can take on more than one form depending on the context. The program
will determine which meaning or usage is necessary foreach execution of that object, cutting down
the need to duplicate code.
Polymorphism is the process of using same method name by multiple classes and redefines

519
methods for the derived classes.

Object-oriented programming languages


While Simula is credited as the first object-oriented programming language, themost popular OOP
languages are:
• Java
• JavaScript
• Python
• C++
• Visual Basic .NET
• Ruby
• Scala
• PHP
• OOPSLA is the annual conference for Object-Oriented Programming Systems, Languages
and Applications.

Criticism of OOP
The object-oriented programming model has been criticized by developers for multiple reasons.
The largest concern is that OOP overemphasizes the data component of software development
and does not focus enough on computationor algorithms. Additionally, OOP code may be more
complicated to write and takelonger to compile.

Alternative methods to OOP include:


• functional programming
• structured programming
• imperative programming
Most advanced programming languages give developers the option to combinethese models.
Object Oriented Programming Paradigm (OOPP)
The Object Oriented programming paradigm plays an important role in human computer interface.
It has different components that takes real world objects andperforms actions on them, making live
interactions between man and the machine. Following are the components of OOPP −
• This paradigm describes a real-life system where interactions are among real
objects.
• It models applications as a group of related objects that interact with eachother.
• The programming entity is modeled as a class that signifies the collection of
related real world objects.
• Programming starts with the concept of real world objects and classes.
• Application is divided into numerous packages.
• A package is a collection of classes.A class is an encapsulated group of similar
real world objects.

Objects
520
Real-world objects share two characteristics − They all have state and behavior.see the following
pictorial example to understand Objects.

In the above diagram, the object ‘Dog’ has both state and behavior.
An object stores its information in attributes and discloses its behavior through methods. now
discuss in brief the different components of object oriented programming.

Public Interface
The point where the software entities interact with each other either in a singlecomputer or in a
network is known as pubic interface. This help in data security.Other objects can change the state
of an object in an interaction by using only those methods that are exposed to the outer world
through a public interface.

Class
A class is a group of objects that has mutual methods. It can be considered as theblueprint using
which objects are created.
Classes being passive do not communicate with each other but are used toinstantiate objects that
interact with each other.

Example
Object Oriented Modeling of User Interface Design
Object oriented interface unites users with the real-world manipulating softwareobjects for
designing purpose. see the diagram.

521
Interface design strive to make successful accomplishment of user’s goals with the help of
interaction tasks and manipulation.
While creating the OOM for interface design, first of all analysis of user requirements is done. The
design specifies the structure and components required for each dialogue. After that, interfaces are
developed and testedagainst the Use Case. Example − Personal banking application.
The sequence of processes documented for every Use Case are then analyzed forkey objects. This
results into an object model. Key objects are called analysis objects and any diagram showing
relationships between these objects is called object diagram.

C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic requirement of any
language. Every language has its own rulesfor naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in aprogram which are
given below:
• Constants
522
• Variables
• Functions
• Labels
• Defined data types
• Some naming rules are common in both C and C++. They are as follows:
• Only alphabetic characters, digits, and underscores are allowed.
• The identifier name cannot start with a digit, i.e., the first letter should be
alphabetical. After the first letter, we can use letters, digits, or underscores.
• In C++, uppercase and lowercase letters are distinct. Therefore, we cansay that
C++ identifiers are case-sensitive.
• A declared keyword cannot be used as a variable name.

For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in
uppercase while lowercase in second. Therefore, it proves that identifiers arecase-sensitive.

Valid Identifiers
The following are the examples of valid identifiers are:

Result

Test2

_sum

power

Invalid Identifiers
The following are the examples of invalid identifiers:

Sum-1 // containing special character '-'.

2data // the first letter is a digit.

break // use of a keyword.

Note: Identifiers cannot be used as the keywords. It may not conflict with the keywords, but it is
highly recommended that the keywords should not be used as the identifier name. We should
always use a consistent way to name the identifiers so that our code will be more readable and
maintainable.
The major difference between C and C++ is the limit on the length of the name ofthe variable. ANSI
C considers only the first 32 characters in a name while ANSI C++ imposes no limit on the length
of the name.
523
Constants are the identifiers that refer to the fixed value, which do not change during the execution
of a program. Both C and C++ support various kinds of literalconstants, and they do have any
memory location. For example, 123, 12.34, 037, 0X2, etc. are the literal constants.

A simple example to understand the concept of identifiers.


#include <iostream> using namespace std;int main ()

int a;

int A;

cout<<"Enter the values of 'a' and 'A'";cin>>a;

cin>>A;

cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;

return 0;
}

What are the keywords?


Keywords are the reserved words that have a special meaning to the compiler. They are reserved
for a special purpose, which cannot be used as the identifiers.For example, 'for', 'break', 'while', 'if',
'else', etc. are the predefined words wherepredefined words are those words whose meaning is
already known by the compiler. Whereas, the identifiers are the names which are defined by the
programmer to the program elements such as variables, functions, arrays,objects, classes

Differences between Identifiers and Keywords

The following is the list of differences between identifiers and keywords:

Identifiers Keywords

Identifiers are the names defined by theprogrammer Keywords are the reserved wordswhose
to the basic elements of a program. meaning is known by the compiler.

524
It is used to identify the name of thevariable. It is used to specify the type ofentity.

It can consist of letters, digits, andunderscore. It contains only letters.

It can use both lowercase and uppercaseletters. It uses only lowercase letters.

No special character can be used exceptthe


It cannot contain any specialcharacter.
underscore.

The starting letter of identifiers can belowercase, It can be started only with thelowercase
uppercase or underscore. letter.

It can be classified as internal and external


It cannot be further classified.
identifiers.

Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break',etc.

C++ Variable

A variable is a name of memory location. It is used to store data. Its value can bchanged
and it can be reused many times.It is a way to represent memory location through symbol
so that it can be easilyidentified.
type variable_list;
The example of declaring variable is given below:
The syntax to declare a variable:

int x;
float y;
char z;
525
Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:
int x=5,b=10; //declaring 2 variable of integer type
float f=30.8;
char c='A';

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start withdigit.
No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.
Valid variable names:int a;

int _ab;
int a30;

Invalid variable names:int 4;

int x y;
int double; C++ Data Types

A data type specifies the type of data that a variable can store such as integer,floating, character
etc.

There are 4 types of data types in C++ language.


526
Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

The memory size of basic data types may change according to 32 or 64 bitoperating system.
the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

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

unsigned int 2 byte 0 to 32,767

527
short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 byte

C++ Operators
An operator is simply a symbol that is used to perform operations. There can bemany types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations inC language.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operator
• Unary operator
• Ternary or Conditional Operator
• Misc Operator

528
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated firstand next.
The associativity specifies the operators direction to be evaluated, itmay be left to right or
right to left. the precedence by the example given below:

1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) isevaluated before
+ (additive operator).

The precedence and associativity of C++ operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Right to left

529
Shift << >> Left to right

Relational < <= > >= Left to right

Equality == !=/td> Right to left

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Right to left

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Decision making in C++ - if, else and else if


Decision making is about deciding the order of execution of statements based oncertain conditions
or repeat a group of statements until certain specified conditions are met. C++ handles decision-
making by supporting the following statements,
• if statement
• switch statement
• conditional operator statement
• goto statement

Decision making with if statement


The if statement may be implemented in different forms depending on thecomplexity of conditions
to be tested. The different forms are,
1. Simple if statement
2. if else statement
3. Nested if else statement
530
4. else if statement

Simple if statement
The general form of a simple if statement is,

if(expression)

statement-inside;

statement-outside;

If the expression is true, then 'statement-inside' will be executed, otherwise'statement-inside' is


skipped and only 'statement-outside' will be executed.

Example: #include< iostream.h>int main( )

int x,y;x=15; y=13;

if (x > y )

cout << "x is greater than y";

} statement-block1;

else

statement-block2;

}
531
else

statement-block3.

Output: x is greater than y y is greater than x Nested if else statement The general form
of a nested if else statement is if(expression)

{if(expression1)
{
if 'expression' is false or returns false, then the 'statement-block3' will beexecuted,
otherwise execution will enter the if condition and check for 'expression 1'. Then if the
'expression 1' is true or returns true, then the 'statement-block1' will be executed
otherwise 'statement-block2' will be executed.
Example: void main()

int a,b,c;
cout << "enter 3 number";cin >> a >> b >> c; if(a > b)

if( a > c) {

cout << "a is greatest";

else

cout << "c is greatest";

else

{
532
if( b> c)

cout << "b is greatest";

else
{

cout << "c is greatest";

}}

The above code will print different statements based on the valuesof a, b and c variables
if(expression 1)

{
statement-block1;

}
else if(expression 2)

{
statement-block2;

}
else if(expression 3 )
{

statement-block3;
}

else
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as thetrue condition is
found, the statement associated with it is executed.

Example:

void main( )
int a;
533
cout << "enter a number";cin >> a;

if( a%5==0 && a%8==0)

cout << "divisible by both 5 and 8";

else if( a%8==0 )

cout << "divisible by 8";

else if(a%5==0)

cout << "divisible by 5";

{
else

cout << "divisible by none";

If We enter value 40 for the variable a, then the output will be:

534
Output

divisible by both 5 and 8

Points to Remember

In if statement, a single statement can be included without enclosing it into


curly braces { }.

int a = 5;

if(a > 4)

cout << "success";

Output
success

No curly braces are required in the above case, but if we have more than one
statement inside if condition, then we must enclose them inside curly braces
otherwise only the first statement after the if condition will be considered.

int a = 2;

if(a > 4)

cout << "success";

// below statement is outside the if condition

cout << "Not inside the if condition"

Output

Not inside the if condition

535
Output

hello

C++ Functions
The function in C++ language is also known as procedure or subroutine in other programming
languages.
To perform any task, we can create function. A function can be called many times. It provides
modularity and code reusability.

Advantage of functions in C
There are many advantages of functions.

1) Code Reusability
By creating functions in C++, we can call it many times. So we don't need to writethe same code
again and again.

2) Code optimization
It makes the code optimized, we don't need to write much code.
Suppose, we have to check 3 numbers (531, 883 and 781) whether it is prime number or not.
Without using function, we need to write the prime number logic3 times. So, there is repetition of
code.
But if we use functions, we need to write the logic only once and we can reuse itseveral times.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header filessuch as ceil(x),
cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++ programmer, so that
he/she can use it many times. It reduces complexity of a bigprogram and optimizes the code.

536
Declaration of a function
The syntax of creating function in C++ language is given below:

return_type function_name(data_type parameter...)

//code to be executed

C++ Function Example


the simple example of C++ function.

Output: #include <iostream> using namespace std;void func() {

static int i=0; //static variable

int j=0; //local variablei++;

j++;

cout<<"i=" << i<<" and j=" <<j<<endl;

int main()

func();

func();

func();

i= 1 and j= 1

i= 2 and j= 1

537
i= 3 and j= 1

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.

Understand call by value and call by reference in C++ language one by one.

Call by value in C++


In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the functionparameter in
stack memory location. If We change the value of function parameter, it is changed for the current
function only. It will not change the valueof variable inside the caller method such as main().

The concept of call by value in C++ language by the example given below:
#include <iostream> using namespace std;void change(int data);int main()

int data = 3; change(data);

cout << "Value of the data is: " << data<< endl;

return 0;

538
void change(int data)

Output:

Value of the data is: 3

Call by reference in C++

In call by reference, original value is modified because we pass reference

data = 5;

(address).

Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside thefunction, is reflected inside as well as outside
the function.
Note: To understand the call by reference, We must have the basic knowledge ofpointers.
the concept of call by reference in C++ language by the example given below:
539
#include<iostream> using namespace std; void swap(int *x, int *y)

int swap;swap=*x;

*x=*y;

*y=swap;

int main()

int x=500, y=100;

swap(&x, &y); // passing value to functioncout<<"Value of x is: "<<x<<endl; cout<<"Value

of y is: "<<y<<endl;

return 0;

Output:

Value of x is: 100

Value of y is: 500

Difference between call by value and call by reference in C++

No. Call by value Call by reference

An address of value is passed tothe


1 A copy of value is passed to thefunction
function

540
Changes made inside the function isnot Changes made inside the functionis
2
reflected on other functions reflected outside the function also

Actual and formal arguments will becreated Actual and formal arguments willbe created
3
in different memory location in same memory location

C++ virtual function


• A C++ virtual function is a member function in the base class that Weredefine
in a derived class. It is declared using the virtual keyword.
• It is used to tell the compiler to perform dynamic linkage or late bindingon the
function.
• There is a necessity to use the single pointer to refer to all the objects ofthe
different classes. So, we create the pointer to the base class that refers to all the derived objects.
But, when base class pointer contains the address of the derived class object, always executes the
base class function. This issue can only be resolved by using the 'virtual' function.
• A 'virtual' is a keyword preceding the normal declaration of a function.
• When the function is made virtual, C++ determines which function is to be
invoked at the runtime based on the type of the object pointed by the base class pointer.

Late binding or Dynamic linkage


In late binding function call is resolved during runtime. Therefore compilerdetermines the type of
object at runtime, and then binds the function call.

Rules of Virtual Function


• Virtual functions must be members of some class.
• Virtual functions cannot be static members.
• They are accessed through object pointers.
• They can be a friend of another class.
• A virtual function must be defined in the base class, even though it is notused.
• The prototypes of a virtual function of the base class and all the derivedclasses
must be identical. If the two functions with the same name but different prototypes, C++ will
consider them as the overloaded functions.
• We cannot have a virtual constructor, but we can have a virtualdestructor
• Consider the situation when we don't use the virtual keyword.
#include <iostream> using namespace std;class A

541
{

int x=5;
public:
void display()

std::cout << "Value of x is : " << x<<std::endl;

};

class B: public A

int y = 10;

public:

void display()

std::cout << "Value of y is : " <<y<< std::endl;

};

int main()

A *a;

B b;

a = &b;

a- >display();

return 0;

542
Output:
Value of x is: 5

Derived Class is invoked

Output: void display()

cout << "Derived Class is invoked"<<endl;

};

int main()

A* a; //pointer of base class B b; //object of derived classa = &b;

a->display(); //Late Binding occurs

}
Pure Virtual Function

• A virtual function is not used for performing any task. It only serves as a
placeholder.
• When the function has no definition, such function is known as "do-nothing"
function.
• The "do-nothing" function is known as a pure virtual function. A purevirtual
function is a function declared in the base class that has no definition relative to the base class.
• A class containing the pure virtual function cannot be used to declare the
objects of its own, such classes are known as abstract base classes.

• The main objective of the base class is to provide the traits to the derived
classes and to create the base pointer used for achieving theruntime polymorphism.

Pure virtual function can be defined as:

1. virtual void display() = 0;

543
A simple example:

Output:
{

Base *bptr;

//Base b;

Derived d;

bptr = &d;

bptr->show();

eturn 0;

}
Derived class is derived from the base class.
In the above example, the base class contains the pure virtual function. Therefore,the base class is
an abstract base class. We cannot create the object of the base class.

C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties andbehaviors of its
parent object automatically. In such way, we can reuse, extend or modify the attributes and
behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derivedclass is the specialized class for the
base class.
Advantage of C++ Inheritance

Code reusability: Now we can reuse the members of our parent class. So, there isno need to define
the member again. So less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

➢ Single inheritance
➢ Multiple inheritance
➢ Hierarchical inheritance
➢ Multilevel inheritance
➢ Hybrid inheritance

544
Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name


{

// body of the derived class.


}

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the baseclass are publicly
inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members of
the base class becomes the private members of the derived class. Therefore, the public members
of the base class are not accessible by the objects of the derived class only by the member
functions of the derived class.

o When the base class is publicly inherited by the derived class, public members of
the base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by theobjects of the derived class as well as by the
member functions of the baseclass.
Note:
545
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class isinherited from the only
one base class.

Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as single level inheritance. theexample of single
level inheritance which inherits the fields only.
#include <iostream> using namespace std;class Account {

public:

float salary = 60000;

};

class Programmer: public Account {

public:

float bonus = 5000;

};

int main(void) { Programmer p1;

cout<<"Salary: "<<p1.salary<<endl;cout<<"Bonus: "<<p1.bonus<<endl;return 0;

Output:
Salary: 60000

Bonus: 5000

In the above example, Employee is the base class and Programmer isthe derived class.
#include <iostream> using namespace std;class Animal {

public:

546
void eat() { cout<<"Eating..."<<endl;

};

class Dog: public Animal

public:

void bark(){ cout<<"Barking...";

}; C++ Single Level Inheritance Example: Inheriting Methods :another example of


inheritance in C methods only.
int main(void) {Dog d1; d1.eat();

d1.bark();

return 0;

}
Output: Eating...

Barking...

• Public: When the member is declared as public, it is accessible to all the


functions of the program.
• Private: When the member is declared as private, it is accessible withinthe class only.
• Protected: When the member is declared as protected, it is accessiblewithin
its own class as well as the class immediately derived from it.

Visibility of Inherited Members:

How to make a Private Member Inheritable


The private member is not inheritable. If we modify the visibility mode by makingit public,
but this takes away the advantage of data hiding.
547
C++ introduces a third visibility modifier, i.e., protected. The member which is declared as
protected will be accessible to all the member functions within theclass as well as the class
immediately derived from it.
Visibility modes can be classified into three categories:

Base class visibility Derived class visibility

Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.

public:

void bark(){

548
cout<<"Barking..."<<endl;

#include <iostream>

using namespace std;

class Animal {

public:

void eat() {

cout<<"Eating..."<<endl;

};

class Dog: public Animal

C++ Multi Level Inheritance Example


When one class inherits another class which is further inherited by another class,it is
known as multi level inheritance in C++. Inheritance is transitive so the last derived class
acquires all the members of all its base classes.
the example of multi level inheritance in C++.

};

class BabyDog: public Dog


{

public:
void weep() {
cout<<"Weeping...";
}

549
};

int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Output:

Eating...

Barking...

Weeping...

C++ Multiple Inheritance

Multiple inheritance is the process of deriving a new class that inherits theattributes from two or
more classes.

Syntax of the Derived class:


class D : visibility B-1, visibility B-2, ?

{
// Body of the class;

Ambiguity Resolution in Inheritance


Ambiguity can be occurred in using the multiple inheritance when a function withthe same name
occurs in more than one base class.
The above issue can be resolved by using the class resolution operatorwith the function. In the
above example, the derived class code can berewritten as:

class C : public A, public B

550
void view()
An ambiguity can also occur in single inheritance.

Consider the following situation:


class A

public:

void display()

cout<<?Class A?;

};

class B

{
public: void display()

{
cout<<?Class B?;
}

};

551
{

// body of class B.

class C : public A

// body of class C.

class D : public A

// body of class D.

C++ Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one classfrom a
base class.

552
In the above case, the function of the derived class overrides the method of the
base class. Therefore, call to the display() function will simply call the function
defined in the derived class. If we want to invoke the base class function, we canuse the
class resolution operator.
int main()

{
B b; b.display();// Calling the display() function of B class. b.B :: display();// Calling the
display() function defined in B class.
// Calling the display() function defined in B class.

Object is a runtime entity; it is created at runtime.


Object is an instance of a class. All the members of the class can be accessedthrough object.

An example to create object of student class using s1 as the reference variable.

Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers tothe instance of
Student class.

C++ Class

In C++, object is a group of similar objects. It is a template from which objects arecreated. It
can have fields, methods, constructors etc.An example of C++ class that has three fields
only.

There can be two types of constructors in C++.


• Default constructor
• Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It isinvoked at the time of
creating object.
553
the simple example of C++ default Constructor.
#include <iostream> using namespace std;class Employee

public:

Employee()

cout<<"Default Constructor Invoked"<<endl;

};

int main(void)

Employee e1; //creating an object of EmployeeEmployee e2;

return 0;

Output:

Default Constructor Invoked

Default Constructor Invoked

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.

C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.A destructor is
defined like constructor. It must have same name as class. But it iprefixed with a tilde sign
(~).
Note: C++ destructor cannot have parameters. Moreover, modifiers can't beapplied on

554
destructors.

C++ Constructor and Destructor Example


An example of constructor and destructor in C++ which is called automatically#include

<iostream> using namespace std;class Employee

{
public:

Employee()

cout<<"Constructor Invoked"<<endl;

555
~Employee()

cout<<"Destructor Invoked"<<endl;

};

int main(void)

Employee e1; //creating an object of Employee

Employee e2; //creating an object of Employee

return 0;

Output:

Constructor Invoked

Constructor Invoked

Destructor Invoked

Destructor Invoked

C++ Overloading (Operator and Function)

C++ allows us to specify more than one definition for a function name or
an operator in the same scope, which is called function overloading and operator overloading
respectively.
An overloaded declaration is a declaration that is declared with the same name asa previously
declared declaration in the same scope, except that both declarations have different arguments
and obviously different definition(implementation).
When we call an overloaded function or operator, the compiler determines the most appropriate
definition to use, by comparing the argument types We have used to call the function or operator
with the parameter types specified in the definitions. The process of selecting the most appropriate
overloaded function oroperator is called overload resolution.
Function Overloading in C++

556
we can have multiple definitions for the same function name in the same scope. The definition of
the function must differ from each other by the types and/or the number of arguments in the
argument list. We cannot overload function declarations that differ only by return type.
Following is the example where same function print() is being used to printdifferent data types −

#include <iostream>

using namespace std;

class printData {

public:

void print(int i) {

cout << "Printing int: " << i << endl;

void print(double f) {

cout << "Printing float: " << f << endl;

void print(char* c) {

cout << "Printing character: " << c << endl;

};

int main(void) {printData pd;

// Call print to print integerpd.print(5);

// Call print to print floatpd.print(500.263);

// Call print to print characterpd.print("Hello C++");

return 0;

}
557
When the above code is compiled and executed, it produces the following result −Printing int: 5
Printing float: 500.263 Printing character: Hello C++ Operators Overloading in C++ We can redefine
or overload most of the built-in operators available in C++. Thus,a programmer can use operators
with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the
symbol for the operator being defined. Like any other function, an overloaded operator has a return
type and a parameter list.

Box operator+(const Box&);


declares the addition operator that can be used to add two Box objects and returns final Box object.
Most overloaded operators may be defined as ordinarynon-member functions or as class member
functions. In case we define above function as non-member function of a class then we would have
to pass two arguments for each operand as follows −
Box operator+(const Box&, const Box&);

Following is the list of operators which can be overloaded −

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which can not be overloaded −

:: .* . ?:

Operator Overloading Examples


Here are various operator overloading examples to help us in understanding theconcept.

558
Sr.No Operators & Example

1 Unary Operators Overloading

2 Binary Operators Overloading

3 Relational Operators Overloading

4 Input/Output Operators Overloading

5 ++ and -- Operators Overloading

6 Assignment Operators Overloading

7 Function call () Operator Overloading

8 Subscripting [] Operator Overloading

9 Class Member Access Operator -> Overloading

Templates in C++
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a
parameter so that we don’t need to write the same code fordifferent data types. For example, a
software company may need sort () for different data types. Rather than writing and maintaining
the multiple codes, wecan write one sort () and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’.The second keyword
can always be replaced by keyword ‘class’.

How templates work?


Templates are expanded at compiler time. This is like macros. The difference is, compiler does
type checking before template expansion. The idea is simple, source code contains only
function/class, but compiled code may contain multiplecopies of same function/class.

559
Function Templates We write a generic function that can be used for different data types. Examples
of function templates are sort(), max(), min(), printArray().
#include <iostream> using namespace std;

// One function works for all data types. This would work

// even for user defined types if operator '>' is overloadedtemplate <typename T>

T myMax(T x, T y)

return (x > y)? x: y;

int main()

{
cout << myMax<int>(3, 7) << endl; // Call myMax for int

cout << myMax<double>(3.0, 7.0) << endl; // call myMax for doublecout <<

myMax<char>('g', 'e') << endl; // call myMax for char return 0;

}
Class Templates Like function templates, class templates are useful when a class defines
something that is independent of the data type. Can be useful for classes like LinkedList,
BinaryTree, Stack, Queue, Array, etc.

560
C++ Exception Handling
An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an attempt
to divide by zero.
Exceptions provide a way to transfer control from one part of a program toanother. C++ exception
handling is built upon three keywords: try,
catch, and throw.
➢ throw − A program throws an exception when a problem shows up. Thisis done using a throw
keyword.
➢ catch − A program catches an exception with an exception handler atthe place in a program
where We want to handle the problem.
The catch keyword indicates the catching of an exception.
➢ try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around thecode that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch as follows −
try {

// protected code

} catch( ExceptionName e1 ) {

// catch block

} catch( ExceptionName e2 ) {

// catch block

} catch( ExceptionName eN ) {

// catch block

We can list down multiple catch statements to catch different type of exceptionsin case our try
block raises more than one exception in different situations.

Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement. The operand of
the throw statement determines a type for the exception and canbe any expression and the type of
the result of the expression determines the type of exception thrown.
561
Following is an example of throwing an exception when dividing by zero conditionoccurs −
double division(int a, int b) {if( b == 0 ) {

throw "Division by zero condition!";

return (a/b);
}

Catching Exceptions
The catch block following the try block catches any exception. We can specify what type of
exception We want to catch and this is determined by the exceptiondeclaration that appears in
parentheses following the keyword catch.

try {

// protected code

} catch( ExceptionName e ) {

// code to handle ExceptionName exception

Above code will catch an exception of Exception Name type. If We want to specifythat a catch block
should handle any type of exception that is thrown in a try block, We must put an ellipsis, ..., between
the parentheses enclosing the
exception declaration as follows –
try {

// protected code

} catch(...) {

// code to handle any exception

C++ Standard Exceptions


C++ provides a list of standard exceptions defined in <exception> which we canuse in our
programs. These are arranged in a parent-child class hierarchy shownbelow –

562
Here is the small description of each exception mentioned in the above hierarchy

Sr.No Exception & Description

563
std::exception
1
An exception and parent class of all the standard C++ exceptions.

std::bad_alloc
2
This can be thrown by new.

std::bad_cast
3
This can be thrown by dynamic_cast.

std::bad_exception
4
This is useful device to handle unexpected exceptions in a C++ program.

std::bad_typeid
5
This can be thrown by typeid.

std::logic_error
6
An exception that theoretically can be detected by reading the code.

std::domain_error
7
This is an exception thrown when a mathematically invalid domain is used.

std::invalid_argument
8
This is thrown due to invalid arguments.

std::length_error
9
This is thrown when a too big std::string is created.

std::out_of_range
10 This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().

564
std::runtime_error
11
An exception that theoretically cannot be detected by reading the code.

std::overflow_error
12
This is thrown if a mathematical overflow occurs.

std::range_error
13
This is occurred when We try to store a value which is out of range.

std::underflow_error
14
This is thrown if a mathematical underflow occurs.

C++ Files and Streams


another standard C++ library called fstream, which defines three new data types –

Sr.No Data Type & Description

ofstream
1 This data type represents the output file stream and is used to create filesand to write
information to files.

ifstream
2
This data type represents the input file stream and is used to readinformation from files.

565
fstream

3 This data type represents the file stream generally, and has the capabilitiesof both
ofstream and ifstream which means it can create files, write information to files, and
read information from files.

To perform file processing in C++, header files <iostream> and <fstream> must beincluded in our
C++ source file.

Opening a File
A file must be opened before We can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. Andifstream object is used
to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member offstream, ifstream, and
ofstream objects.void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be openedand the second
argument of the open() member function defines the mode in which the file should be opened.

Sr.No Mode Flag & Description

ios::app
1
Append mode. All output to that file to be appended to the end.

ios::ate
2
Open a file for output and move the read/write control to the end of thefile.

ios::in
3
Open a file for reading.

ios::out
4
Open a file for writing.

566
ios::trunc
5
If the file already exists, its contents will be truncated before opening thefile.

we can combine two or more of these values by ORing them together. For example if We want to
open a file in write mode and want to truncate it in casethat already exists, following will be the
syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc ); Similar way, We can open a file for reading and writing
purpose as follows −fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
When a C++ program terminates it automatically flushes all the streams, releaseall the allocated
memory and close all the opened files. But it is always a good practice that a programmer should
close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member offstream, ifstream, and
ofstream objects.
void close();

Writing to a File
While doing C++ programming, We write information to a file from our programusing the stream
insertion operator (<<) just as We use that operator to output information to the screen. The only
difference is that We usean ofstream or fstream object instead of the cout object.

Reading from a File


We read information from a file into our program using the stream extractionoperator (>>) just as
We use that operator to input information from the keyboard. The only difference is that We use an
ifstream or fstream object instead of the cin object.

File Position Pointers


Both istream and ostream provide member functions for repositioning the file-position pointer.
These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argumentcan be specified
to indicate the seek direction. The seek direction can
be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning
relative to the current position in a streamor ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file asa number of bytes
from the file's starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)fileObject.seekg( n );

567
// position n bytes forward in fileObject

fileObject.seekg( n, ios::cur );

// position n bytes back from end of fileObjectfileObject.seekg( n, ios::end );

// position at end of fileObjectfileObject.seekg( 0, ios::end ); C++ Exceptions

C++ Exceptions
When executing C++ code, different errors can occur: coding errors made by theprogrammer, errors
due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. Thetechnical term for
this is: C++ will throw an exception (throw an error).

C++ try and catch


Exception handling in C++ consist of three keywords: try, throw and catch:
The try statement allows We to define a block of code to be tested for errors while it is being
executed.
The throw keyword throws an exception when a problem is detected, which letsus create a custom
error.
The catch statement allows We to define a block of code to be executed, if anerror occurs in the try
block.
The try and catch keywords come in pairs:

Example
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}

Web Programming
Web programming refers to the writing, markup and coding involved in Web development, which
includes Web content, Web client and server scripting and network security. The most common
languages used for Web programming are XML, HTML, JavaScript, Perl 5 and PHP. Web
programming is different from just programming, which requires interdisciplinary knowledge on the
application area,client and server scripting, and database technology.
Web programming can be briefly categorized into client and server coding. The client side needs
programming related to accessing data from users and providing information. It also needs to
ensure there are enough plug ins to enrich user experience in a graphic user interface, including
security measures.

568
1. To improve user experience and related functionalities on the client side, JavaScript is
usually used. It is an excellent client-side platform for designing and implementing Web
applications.
2. HTML5 and CSS3 supports most of the client-side functionality provided byother application
frameworks.
3. The server side needs programming mostly related to data retrieval, security and
performance. Some of the tools used here include ASP, Lotus Notes, PHP, Java and MySQL.
There are certain tools/platforms that aid in both client- and server-side programming. Some
examples of these are Opa and Tersus.

Hypertext Markup Language (HTML)


Hypertext markup language (HTML) is the major markup language used to displayWeb pages on
the Internet. In other words, Web pages are composed of HTML, which is used to display text,
images or other resources through a Web browser.
All HTML is plain text, meaning it is not compiled and may be read by humans.The file extension for
an HTML file is .htm or .html.
New Web developers may mistake HTML for a programming language when it is actually a markup
language. HTML is used with other technologies because all HTML really does is organize
documents. On the client side, JavaScript (JS) is usedto provide interactivity. On the server side, a
Web development platform like Ruby, PHP or ASP.NET is used.
When a Web developer builds an application, the work is performed on the server, and raw HTML
is sent out to the user. The line between server-side development and client side development is
blurry with technologies like AJAX.
HTML was never designed for the Web that exists today, as it is just a markuplanguage with severe
limitations, in terms of control and design. Numerous technologies have been used to work around
this issue - the most significant being cascading style sheet (CSS).
The long term solution is (or hopefully will be) HTML5, which is the next generation of HTML and
allows for more control and interactivity. As with any development on the Web, the move to
standards is a slow and arduous process, and Web developers and designers have to make due
with current and supportedtechnologies, which means that basic HTML will continue to be used for
some time.

Applications of HTML
As mentioned before, HTML is one of the most widely used language over theweb. I'm going to list
few of them here:

1. Web pages development - HTML is used to create pages which are rendered over the web.
Almost every page of web is having html tags in itto render its details in browser.
2. Internet Navigation - HTML provides tags which are used to navigate from one page to
another and is heavily used in internet navigation.
3. Responsive UI - HTML pages now-a-days works well on all platform, mobile,tabs, desktop or
laptops owing to responsive design strategy.
4. Offline support HTML pages once loaded can be made available offline on the machine
569
without any need of internet.
5. Game development- HTML5 has native support for rich experience and is now useful in
gaming developent arena as well.

• Basic HTML Document


In its simplest form, following is an example of an HTML document −

<!DOCTYPE html>

<html>

<head>

<title>This is document title</title>

</head>

<body>

<h1>This is a heading</h1>

<p>Document content goes here. ... </p>

</body>

</html>

HTML Tags
As told earlier, HTML is a markup language and makes use of various tags to format the content.
These tags are enclosed within angle braces <Tag Name>.Except few tags, most of the tags have
their corresponding closing tags. For example, <html> has its closing tag </html> and <body> tag
has its closing tag </body> tag etc.
Above example of HTML document uses the following tags − 1

Sr.No Tag & Description

<!DOCTYPE...>
1
This tag defines the document type and HTML version.

570
<html>

2 This tag encloses the complete HTML document and mainly comprises ofdocument
header which is represented by <head>...</head> and document body which is
represented by <body>...</body> tags.

<head>
3 This tag represents the document's header which can keep other HTMLtags like <title>,
<link> etc.

<title>
4
The <title> tag is used inside the <head> tag to mention the documenttitle.

<body>
5
This tag represents the document's body which keeps other HTML tags

like <h1>, <div>, <p> etc.

<h1>
6
This tag represents the heading.

<p>
7
This tag represents a paragraph.

To learn HTML, we will need to study various tags and understand how they behave, while
formatting a textual document. Learning HTML is simple as users have to learn the usage of
different tags in order to format the text or images tomake a beautiful webpage.
World Wide Web Consortium (W3C) recommends using lowercase tags startingfrom HTML 4.

HTML Document Structure


A typical HTML document will have the following structure −

571
<html>

<head>

Document header related tags

</head>

<body>

Document body related tags

</body>

</html>

The <!DOCTYPE> Declaration


The <!DOCTYPE> declaration tag is used by the web browser to understand theversion of the HTML
used in the document. Current version of HTML is 5 and itmakes use of the following declaration

<!DOCTYPE html>
There are many other declaration types which can be used in HTML documentdepending on what
version of HTML is being used.
Extensible Markup Language (XML)
Extensible Markup Language (XML) is a universal format, maintained by the W3C, used for
representation and transfer of structured data on the web or between different applications.
The language uses a structured representation by allowing users to create customdefined tags
according to XML Document Type Definition (DTD) standards. The structure of an XML document
can be represented in the form of a tree known asa Document Object Model (DOM).
XML is designed to describe data but is not concerned with the data’s visualization. The tags
created in XML are self explanatory and the user is free to define their own tags — hence the
“extensible.”
XML support is provided by many programming language platforms to create andprocess XML
data. Simplicity, portability, platform independence, and usability are some of the key features that
have resulted in the increasing popularity of theuse of XML-based standards.
XML has been the main source of motivation for development of service orientedarchitecture (SOA)
platforms such as web services that are not tied to any particular language and collaborate
effectively in heterogeneous environments. RSS, Atom, SOAP and XHTML are some of the
standards influenced by XML.

572
JavaScript (JS)

Javascript (JS) is a scripting languages, primarily used on the Web. It is used to enhance HTML
pages and is commonly found embedded in HTML code. JavaScriptis an interpreted language.
Thus, it doesn't need to be compiled. JavaScript renders web pages in an interactive and dynamic
fashion. This allowing the pages to react to events, exhibit special effects, accept variable text,
validate data,
create cookies, detect a user’s browser, etc.

HTML pages are fine for displaying static content, e.g. a simple image or text.However, most pages
nowadays are rarely static. Many of today’s pages havemenus, forms, slideshows and even images
that provide user interaction.
Javascript is the language employed by web developers to provide such interaction. Since
JavaScript works with HTML pages, a developer needs to know HTML to harness this scripting
language’s full potential. While there are other languages that can be used for scripting on the Web,
in practice it is essentially allJavascript.
There are two ways to use JavaScript in an HTML file. The first one involves embedding all the
JavaScript code in the HTML code, while the second method makes use of a separate JavaScript
file that’s called from within a Script element, i.e., enclosed by Script tags. JavaScript files are
identified by the .js extension.
Although JavaScript is mostly used to interact with HTML objects, it can also be made to interact
with other non-HTML objects such as browser plugins, CSS (Cascading Style Sheets) properties,
the current date, or the browser itself. To write JavaScript code, all We need is a basic text editor
like Notepad in Windows, Gimp in Linux, or BBEdit. Some text editors, like BBEdit feature syntax
highlightingfor JavaScript. This will allow We easily identify elements of JavaScript code. The latest
versions of Internet Explorer, Firefox, and Opera all support JavaScript.
Java
Java is a programming language that produces software for multiple platforms. When a
programmer writes a Java application, the compiled code (known as

bytecode) runs on most operating systems (OS), including Windows, Linux and Mac OS. Java
derives much of its syntax from the C and C++ programming languages.

Java was developed in the mid-1990s by James A. Gosling, a former computerscientist with Sun
Microsystems.
Java produces applets (browser-run programs), which facilitate graphical user interface (GUI) and
object interaction by Internet users. Prior to Java applets, Webpages were typically static and non-
interactive. Java applets have diminished in popularity with the release of competing products,
such as Adobe Flash and Microsoft Silverlight.

Java applets run in a Web browser with Java Virtual Machine (JVM), which translates Java

573
bytecode into native processor instructions and allows indirect OS or platform program execution.
JVM provides the majority of components neededto run bytecode, which is usually smaller than
executable programs written through other programming languages. Bytecode cannot run if a
system lacks required JVM.

Java program development requires a Java software development kit (SDK) thattypically includes
a compiler, interpreter, documentation generator and other tools used to produce a complete
application.

Development time may be accelerated through the use of integrated development environments
(IDE) - such as JBuilder, Netbeans, Eclipse or JCreator.IDEs facilitate the development of GUIs,
which include buttons, text boxes, panels, frames, scrollbars and other objects via drag-and-drop
and point-and-clickactions.

Java programs are found in desktops, servers, mobile devices, smart cards andBlu-ray Discs (BD).

Java is −
➢ Object Oriented − In Java, everything is an Object. Java can be easilyextended since it is
based on the Object model.
➢ Platform Independent − Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by the
VirtualMachine (JVM) on whichever platform it is being run on.
➢ Simple − Java is designed to be easy to learn. If We understand the basicconcept of OOP
Java, it would be easy to master.
➢ Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-keyencryption.
➢ Architecture-neutral − Java compiler generates an architecture-neutralobject file format,
which makes the compiled code executable on manyprocessors, with the presence of Java
runtime system.
➢ Portable − Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable. Compiler inJava is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
➢ Robust − Java makes an effort to eliminate error prone situations byemphasizing mainly on
compile time error checking and runtime checking.
➢ Multithreaded − With Java's multithreaded feature it is possible to writeprograms that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
➢ Interpreted − Java byte code is translated on the fly to native machineinstructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is
an incremental and light-weight process.

574
➢ High Performance − With the use of Just-In-Time compilers, Javaenables high performance.
➢ Distributed − Java is designed for the distributed environment of theinternet.
➢ Dynamic − Java is considered to be more dynamic than C or C++ since itis designed to adapt
to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
Dynamic HyperText Markup Language (DHTML)
Dynamic HyerText Markup Language (DHTML) is a combination of Web development technologies
used to create dynamically changing websites. Web pages may include animation, dynamic menus
and text effects. The technologiesused include a combination of HTML, JavaScript or VB Script,
CSS and the document object model (DOM).

Designed to enhance a Web user’s experience, DHTML includes the followingfeatures:


➢ Dynamic content, which allows the user to dynamically change Webpage content
➢ Dynamic positioning of Web page elements
➢ Dynamic style, which allows the user to change the Web page’s color,font, size or content
While DHTML enhances the website user’s experience, the technology may alsobe frustrating for
users when it is used incorrectly. For example, a website menuwith flashy DHTML animations can
easily confuse user navigation. Another DHTML issue occurs when Web developers attempt to
create cross-browser DHTML, which is very difficult.

For Web developers, DHTML poses the following problems:

➢ It can be difficult to develop and debug because of lack of Web browserand technological
support.
➢ DHTML scripts may not work correctly in various Web browsers.
➢ The Web page layout may not display correctly when it is developed to display in different
screen size combinations and in different browsers.
As a result of these problems, Web developers must determine whether DHTML enhances the user
experience in any given context. Most Web developers abandon complex DHTML and use simple
cross-browser routines to improve userexperience, as opposed to integrating excessive DHTML
visual effects.
Components of Dynamic HTML
DHTML consists of the following four components or languages:
➢ HTML 4.0
➢ CSS
➢ JavaScript
➢ DOM.

HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML.It defines the
structure of a web page with various defined basic elements or tags.

575
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developersfor controlling the
style and layout of the HTML elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statementsin JavaScript are the commands which tell the
browser for performing an action.

DOM
DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects andproperties of all elements in
HTML.
Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):

o It is used for designing the animated and interactive web pages that aredeveloped in real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus orrollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their content
automatically.
Features of DHTML
Following are the various characteristics or features of DHTML (Dynamic HTML):

o Its simplest and main feature is that we can create the web pagedynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size,color, and content of a
web page.
o It provides the facility for using the events, methods, and properties. And,also provides the
feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites orweb pages.
o With the help of DHTML, users can easily change the tags and theirproperties.
o The web page functionality is enhanced because the DHTML uses low-bandwidth effect.
Difference between HTML and DHTML

o Following table describes the differences between HTML and DHTML:

576
HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markuplanguage)

1. HTML is simply a markup language. 1. DHTML is not a language, but it is a set of


technologies of web development.

2. It is used for developing and creating web 2. It is used for creating and designing theanimated
pages. and interactive web sites or pages.

3. This markup language creates static web 3. This concept creates dynamic webpages.
pages.

4. It does not contain any server-sidescripting 4. It may contain the code of server-sidescripting.
code.

5. The files of HTML are stored withthe .html or 5. The files of DHTML are stored with the
.htm extension in a .dhtm extension in a system.

system.

6. A simple page which is created by a user 6. A page which is created by a user usingthe HTML,
without using the scripts or styles called as an CSS, DOM, and JavaScript technologies called a
HTML page. DHTML page.

7. This markup language does not need 7. This concept needs database connectivity
database connectivity. because it interacts withusers.

DHTML JavaScript

577
JavaScript can be included in HTML pages, which creates the content of the pageas dynamic. We
can easily type the JavaScript code within the <head> or <body>tag of a HTML page. If we want to
add the external source file of JavaScript, we can easily add using the <src> attribute.
Following are the various examples, which describes how to use the JavaScripttechnology with the
DHTML:
Scripting Language
A scripting language is a language that uses a sophisticated method to bring codesto a runtime
environment. In key ways, scripting languages are made for specific runtime environments, and
they automate some of the code implementation.
In that sense, they are modernizations of a system that previously used compilers to interpret
inputs.
Examples of scripting language implementation involve their use in operatingsystem shells and
web browser technologies, and elsewhere, where the interpreter can enhance how the language is
used.

Example: Python
A basic comparison of scripting languages in programming evolution involves Python, one of the
most popular languages used for many new kinds of projectsinvolving machine learning.
Python is known as a scripting language in its modular and automated build, compared to legacy
programming languages like COBOL and BASIC, which areknown as compiled languages.
Interpreted Languages
In many cases, a scripting language uses an interpreter instead of a compiler, andthat's how We
can tell whether a language is a scripting language or not.
Compiled languages use a compiler to make code into assembly language ormachine language. By
contrast, scripting languages and other interpreted languages use an interpreter.
The interpreter is responsible to interpret the source code for program execution.We could say that
in a scripting language with an interpreter, the code is the language itself, and it gets interpreted
relatively on-the-fly. Other kinds of systems like just-in-time compiling can also apply.
Hybrids
An example of the complexity of compiler languages and interpreted languages such as scripting
languages is evident in the evolution of Sun Microsystems and itsJava computer programming
language set, which has been so much a fundamental part of computer science for so many years.
Classic Java is commonly known as a compiler language. It uses the traditionalcompiler system to
convert code into machine language, as do C++ and other object oriented programming methods
of its time.
However, languages like JavaScript are known as interpreter languages, where instead of using a
compiler, an interpreter tool is used to change the way that the

code syntax is used and implemented. If We, for example, have a virtual machinefriendly language
like ByteCode interpreting Java script for a compiler, that wouldbe an interpreted language.

578
Benefits and Disadvantages of Scripting and Interpreted Languages

There are various benefits and disadvantages associated with the use of interpreted languages
over compiler languages. The uniqueness of domain- specific scripting languages and their use in
various runtime environments has been discussed. There's also the idea that interpreted language
systems can helpwhen distributed systems have different machine languages in play that make it
difficult for compiled languages to bridge these cross-platform gaps.
On the other hand, some experts talk about latency with interpreted programs,just because the code
has to run through an interpreter instead of being traditionally compiled. Experts have to assess
these sorts of trade-offs as they consider whether using a scripting language makes sense in a
given project environment.
Generally, though, the ability to abstract programming in this way is an attractivepart of modernizing
our codebase tools.
Java Servlet
Java Servlets are server-side Java program modules that process and answer clientrequests and
implement the servlet interface. It helps in enhancing Web server functionality with minimal
overhead, maintenance and support.
A servlet acts as an intermediary between the client and the server. As servlet modules run on the
server, they can receive and respond to requests made by theclient. Request and response objects
of the servlet offer a convenient way to handle HTTP requests and send text data back to the client.
Since a servlet is integrated with the Java language, it also possesses all the Javafeatures such as
high portability, platform independence, security and Java database connectivity.

There are two Java Servlet types: Basic and HTTP.HTTP servlets are used as follows:
• When an HTML form is submitted, the servlet processes and stores the data.
• When a client supplies a database query, the results are provided to theclient by the servlet.
• In most cases, the server uses the common gateway interface (CGI).However, Java Servlets
have many advantages over CGI, including:
• A servlet runs in the same process, eliminating the need to create a new process for every
request.
• The CGI program must be reloaded for each CGI request. A servlet, however,does not require
reloading and remains in the memory between requests.
• A servlet answers multiple requests simultaneously by using one instance,saving memory and
easily managing persistent data.
• The servlet engine runs in a sandbox or restricted environment, protecting the server from
potentially harmful servlets.
Servlet Life Cycle
The servlet life cycle is the Java servlet processing event sequence that occurs from servlet
instance creation to destruction. The servlet life cycle is controlled bythe container that deploys the
servlet.
The servlet life cycle is made up of four stages:
579
• Instantiation
• Initialization
• Client request handling
• Destruction

When a servlet request is mapped, the servlet container checks for the existenceof a servlet class
instance. If an instance does not exist, the Web container loads the servlet class, creates an
instance of this class and initializes this instance by calling the init() method.

The initialization process is completed prior to client request handling. The container does not call
the init() method again, unless a servlet is reloaded. Afterthe instantiation and initialization are
completed, the servlet container calls the service() method to respond to the request. When the
servlet is no longer needed, the container destroys the servlet with the destroy() method. This
method is also executed only one time.
Applications of Servlet
➢ Read the explicit data sent by the clients (browsers). This includes anHTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
➢ Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
➢ Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Webservice, or computing the response directly.
➢ Send the explicit data (i.e., the document) to the clients (browsers). Thisdocument can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
➢ Send the implicit HTTP response to the clients (browsers). This includestelling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Java Applet
A Java applet is a small dynamic Java program that can be transferred via the Internet and run by
a Java-compatible Web browser. The main difference between Java-based applications and
applets is that applets are typically executedin an AppletViewer or Java-compatible Web browser.
All applets import
the java.awt package.

The following are two issues with Java applets:


➢ Security: Java resolves the security issue by restricting applets to Java’s execution
environment and preventing access to system resources.
➢ Portability: Portability is defined as the applet’s ability to run on different computers and
operating systems.
Any browser with Java Virtual Machine (JVM) can execute bytecode, which is theoutput of a Java
compiler and can be run only in a JVM. Bytecode is Java’s solution for security and portability.

580
Application Conversion to Applets
It is easy to convert a graphical Java application (that is, an application that usesthe AWT and that
We can start with the Java program launcher) into an applet that We can embed in a web page.
Following are the specific steps for converting an application to an applet.
➢ Make an HTML page with the appropriate tag to load the applet code.
➢ Supply a subclass of the JApplet class. Make this class public. Otherwise,the applet cannot
be loaded.
➢ Eliminate the main method in the application. Do not construct a frame window for the
application. Our application will be displayed inside thebrowser.
➢ Move any initialization code from the frame window constructor to the init method of the
applet. We don't need to explicitly construct the applet object. The browser instantiates it for
We and calls the init method.
➢ Remove the call to setSize; for applets, sizing is done with the width andheight parameters in
the HTML file.
➢ Remove the call to setDefaultCloseOperation. An applet cannot beclosed; it terminates when
the browser exits.
➢ If the application calls setTitle, eliminate the call to the method. Appletscannot have title bars.
(You can, of course, title the web page itself, using the HTML title tag.)
➢ Don't call setVisible(true). The applet is displayed automatically.

Computer Graphics
Computer Graphics involves technology to access. The Process transforms and presents
information in a visual form. The role of computer graphics insensible. In today life, computer
graphics has now become a common element in user interfaces, T.V. commercial motion pictures.
Computer Graphics is the creation of pictures with the help of a computer. Theend product of the
computer graphics is a picture it may be a business graph, drawing, and engineering.
In computer graphics, two or three-dimensional pictures can be created that are used for research.
Many hardware devices algorithm has been developing for improving the speed of picture
generation with the passes of time. It includes thecreation storage of models and image of objects.
These models for various fields like engineering, mathematical and so on.
Today computer graphics is entirely different from the earlier one. It is not possible. It is an
interactive user can control the structure of an object of variousinput devices.

Definition of Computer Graphics:


It is the use of computers to create and manipulate pictures on a display device. Itcomprises of
software techniques to create, store, modify, represents pictures.

Why computer graphics used?


Suppose a shoe manufacturing company want to show the sale of shoes for five years. For this
vast amount of information is to store. So a lot of time and memorywill be needed. This method will
be tough to understand by a common man. In this situation graphics is a better alternative. Graphics
581
tools are charts and graphs.Using graphs, data can be represented in pictorial form. A picture can
be understood easily just with a single look.
Interactive computer graphics work using the concept of two-way communication between
computer users. The computer will receive signals from the input device,and the picture is modified
accordingly. Picture will be changed quickly when we apply command.

Display Devices in Computer Graphics


The display device is an output device used to represent the information in theform of images
(visual form). Display systems are mostly called a video monitor or Video display unit (VDU).
Display devices are designed to model, display, view, or display information. Thepurpose of display
technology is to simplify information sharing.
Today, the demand for high-quality displays is increasing.There are some display devices given

below:

1. Cathode-Ray Tube(CRT)
2. Color CRT Monitor
3. Liquid crystal display(LCD)
4. Light Emitting Diode(LED)
5. Direct View Storage Tubes(DVST)
6. Plasma Display
7. 3D Display

1. Cathode-ray Tube (CRT): Here, CRT stands for Cathode ray tube. It is a technology which is used
in traditional computer monitor and television.
Cathode ray tube is a particular type of vacuum tube that displays images whenan electron beam
collides on the radiant surface.

582
Component of CRT:
• Electron Gun: The electron gun is made up of several elements, mainly a heating filament
(heater) and a cathode.
The electron gun is a source of electrons focused on a narrow beam facing theCRT.
• Focusing & Accelerating Anodes: These anodes are used to produce anarrow and sharply
focused beam of electrons.
• Horizontal & Vertical Deflection Plates: These plates are used to guide thepath of the electron
the beam. The plates produce an electromagnetic fieldthat bends the electron beam through
the area as it travels.
• Phosphorus-coated Screen: The phosphorus coated screen is used toproduce bright spots
when the high-velocity electron beam hits it.

There are two ways to represent an object on the screen:


1. Raster Scan: It is a scanning technique in which the electron beam moves along the screen. It
moves from top to bottom, covering one line at a time.
A raster scan is based on pixel intensity control display as a rectangular box on thescreen called a
raster.
Picture description is stored in the memory area called as Refresh buffer, orFrame Buffer.
Frame buffer is also known as Raster or Bitmap. Raster scan provides the refreshrate of 60 to 80
frames per second.

For Example: Television


The beam refreshing has two types:
1. Horizontal Retracing
2. Vertical Retracing
When the beam starts from the top left corner and reaches bottom right, andagain return to the top
left, it is called the vertical retrace.
It will call back from top to bottom more horizontally as a horizontal reversal.

583
Advantages:
1. Real image
2. Many colors to be produced
3. Dark scenes can be pictured

Disadvantages:
1. Less resolution
2. Display picture line by line
3. More costly

2. Random Scan (Vector scan): It is also known as stroke-writing display or calligraphic display.
In this, the electron beam points only to the area in which thepicture is to be drawn.
It uses an electron beam like a pencil to make a line image on the screen. The image is constructed
from a sequence of straight-line segments. On the screen, each line segment is drawn by the beam
to pass from one point on the screen tothe other, where its x & y coordinates define each point.

584
After compilation of picture drawing, the system cycle back to the first line andcreate all the lines
of picture 30 to 60 times per second.

Fig: A Random Scan display draws the lines of an object in a specific orderAdvantages:

1. High Resolution
2. Draw smooth line Drawing
Disadvantages:
1. It does only the wireframe.
2. It creates complex scenes due to flicker.

2. Color CRT Monitor: It is similar to a CRT monitor.


The basic idea behind the color CRT monitor is to combine three basic colors- Red,
Green, and Blue. By using these three colors, we can producemillions of different colors.

The two basic color display producing techniques are:


1. Beam–Penetration Method: It is used with a random scan monitor for displaying pictures.
There are two phosphorus layers- Red and Green are coated inside the screen. The color shown
depends on how far the electronbeam penetrates the phosphorus surface.
A powerful electron beam penetrates the CRT, it passes through the red layer andexcites the green
layer within.
A beam with slow electrons excites only the red layer.

A beam with the medium speed of electrons, a mixture of red and green light isemitted to display
two more colors- orange and yellow.

585
Advantages:
1. Better Resolutio
2. Half cost
3. Inexpensive

Disadvantages:

1. Only four possible colors


2. Time Consuming

2. Shadow–Mask Method: It is used with a raster scan monitor for displaying pictures. It has
more range of color than the beam penetration method. It is usedin television sets and monitors.
Structure:

1. It has three phosphorus color dots at each position of the pixel.First Dot: Red color Second Dot:
Green colorThird Dot: Blue color

1. It has three different guns. Each for one color.


2. It has a metal screen or plate just before the phosphorus screen,named “Shadow-Mask.”
3. It also has a shadow grid just behind the phosphorus coated screen withtiny holes in a triangular
shape.
Working: A Shadow Mask is a metal plate with tiny holes present inside a colormonitor.
A Shadow Mask directs the beam by consuming the electrons so that the beamhits only the desired
point and displays a resulting picture.
It has three different guns. These guns direct their beams to shadow mask, whichallows them to
pass. It is a task of a shadow mask to direct the beam on its particular dot on the screen and
produce a picture on the screen.
A Shadow Mask can display a wider range of pictures than beam penetration.

586
Advantages:
1. Display a wider range picture.
2. Display realistic images.
3. In-line arrangement of RGB color.

Disadvantages:
Difficult to cover all three beams on the same hole.Poor Resolution.

3. Liquid crystal display (LCD): The LCD depends upon the light modulatingproperties of liquid
crystals.
LCD is used in watches and portable computers. LCD requires an AC power supplyinstead of DC,
so it is difficult to use it in circuits.
It generally works on flat panel display technology. LCD consumes less power thanLED. The LCD
screen uses the liquid crystal to turn pixels on or off.
Liquid Crystals are a mixture of solid and liquid. When the current flows inside it,its position changes
into the desired color.

For Example: TFT(Thin Film Transistor)


Advantages:
1. Produce a bright image
2. Energy efficient
3. Completely flat screen

Disadvantages:
Fixed aspect ratio & ResolutionLower Contrast

More Expensive
4. Light Emitting Diode (LED): LED is a device which emits when current passesthrough it. It is a
semiconductor device.
The size of the LED is small, so we can easily make any display unit by arranging alarge number of
587
LEDs.
LED consumes more power compared to LCD. LED is used on TV, smartphones,motor vehicles,
traffic light, etc.
LEDs are powerful in structure, so they are capable of withstanding mechanicalpressure. LED also
works at high temperatures.
Advantages:

1. The Intensity of light can be controlled.


2. Low operational Voltage.
3. Capable of handling the high temperature.

Disadvantages:
More Power Consuming than LCD.

5. Direct View Storage Tube (DVST): It is used to store the picture information as a charge
distribution behind the phosphor-coated screen.
There are two guns used in DVST:

2.Flood / Secondary Gun: It is used to display a picture on the screen.

Advantages:
Less Time Consuming

No Refreshing Required

High-Resolution

Less Cost
1.Primary Gun: It
588
is used to store the picture information.

Disadvantages:
The specific part of the image cannot be erased.They do not display color.

6.Plasma Display: It is a type of flat panel display which uses tiny plasma cells. It isalso known as
the Gas-Discharge display.
Components of plasma display:
1. Anode: It is used to deliver a positive voltage. It also has the line wires.
2. Cathode: It is used to provide negative voltage to gas cells. It also has fine wires.
3. Gas Plates: These plates work as capacitors. When we pass the voltage, the celllights regularly.
4. Fluorescent cells: It contains small pockets of gas liquids when the voltage ispassed to this
neon gas. It emits light.

Advantages:
1. Wall Mounted
2. Slim
3. Wider angle

Disadvantages:
Phosphorus loses luminosity over time.It consumes more electricity than LCD. Large Size

D Display: It is also called stereoscope display technology. This technology iscapable of bringing
589
depth perception to the viewer.
It is used for 3D gaming and 3D TVs.

For Example: Fog Display, Holographic Display, Retina Display Etc.


Advantages:
• Impressive Picture Quality
• High Definition
• Motion Communicates

Disadvantage:
• Expensive
• Binocular Fusion
Raster Scan

In a raster scan system, the electron beam is swept across the screen, one row ata time from top
to bottom. As the electron beam moves across each row, the beam intensity is turned on and off
to create a pattern of illuminated spots.
A Raster Scan Display is based on intensity control of pixels in the form of a rectangular box called
Raster on the screen. Information of on and off pixels is stored in refresh buffer or Frame buffer.
Televisions in our house are based on Raster Scan Method. The raster scan system can store
information of each pixel position, so it is suitable for realistic display of objects. Raster Scan
provides arefresh rate of 60 to 80 frames per second.
Frame Buffer is also known as Raster or bit map. In Frame Buffer the positions arecalled picture
elements or pixels. Beam refreshing is of two types. First is horizontal retracing and second is
vertical retracing. When the beam starts from the top left corner and reaches the bottom right scale,
it will again return to the top left side called at vertical retrace. Then it will again more horizontally
from top to bottom call as horizontal retracing shown in fig:

Types of Scanning or travelling of beam in Raster Scan


1. Interlaced Scanning
2. Non-Interlaced Scanning

In Interlaced scanning, each horizontal line of the screen is traced from top to bottom. Due to which
fading of display of object may occur. This problem can besolved by Non-Interlaced scanning. In
this first of all odd numbered lines are traced or visited by an electron beam, then in the next circle,
even number of lines are located.
For non-interlaced display refresh rate of 30 frames per second used. But it gives flickers. For
interlaced display refresh rate of 60 frames per second is used.
Picture definition is stored in memory area called the Refresh Buffer or FrameBuffer. This memory
area holds the set of intensity values for all the screen points. Stored intensity values are then
retrieved from the refresh buffer and “painted” on the screen one row scanlinescanline at a time as
shown in the following illustration.

590
Each screen point is referred
to as a pixel pictureelementpictureelement or pel.At the end of each scan line, the electron beam
returns to the left side of the screen to begin displaying the next scan line.

Advantages:
1. Realistic image
2. Million Different colors to be generated
3. Shadow Scenes are possible.

Disadvantages:
1. Low Resolution
2. Expensive

Random Scan VectorScanVectorScan


In this technique, the electron beam is directed only to the part of the screen where the picture is
to be drawn rather than scanning from left to right and top tobottom as in raster scan. It is also
called vector display, stroke-writing display, or calligraphic display.

Random Scan System uses an electron beam which operates like a pencil to create a line image
on the CRT screen. The picture is constructed out of a sequence of straight-line segments. Each
line segment is drawn on the screen by directing the beam to move from one point on the screen
to the next, where its x& y coordinates define each point. After drawing the picture. The system
cycles back to the first line and design all the lines of the image 30 to 60 time eachsecond. The
process is shown in fig:
Random-scan monitors are also known as vector displays or stroke-writingdisplays or calligraphic
displays.
Picture definition is stored as a set of line-drawing commands in an area of memory referred to as
the refresh display file. To display a specified picture, the system cycles through the set of
commands in the display file, drawing each component line in turn. After all the line-drawing
commands are processed, the system cycles back to the first line command in the list.
Random-scan displays are designed to draw all the component lines of a picture30 to 60 times each
second.
591
Advantages:
1. A CRT has the electron beam directed only to the parts of the screen wherean image is to be
drawn.
2. Produce smooth line drawings.
3. High Resolution
Disadvantages:
1. Random-Scan monitors cannot display realistic shades scenes.
Differentiate between Random and Raster Scan Display:

Random Scan Raster Scan


1. It has high Resolution 1. Its resolution is low.
2. It is more expensive 2. It is less expensive
3. Any modification if needed iseasy 3.Modification is tough
4. Solid pattern is tough to fill 4.Solid pattern is easy to fill
5. Refresh rate depends orresolution 5. Refresh rate does not depend onthe picture.
6. Only screen with view on an areais displayed. 6. Whole screen is scanned.
7. Beam Penetration technologycome under it. 7. Shadow mark technology cameunder this.
8. It does not use interlacingmethod. 8. It uses interlacing
9. It is restricted to line drawing 9. It is suitable for realistic display.

applications

Input Devices
The Input Devices are the hardware that is used to transfer transfers input to the

592
These Devices include:

1. Keyboard

computer. The data can be in the form of text, graphics, sound, and text. Output
device display data from the memory of the computer. Output can be text,
numeric data, line, polygon, and other objects.

2. Mouse
3. Trackball
4. Spaceball
5. Joystick
6. Light Pen
7. Digitizer
8. Touch Panels
9. Voice Recognition10.Image Scanner

Keyboard:
The most commonly used input device is a keyboard. The data is entered by pressing the set of
keys. All keys are labeled. A keyboard with 101 keys is called aQWERTY keyboard.

593
The keyboard has alphabetic as well as numeric keys. Some special keys are alsoavailable.

1. Numeric Keys: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2. Alphabetic keys: a to z (lower case), A to Z (upper case)
3. Special Control keys: Ctrl, Shift, Alt
4. Special Symbol Keys: ; , " ? @ ~ ? :
5. Cursor Control Keys: ↑ → ← ↓
6. Function Keys: F1 F2 F3 F9.
7. Numeric Keyboard: It is on the right-hand side of the keyboard and used for fast entry of
numeric data.

Function of Keyboard:
1. Alphanumeric Keyboards are used in CAD. (Computer Aided Drafting)
2. Keyboards are available with special features line screen co-ordinatesentry, Menu selection or
graphics functions, etc.
3. Special purpose keyboards are available having buttons, dials, and switches.Dials are used to
enter scalar values. Dials also enter real numbers. Buttons and switches are used to enter
predefined function values.
Advantage:
1. Suitable for entering numeric data.
2. Function keys are a fast and effective method of using commands, withfewer errors.

Disadvantage:
594
1. Keyboard is not suitable for graphics input.

Mouse:
A Mouse is a pointing device and used to position the pointer on the screen. It is asmall palm size
box. There are two or three depression switches on the top. The movement of the mouse along the
x-axis helps in the horizontal movement of thecursor and the movement along the y-axis helps in
the vertical movement of the cursor on the screen. The mouse cannot be used to enter text.
Therefore, they are used in conjunction with a keyboard.

Advantage:
1. Easy to use
2. Not very expensive

Filled Area Primitives:


Region filling is the process of filling image or region. Filling can be of boundary orinterior region as
shown in fig. Boundary Fill algorithms are used to fill the boundary and flood-fill algorithm are used
to fill the interior.

Scan Line Polygon Fill Algorithm:


This algorithm lines interior points of a polygon on the scan line and these pointsare done on or off
according to requirement. The polygon is filled with various colors by coloring various pixels.
In above figure polygon and a line cutting polygon in shown. First of all, scanning is done. Scanning
is done using raster scanning concept on display device. The beam starts scanning from the top
left corner of the screen and goes toward the bottom right corner as the endpoint. The algorithms
find points of intersection ofthe line with polygon while moving from left to right and top to bottom.
The various points of intersection are stored in the frame buffer. The intensities of such points is
keep high. Concept of coherence property is used. According to thisproperty if a pixel is inside the
polygon, then its next pixel will be inside the polygon.

Side effects of Scan Conversion:


1. Staircase or Jagged: Staircase like appearance is seen while the scan wasconverting line or
circle.
2. Unequal Intensity: It deals with unequal appearance of the brightness of different lines. An
inclined line appears less bright as compared to the horizontaland vertical line.

595
Flood Fill Algorithm:
In this method, a point or seed which is inside region is selected. This point iscalled a seed point.
Then four connected approaches or eight connected approaches is used to fill with specified color.
The flood fill algorithm has many characters similar to boundary fill. But this method is more
suitable for filling multiple colors boundary. When boundary is ofmany colors and interior is to be
filled with one color we use this algorithm.

In fill algorithm, we start from a specified interior point (x, y) and reassign all pixel values are
currently set to a given interior color with the desired color. Using

either a 4-connected or 8-connected approaches, we then step through pixel positions until all
interior points have been repainted.

Disadvantage:

596
1. Very slow algorithm

#include<dos.h>

May be fail for large polygons

Initial pixel required more knowledge about surrounding pixels.


Algorithm:

Procedure floodfill (x, y,fill_ color, old_color: integer)

If (getpixel (x, y)=old_color)

setpixel (x, y, fill_color);

fill (x+1, y, fill_color, old_color);

fill (x-1, y, fill_color, old_color);

fill (x, y+1, fill_color, old_color);

fill (x, y-1, fill_color, old_color);

Program1: To implement 4-connected flood fill algorithm:


#include<stdio.h>

#include<conio.h>

#include<graphics.h>
void flood(int,int,int,int);
void main()
{
intgd=DETECT,gm;

initgraph(&gd,&gm,"C:/TURBOC3/bgi");

rectangle(50,50,250,250);

597
flood(55,55,10,0);

getch();
}
void flood(intx,inty,intfillColor, intdefaultColor)
{
if(getpixel(x,y)==defaultColor)
{
delay(1);

putpixel(x,y,fillColor);

flood(x+1,y,fillColor,defaultColor);

flood(x-1,y,fillColor,defaultColor);

flood(x,y+1,fillColor,defaultColor);

flood(x,y-1,fillColor,defaultColor);

}
}

Output:

598
Boundary Filled Algorithm:
This algorithm uses the recursive method. First of all, a starting pixel called as the seed is
considered. The algorithm checks boundary pixel or adjacent pixels are colored or not. If the
adjacent pixel is already filled or colored then leave it, otherwise fill it. The filling is done using four
connected or eight connected approaches.

Four connected approaches is more suitable than the eight connectedapproaches.


1. Four connected approaches: In this approach, left, right, above, below pixelsare tested.
2. Eight connected approaches: In this approach, left, right, above, below andfour diagonals are
selected.

Boundary can be checked by seeing pixels from left and right first. Then pixels arechecked by seeing
pixels from top to bottom. The algorithm takes time and memory because some recursive calls are
needed.

Problem with recursive boundary fill algorithm:

It may not fill regions sometimes correctly when some interior pixel is already filled with color. The
algorithm will check this boundary pixel for filling and will found already filled so recursive process
will terminate. This may vary because ofanother interior pixel unfilled.
So check all pixels color before applying the algorithm.

Algorithm:
fill (x, y+1, color, color 1);

fill (x, y-1, color, color 1);

599
Procedure fill (x, y, color, color1: integer)

int c;

c=getpixel (x, y);

if (c!=color) (c!=color1)

setpixel (x, y, color)

fill (x+1, y, color, color 1);

fill (x-1, y, color, color 1);

MidPoint Circle Algorithm


It is based on the following function for testing the spatial relationship between the arbitrary
point (x, y) and a circle of radius r centered at the origin:

600
Now, consider the coordinates of the point halfway between pixel T and pixel S This is called

midpoint (xi+1,yi- ) and we use it to define a decision parameter:

Pi=f (xi+1,yi- ) = (xi+1)2+(yi- )2-r2 equation 2

If Pi is -ve ⟹midpoint is inside the circle and we choose pixel T


If Pi is+ve ⟹midpoint is outside the circle (or on the circle)and we choose pixel S.The decision

parameter for the next step is:

Pi+1=(xi+1+1)2+(yi+1- )2- r2 ........... equation 3

Since xi+1=xi+1, we have

If pixel T is choosen ⟹Pi<0

We have yi+1=yi
If pixel S is choosen ⟹Pi≥0

We have yi+1=yi-1

We can continue to simplify this in n terms of (xi,yi) and get

Now, initial value of Pi (0,r)from equation 2

We can put ≅1
601
∴r is an integerSo, P1=1-r
Algorithm:

Step1: Put x =0, y =r in equation

Step2: Repeat steps while x ≤ y


2We have p=1-r Plot (x,
y)
If (p<0)
Then set p = p + 2x + 3Else
p = p + 2(x-y)+5
y =y - 1 (end if)
x =x+1 (end loop)

Step3: End

Program to draw a circle using Midpoint Algorithm:

#include <graphics.h>

#include <stdlib.h>

#include <math.h>

#include <stdio.h>

#include <conio.h>

#include <iostream.h>

class bresen
{
float x, y,a, b, r, p;

public:

void get ();

void cal ();

};
602
void main ()

bresen b;

b.get ();

b.cal ();

getch ();

Void bresen :: get ()

cout<<"ENTER CENTER AND RADIUS";

cout<< "ENTER (a, b)";

cin>>a>>b;

cout<<"ENTER r";

cin>>r;

void bresen ::cal ()

/* request auto detection */

int gdriver = DETECT,gmode, errorcode;

int midx, midy, i;

/* initialize graphics and local variables */

initgraph (&gdriver, &gmode, " ");

/* read result of initialization */

errorcode = graphresult ();


603
if (errorcode ! = grOK) /*an error occurred */

printf("Graphics error: %s \n", grapherrormsg (errorcode);

printf ("Press any key to halt:");

getch ();

exit (1); /* terminate with an error code */

x=0;

y=r;

putpixel (a, b+r, RED);

putpixel (a, b-r, RED);

putpixel (a-r, b, RED);

putpixel (a+r, b, RED);

p=5/4)-r;

while (x<=y)

If (p<0)

p+= (4*x)+6;

else

p+=(2*(x-y))+5;

y--;

604
x++;

putpixel (a+x, b+y, RED);

putpixel (a-x, b+y, RED);

putpixel (a+x, b-y, RED);

putpixel (a+x, b-y, RED);

putpixel (a+x, b+y, RED);

putpixel (a+x, b-y, RED);

putpixel (a-x, b+y, RED);

putpixel (a-x, b-y, RED);

}
}

Output:

Bresenham's Line Algorithm

This algorithm is used for scan converting a line. It was developed by Bresenham. It is an
efficient method because it involves only integer addition, subtractions, and multiplication
operations. These operations can be performed very rapidly solines can be generated
quickly.

In this method, next pixel selected is that one who has the least distance fromtrue line.
605
The method works as follows:

Assume a pixel P1'(x1',y1'),then select subsequent pixels as we work our may tothe night,
one pixel position at a time in the horizontal direction toward P2'(x2',y2').
Once a pixel in choose at any stepThe next pixel is

1. Either the one to its right (lower-bound for the line)


2. One top its right and up (upper-bound for the line)
The line is best approximated by those pixels that fall the least distance from thepath between
P1',P2'.

To chooses the next one between the bottom pixel S and top pixel T.
If S is chosen

We have xi+1=xi+1 and yi+1=yi


If T is chosen
The actual y coordinates of the line at x = xi+1is
We have xi+1=xi+1 and yi+1=yi+1
y=mxi+1+b

The distance from S to the actual line in y directions = y-yi


The distance from T to the actual line in y directiont = (yi+1)-y

Now consider the difference between these 2 distance valuess - t


When (s-t) <0 ⟹ s < tThe closest pixel is S
When (s-t) ≥0 ⟹ s < t
606
The closest pixel is T
Since x_(i+1)=xi+1,we have
di+1+di=2𝗈y.(xi+1-xi)- 2𝗈x(yi+1-yi)Special Cases

If chosen pixel is at the top pixel T (i.e., di≥0)⟹ yi+1=yi+1di+1=di+2𝗈y-2𝗈x


If chosen pixel is at the bottom pixel T (i.e., di<0)⟹ yi+1=yidi+1=di+2𝗈y
Finally, we calculate d1
d1=𝗈x[2m(x1+1)+2b-2y1-1]d1=𝗈x[2(mx1+b-y1)+2m-1]

Since mx1+b-yi=0 and m = , we haved1=2𝗈y-𝗈x


Advantage:
1. It involves only integer arithmetic, so it is simple.
2. It avoids the generation of duplicate points.
3. It can be implemented using hardware because it does not use multiplicationand division.
4. It is faster as compared to DDA (Digital Differential Analyzer) because it does not involve
floating point calculations like DDA Algorithm.
Disadvantage:
1. This algorithm is meant for basic line drawing only Initializing is not a part of Bresenham's line
algorithm. So to draw smooth lines, We should want to look intoa different algorithm.
Bresenham's Line Algorithm:

Step1: Start Algorithm

Step2: Declare variable x1,x2,y1,y2,d,i1,i2,dx,dy

Step3: Enter value of x1,y1,x2,y2


Where x1,y1are coordinates of starting pointAnd x2,y2 are coordinates of Ending point
Step4: Calculate dx = x2-x1
Calculate dy = y2-y1 Calculate i1=2*dy Calculate i2=2*(dy-dx)Calculate d=i1-dx
Step5: Consider (x, y) as starting point and xendas maximum possible value of x.
If dx < 0
Then x = x2y = y2 xend=x1
If dx > 0 Then x = x1
y = y1
xend=x2

Step6: Generate point at (x,y)coordinates.


Step7: Check if whole line is generated.
If x > = xendStop.
Step8: Calculate co-ordinates of the next pixelIf d < 0
Then d = d + i1If d ≥ 0
Then d = d + i2 Increment y = y + 1
Step9: Increment x = x + 1
Step10: Draw a point of latest (x, y) coordinates
607
Step11: Go to step 7

Step12: End of Algorithm


Example: Starting and Ending position of the line are (1, 1) and (8, 5). Findintermediate points.
Solution: x1=1
y1=1x2=8y2=5
dx= x2-x1=8-1=7dy=y2-y1=5-1=4
I1=2* ∆y=2*4=8 I2=2*(∆y-∆x)=2*(4-7)=-6d = I1-∆x=8-7=1

x y d=d+I1 or I2

1 1 d+I2=1+(-6)=-5

2 2 d+I1=-5+8=3

3 2 d+I2=3+(-6)=-3

4 3 d+I1=-3+8=5

5 3 d+I2=5+(-6)=-1

6 4 d+I1=-1+8=7

7 4 d+I2=7+(-6)=1

8 5

608
Program to implement Bresenham's Line Drawing Algorithm:
{

#include<stdio.h>

#include<graphics.h>

void drawline(int x0, int y0, int x1, int y1)

int dx, dy, p, x, y;

dx=x1-x0;

dy=y1-y0;

x=x0;

y=y0;

p=2*dy-dx;

while(x<x1)

if(p>=0)

putpixel(x,y,7);

y=y+1;

p=p+2*dy-2*dx;

else

putpixel(x,y,7);

p=p+2*dy;}

x=x+1;

609
}

}
int main()
{
int gdriver=DETECT, gmode, error, x0, y0, x1, y1;

initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

printf("Enter co-ordinates of first point: ");

scanf("%d%d", &x0, &y0);

printf("Enter co-ordinates of second point: ");


scanf("%d%d", &x1, &y1);

drawline(x0, y0, x1, y1); return 0;

Output:

Midpoint Ellipse Algorithm:


This is an incremental method for scan converting an ellipse that is centered at the origin in
standard position i.e., with the major and minor axis parallel to coordinate system axis. It is very
similar to the midpoint circle algorithm. Becauseof the four-way symmetry property we need to
consider the entire elliptical curvein the first quadrant.
first rewrite the ellipse equation and define the function f that can be used todecide if the midpoint
between two candidate pixels is inside or outside the ellipse:

610
Now divide the elliptical curve from (0, b) to (a, 0) into two parts at point Q wherethe slope of the
curve is -1.

Slope of the curve is defined by the f(x, y) = 0 is where fx & fy are partialderivatives of f(x, y) with
respect to x & y.

We have fx = 2b2 x, fy=2a2 y & Hence we can monitor the slope valueduring the scan conversion
process to detect Q. Our starting point is (0, b)
Suppose that the coordinates of the last scan converted pixel upon entering step iare (xi,yi). We are
to select either T (xi+1),yi) or S (xi+1,yi-1) to be the next pixel. The midpoint of T & S is used to define
the following decision parameter.

pi = f(xi+1),yi- )

pi=b2 (xi+1)2+a2 (yi- )2-a2 b2


If pi<0, the midpoint is inside the curve and we choose pixel T.

If pi>0, the midpoint is outside or on the curve and we choose pixel S.Decision parameter for the

next step is:


611
pi+1=f(xi+1+1,yi+1- )

= b2 (xi+1+1)2+a2 (yi+1- )2-a2 b2


Since xi+1=xi+1,we have

pi+1-pi=b2[((xi+1+1)2+a2 (yi+1- )2-(yi - )2] pi+1= pi+2b2 xi+1+b2+a2 [(yi+1- )2-(yi - )2]

If T is chosen pixel (pi<0), we have yi+1=yi.

If S is chosen pixel (pi>0) we have yi+1=yi-1. Thus we can express


pi+1in terms of pi and (xi+1,yi+1): pi+1= pi+2b2 xi+1+b2 if pi<0 =pi+2b2 xi+1+b2-2a2 yi+1 if pi>0
The initial value for the recursive expression can be obtained by the evaluatingthe original definition
of pi with (0, b):

p1 = (b2+a2 (b- )2-a2 b2


= b2-a2 b+a2/4
Suppose the pixel (xj yj) has just been scan converted upon entering step j. The next pixel is either
U (xj ,yj-1) or V (xj+1,yj-1). The midpoint of the horizontal lineconnecting U & V is used to define the
decision parameter:

qj=f(xj+ ,yj-1)

qj=b2 (xj+ )2+a2 (yj -1)2-a2 b2


If qj<0, the midpoint is inside the curve and we choose pixel V.

If qj≥0, the midpoint is outside the curve and we choose pixel U.Decisionparameter for the next step
is:

qj+1=f(xj+1+ ,yj+1-1)

= b2 (xj+1+ )2+ a2 (yj+1-1)2- a2 b2


Since yj+1=yj-1,we have

qj+1-qj=b2 [(xj+1+ )2-(xj + )2 ]+a2 (yj+1-1)2-( yj+1)2 ]


qj+1=qj+b2 [(xj+1+ )2-(xj + )2]-2a2 yj+1+a2
If V is chosen pixel (qj<0), we have xj+1=xj.

If U is chosen pixel (pi>0) we have xj+1=xj. Thus we can expressqj+1in terms of qj and (xj+1,yj+1 ):
qj+1=qj+2b2 xj+1-2a2 yj+1+a2 if qj < 0
=qj-2a2 yj+1+a2 if qj>0
The initial value for the recursive expression is computed using the original definition of qj. And the
coordinates of (xk yk) of the last pixel choosen for the part1 of the curve:

q1 = f(xk+ ,yk-1)=b2 (xk+ )2-a2 (yk-1)2- a2 b2


Algorithm:

612
int x=0, y=b; [starting point]
int fx=0, fy=2a2 b [initial partial derivatives]int p = b2-a2 b+a2/4

while (fx<="" 1="" {="" set="" pixel="" (x,="" y)="" x++;="" fx="fx" +="" 2b2;if (p<0)

p = p + fx +b2;else
{
y--;

fy=fy-2a2
p = p + fx +b2-fy;
}
}
Setpixel (x, y);

p=b2(x+0.5)2+ a2 (y-1)2- a2 b2
while (y>0)
{
y--;

fy=fy-2a2;if (p>=0) p=p-fy+a2else

{
x++;
fx=fx+2b2 p=p+fx-fy+a2;

}
Setpixel (x,y);
}
Transformations
Computer Graphics provide the facility of viewing object from different angles.The architect can
study building from different angles i.e.
1. Front Evaluation
2. Side elevation
3. Top plan

A Cartographer can change the size of charts and topographical maps. So if graphics images are
coded as numbers, the numbers can be stored in memory. These numbers are modified by
mathematical operations called as Transformation.
The purpose of using computers for drawing is to provide facility to user to viewthe object from
different angles, enlarging or reducing the scale or shape of object called as Transformation.

Two essential aspects of transformation are given below:


1. Each transformation is a single entity. It can be denoted by a unique nameor symbol.
2. It is possible to combine two transformations, after connecting a single transformation is
obtained, e.g., A is a transformation for translation. The Btransformation performs scaling. The
613
combination of two is C=AB. So C is obtained by concatenation property.
There are two complementary points of view for describing objecttransformation.

1. Geometric Transformation: The object itself is transformed relative to the coordinate system
or background. The mathematical statement of this viewpoint is defined by geometric
transformations applied to each point ofthe object.
2. Coordinate Transformation: The object is held stationary while the coordinate system is
transformed relative to the object. This effect isattained through the application of coordinate
transformations.

An example that helps to distinguish these two viewpoints:


The movement of an automobile against a scenic background we can simulatethis by
o Moving the automobile while keeping the background fixed-(GeometricTransformation)
o We can keep the car fixed while moving the background scenery-(Coordinate Transformation)

Types of Transformations:
1. Translation
2. Scaling
3. Rotating
4. Reflection
5. Shearing

Note: Translation, Scaling, and Rotation are also called as Basic Transformations.

Translation
It is the straight line movement of an object from one position to another is calledTranslation. Here
the object is positioned from one coordinate location to another.

Translation of point:
To translate a point from coordinate position (x, y) to another (x1 y1), we add algebraically the
translation distances Tx and Ty to original coordinate.
x1=x+Txy1=y+Ty

The translation pair (Tx,Ty) is called as shift vector.

Translation is a movement of objects without deformation. Every position or point is translated by


the same amount. When the straight line is translated, thenit will be drawn using endpoints.
For translating polygon, each vertex of the polygon is converted to a new position. Similarly, curved
objects are translated. To change the position of the circle or ellipse its center coordinates are
transformed, then the object is drawnusing new coordinates.
Let P is a point with coordinates (x, y). It will be translated as (x1 y1).

614
Matrix for Translation:

Scaling:
It is used to alter or change the size of objects. The change is done using scalingfactors. There are
two scaling factors, i.e. Sx in x direction Sy in y-direction. If the

original position is x and y. Scaling factors are Sx and Sy then the value ofcoordinates after scaling
will be x1 and y1.
If the picture to be enlarged to twice its original size then Sx = Sy =2. If Sxand Sy arenot equal then
615
scaling will occur but it will elongate or distort the picture.

If scaling factors are less than one, then the size of the object will be reduced. If
scaling factors are higher than one, then the size of the object will be enlarged.

If Sxand Syare equal it is also called as Uniform Scaling. If not equal then called as
Differential Scaling. If scaling factors with values less than one will move the
object closer to coordinate origin, while a value higher than one will move
coordinate position farther from origin.

Enlargement: If T1= ,If (x1 y1)is original position and T1is translation vector
then (x2 y2) are coordinated after scaling

The image will be enlarged two times

Reduction: If T1= . If (x1 y1) is original position and T1 is translation vector, then (x2 y2) are
coordinates after scaling

616
617
Matrix for Scaling:

Example: Prove that 2D Scaling transformations are commutative i.e, S1 S2=S2 S1.

Solution: S1 and S2 are scaling matrices

618
Rotation:
It is a process of changing the angle of the object. Rotation can be clockwise or anticlockwise. For
rotation, we have to specify the angle of rotation and rotationpoint. Rotation point is also called a
pivot point. It is print about which object is rotated.

Types of Rotation:
1. Anticlockwise
2. Counterclockwise
The positive value of the pivot point (rotation angle) rotates an object in acounter-clockwise
(anti-clockwise) direction.

The negative value of the pivot point (rotation angle) rotates an object in aclockwise direction.

When the object is rotated, then every point of the object is rotated by the same
angle.

Straight Line: Straight Line is rotated by the endpoints with the same angle andredrawing
the line between new endpoints.

Polygon: Polygon is rotated by shifting every vertex using the same rotationalangle.

Curved Lines: Curved Lines are rotated by repositioning of all points and drawingof the
curve at new positions.

Circle: It can be obtained by center position by the specified angle.

Ellipse: Its rotation can be obtained by rotating major and minor axis of an ellipseby the
desired angle.

619
Matrix for rotation is a clockwise direction.

620
Matrix for rotation is an anticlockwise direction.

Matrix for homogeneous co-ordinate rotation (clockwise)

Matrix for homogeneous co-ordinate rotation (anticlockwise)

Rotation about an arbitrary point: If we want to rotate an object or point about


an arbitrary point, first of all, we translate the point about which we want to
rotate to the origin. Then rotate point or object about the origin, and at the end,
we again translate it to the original place. We get rotation about an arbitrary
point.

Example: The point (x, y) is to be rotated

The (xc yc) is a point about which counterclockwise rotation is done

Step1: Translate point (xc yc) to origin

621
Step2: Rotation of (x, y) about the origin

Step3: Translation of center of rotation back to its original position

622
Example1: Prove that 2D rotations about the origin are commutative i.e.R1 R2=R2 R1.

Solution: R1 and R2are rotation matrices

Example2: Rotate a line CD whose endpoints are (3, 4) and (12, 15) about originthrough a 45°
anticlockwise direction.

Solution: The point C (3, 4)

623
624
Example3: Rotate line AB whose endpoints are A (2, 5) and B (6, 12) about originthrough a 30°
clockwise direction.

Solution: For rotation in the clockwise direction. The matrix is

Step1: Rotation of point A (2, 5). Take angle 30°

Step2: Rotation of point B (6, 12)

Reflection:
625
It is a transformation which produces a mirror image of an object. The mirrorimage can be either
about x-axis or y-axis. The object is rotated by180°.
Types of Reflection:

1. Reflection about the x-axis

626
Reflection about the y-axis

Reflection about an axis perpendicular to xy plane and passing through the


origin

Reflection about line y=x

1. Reflection about x-axis: The object can be reflected about x-axis with the help
of the following matrix

In this transformation value of x will remain same whereas the value of y will
become negative. Following figures shows the reflection of the object axis. The
object will lie another side of the x-axis.

627
2. Reflection about y-axis: The object can be reflected about y-axis with the help of
following transformation matrix

Here the values of x will be reversed, whereas the value of y will remain the same.The object will lie
another side of the y-axis.
The following figure shows the reflection about the y-axis

628
3. Reflection about an axis perpendicular to xy plane and passing through origin:
In the matrix of this transformation is given below

In this value of x and y both will be reversed. This is also called as half revolutionabout the origin.

4. Reflection about line y=x: The object may be reflected about line y = x with the help of
629
following transformation matrix

First of all, the object is rotated at 45°. The direction of rotation is clockwise. Afterit reflection is
done concerning x-axis. The last step is the rotation of y=x back to its original position that is
counterclockwise at 45°.
Example: A triangle ABC is given. The coordinates of A, B, C are given as

A (3 4)
B (6 4)
C (4 8)
Find reflected position of triangle i.e., to the x-axis.

Solution:

630
The a point coordinates after reflection

The b point coordinates after reflection

The coordinate of point c after reflection

a (3, 4) becomes a1 (3, -4)


b (6, 4) becomes b1 (6, -4)
c (4, 8) becomes c1 (4, -8)

Program to perform Mirror Reflection about a line:

631
#include <iostream.h>

#include <conio.h>

#include <graphics.h>

#include <math.h>

#include <stdlib.h>

#define pi 3.14

class arc

float x[10],y[10],theta,ref[10][10],ang;

float p[10][10],p1[10][10],x1[10],y1[10],xm,ym;

int i,k,j,n;

public:

void get();

void cal ();

void map ();

void graph ();

void plot ();

void plot1();

};

void arc::get ()

cout<<"\n ENTER ANGLE OF LINE INCLINATION AND Y INTERCEPT";

cin>> ang >> b;

cout <<"\n ENTER NO OF VERTICES";


632
cin >> n;

cout <<"\n ENTER";

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

cout<<"\n x["<<i<<"] and y["<<i<<"]";

theta =(ang * pi)/ 180;

ref [0] [0] = cos (2 * theta);

ref [0] [1] = sin (2 * theta);

ref [0] [2] = -b *sin (2 * theta);

ref [1] [0] = sin (2 * theta);

ref [1] [1] = -cos (2 * theta);

ref [1] [2] = b * (cos (2 * theta)+1);

ref [2] [0]=0;

ref [2] [1]=0;

ref [2] [2] = 1;

void arc :: cal ()

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

p[0] [i] = x [i];

p [1] [i] = y [i];

p [2] [i] = 1;
633
}

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

for (j=0; j<n; j++)

p1 [i] [j]=0;

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

p1 [i] [j] + = ref [i] [k] * p [k] [j];

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

x1 [i]=p1[0] [i];

y1 [i] = p1 [1] [i];

void arc :: map ()

int gd = DETECT,gm;

initgraph (&gd, &gm, " ");

int errorcode = graphresult ();

/* an error occurred */

if (errorcode ! = grOK)

{
634
printf ("Graphics error: %s \n", grapherrormsg (errorcode));

printf ("Press any key to halt:");

getch ();

exit (1); /* terminate with an error code */

void arc :: graph ()

xm=getmaxx ()/2;

ym=getmaxy ()/2;

line (xm, 0, xmm 2*ym);

void arc :: plot 1 ()

for (i=0; i <n-1; i++)

circle (x1[i]+xm, (-y1[i]+ym), 2);

line (x1[i]+xm, (-y1[i]+ym), x1[i+1]+xm, (-y1[i+1]+ym));

line (x1[n-1)+xm, (-y1[n-1]+ym), x1[0]+xm, (-y1[0]+ym));

getch();

void arc :: plot ()

635
line (x1[i]+xm, (-y1[i]+ym), x[i+1]+xm, (-y1[i+1]+ym));

line (x[n-1]+xm, (-y1[n-1]+ym), x[0]+xm, (-y[0]+ym));

getch();

void main ()

class arc a;

clrscr();

a.map();

a.graph();

a.get();

a.cal();

a.plot();

a.plot1();

getch();

Output:
{

for (i=0; i <n-1; i++)

circle (x1[i]+xm, (-y1[i]+ym, 2);

636
Shearing:

It is transformation which changes the shape of object. The sliding of layers ofobject occur. The
shear can be in one direction or in two directions.
Shearing in the X-direction: In this horizontal shearing sliding of layers occur. Thehomogeneous
matrix for shearing in the x-direction is shown below:

Shearing in the Y-direction: Here shearing is done by sliding along vertical or y-axis.

Shearing in X-Y directions: Here layers will be slided in both x as well as y


direction. The sliding will be in horizontal as well as vertical direction. The shape
of the object will be distorted. The matrix of shear in both directions is given by:

Matrix Representation of 2D Transformation

637
Homogeneous Coordinates

The rotation of a point, straight line or an entire image on the screen, about a
point other than origin, is achieved by first moving the image until the point of
rotation occupies the origin, then performing rotation, then finally moving the
image to its original position.

The moving of an image from one place to another in a straight line is called a translation. A
translation may be done by adding or subtracting to each point, theamount, by which picture is
required to be shifted.

Translation of point by the change of coordinate cannot be combined with other transformation by

638
using simple matrix application. Such a combination is essentialif we wish to rotate an image about
a point other than origin by translation, rotation again translation.
To combine these three transformations into a single transformation, homogeneous coordinates
are used. In homogeneous coordinate system, two- dimensional coordinate positions (x, y) are
represented by triple-coordinates.
Homogeneous coordinates are generally used in design and construction applications. Here we
perform translations, rotations, scaling to fit the pictureinto proper position.
Example of representing coordinates into a homogeneous coordinate system: For two-
dimensional geometric transformation, we can choose
homogeneous parameter h to any non-zero value. For our convenience take it asone. Each two-
dimensional position is then represented with homogeneous coordinates (x, y, 1).

Following are matrix for two-dimensional transformation in homogeneouscoordinate:

Composite Transformation:
A number of transformations or sequence of transformations can be combined into single one
called as composition. The resulting matrix is called as composite matrix. The process of
combining is called as concatenation.

Suppose we want to perform rotation about an arbitrary point, then we can perform it by the
sequence of three transformations
639
1. Translation
2. Rotation
3. Reverse Translation

The ordering sequence of these numbers of transformations must not be changed. If a matrix is
represented in column form, then the composite transformation is performed by multiplying matrix
in order from right to left side.The output obtained from the previous matrix is multiplied with the
new coming matrix.

Example showing composite transformations:


The enlargement is with respect to center. For this following sequence of transformations will be
performed and all will be combined to a single one
Step1: The object is kept at its position as in fig (a)
Step2: The object is translated so that its center coincides with the origin as in fig(b)
Step3: Scaling of an object by keeping the object at origin is done in fig (c)
Step4: Again translation is done. This second translation is called a reverse translation. It will
position the object at the origin location.
Above transformation can be represented as TV.STV-1

640
Note: Two types of rotations are used for representing matrices one is column

method. Another is the row method.

641
Advantage of composition or concatenation of matrix:
1. It transformations become compact.
2. The number of operations will be reduced.
3. Rules used for defining transformation in form of equations are complex as compared to
matrix.
Composition of two translations:
Let t1 t2 t3 t4are translation vectors. They are two translations P1 and P2. The matrix of P1 and P2
given below. The P1 and P2are represented using Homogeneous matrices and P will be the final
transformation matrix obtainedafter multiplication.
Above resultant matrix show that two successive translations are additive.

Composition of two Rotations: Two Rotations are also additive


Composition of two Scaling: The composition of two scaling is multiplicative. LetS11 and S12are
matrix to be multiplied.

642
Computer Graphics Window to Viewport Co-ordinate Transformation

Once object description has been transmitted to the viewing reference frame, we choose the
window extends in viewing coordinates and selects the viewport limitsin normalized coordinates.
Object descriptions are then transferred to normalized device coordinates:
We do this thing using a transformation that maintains the same relative placement of an object in
normalized space as they had in viewing coordinates.
If a coordinate position is at the center of the viewing window:
It will display at the center of the viewport.

Fig shows the window to viewport mapping. A point at position (xw, yw) inwindow mapped into
position (xv, yv) in the associated viewport.

643
In order to maintain the same relative placement of the point in the viewport asin the window, we
require:

Solving these impressions for the viewport position (xv, yv), we havexv=xvmin+(xw-xwmin)sx
yv=yvmin+(yw-ywmin)sy equation 2
Where scaling factors are

Equation (1) and Equation (2) can also be derived with a set of transformation that converts the
window or world coordinate area into the viewport or screencoordinate area. This conversation is
performed with the following sequence oftransformations:
644
1. Perform a scaling transformation using a fixed point position (xwmin,ywmin) that scales the
window area to the size of the viewport.
2. Translate the scaled window area to the position of the viewport. Relativeproportions of objects
are maintained if the scaling factors are the same (sx=sy).
From normalized coordinates, object descriptions are mapped to the variousdisplay devices.
Any number of output devices can we open in a particular app, and three windows to viewport
transformation can be performed for each open outputdevice.
This mapping called workstation transformation (It is accomplished by selecting awindow area in
normalized space and a viewport area in the coordinates of the display device).
As in fig, workstation transformation to partition a view so that different parts ofnormalized space
can be displayed on various output devices).

Matrix Representation of the above three steps of Transformation:

645
Step1:Translate window to origin 1Tx=-Xwmin Ty=-Ywmin

Step2:Scaling of the window to match its size to the viewportSx=(Xymax-Xvmin)/(Xwmax-Xwmin)


Sy=(Yvmax-Yvmin)/(Ywmax-Ywmin)

Step3:Again translate viewport to its correct position on screen.


Tx=XvminTy=Yvmin
Above three steps can be represented in matrix form:VT=T * S * T1
T = Translate window to the origin S=Scaling of the window to viewport sizeT1=Translating viewport

on screen.

Viewing Transformation= T * S * T1

Advantage of Viewing Transformation:


We can display picture at device or display system according to our need andchoice.

Note:
➢ World coordinate system is selected suits according to the applicationprogram.
➢ Screen coordinate system is chosen according to the need of design.
➢ Viewing transformation is selected as a bridge between the world andscreen coordinate.

Line Clipping:
It is performed by using the line clipping algorithm. The line clipping algorithmsare:
1. Cohen Sutherland Line Clipping Algorithm
2. Midpoint Subdivision Line Clipping Algorithm
3. Liang-Barsky Line Clipping Algorithm

Cohen Sutherland Line Clipping Algorithm:


In the algorithm, first of all, it is detected whether line lies inside the screen or it isoutside the screen.
All lines come under any one of the following categories:
1. Visible
2. Not Visible
646
3. Clipping Case

1. Visible: If a line lies within the window, i.e., both endpoints of the line lieswithin the window. A
line is visible and will be displayed as it is.
2. Not Visible: If a line lies outside the window it will be invisible and rejected. Such lines will not
display. If any one of the following inequalities is satisfied, thenthe line is considered invisible. Let
A (x1,y2) and B (x2,y2) are endpoints of line.
xmin,xmax are coordinates of the window.
ymin,ymax are also coordinates of the window.x1>xmax
x2>xmax y1>ymax
y2>ymax x1<xmin x2<xmin y1<ymin y2<ymin

3. Clipping Case: If the line is neither visible case nor invisible case. It is
considered to be clipped case. First of all, the category of a line is found based on
nine regions given below. All nine regions are assigned codes. Each code is of 4
bits. If both endpoints of the line have end bits zero, then the line is considered to
be visible.

The center area is having the code, 0000, i.e., region 5 is considered a rectangle
window.

Following figure show lines of various types

647
Line AB is the visible case Line OP is an invisible case Line PQ is an invisible line Line IJ are clipping
candidates
Line MN are clipping candidateLine CD are clipping candidate

Advantage of Cohen Sutherland Line Clipping:


1. It calculates end-points very quickly and rejects and accepts lines quickly.
2. It can clip pictures much large than screen size.
Algorithm of Cohen Sutherland Line Clipping: Step1:Calculate positions of both endpoints of the

line Step2:Perform OR operation on both of these end-points

Step3:If the OR operation gives 0000Then


line is considered to be visible
else
Perform AND operation on both endpointsIf And ≠ 0000

then the line is invisibleelse


And=0000
Line is considered the clipped case.

Step4:If a line is clipped case, find an intersection with boundaries of the windowm=(y2-y1 )(x2-x1)
(a) If bit 1 is "1" line intersects with left boundary of rectangle windowy3=y1+m(x-X1)
where X = Xwmin
where Xwminis the minimum value of X co-ordinate of window

(b) If bit 2 is "1" line intersect with right boundaryy3=y1+m(X-X1)


where X = Xwmax
where X more is maximum value of X co-ordinate of the window

648
(c) If bit 3 is "1" line intersects with bottom boundaryX3=X1+(y-y1)/m
where y = ywmin
ywmin is the minimum value of Y co-ordinate of the window

(d) If bit 4 is "1" line intersects with the top boundaryX3=X1+(y-y1)/m


where y = ywmax
ywmax is the maximum value of Y co-ordinate of the window

Example of Cohen-Sutherland Line Clipping Algorithm:


Let R be the rectangular window whose lower left-hand corner is at L (-3, 1) andupper right-hand
corner is at R (2, 6). Find the region codes for the endpoints infig:

The region code for point (x, y) is set according to the scheme Bit 1 = sign (y-ymax)=sign (y-6) Bit 3
= sign (x-xmax)= sign (x-2)Bit 2 = sign (ymin-y)=sign(1-y) Bit 4 = sign (xmin-x)=sign(-3-x)
Here

649
So

A (-4, 2)→ 0001 F (1, 2)→ 0000


B (-1, 7) → 1000 G (1, -2) →0100
C (-1, 5)→ 0000 H (3, 3) → 0100
D (3, 8) → 1010 I (-4, 7) → 1001
E (-2, 3) → 0000 J (-2, 10) → 1000
We place the line segments in their appropriate categories by testing the regioncodes found in the
problem.

Category1 (visible): EF since the region code for both endpoints is 0000.
Category2 (not visible): IJ since (1001) AND (1000) =1000 (which is not 0000).

Category 3 (candidate for clipping): AB since (0001) AND (1000) = 0000, CD since(0000) AND
(1010) =0000, and GH. since (0100) AND (0010) =0000.
The candidates for clipping are AB, CD, and GH.

In clipping AB, the code for A is 0001. To push the 1 to 0, we clip against the
boundary line xmin=-3. The resulting intersection point is I1 (-3,3 ). We clip (do not display) AI1 and I1
B. The code for I1is 1001. The clipping category for I1 B is 3since (0000) AND (1000) is (0000). Now
B is outside the window (i.e., its code is 1000), so we push the 1 to a 0 by clipping against the line
ymax=6. The resulting
intersection is l2 (-1 ,6). Thus I2 B is clipped. The code for I2 is 0000. The remaining segment I1 I2 is
displayed since both endpoints lie in the window (i.e.,their codes are 0000).
For clipping CD, we start with D since it is outside the window. Its code is 1010.We push the first 1
to a 0 by clipping against the line ymax=6. The resulting
intersection I3 is ( ,6),and its code is 0000. Thus I3 D is clipped and the remainingsegment CI3 has
both endpoints coded 0000 and so it is displayed.
For clipping GH, we can start with either G or H since both are outside the window. The code for G
is 0100, and we push the 1 to a 0 by clipping against the
line ymin=1.The resulting intersection point is I4 (2 ,1) and its code is 0010. We clip GI4 and work on
I4 H. Segment I4 H is not displaying since (0010) AND (0010)
=0010.

Polygon:
Polygon is a representation of the surface. It is primitive which is closed in nature.It is formed using
a collection of lines. It is also called as many-sided figure. The lines combined to form polygon are
called sides or edges. The lines are obtained by combining two vertices.

Example of Polygon:
1. Triangle
2. Rectangle
650
3. Hexagon
4. Pentagon

Following figures shows some polygons.

Types of Polygons
1. Concave
2. Convex
A polygon is called convex of line joining any two interior points of the polygon lies inside the
polygon. A non-convex polygon is said to be concave. A concavepolygon has one interior angle
greater than 180°. So that it can be clipped intosimilar polygons.

651
A polygon can be positive or negative oriented. If we visit vertices and vertices
visit produces counterclockwise circuit, then orientation is said to be positive.

652
Polygon Clipping SutherlandHodgmanAlgorithmSutherlandHodgmanAlgorithm
A polygon can also be clipped by specifying the clipping window. Sutherland Hodgeman polygon
clipping algorithm is used for polygon clipping. In this algorithm, all the vertices of the polygon are
clipped against each edge of theclipping window.
First the polygon is clipped against the left edge of the polygon window to get new vertices of the
polygon. These new vertices are used to clip the polygon against right edge, top edge, bottom edge,
of the clipping window as shown in thefollowing figure.

653
While processing an edge of a polygon with clipping window, an intersection
point is found if edge is not completely inside clipping window and the a partial
edge from the intersection point to the outside edge is clipped. The following
figures show left, right, top and bottom edge clippings −

654
Object Representation, Geometric Transformations and Viewing

9. 3D Object Representations

Methods:
➢ Polygon and Quadric surfaces: For simple Euclidean objects
➢ Spline surfaces and construction: For curved surfaces
➢ Procedural methods: Eg. Fractals, Particle systems
➢ Physically based modeling methods
➢ Octree Encoding
➢ Isosurface displays, Volume rendering, etc.

Classification:
Boundary Representations (B-reps) eg. Polygon facets and spline patches Space- partitioning
representations eg. Octree Representation
Objects may also associate with other properties such as mass, volume, so as todetermine their
response to stress and temperature etc.

Polygon Surfaces
Objects are represented as a collection of surfaces. 3D object representation isdivided into two
categories.
• Boundary Representations B−repsB−reps − It describes a 3D object as a setof surfaces that

655
separates the object interior from the environment.
• Space–partitioning representations − It is used to describe interior properties, by partitioning
the spatial region containing an object into a setof small, non-overlapping, contiguous solids
usuallycubesusuallycubes.
The most commonly used boundary representation for a 3D graphics object is a set of surface
polygons that enclose the object interior. Many graphics system usethis method. Set of polygons
are stored for object description. This simplifies and speeds up the surface rendering and display
of object since all surfaces can be described with linear equations.
The polygon surfaces are common in design and solid-modeling applications, since their wireframe
display can be done quickly to give general indication ofsurface structure. Then realistic scenes are
produced by interpolating shadingpatterns across polygon surface to illuminate.

Curved Surfaces
1. Regular curved surfaces can be generated as
- Quadric Surfaces, eg. Sphere, Ellipsoid, or
- Superquadrics, eg. Superellipsoids

656
2. Irregular surfaces can also be generated using some special formulating approach, to forma
kind of blobby objects -- Theshapes showing a certain degree of fluidity.

3. Spline Representations
Spline means a flexible strip used to produce a smooth curve through a designated set of points.
Several small weights are distributed along thelength of the strip to hold it in position on the drafting
table as the curve is drawn.
We can mathematically describe such a curve with a piecewise cubic polynomial function => spline
curves. Then a spline surface can be described with 2 sets of orthogonal spline curves.

Quadric Surfaces
Quadric surfaces are defined by quadratic equations in two dimensional space. Spheres and cones
are examples of quadrics. The quadric surfaces of RenderMan are surfaces of revolution in which
a finite curve in two dimensions is swept in three dimensional space about one axis to create a
surface. A circle centered at the origin forms a sphere. If the circle is not centered at the origin, the
circle sweeps out a torus. A line segment with one end lying on the axis of rotation forms a cone.
A line segment parallel to the axis of rotation forms a cylinder. The generalization of a line segment
creates a hyperboloid by rotating an arbitrary linesegment in three dimensional space about the Z
axis. The axis of rotation is always the z axis. Each quadric routine has a sweep parameter,
specifying the

angular extent to which the quadric is swept about z axis. Sweeping a quadric byless than 360
degrees leaves an open surface.
Quadrics

Many common shapes can be modeled with quadrics. Although it is possible to convert quadrics
to patches, they are defined as primitives because special- purpose rendering programs render
them directly and because their surface parameters are not necessarily preserved if they are
converted to patches.
Quadric primitives are particularly useful in solid and molecular modelingapplications.
All the following quadrics are rotationally symmetric about the z axis. In all thequadrics u and v are
assumed to run from 0 to 1. These primitives all define
a bounded region on a quadric surface. It is not possible to define
infinite quadrics. Note that each quadric is defined relative to the origin of the object coordinate
657
system. To position them at another point or with their symmetry axis in another direction requires
the use a modeling transformation.
The geometric normal to the surface points ``outward'' from the z-axis, if
the current orientation matches the orientation of the current transformation and"inward" if they
don't match. The sense of a quadric can be reversed by giving negative parameters. For example,
giving a negative thetamax parameter in any of the following definitions will turn the quadric inside-
out.
Each quadric has a parameterlist. This is a list of token-array pairs where each token is one of the
standard geometric primitive variables or a variable which has been defined with RiDeclare.
Position variables should not be given with quadrics.All angular arguments to these functions are
given in degrees. The trigonometric functions used in their definitions are assumed to also accept
angles in degrees.
RiSphere( radius, zmin, zmax, thetamax, parameterlist )

RtFloat radius;
RtFloat zmin, zmax;

RtFloat thetamax;
Requests a sphere defined by the following equations:

658
Note that if zmin > -radius or zmax < radius, the bottom or top of the sphere is
open, and that if thetamax is not equal to 360 degrees, the sides are also open.

RIB BINDING

Sphere radius zmin zmax thetamax parameterlist

Sphere [radius zmin zmax thetamax] parameterlist

EXAMPLE

RiSphere(0.5, 0.0, 0.5, 360.0, RI_NULL);

RiCone( height, radius, thetamax, parameterlist )


RtFloat height;
RtFloat radius;

RtFloat thetamax;

Requests a cone defined by the following equations:

Note that the bottom of the cone is open, and if thetamax is not equal to 360degrees, the sides are
open.
RIB BINDING

Cone height radius thetamax parameterlist


Cone [height radius thetamax] parameterlistEXAMPLE

RtColor four_colors[4];

RiCone(0.5, 0.5, 270.0, "Cs", (RtPointer)four_colors, RI_NULL);

RiCylinder( radius, zmin, zmax, thetamax, parameterlist )


RtFloat radius;

RtFloat zmin, zmax;


RtFloat thetamax;

Requests a cylinder defined by the following equations:

Note that the cylinder is open at the top and bottom, and if thetamax is not equalto 360 degrees,
the sides also are open.

RIB BINDING
Cylinder radius zmin zmax thetamax parameterlist

Cylinder [radius zmin zmax thetamax] parameterlist


Bezier Curves
659
Bezier curve is discovered by the French engineer Pierre Bézier. These curves canbe generated
under the control of other points. Approximate tangents by using control points are used to
generate curve. The Bezier curve can be represented mathematically as −

Where pipi is the set of points and Bni(t)Bin(t) represents the Bernsteinpolynomials which are given
by −

Where n is the polynomial degree, i is the index, and t is the variable.


The simplest Bézier curve is the straight line from the point P0P0 to P1P1. A quadratic Bezier curve
is determined by three control points. A cubic Bezier curveis determined by four control points.

Properties of Bezier Curves


Bezier curves have the following properties −

• They generally follow the shape of the control polygon, which consists ofthe segments joining
the control points.
• They always pass through the first and last control points.
• They are contained in the convex hull of their defining control points.
• The degree of the polynomial defining the curve segment is one less that the number of
defining polygon point. Therefore, for 4 control points, thedegree of the polynomial is 3, i.e.
cubic polynomial.
• A Bezier curve generally follows the shape of the defining polygon.
• The direction of the tangent vector at the end points is same as that of thevector determined
by first and last segments.
• The convex hull property for a Bezier curve ensures that the polynomialsmoothly follows the
control points.

660
• No straight line intersects a Bezier curve more times than it intersects itscontrol polygon.
• They are invariant under an affine transformation.

• Bezier curves exhibit global control means moving a control point alters theshape of the whole
curve.
• A given Bezier curve can be subdivided at a point t=t0 into two Bezier segments which join
together at the point corresponding to the parametervalue t=t0.

B-Spline Curves
The Bezier-curve produced by the Bernstein basis function has limited flexibility.

• First, the number of specified polygon vertices fixes the order of theresulting polynomial which
defines the curve.
• The second limiting characteristic is that the value of the blending functionis nonzero for all
parameter values over the entire curve.
The B-spline basis contains the Bernstein basis as the special case. The B-splinebasis is non-
global.
A B-spline curve is defined as a linear combination of control points Pi and B-spline basis
function Ni,Ni, k tt given by

Where,

661
Properties of B-spline Curve
B-spline curves have the following properties −

• The sum of the B-spline basis functions for any parameter value is 1.
• Each basis function is positive or zero for all parameter values.
• Each basis function has precisely one maximum value, except for k=1.
• The maximum order of the curve is equal to the number of vertices ofdefining polygon.
• The degree of B-spline polynomial is independent on the number ofvertices of defining polygon.
• B-spline allows the local control over the curve surface because each vertexaffects the shape
of a curve only over a range of parameter values where itsassociated basis function is nonzero.
• The curve exhibits the variation diminishing property.
• The curve generally follows the shape of defining polygon.
• Any affine transformation can be applied to the curve by applying it to thevertices of defining
polygon.
• The curve line within the convex hull of its defining polygon.

Bezier and B-spline SurfacesBezier Surfaces.

Like the Bezier curves, the Bezier surfaces use the Bernstein polynomials as blending functions.
We now have the control points being points on a design net,which is again a rectangular mesh
spread over area of interest. The x and y coordinates of the control points are fixed and the shape
of the surface varies as the control points are moved up or down. The figure below shows a Bezier
surface with an associated control net of 3 points by 4 points. The values of the points are stored
in an array B(4,3) and the blending functions are obtained fromthe equations of the Bezier curves.

662
Bezier Surface and Control Net
Thus, the three point Bezier curve is given by :

B(v) = (1-v)2B(I,1) + 2v(1-v)B(I,2) + v2B(I,3)

or
B(v) = b(20)(v) B(I,1) + b(21)(v) B(I,2) + b(22)(v) B(I,3)

and the 4-point Bezier curve needed in the u-direction has the form: B(u) = (1-u)3B(1,J) + 3u(1-

u)2B(2,J) + 3u2(1-u)B(3,J) + u3B(4,J)

or B(u) = b{30}(u)B(1,J) + b{31}(u) B(2,J) + b{32}(u) B(3,J) + b{33}(u) B(4,J)


These must be combined together in the matrix equation to calculate any pointon the surface. The
equation of a point on the Bezier surface is given by:
r(u,v) = [b{30}(u) b{31}(u) b{32}(u) b{33}(u)] B(1,1)B(1,2) B(1,3) b{20}(v)
B(2,1) B(2,2) B(2,3) b{21}(v)

B(3,1) B(3,2) B(3,3) b{22}(v)B(4,1) B(4,2) B(4,3)

To obtain the equation of one of the edge-curves, e.g. when u=0, we mustsubstitute in the matrix
equation:

r(0,v) = B(1,1) B(1,2) B(1,3) (1-v)(1-v)


2v(1-v)

v*v
which becomes r(0,v) = (1-v)(1-v)B(1,1) + 2v(1-v)B(1,2) + v*vB(1,3) and similarly for the other edge
curves. This form of the Bezier curve assumes a rectangular mesh with m+1 points in the one
direction and n+1 points in the other. It requiresthe edge curves defining the patches to be coplanar
and does not provide local control within a patch. A surface may be made up of several Bezier
patches and, as for the curves, if we require the tangents to be continuous across the joins, then
the sets of control points across the curves must be not only coplanar but also collinear.
The Proceedings of the Royal Society, Series A, for February 1971 contained the papers from a
meeting on `Computer Aids in Mechanical Engineering Design'. Thisincluded a paper by Bezier on
his `Unisurf' package used by the Renault car company to design their car bodies. Although it is not
obvious from the paper, this was the earliest use of Bezier surfaces, which were invented for this
package. Another paper described the `Multiobject' package by Armit, which used the same
equations. The paper by Sabin, discribing the `Numerical Master Geometry' in use at the British
Aircraft Corporation, shows the extensive use of Bicubic Surface tiles in their work because they
are particularly concerned to get the extrasmoothness of functions which can only be guaranteed
by bicubic or higher-orderpatches.
This volume of the proceedings gives an interesting insight into the way that these packages were
viewed at the time. In some respects, things have changed little since then. They describe a
situation where many users had their own two orthree C.A.D. programs to use, and there was very
663
little guidance on the best choice for a newcomer to the field. Nowadays, there is a bewildering
variety of large and comprehensive packages for C.A.D. but the newcomer still has little

guidance amongst an even larger choice of software. Unfortunately the cost of amistake is very
much larger, since these packages are now big business.
B-Spline Surfaces.

The use of B-Spline surfaces is necessary in some CAD applications to give localcontrol of the
shape. The equation of this surface is given by
Q(u,v) = sum{i=0 to m} sum{j=0 to n} B(i+1,j+1) N{i,k}(u) M{j,l}(v) In the x-direction, x(i) are the

elements of the k-knot vector and

N{i,1}(u) = 1 if x(i) <= u <= x(i+1)


= 0 otherwise

and
N{i.k}(u) = (u-x(i)) * N{i,k-1}(u) + (x(i+k)-u) * N{i+1,k-1}(u)

(x(i+k-1)-x(i)) (x(i+k)-x(i+1))

In the y-direction, the y(j) are elements of the l-knot vector and we have similarexpressions for
M{j,1}(v) and M{j,l}(v).
This simple version of the B-Spline expects a rectangular net and requires all polygons in the one-
direction to have the same degree of multiplicity (i.e. to use one knot-vector for all lines across the
net). We can obtain greater flexibility by relaxing these conditions, but at the expense of greater
complexity. These curvesare widely used in many CAD packages.

Illumination model
Illumination model, also known as Shading model or Lightning model, is used to calculate the
intensity of light that is reflected at a given point on surface. Thereare three factors on which
lightning effect depends on:
1. Light Source :
Light source is the light emitting source. There are three types of lightsources:
1. Point Sources – The source that emit rays in all directions (A bulb in aroom).
2. Parallel Sources – Can be considered as a point source which is farfrom the surface (The sun).
3. Distributed Sources – Rays originate from a finite area (A tubelight).

Their position, electromagnetic spectrum and shape determine the lightningeffect.


2. Surface :
When light falls on a surface part of it is reflected and part of it is absorbed.Now the surface
structure decides the amount of reflection and absorptionof light. The position of the surface
and positions of all the nearby surfaces also determine the lightning effect.
3. Observer :
The observer’s position and sensor spectrum sensitivities also affect thelightning effect.
664
1. Ambient Illumination :
Assume We are standing on a road, facing a building with glass exterior and sun rays are falling
on that building reflecting back fromit and the falling on the object under observation. This
would
be Ambient Illumination. In simple words, Ambient Illumination isthe one where source of light
is indirect.

The reflected intensity Iamb of any point on the surface is:

2. Diffuse Reflection :
Diffuse reflection occurs on the surfaces which are rough or grainy. In this reflection the
brightness of a point depends upon the angle made by the lightsource and the surface.

The reflected intensity Idiff of a point on the surface is:

665
3. Specular Reflection :
When light falls on any shiny or glossy surface most of it is reflected back, suchreflection is
known as Specular Reflection.
Phong Model is an empirical model for Specular Reflection which provides us withthe formula
for calculation the reflected intensity Ispec:

Polygen Rending Methods

666
Image of Flow Chart of polygen rending methods

Gouraud shading
This Intensity-Interpolation scheme, developed by Gouraud and usually referred to as Gouraud
Shading, renders a polygon surface by linear interpolating intensity value across the surface.
Intensity values for each polygon are coordinate with the value of adjacent polygons along the
common edges, thus eliminating the intensity discontinuities that can occur in flat shading.
Each polygon surface is rendered with Gouraud Shading by performing thefollowing calculations:
1. Determining the average unit normal vector at each polygon vertex.
2. Apply an illumination model to each vertex to determine the vertexintensity.
3. Linear interpolate the vertex intensities over the surface of the polygon.

At each polygon vertex, we obtain a normal vector by averaging the surfacenormals of all polygons
staring that vertex as shown in fig:

Thus, for any vertex position V, we acquire the unit vertex normal
with the
calculation

Once we have the vertex normals, we can determine the intensity at the
vertices
from a lighting model.

Following figures demonstrate the next step: Interpolating intensities


667
along the polygon edges. For each scan line, the intensities at the
intersection of the scan line with a polygon edge are linearly
obtaining the intensities at point 4 is to interpolate between intensities I1 and I2 using only the
vertical displacement of the scan line.

Similarly, the intensity at the right intersection of this scan line (point 5) is interpolated from the
intensity values at vertices 2 and 3. Once these bounding intensities are established for a scan line,
an interior point (such as point P in theprevious fig) is interpolated from the bounding intensities at
point 4 and 5 as

668
Incremental calculations are used to obtain successive edge intensity values between scan lines
and to obtain successive intensities along a scan line as shownin fig:

If the intensity at edge position (x, y) is interpolated as

Then we can obtain the intensity along this edge for the next scan line, Y-1 as

Similar calculations are used to obtain intensities at successive horizontal pixel


positions along each scan line.

When surfaces are to be rendered in color, the intensities of each color

component is calculated at the vertices. Gouraud Shading can be connected witha hidden-surface
algorithm to fill in the visible polygons along each scan-line. An example of an object-shaded with
the Gouraud method appears in the followingfigure:

669
Gouraud Shading discards the intensity discontinuities associated with the constant-shading
model, but it has some other deficiencies. Highlights on the surface are sometimes displayed with
anomalous shapes, and the linear intensity interpolation can cause bright or dark intensity streaks,
called Match bands, to appear on the surface. These effects can be decreased by dividing the
surface intoa higher number of polygon faces or by using other methods, such as Phong shading,
that requires more calculations.

Viewing-Pipeline
The viewing-pipeline in 3 dimensions is almost the same as the 2D-viewing- pipeline. Only after the
definition of the viewing direction and orientation (i.e., ofthe camera) an additional projection step
is done, which is the reduction of 3D- data onto a projection plane:

670
This projection step can be arbitrarily complex, depending on which 3D-viewingconcepts should be
used.

Viewing-Coordinates
Similar to photography there are certain degrees of freedom when specifying thecamera:
1. Camera position in space
2. Viewing direction from this position
3. Orientation of the camera (view-up vector)
4. Size of the display window (corresponds to the focal length of a photo-camera)
With these parameters the camera-coordinate system is defined (viewingcoordinates). Usually the
xy-plane of
this viewing-coordinate system is orthogonal to the main viewing direction andthe viewing direction
is in the direction of the negative z-axis.
Based on the camera position the usual way to define the viewing-coordinatesystem is:

In animations the camera-definition is often automatically calculated according to certain


conditions, e.g. when the camera moves around an object or in flight- simulations, such that desired
effects can be achieved in an uncomplicated way.
To convert world-coordinates to viewing-coordinates a series of simple transformations is needed:
mainly a translation of the coordinate origins onto each other and afterwards 3 rotations, such that
the coordinate-axes also coincide (two rotations for the first axis, one for the second axis, and the
third axisis already correct then). Of course, all these
transformations can be merged by multiplication into one matrix, which looksabout like this:

MWC,VC = Rz· Ry· Rx· T


Projection
It is the process of converting a 3D object into a 2D object. It is also defined as mapping or
transformation of the object in projection plane or view plane. Theview plane is displayed surface.

671
1. Choose a camera position (also called eye-point, or view-point).

2. Choose a viewing direction = Choose the z– direction of the viewing-


coordinates.

3. Choose a direction „upwards“. From this, the x-axis and y-axis can be
calculated: the image-plane is orthogonal to the viewing direction. The parallel
projection of the „view-up vector“ onto this image plane defines the y-axis of
the viewing coordinates.

4. Calculate the x-axis as vector-product of the z- and y-axis.

5. The distance of the image-plane from the eye-point defines the viewing angle,
which is the size of the scene to be displayed.

672
Perspective Projection
In perspective projection farther away object from the viewer, small it appears. This property of
projection gives an idea about depth. The artist use perspective projection from drawing three-
dimensional scenes.

Two main characteristics of perspective are vanishing points and perspective foreshortening. Due
to foreshortening object and lengths appear smaller from thecenter of projection. More we increase

673
the distance from the center of projection,smaller will be the object appear.

Vanishing Point
It is the point where all lines will appear to meet. There can be one point, twopoint, and three point
perspectives.
One Point: There is only one vanishing point as shown in fig (a)
Two Points: There are two vanishing points. One is the x-direction and other inthe y -direction as
shown in fig (b)

Three Points: There are three vanishing points. One is x second in y and third intwo directions.
In Perspective projection lines of projection do not remain parallel. The lines converge at a single
point called a center of projection. The projected image on the screen is obtained by points of
intersection of converging lines with the planeof the screen. The image on the screen is seen as of
viewer's eye were located at the centre of projection, lines of projection would correspond to path
travel by light beam originating from object.

Important terms related to perspective


1. View plane: It is an area of world coordinate system which is projected intoviewing plane.
2. Center of Projection: It is the location of the eye on which projected lightrays converge.
3. Projectors: It is also called a projection vector. These are rays start from theobject scene and
are used to create an image of the object on viewing or view plane.

Anomalies in Perspective Projection


It introduces several anomalies due to these object shape and appearance getsaffected.
1. Perspective foreshortening: The size of the object will be small of itsdistance from the center

674
of projection increases.
2. Vanishing Point: All lines appear to meet at some point in the view plane.
3. Distortion of Lines: A range lies in front of the viewer to back of viewer isappearing to six
rollers.

Foreshortening of the z-axis in fig (a) produces one vanishing point, P1. Foreshortening the x and z-
axis results in two vanishing points in fig (b). Adding ay-axis foreshortening in fig (c) adds vanishing
point along the negative y-axis.

Parallel Projection
Parallel Projection use to display picture in its true shape and size. When projectors are
perpendicular to view plane then is called orthographic projection.

The parallel projection is formed by extending parallel lines from each vertex on the object until
they intersect the plane of the screen. The point of intersection isthe projection of vertex.
Parallel projections are used by architects and engineers for creating working drawing of the object,
675
for complete representations require two or more views ofan object using different planes.

1. Isometric Projection: All projectors make equal angles generally angle is of30°.
2. Dimetric: In these two projectors have equal angles. With respect to twoprinciple axis.
3. Trimetric: The direction of projection makes unequal angle with theirprinciple axis.
4. Cavalier: All lines perpendicular to the projection plane are projected withno change in length.

676
5. Cabinet: All lines perpendicular to the projection plane are projected toone
half of their length. These give a realistic appearance of object.

677
678
679
Frames of Reference
Computers will do exactly what We tell them to do. The question is about understanding what do
we actually want to do and explaining that to a computerwith enough rigor. For example we might
want the computer to render a square,but this sentence is way too abstract for the computer to
understand. More rigorous way to think about this is that we want lines between pairs of
vertices (1,1), (−1,1), (−1,−1) and (1,−1), that are represented in the world space,to be drawn in a
400×300 area of the screen so that there is a linear mapping:

680
[−4,4]×[−3,3]→[0,400]×[0,300].
This will already specify which pixels to color for our vertices. For example the vertex (1,1)(1,1)
would be drawn on the pixel located at coordinates (250,200).Here We might notice a couple of
problematic things:
➢ Our geometry will be mirrored in the y direction, because in our worldspace y will point up, but
in the screen space, y will point down.
➢ We are mapping from 2D to 2D. How to do it from 3D to 2D? What if weare not looking from
the positive z direction?
On the other hand we might notice that with this kind of mapping our scene would always show the
same amount of the scene if the resolutionschanges. Although we might want to change that also.
There are actually many frames of references and transformations between ourvertices and what
we see on the screen. look at them one at a time.

World Space

First, our vertices are usually defined in the object space. We will try to center ourobject around
some object origin (Object) that will serve as the scaling and rotation fixed point. Our object is
located somewhere in the world space though, so we will use modelling transformations to
represent the vertices with world space coordinates. Imagine if there are multiple triangles, they
can not all be located in the world space origin, they are probably scattered all around the world
space, and thus each have distinct world space coordinates. Although they might have the same
object space (local) coordinates.

Camera Space

681
Secondly, there is a camera somewhere in the world space. This camera has its own coordinates
in the world space and is transformed just like any other object /vertex. Our goal here is to position
everything into camera space so that camera and world frames match. In other words, transform
everything so that camera willbe located at the world origin and the axes will be aligned.
Usually there is a function called lookAt(), where We can say where in the world is our camera
located, which is the up direction and to what point is it pointed (is looking) at. This is a convenience
function that underneath will construct the corresponding matrix that will do the camera
transformation in this step. see, how this can be done.
We know:

➢ Camera's position in world space. Call it pp.


➢ Camera's up-vector. Call it uu.
➢ Camera's looking direction. Call it ll.

Well, the first step would be to align the origins. So we want to move all ourobjects so that the
camera would be in the world origin. We had a
translation pp that moved camera away from the origin, so the reverse would bejust −p.

So the first transformations would be:

Next we need to align the axes. Now, the vector ll shows the direction we are facing, but because
the z-axis should be in the negative direction, we will reverse it: w=−l. We assume that vectors uu
and ww are orthogonal to each other and of unit length. We still need one orthogonal vector, the
right vector, in order to have

the camera basis. We could use the Gram-Schmidt process here, but a more simpler way to find an
orthogonal unit vector, given already two, would be to usethe cross product of vectors. So v=w×u.
Notice that the cross product is not commutative and will follow the right-hand rule. The vector vv
will emerge
from the plane defined by ww and uu in the direction where the angle
from w to u will be counter-clockwise. If We exchange ww and uu in the crossproduct, then the
result will point to the opposite direction.
Now we have the vectors u, v and w that are the basis of the camera's frame ofreference. The
transformation that would transform the camera basis from the world basis (ignoring the
translation for now) would be:

682
Remember that we can look at the columns of the matrix to determine how the basis would
transform. But that would be the transformation which would transform the camera space
(coordinates) to the world space. We need to find a transformation to get from world space to
camera space. Or in other words, transform the camera basis to be the current world space basis.
We might remember from algebra that the inverse of an orthogonal matrix is the transposeof it. All
rotation matrices are orthogonal matrices and a multiplication of two rotation matrices is a rotation
matrix. Our camera basis will differ from the worldbasis only by a number of rotations. So in order
to find out how to transform the world so that the camera basis would be aligned with the world
basis, we only need to take the inverse of those rotation. That is the inverse of the matrix we just
found. The inverse is currently just the transpose of it.

The total view transformation would be then:

In some sources the view transformation is called the inverse of the camera transformation. There
the camera transformation is the transformation that transforms the actual camera as an object.
In other sources the camera transformation is the transformation that transforms all the vertices
into the camera space. One should explain what is actually meant when using those terms.The term
view transformation (the view matrix) is generally more common.

Clip Space
Third step is to construct the clip space. This is the space that should be seen fromthe camera. In
our illustration here there is a 2D projection of it. In 3D We will also have a top and a bottom plane.
683
Based on the transformation We might have to specify those plains directly or, as is the case with
perspective projection, We can specify a field of view parameter that will calculate those itself.
Everything outside this clip space is clipped, i.e. ignored in rendering. It might depend on what kind
of clipping techniques are in use. For example if a line crosses the clip space, then it might be
segmented: another vertex is created at the border of the clip space. Objects that are wholly outside
of the clip space, areignored. This is one place where we want to be able to determine the rough
locations of our objects quickly. Later we will see different methods (e.g. binary space partitioning,
bounding volume hierarchy) that help to determine that.
Mathematically We can think that the equations of the planes are constructed and intersections
with other planes (ones defined by all of the triangles in the scene) are checked for. Of course, if
we are only interested about vertices, thenwe can put every vertex in the plane equation and see
which side of the plane avertex lies.
We will look this and the next step in more detail when talking about differentprojections.

Canonical View Volume

Fourth step is to transform everything so that the clip space will form a canonicalview volume. This
canonical view volume is a cube in the
coordinates [−1,1]×[−1,1]×[−1,1]. As we can see from the previous illustration wehad kind of a weird
shape for the clip space. This shape is a frustum of a pyramid in the case of perspective projection.
In computer graphics we call it the view frustum. Transforming that into a cube will transform the
whole space in a very affecting way. This is the part where we leave the world of affine
transformationsand perform a perspective projection transformation. It is actually quite simple, we
will just put a non-zero value in the third column of the last row of our transformation matrix. As we
remember, affine transformations needed the last row to be (0,0,0,1), but for perspective
transformation we will have (0,0,p,0).
Depending on how an API is implemented, we might have p=1 or p=−1 or evensomething else. After
this transformation, there is a need for the perspective division, because the value of w will usually

684
no longer be 1. Remember that in homogeneous coordinates (x,y,z,w)=(x/w,y/w,z/w).
As We can see, coordinates will be divided based on the value of w, which will depend on the value
of z. This actually causes the objects further away to be projected smaller then objects that are
closer to the camera - the same way wesee the world.

Screen Space

Final step is to project the canonical view volume into screen space. Our screen has usually
mapped the coordinates of pixels so that (0,0)(0,0) is in the top-left corner and positive directions
are to the right and down. Depending on the actually screen resolution (or window / viewport size
if we are not rendering full-screen), we will have to map the canonical view volume coordinates to
different ranges. In either way, this will just be a linear mapping from the
ranges [−1,1]×[−1,1]→[0,width]×[0,height] like we saw in the beginning.
This mapping is called the viewport transformation and the matrix that does it is quite simple. This
step is usually done automatically. For the proportional linear mapping from one range into another
we just need to scale the initial range to beof the same length as the final range, and then translate
it so that they cover eachother.
685
Notice that the z value is brought along here. This is useful in order to later determine which objects
are in front of other objects. Also the y values still seemto be reversed. This will be handled later by
OpenGL, currently we just assume that the (0,0) in the screen space is at the bottom-left corner and
the positive directions are up and right. Also the z value will later be normalized to a
range [0,1].

1) What is the 16-bit compiler allowable range for integer constants?


a) -3.4e38 to 3.4e38
b) -32767 to 32768
c) -32668 to 32667
d) -32768 to 32767
Answer: (d) -32768 to 32767
Explanation: In a 16-bit C compiler, we have 2 bytes to store the value.
• The range for signed integers is -32768 to 32767.
• The range for unsigned integers is 0to 65535.
• The range for unsigned character is 0 to 255.

2) Study the following program:


1. main()
2. {printf("javatpoint");
3. main();}
What will be the output of this program?
a. Wrong statement
b. It will keep on printing javatpoint
c. It will Print javatpoint once
d. None of the these
Answer: (b) It will keep on printing javatpoint
Explanation: In this program, the main function will call itself again and again. Therefore, it will
continue to print javatpoint.

3) What is required in each C program?


a. The program must have at least one function.
b. The program does not require any function.
c. Input data
d. Output data
Answer: (a) The program must have at least one function.
Explanation: Any C program has at least one function, and even the most trivial programs can
specify additional functions. A function is a piece of code. In other words, it works like a sub-
program.

4) What will this program print?


1. main() 2. {
3. int i = 2;

686

You might also like