3. Programming Languages and Computer
3. Programming Languages and Computer
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
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.
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:
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.
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.
n1=n-1,
sum (n1,
r1),r=r1+n
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.
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.
// outputs. #include<iostream>
class Base
public:
};
public:
};
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.
public:
};
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!
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 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
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.
Attribute of a variable:
example of variable in "ALGOL Language"y:=9;
434
We can say that it has four attributes
2) The name of description of a current content.i.e. 9 we can also say that square of 3.
The name of the box and its storage location are fixed, but the contents and itname may vary
over time.
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:
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.
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
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.
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.
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.
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.
Floating-point real numbers Fixed-point real numbers Other Data Types - Complex numbers
Rational numbers Enumerations Booleans Characters
Integers Specification Maximal and minimal valuesOperations:
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
Implementation
Mantissa - exponent model. Example: 10.5 = 0.105 x 102,Mantissa: 105, Exponent: 2
Implementation:
Directly supported by hardware or simulated by software
Rational numbers: the quotient of two integers. Enumerations: Ordered list of different values
Booleans
Characters
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.
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
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.
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)
• Relational operations
• Assignment and
• To test character for- Letter, Digit, Special Character
In C Character is declared
444
Composite Data Types
Unbounded length: storage allocation at run time. String can be any length
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
•
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.
Characteristics:
• Usually resideon secondary storage devicesas disks, tapes.
• Lifetime is greater than the lifetime of the program that hascreated the files.
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.
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
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 */
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.
do if static while
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.
• 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.
449
Keyword Identifier
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’};
// declaration of 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
452
signed short 2 byte −32,768 to 32,767
float 4 byte
double 8 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:
• #include<conio.h>main()
• {
• int i, marks[10], sum=0;float avg;
sum=sum+marks[i]; avg=sum/10.0;
printf(“Average is %f”,avg);
getch();
}Explanation:
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>
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++)
for(j=0;j<3;j++)
printf("%d ",c[i][j]);printf("\n");
}
getch();
}
Explanation:
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
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];
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.
460
struct Student
char name[25];
int age;
char branch[10];
char gender;
};
struct Student
char name[25];
int age;
char branch[10];
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However, this approach is not much
recommended.
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];
char gender;
};
int main()
/*
*/
s1.age = 18;
/*
*/
462
strcpy(s1.name, "Viraaj");
/*
*/
return 0;
}
Name of Student 1: ViraajAge of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized atcompile time.
or,
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()
int dummy;
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
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
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;
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
return 0;
}
Output:
Enter Rollno:1
Enter Name:Sonoo Enter Rollno:2 Enter Name:Ratan Enter Rollno:3 Enter Name:Vimal
466
Student Information List:Rollno:1, Name:Sonoo Rollno:2, Name:Ratan Rollno:3,
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];
};
printf("Printing the employee information.........\n");
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];
}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;
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
#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( )
470
e1.id=101;
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
return 0;
char name[20];
};
void main ()
display(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;};
show(std);
#include<stdio.h>
struct Student
char name[10];
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.
473
union test
int a;
float b;
char c;
}t;
t.b;
t.c;
#include <stdio.h>
union item
int a;
float b;
char ch;
};
int main( )
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.
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,
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 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,
476
#include <stdio.h>
int main() {
char name[10];
int age;
Output:
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];
gets(full_name);
return 0;
Output:
#include <stdio.h>
int main() {
char name[10];
return 0;}
Output:
478
Enter your name plz: Carlos
My name is Carlos
• 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);
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:
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];
return 0;}
Function Purpose
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.
int val;
//string comparison
else{
//string concatenation
//string length
string:%d",strlen(string2));
//string copy
return 0;}
481
Strings are not equal
Output:
return 0;}
Output:
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.
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).
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
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 */
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.
int main()
{
int a=10; //variable declaration
Serves 2 purpose
* • Declaration of a pointer
• Returns the value of thereferenced
variable
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
{
}
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
of program below
• #include <stdio.h>
487
The address of var = 4202496
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:
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
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;
#include <stdio.h>
int main()
{
printf("\n%x",*p); //printing array elements
p++; //incrementing to the next element, you can also write p=p+1
return 0;
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.
p=str;
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
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(){
int i ;
return 0;}
Output:
iron
copper
gold
Advantages of Pointers
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.
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
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
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.
2. It makes our code reusable. We just have to call the function by its name to
use it, wherever required.
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 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,...)
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.
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.
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.
greatNum();{
// function call
499
return 0;
void greatNum()
// function definition
int i, j;
if(i > j) {
}
else {
}}
if(i > j) {
greaterNum = i;
else {
greaterNum = j;
return greaterNum;
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.
return 0;
if(x > y) {
else {
#include<stdio.h>
int main()
int i, j, result;
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.
return 0;
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()
function2();
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
503
#include<stdio.h>
void main()
int a, b;
printf("Enter a number...");
scanf("%d", &a);
printf("%d", b);
int r = 1;
if(x == 1)
return 1;
else
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
505
8 fputw() writes an integer to file
• The mode in which the file is to be opened. It is a string.We can use one of the
Mode Description
506
rb+ opens a binary file in read and write mode
Output
#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) ;
}
#include; void main( )
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 );
508
C fputs() and fgets()
C fseek()
C fseek() example
Example:
#include <stdio.h>
main(){
FILE *fp;
fclose(fp);//closing file
FILE *fptr;
509
int id;
char name[30];
float salary;
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
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.
FILE *fp;
fclose(fp);
}
Output:
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);
fclose(fptr);
Output:
Enter the id
sonoo
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
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>
}
else{
}
Example
the example of command line arguments where we are passing one argumentwith file
name.
./program hello
program.exe hello
Output:
Output:
512
Program name is: program
Output:
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 −
#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
#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.
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.
#include <stdio.h>
int main() {
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>
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
−
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>
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;
}
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>
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
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.
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.
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:
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.
int a;
int A;
cin>>A;
return 0;
}
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 use both lowercase and uppercaseletters. It uses only lowercase letters.
The starting letter of identifiers can belowercase, It can be started only with thelowercase
uppercase or underscore. letter.
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';
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;
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.
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.
527
short int 2 byte -32,768 to 32,767
float 4 byte
double 8 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).
529
Shift << >> Left to right
Simple if statement
The general form of a simple if statement is,
if(expression)
statement-inside;
statement-outside;
if (x > 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) {
else
else
{
532
if( b> c)
else
{
}}
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;
else if(a%5==0)
{
else
If We enter value 40 for the variable a, then the output will be:
534
Output
Points to Remember
int a = 5;
if(a > 4)
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)
Output
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:
//code to be executed
j++;
int main()
func();
func();
func();
i= 1 and j= 1
i= 2 and j= 1
537
i= 3 and j= 1
Understand call by value and call by reference in C++ language one by one.
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()
cout << "Value of the data is: " << data<< endl;
return 0;
538
void change(int data)
Output:
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()
of y is: "<<y<<endl;
return 0;
Output:
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
541
{
int x=5;
public:
void display()
};
class B: public A
int y = 10;
public:
void display()
};
int main()
A *a;
B b;
a = &b;
a- >display();
return 0;
542
Output:
Value of x is: 5
};
int main()
}
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.
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.
Where,
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.
Where 'A' is the base class, and 'B' is the derived class.
public:
};
public:
};
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;
};
public:
d1.bark();
return 0;
}
Output: Eating...
Barking...
public:
void bark(){
548
cout<<"Barking..."<<endl;
#include <iostream>
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
};
};
public:
void weep() {
cout<<"Weeping...";
}
549
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Output:
Eating...
Barking...
Weeping...
Multiple inheritance is the process of deriving a new class that inherits theattributes from two or
more classes.
{
// Body of the class;
550
void view()
An ambiguity can also occur in single inheritance.
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.
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.
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.
public:
Employee()
};
int main(void)
return 0;
Output:
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.
{
public:
Employee()
cout<<"Constructor Invoked"<<endl;
555
~Employee()
cout<<"Destructor Invoked"<<endl;
};
int main(void)
return 0;
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
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>
class printData {
public:
void print(int i) {
void print(double f) {
void print(char* 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.
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
558
Sr.No Operators & Example
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’.
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)
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for doublecout <<
}
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 ) {
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 ) {
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(...) {
562
Here is the small description of each exception mentioned in the above hierarchy
−
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.
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.
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.
567
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
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).
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.
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.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This is a heading</h1>
</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
<!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
<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.
571
<html>
<head>
</head>
<body>
</body>
</html>
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).
➢ 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
576
HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markuplanguage)
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.
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.
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.
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.
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:
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
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.
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:
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:
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.
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:
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 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:
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
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>
#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.
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.
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);
599
Procedure fill (x, y, color, color1: integer)
int c;
if (c!=color) (c!=color1)
600
Now, consider the coordinates of the point halfway between pixel T and pixel S This is called
We have yi+1=yi
If pixel S is choosen ⟹Pi≥0
We have yi+1=yi-1
We can put ≅1
601
∴r is an integerSo, P1=1-r
Algorithm:
Step3: End
#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:
};
602
void main ()
bresen b;
b.get ();
b.cal ();
getch ();
cin>>a>>b;
cout<<"ENTER r";
cin>>r;
getch ();
x=0;
y=r;
p=5/4)-r;
while (x<=y)
If (p<0)
p+= (4*x)+6;
else
p+=(2*(x-y))+5;
y--;
604
x++;
}
}
Output:
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
To chooses the next one between the bottom pixel S and top pixel T.
If S is chosen
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>
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;
Output:
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- )
If pi>0, the midpoint is outside or on the curve and we choose pixel S.Decision parameter for the
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]
qj=f(xj+ ,yj-1)
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)
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:
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--;
{
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.
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.
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
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
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.
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.
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.
621
Step2: Rotation of (x, y) about the origin
622
Example1: Prove that 2D rotations about the origin are commutative i.e.R1 R2=R2 R1.
Example2: Rotate a line CD whose endpoints are (3, 4) and (12, 15) about originthrough a 45°
anticlockwise direction.
623
624
Example3: Rotate line AB whose endpoints are A (2, 5) and B (6, 12) about originthrough a 30°
clockwise direction.
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:
626
Reflection about the y-axis
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
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 plot1();
};
void arc::get ()
p [2] [i] = 1;
633
}
p1 [i] [j]=0;
x1 [i]=p1[0] [i];
int gd = DETECT,gm;
/* an error occurred */
if (errorcode ! = grOK)
{
634
printf ("Graphics error: %s \n", grapherrormsg (errorcode));
getch ();
xm=getmaxx ()/2;
ym=getmaxy ()/2;
getch();
635
line (x1[i]+xm, (-y1[i]+ym), x[i+1]+xm, (-y1[i+1]+ym));
getch();
void main ()
class arc a;
clrscr();
a.map();
a.graph();
a.get();
a.cal();
a.plot();
a.plot1();
getch();
Output:
{
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.
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).
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.
640
Note: Two types of rotations are used for representing matrices one is column
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.
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).
645
Step1:Translate window to origin 1Tx=-Xwmin Ty=-Ywmin
on screen.
Viewing Transformation= T * S * T1
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
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.
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
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
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
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
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
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
EXAMPLE
RtFloat thetamax;
Note that the bottom of the cone is open, and if thetamax is not equal to 360degrees, the sides are
open.
RIB BINDING
RtColor four_colors[4];
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
Where pipi is the set of points and Bni(t)Bin(t) represents the Bernsteinpolynomials which are given
by −
• 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.
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 :
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-
To obtain the equation of one of the edge-curves, e.g. when u=0, we mustsubstitute in the matrix
equation:
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
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).
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.
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:
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.
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:
Then we can obtain the intensity along this edge for the next scan line, Y-1 as
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:
671
1. Choose a camera position (also called eye-point, or view-point).
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.
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.
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:
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.
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.
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.
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].
686