0% found this document useful (0 votes)
110 views216 pages

U - 3 Programming Language & Computer Graphics

The document discusses programming languages and their design, covering key concepts such as language types, paradigms, and notable languages like FORTRAN, C, and Java. It explains the differences between low-level and high-level languages, as well as various programming paradigms including imperative, procedural, and object-oriented programming. Additionally, it highlights the evolution of languages and their applications in different domains such as business and education.

Uploaded by

V Karthikreddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views216 pages

U - 3 Programming Language & Computer Graphics

The document discusses programming languages and their design, covering key concepts such as language types, paradigms, and notable languages like FORTRAN, C, and Java. It explains the differences between low-level and high-level languages, as well as various programming paradigms including imperative, procedural, and object-oriented programming. Additionally, it highlights the evolution of languages and their applications in different domains such as business and education.

Uploaded by

V Karthikreddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 216

DIWAKAR EDUCATION HUB

PROGRAMMING LANGUAGES AND


COMPUTER GRAPHICS UNIT - 3
As per updated syllabus
DIWAKAR EDUCATION HUB

THE LEARN WITH EXPERTIES


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Language Design
Language design techniques are the most important topic to design the Programming
Language and to solve various types of problems in the discipline of Comp. Science and IT. The
following are the major topics covered in Language Design.
1. Programming Language Concepts
2. PL-Paradigms and Models
3. Programming Environments
4. Translation process
Programming Language Concepts
Computer programming language, any of various languages for expressing a set of detailed
instructions for a digital computer. Such instructions can be executed directly when they are in
the computer manufacturer-specific numerical form known as machine language, after a
simple substitution process when expressed in a corresponding assembly language, or after
translation from some “higher-level” language. Although there are many computer languages,
relatively few are widely used.
Machine and assembly languages are “low-level,” requiring a programmer to manage 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.

DIWAKAR EDUCATION HUB Page 2


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Basic theories like abstract syntax, interpretation, stack, heap organization, compilation
techniques, different types of 'type checking' and 'error checking' various for each
Programming 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 used operations 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 scientific computations with real
numbers and collections of them organized as one- or multidimensional arrays. Its control
DIWAKAR EDUCATION HUB Page 3
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 as for 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 might contain both data and instructions and have the same structure as an
entire program. Block structure became a powerful tool for building large programs out of
small components.
ALGOL contributed a notation for describing the structure of a programming language,
Backus–Naur Form, which in some variation became the standard tool for stating
the syntax (grammar) of programming languages. ALGOL was widely used in Europe, and for
many years it remained the language in which computer algorithms were published. Many
important languages, such as Pascal and Ada (both described later), are its descendants.
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 own definition). 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 AI programs capable of
“learning” could be written in LISP as self-modifying programs. LISP has evolved through
numerous dialects, such as Scheme and Common LISP.
C
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 as well 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

DIWAKAR EDUCATION HUB Page 4


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 in order 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 COBOL introduced 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 with both last_name Smith and city New York.”
Commercial database programs commonly use a SQL-like language for their queries.
Education-oriented languages
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 was intended 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 was translated 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 personal computers.
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 control structures 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 to
introduce 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 languages for
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.
DIWAKAR EDUCATION HUB Page 5
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 program a 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.
Hypertalk
Hypertalk was designed as “programming for the rest of us” by Bill Atkinson for Apple’s
Macintosh. Using a simple English-like syntax, Hypertalk enabled anyone 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
market share 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).
Object-oriented languages
Object-oriented languages help to manage complexity in large programs. Objects package data
and the operations on them so that only the operations are publicly accessible 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
repeating all 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 assistant to 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

DIWAKAR EDUCATION HUB Page 6


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 the Department
of Defense, Ada remains an effective language for engineering large programs.
Java
In the early 1990s, Java was designed by Sun Microsystems, Inc., as a programming language
for the World Wide Web (WWW). Although it resembled C++ in appearance, it was fully
object-oriented. In particular, Java dispensed with lower-level features, including the ability to
manipulate data addresses, a capability that is neither desirable nor useful in programs for
distributed systems. In order to be portable, Java programs are translated by a Java Virtual
Machine specific to each computer platform, which then executes the Java program. In
addition to adding interactive capabilities to the Internet through Web “applets,” Java has
been widely used for programming small and portable devices, such as mobile telephones.
PL-Paradigms and Models
A programming paradigm is a various system design of ideas that have been used to
guide/implement the programming.
Paradigm can also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language or
also we can say it is a method to solve a problem using tools and techniques that are available
to us following some approach. There are lots for programming language that are known but
all of them need to follow some strategy when they are implemented and this
methodology/strategy is paradigms. Apart from varieties of programming language there are
lots of paradigms to fulfil each and every demand.

Following list of paradigms

Imperative: Explicit sequence [such as assignment statements] of statements that change the
state of the computer.
It is one of the oldest programming paradigm. It features close relation relation to machine
architecture. It is based on Von Neumann architecture. It works by changing the program state
through assignment statements. It performs step by step task by changing state. The main

DIWAKAR EDUCATION HUB Page 7


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
focus is on how to achieve the goal. The paradigm consist of several statements and after
execution of all the result is stored.
Advantage:
1. Very simple to implement
2. It contains loops, variables etc.
Disadvantage:
1. Complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible
Examples of Imperative programming paradigm:
C : developed by Dennis Ritchie and Ken Thompson
Fortan : developed by John Backus for IBM
Basic : developed by John G Kemeny and Thomas E Kurtz

// average of five number in C


int marks[5] = { 12, 32, 45, 13, 19 } int sum = 0;
float average = 0.0;
for (int i = 0; i < 5; i++) {
sum = sum + marks[i];
}
average = sum / 5;
Imperative programming is divided into three broad categories: Procedural, OOP and parallel
processing. These paradigms are as follows:
Procedural: Imperative programming with procedure calls something like the re-use of code.
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.
Examples of Procedural programming paradigm:

C : developed by Dennis Ritchie and Ken Thompson


C++ : developed by Bjarne Stroustrup
Java : developed by James Gosling at Sun Microsystems
ColdFusion : developed by J J Allaire
Pascal : developed by Niklaus Wirth
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.
DIWAKAR EDUCATION HUB Page 8
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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
processors. A parallel processing system posses many numbers of processor 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 and mentioning
how to get the result.
It is divided as Logic, Functional, Database. In computer science the declarative
programming is a style of building programs that expresses logic of computation without
talking about its control flow. It often considers programs as theories of some logic.It may
simplify writing parallel programs. The focus is on what needs to be done rather how it should
be done basically emphasize on what code code is actually doing. It just declare the result we
want rather how it has be produced. This is the only difference between imperative (how to
do) and declarative (what to do) programming paradigms. Getting into deeper we would see
logic, functional and database.
Logic (as per defined rules): Specifying a set of rules/business logic in the programming. 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 base which 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 the problem.
sum of two number in prolog:
predicates
sumoftwonumber(integer, integer)
clauses
sum(0, 0).
sum(n, r):-
n1=n-1,
sum(n1, r1),

DIWAKAR EDUCATION HUB Page 9


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
r=r1+n
Functional (Application-oriented): Expressing the calculations as evaluation of math-function,
Function call programming with to avoid any global state change.
The functional programming paradigms has its roots in mathematics and it is language
independent. The key principal of this paradigms is the execution of series of mathematical
functions. The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to functions.The
function hide their implementation. Function can be replaced with their values without
changing the meaning of the program. Some of the languages like perl, javascript mostly uses
this paradigm.
Examples of Functional programming paradigm:

JavaScript : developed by Brendan Eich


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

Structured: Clean programming like goto-free, with proper nested control structures.
This programming methodology is based on data and its movement. Program statements are
defined by data rather than hard-coding a series of steps. A database program is the heart of a
business information system and provides file creation, data entry, update, query and
reporting functions. There are several programming languages that are developed mostly for
database application. For example SQL. It is applied to streams of structured data, for filtering,
transforming, aggregating (such as computing statistics), or calling other programs. So it has its
own wide application.
CREATE DATABASE databaseAddress;
CREATE TABLE Addr (
PersonID int,
LastName varchar(200),
FirstName varchar(200),
Address varchar(200),
City varchar(200),
State varchar(200)
);
Programming Environments
Environment/Setup is not a part of any Programming Language; It is a base step to be
completed before start writing the program i.e. required software/hardware prerequisite.
DIWAKAR EDUCATION HUB Page 10
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Translation process
Translation process: A computer processor only understands the machine code. Programs are
written in high-level languages such as Java cannot be run directly in the processor.

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 the machine
code.
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 object code [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 disk storage, 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. The hypervisor 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 include Microsoft
Hyper-V Manager, VMware Workstation Pro, and Parallels Desktop. These applications allow

DIWAKAR EDUCATION HUB Page 11


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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. Testing software 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 to the 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 enroll a baby at birth and prepay
the current tuition. When the student shows up 18 years later, the tuition is fully paid up, no
matter how high it may be at that moment.
In manufacturing, ordering parts in advance and maintaining an inventory of them is 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. Global variables
are bound to a particular virtual address by the compiler. This exemplifies early binding.
Variables local to a procedure are assigned a virtual address (on the stack) at the time the
procedure is invoked. This is intermediate binding. Variables 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 run there. 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 the early
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 until the window is put on the screen, and it may
even be changed later.
Binding refers to the process of converting identifiers (such as variable and performance
names) into addresses. Binding is done for each variable and functions. For functions, it means
that matching the call with the right function definition by the compiler. It takes place either at
compile time or at runtime.

DIWAKAR EDUCATION HUB Page 12


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 help of virtual
keyword)
// CPP Program to illustrate early binding.
// Any normal function call (without virtual)
// is binded early. Here we have taken base
// and derived class example so that readers
// can easily compare and see difference in
// outputs.
#include<iostream>
using namespace std;
class Base
{
public:
void show() { cout<<" In Base \n"; }
};
class Derived: public Base
{
public:
void show() { cout<<"In Derived \n"; }
};
int main(void)
{
Base *bp = new Derived;
// The function call decided at
// compile time (compiler sees type
// of pointer and calls base class
// function.
bp->show();

DIWAKAR EDUCATION HUB Page 13


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
return 0;
}
Output:
In Base
Late Binding : (Run time polymorphism) In this, the compiler adds code that identifies the
kind of object at runtime then matches the call with the right function definition. This can be
achieved by declaring a virtual function.
// CPP Program to illustrate late binding
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() { cout<<" In Base \n"; }
};
class Derived: public Base
{
public:
void show() { cout<<"In Derived \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}
Output:
In Derived
Syntax in Programming
Syntax is the set of rules that define what the various combinations of symbols mean. This tells
the computer how to read the code. Syntax refers to a concept in writing 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 or
our 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 in a different structure in how
we give it information to get the computer to follow our instructions.

DIWAKAR EDUCATION HUB Page 14


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Web developers primarily focus on HTML, CSS, and JavaScript. That is what we’re going 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 to understand.
For example, a series of English words, such as — subject a need and does sentence a verb —
has little meaning without syntax.
Applying basic syntax results in the sentence — Does a sentence need a subject and verb?
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 that computers
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 by language.
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 be upper case.
For example, class FirstJavaClass. Languages such as C or C++ use an underscore to
separate words. In C, the class name would be first_java_class.
3. Program Filenames. The name of a Java program file must match the class name with
the extension ‘*.java” added to the name. For 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 but have no other stipulations.
Different languages may have rules for adding comments, using white space, or declaring
variables.
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 basics such as phrase
structure, proper syntax and correctly structured code.
Understanding Syntax

DIWAKAR EDUCATION HUB Page 15


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 is read 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.
C Syntax
look at a C program that prints the sentence — My first line of code. All C instructions 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 C programs
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 print must be
surrounded by quotation marks and enclosed in parentheses.
All statements must end with a semicolon ( ; ). For example, to print a second sentence add
the following statement before the right curly bracket:
printf( “just printed!” );
}
The executed program would display: My first line of code just printed!
Why Is Syntax Important in Programming?
Syntax improves code readability. It ensures that the four C’s of coding are maintained:
1. Communication
2. Code integration
3. Consistency
4. Clarity
The concept behind conventions is to make the code explain itself. If the code is self-
explanatory, the focus can be on design and program improvements and not on what does this
mean?
Using consistent standards means that code is predictable and discoverable when read by
other programmers.
When code does not follow conventions, it becomes disorganized and difficult to read. It
becomes what is known as spaghetti code.
The term has a negative connotation indicating that the programmer did not have the skills or
experience needed to write readable code.
The Translation Process.
DIWAKAR EDUCATION HUB Page 16
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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

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

There are three main types of translators; Assemblers,Compilers and Interpreters. A


description of each of these type of translators is given in the following table.
The three main types of translators
Type Description

Assembler Assemblers convert assembly language mnemonics


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

Stages in Translating a Program


Lexical analysis (Scanner): Breaking a program into primitive components, called tokens
(identifiers, numbers, keywords, …)
Syntactic analysis (Parsing): Creating a syntax tree of the program.
Symbol table: Storing information about declared objects (identifiers, procedure names, …)
Semantic analysis: Understanding the relationship among the tokens in the program.
Optimization: Rewriting the syntax tree to create a more efficient program.
Code generation: Converting the parsed program into an executable form.
Elementary Data Types
Variables and Constants
Variables: A variable is it Quadruple which is composed of a name,a set of attributes, a
reference and a value.
A simple variable is an elementary data object with a name and binding of data object to value
may change during its lifetime. This data objects are basically defined and named by
programmer explicitly.
DIWAKAR EDUCATION HUB Page 17
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Attribute of a variable:
example of variable in "ALGOL Language"
y:=9;
We can say that it has four attributes
1) the name of the box:y
2) The name of description of a current contents.
i.e 9 we can also say that square of 3.
3) the box or storage location(s) which holds(s) the value.
4) the content of the box or 9.
The name of the box and its storage location are fixed, but the contents and it name may vary
over time.

another example in C language:


int N;- It declares a simple data object N of type integer.
N=27; beta value 27 is assigned to variable N.
1) declare the variable name N of type integer.
2) lifetime of N is execution end.
3) data object bound to N during end of execution time.
4) value 27 is assigned and may be changed during life of N.
5) hidden from the programmer are other binding made by virtual computer like
creating Activation Record, Storage for this activation record in Run-TimeStack
etc.
Data Object:
Definition: A Data object represents a container for data values, a place where data values
may be stored and later retrieved.
Definition: A runtime grouping of one or more pieces of data in a virtual computer.
Definition: A Location in memory with an assignment name in the actual computer.
Data objects can be:
1) at program execution- Programmer-defined -(example variables, constant, arrays, files
etc)
2) not directly accessible to programmer- system defined- run time storage, stacks, file
buffers, free space lists.

DIWAKAR EDUCATION HUB Page 18


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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

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

A Data Object is elementary if it contains a data value that is always manipulated as a unit.
A Data Object is an Data Structure if it is an aggregate of the data object
Binding and Attributes of Data Object:
DIWAKAR EDUCATION HUB Page 19
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Binding is an association of data values and entity.
1) Type: This associates the data object with the set of data values that the object may
take.
2) location: This associate the binding of a storage location in memory where the data
object is represented. Only storage management routines can only change add data
object in the virtual computer.
3) Value: This binding is usually the result of an assignment operation.
4) Name: The binding to one or more names by which the object maybe referenced during
program execution is usually set up by declaration and modified by subprogram calls the
returns.
5) 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 by a change in
pointer.

Elementary Data Type: Variables And Constants:


Constant:
A data object with a name that is bound to a value (or values) permanently during its lifetime.
The constant value can only be a number, string or identifier which denotes constant.
A constant definition in Pascal introduces an identifier as a synonym for the constant value.
Pascal uses the reserved word const to begin a constant declaration.
const PI=3.1415;
In ALGOL68 we can define constant by
real root2=1.4142135;
That was much acceptable that time.
In Ada, provides a uniform notation for setting constants to initial values and for initializing
variables.
X: Constant INTEGER:=17;
In C language: const is used to initialise the constant value
const int MAX=80;
The constant MAX is a programmer defined constant because the programmer explicitly
defines the name for the value 30.
In C, there is micro definition which is used for control the execution of program and can be
used for declaring constant.
DIWAKAR EDUCATION HUB Page 20
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Example #define MAX30
It is a compile-time operation that causes all references to MAX in program to be changed to
the constant 30.
In this 30 has two names, the programmer defined MAX and literal name 30. Both of which
may be used to refer to a data object containing the value 30.
# define MAX 30 is a command, which the translator used to equate "MAX" with the
value "30", where as the const attribute in C is a translator directive starting that MAX will
always contain the value 30.
Specification of Elementary Data Types
An elementary data object contains a single data values and class of such data objects over
which various operations are defined is termed as elementary data type.
Some elementary data types: Integer, real, character, Boolean, enumeration and pointer and
specification may differ significantly between two languages.
Attributes: Basic attributes of any data object, such as data type and name are usually
invariant during its lifetime.
Some attributes may be stored in a descriptor as a part of the data object daily program
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 data object
contains.
Values: The type of a data object determines the set of possible values that it may contain.
For Example: C defines the following four classes of integer types
int, short, long and char
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 of integer.
Operations:- The set of operations Defined by language is basically refers that how data object
of that data type may be manipulated.
If the operations are primitive operation, means specified as part of language.
Programmer defined operations, in the form of subprograms or method declarations as part of
class definitions.
Example
Integer* integer-> integer
a) integer addition is an operation that take to integer data objects as an arguments and
produces an integer data object as a result.
b) SQRT: real-> real
A Square-root operation, SQRT,on real number data object is specified.

DIWAKAR EDUCATION HUB Page 21


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
(Port of operation)
An algorithm that specifies how to compute the results for any given set of arguments is a
common method for specifying the action of an operation.
In C, we have concept a function prototype which signature of an operation, the number,
order and data types of the arguments in the domain of an operation are given as well as the
order and the data type of the resulting range.
Binary operation: Two arguments with single result
Monolic operation: Single argument with single result.
Implementation of Elementary Data Types:"
Implementation of Elementary data type consists of
 Storage representation for data objects
 Values of that type
 Set of algorithms or procedures that define the operations of the type in terms of
manipulations of the storage representation.
Storage representation of Elementary data type:
1) Hardware Influence: Computer hardware influence the storage of elementary data type.
In this case computer hardware executes the program. If the hardware storage representation
are used, then the basic operations on data of that data type not implemented using hardware
provided operations.
2) Software influenced: If we do not use hardware storage representation, then the
operation must be software simulated and some operation will execute much less efficient.
Two methods to treat Attributes:
It has to be determined by the compiler and not stored in discriptors during execution or not
stored in runtime storage representation. It is usually a method in C language.
It is stored in a descriptor as part of the data object at runtime in LISP, Prolog language .
The storage representation is usually described in terms of
 Size of the block of memory required(the number of memory words bytes, ot bits
needed)
 Layout of attributes and data values within the block.
Implementation of operations:
Each operation defined for data objects of a given type may be implemented in one 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 using the arithmetic
operations built in to hardware.
2) As a Subprogram or procedure: A square root for an example, this operation is not
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 its operation.
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.
DIWAKAR EDUCATION HUB Page 22
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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.
a) fetch value of x from memory
b) if x >0, skip the next instruction
c) set x=-x
d) store new value of x in memory
Here each line is implemented by a single hardware operation.
Scalar Data Types
Scalar data types represent
a single object, i.e. only one value can be derived.
In general, scalar objects follow the hardware architecture of a computer.
Numeric Data Types
Integers
Sub -ranges
Floating-point real numbers
Fixed-point real numbers
Other Data Types -
 Complex numbers
 Rational numbers
 Enumerations Booleans
 Booleans
 Characters
Integers Specification
Maximal and minimal values
Operations:
Arithmetic Relational Assignment Bit operations
Implementation - hardware defined
Sub-ranges Specification:
subtype of integer
a sequence of integer values within some restricted range Example:
Pascal declaration A: 1..10 means that the variable A may be assigned integer values from 1
through 10.
Implementation
smaller storage requirements, better type checking
Floating-point real numbers Specification:
Minimum and maximal value
Round-off issues - the check for equality may fail due to round -off

DIWAKAR EDUCATION HUB Page 23


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Implementation
Mantissa - exponent model. Example: 10.5 = 0.105 x 102,
Mantissa: 105, Exponent: 2
Fixed-point real numbers Specification:
real numbers with predefined decimal places
Implementation :
Directly supported by hardwareor simulatedby software
Other scalar data types
Complex numbers: software simulated with two storage locations one the real portion and
one for the imaginary portion.
Rational numbers: the quotient of two integers. Enumerations: Ordered list of different
values Booleans
Characters
Scalar Data Type Enumeration
An Enumerated data type is a data type whose domain values are given in a list or ordered list
and who's only operations are equality and assignment.
or
An Enumeration is an ordered list of distinct values.
or
An Enumeration is a complete ordered listing of all items in a collection.
Pascal was first language which introduced enumeration. To make enumeration facility useful,
a programming language must provide a mechanism for declaring and defining the new data
type and for declaring variables whose value will come from the element of type.
It is assumed that this literals are distinct and does equality can be directly defined.
"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 variable StudentSex 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 are assigned.
like
fresher=1 , sophomore=2, and so on
and male=0, female =1
Then translator manipulate values as integers.
That creates big problem like
Sophomore =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 as they are of integer
types.
Then languages such as C, article Pascal and Ada includes an Enumeration data type that
allows the programmer to define and manipulate such variables directly.

DIWAKAR EDUCATION HUB Page 24


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Specification of Enumeration
The programmers defined both the literal name to be used for the values and their ordering
using a declaration such as in pascal.
Type months=(jan,feb, mar, apr, june, jul, aug, sep, oct,nov,dec);

In C
enum studentclass{ fresh, soph, junior, senior};
enum studentsex {male, female};
In Pascal, C example can be written as
type class =(fresh, soph, junior, senior};
Followed by declaration for variables such as
Studentclass: Class;
Studentsex class: Class;
Here type definition introduces the type name class, which may be used wherever the
primitive type name such as integer might be used time.
It also introduces the literals of fresh, soph, junior, senior which may be used wherever a
language- defined literal such as "27" might be used. Thus we can write.
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 find error such as
if student class= Male then
As Male is part of student class. Operations which we can perform-
• Relational operations(equal, less-than, greater-than,etc)
• Assignment
• Successor and Predecessor
Implementation of Enumeration
• Each value in the enumeration sequence is represented at run-time by one of the 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}
With this storage representation for enumeration types. Relational operations such as =,>, and
< may be implemented.
Scalar Data Types: Booleans
The Boolean data type is a data type, having two values(usually denoted true or false),
intended to represent the truth values of logic and Boolean algebra.

DIWAKAR EDUCATION HUB Page 25


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Specification: In Pascal and Ada, the Boolean data type is considered simply a language -
defined enumeration, viz;
type Boolean=(false, true);

Which both defines the names true and false for the values of the types and define ordering
false<true
Common Operations in boolean are
and : Boolean*Boolean->Boolean(conjunction)
or : Boolean*Boolean->Boolean(inclusive disjunction )
not : Boolean ->Boolean(negative or complement)
Implementation of boolean data type:
Single bit of storage is provided, no descriptor designated the data type is needed. Because
single bit may not be separately addressable in memory which often takes a byte or word to
represent it if extended. Then the value true and false might be represented in two ways
within the storage unit:
 a particular bit is used for the value(often the sign bit of the number representation),
with '0= false', '1=true', and the rest of the byte or word ignored, or
 A zero value in the entire storage unit represent False, and any other non zero value
represents true

Scalar Data Types: Characters


Specification of Characters
A character data type provides data objects that have a single character as their value. Set of
values in character data type depends upon "Hardware and Operating System" like ASCII
character set. and ordering of the characters in this character set is called Collecting
Sequence And ordering given by the 'Relational Operations'.
Character set includes
• Spaces
• Digits
• Special character @,#,$,& etc.

DIWAKAR EDUCATION HUB Page 26


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Operations on character data include only


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

Implementation of Character Data Type


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

ASCII value of character data type in C are


0 to 9 is 48 to 57/ ASCII value
A to z is 65 to 90
a to z is 97 to 122
And all remaining for special characters.

char a ; //declaration
a='A'; // initializing character data object with A
Where= A=65=1000001

DIWAKAR EDUCATION HUB Page 27


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Composite Data Types


Characterized by a complex data structure organization, processed by the compiler.
 Character Strings
 Pointers and Programmer- Constructed Objects
 Files
Character Strings Specification:
Fixed declared length : storage allocation at translation time. Strings longer than the declared
length are truncated.
Variable length to a declared bound: storage allocation at translation time. An upper bound for
length is set and any string over that length is truncated
Unbounded length: storage allocation at run time. String can be any length
Character Strings - operations
Concatenation – appending two strings
 Relational operations – equal, less than, greater than
o Substring selection using positioning subscripts
o Substring selection using pattern matching
o Input / output formatting
o Dynamic strings - the string is evaluated at run time.
implementation
 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 a contiguous
array of characters with dynamic run-time storage allocation
Pointers and Programmer- Constructed Objects
Objects
Specification:
Reference data objects only of a single type – C, Pascal, Ada.
Reference data objects of any type – Smalltalk

DIWAKAR EDUCATION HUB Page 28


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
C, C++: pointers are data objects and can be manipulated by the program
Java: pointers are hidden data structures, managed by the language implementation
Pointers - implementation
Absolute addresses stored in the pointer. Allows for storing the new object anywhere in the
memory
Relative addresses: offset with respect to some base address.
Advantages: the entire block can be moved to another location without invalidating the
addresses in the pointers, since they are relative, not absolute.
Pointers – implementation problems
 Management of a general heap storage area: to create objects of different size
 Garbage - the contents of pointer is destroyed, and the object still exists
 Dangling references: the object is destroyed however the pointer still contains the
address of the used location, and can be wrongly used by the program.
Characteristics:
 Usually reside on secondary storage devices as disks,
tapes.
 Lifetime is greater than the lifetime of the program that has created the
files.
Implementation – as part of the operating system
Types of Files
Sequential file: a data structure composed of a linear sequence of components
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 an array.
Key: the subscript to access a component.
Implementation: a key table is kept in main memory
Indexed Sequential Files: Similar to direct access files using a key combined with being able to
sequentially process the file. The file must be ordered by the key
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
popular and 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 Software Development Domain. I will list
down some of the key advantages of learning C Programming:
1. Easy to learn
2. Structured language
3. It produces efficient programs
DIWAKAR EDUCATION HUB Page 29
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
4. It can handle low-level activities
5. It can be compiled on a variety of computer platforms
Facts about C
1. C was invented to write an operating system called UNIX.
2. C is a successor of B language which was introduced around the early 1970s.
3. The language was formalized in 1988 by the American National Standard Institute
(ANSI).
4. The UNIX OS was totally written in C.
5. Today C is the most widely used and popular System Programming Language.
6. Most of the state-of-the-art software have been implemented using C.
7. Today's most popular Linux OS and RDBMS MySQL have been written in C.
Hello World using C Programming.
#include <stdio.h
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Applications of C Programming
C was initially used for system development work, particularly the programs that make-up the
operating system. C was adopted as a system development language because 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
Tokens
Tokens are the smallest elements of a program, which are meaningful to the compiler.
The following are the types of tokens: Keywords, Identifiers, Constant, Strings, Operators, etc.
begin with Keywords.
Keywords
Keywords are predefined, reserved words in C and each of which is associated with specific
features. These words help us to use the functionality of C language. They have special
meaning to the compilers.

DIWAKAR EDUCATION HUB Page 30


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
There are total 32 keywords in C.
auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

Identifiers
Each program element in C programming is known as an identifier. They are used for naming
of variables, functions, array etc. These are user-defined names which consist of alphabets,
number, underscore ‘_’. Identifier’s name should not be same or same as keywords. Keywords
are not used as identifiers.
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, or underscore.
 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, and easy to read.
Example of valid identifiers
DIWAKAR EDUCATION HUB Page 31
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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


Example of invalid identifiers

o 2sum (starts with a numerical digit)

o int (reserved word)

o char (reserved word)

o m+n (special character, i.e., '+')


Types of identifiers

 Internal identifier
 External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier. The
external identifiers can be function names, global variables.
Differences between Keyword and Identifier

Keyword Identifier

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

It must be written in a lowercase It can be written in both lowercase and


letter. uppercase letters.

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

It is a combination of alphabetical It is a combination of alphanumeric


characters. characters.

It does not contain the underscore It can contain the underscore character.
character.

an example.
int main()
{

DIWAKAR EDUCATION HUB Page 32


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
int a=10;
int A=20;
printf("Value of a is : %d",a);
printf("\nValue of A is :%d",A);
return 0;
}
Output
Value of a is : 10
Value of A is :20
The above output shows that the values of both the variables, 'a' and 'A' are different.
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 double quotes(“ “).
how to declare String in C language −
1) char string[20] = {‘s’,’t’,’u’,’d’,’y’, ‘\0’};
2) char string[20] = “demo”;
3) char string [] = “demo”;
Here is an example of tokens in C language,
Example
#include >stdio.h>
int main() {
// using keyword char
char a1 = 'H';
int b = 8;
float d = 5.6;
// declaration of string
char string[200] = "demodotcom";
if(b<10)
printf("Character Value : %c\n",a1);
else
printf("Float value : %f\n",d);
printf("String Value : %s\n", string);
return 0;
}
Output
Character Value : H
String Value : demodotcom
Data Types in C
DIWAKAR EDUCATION HUB Page 33
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating
system.
the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

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

DIWAKAR EDUCATION HUB Page 34


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

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

unsigned int 2 byte 0 to 65,535

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

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

unsigned short int 2 byte 0 to 65,535

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

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

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

float 4 byte

double 8 byte

long double 10 byte

Subprogram
A Subprogram is a program inside any larger program that can be reused any number of times.
Control at the subprogram level is concerned with subprogram invocation and the relationship
between the calling module and the called module. What follows is a list of possible ways the
caller and the callee are related.
Characteristics of a Subprogram:
(1) A Subprogram is implemented using the Call & Return instructions in Assembly Language.
(2) The Call Instruction is present in the Main Program and the Return(Ret) Instruction is
present in the subprogram itself.

DIWAKAR EDUCATION HUB Page 35


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

(3) It is important to note that the Main Program is suspended during the execution of any
subprogram. Moreover, after the completion of the subprogram the 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 during the execution of the Call Instruction, the Program Counter
value is first pushed to the 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 Program Counter
value is restored for further execution of the Main Program .
(5) The Main advantage of Subprogram is that it avoids repetition of Code and allows us to
reuse the same code again and again.

DIWAKAR EDUCATION HUB Page 36


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 contiguous manner
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 We need to handle hundreds
of variables or even more than that.
In such scenario, We might be thinking about what variable names should be used, how to
reduce redundant code, etc.
Assume We have to store marks of 100 students and then think about the following:
 What could be our variable naming convention?
 How We efficiently write input instruction to store 100 data.
 How could We easily manipulate data like adding all of them 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.
DIWAKAR EDUCATION HUB Page 37
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Here is the way:
int marks[100];
 Notice square brackets after array name marks. This pair of square brackets is used to
depict array usage.
 Number mention in the square bracket is size of array. In our example we wrote 100, so
size of the array is 100. Thus we have declared 100 variables in one go.
 These 100 variables are all of type int. Since array is a collection of similar elements,
data type for all 100 variables is int.
 Name of the first variable is marks[0], second variable is marks[1], and so on. Therefore
the last variable is marks[99]. Here it is important to note that in C language array
indexing starts with 0 and not from 1.
Example: Program to calculate average of 10 marks
#include<stdio.h>
#include<conio.h>
main()
{
int i, marks[10], sum=0;
float avg;
clrscr();
printf(“Enter 10 numbers”);
for(i=0;i<=9;i++)
scanf(“%d”,&marks[i]);
for(i=0;i<=9;i++)
sum=sum+marks[i];
avg=sum/10.0;
printf(“Average is %f”,avg);
getch();
}
Explanation:
ii. Total numbers of variables in this program are 13. Their names are i, sum, avg,
marks[0], marks[1],…marks[9].
iii. Notice the input statement, scanf() is repeated 10 times, this is possible as we
can access array index with the help of variable. Observe &marks[i] in scanf(),
here i is used for indexing. As the loop proceed value of i changes from 0 to 9.
In this way wee need not to write scanf() 10 times.
iv. Data manipulation becomes also easy, we added all 10 values stored in an
array putting statement sum=sum+marks[i] in the loop.
v. Since we have an array of size 10 and each of these blocks are of type int, to tal
memory consumed for this array is 20 bytes (2 bytes for each).
One dimension array

DIWAKAR EDUCATION HUB Page 38


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
To use an array variable in a program, it must be declared. When defining an array in a
program, three things need to be specified.
► What kind of data it can hold, i.e., int, char, double, string, etc.
► How many values it can hold, i.e., the maximum number it can hold
► A name
In the previous example the array declared known as one dimensional array.
Note: According to our previous example marks is not a variable name but marks[0] is a
variable. Thus we can not assign anything to marks like marks=5;
Two dimension array
C language supports multidimensional arrays also. The simplest form of a multidimensional
array is the two-dimensional array. Both the row's and column's index begins 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.
 Total numbers of blocks are 6, they are all of type int. Memory
allocation done is always sequential but we can assume it as two
arrays each of size 3.
 Logically we can see it as a row column structure. First row is our
0th array and second row is 1st array.
 Two dimensional arrays are used to handle data which is logically
two dimensional like matrix.
Example: Program to add two matrix of order 3 x 3.
#include<conio.h>
#include<stdio.h>
main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf("Enter 9 numbers for first matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("Enter 9 numbers for second matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)

DIWAKAR EDUCATION HUB Page 39


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nSum of matrix is: \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",c[i][j]);
printf("\n");
}
getch();
}
Explanation:
1. Notice the declaration of arrays. We have declared three two dimensional arrays.
2. Observe the style of input. scanf() is repeated with nested loop.
3. Lastly sum of corresponding elements of two matrices are added and stored in third
array.
4. Finally sum is displayed on the screen
Initialization of array at the time of declaration
Initializing one dimension array
int a[5]={ 23,45,11,67,55};
int a[ ]= { 23,45,11,67,55};
int a[5]= {22,45};
int a[5]= {12,23,76,85,43,33};
In the first style we declared an array with size 5 and assign 5 values to them, First value 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 is not 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 22 and 45,
remaining variables are initialized to 0.
Fourth style leads to compilation error. an array can not be intialized with data more 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

DIWAKAR EDUCATION HUB Page 40


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 type which is more
meaningful. It is 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 will have
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 which is 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 to give 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 followed by a
semicolon(;).
Example of Structure
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4
data fields, namely name, age, branch and gender. These fields are called structure elements
or members.
DIWAKAR EDUCATION HUB Page 41
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 is called as the structure
tag.
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition or after
the structure is defined. Structure variable declaration is similar to the declaration of any
normal variable of any other datatype. Structure variables can be declared in following two
ways:
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
2) Declaring Structure variables with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.
Accessing Structure Members
Structure members can be accessed and assigned values in a number of ways. Structure
members have no meaning individually without the structure. In order to assign a value to any
structure member, the member name must be linked with the structure variable using a
dot . operator also called period or member access operator.
For example:
#include<stdio.h>
#include<string.h>
struct Student
{

DIWAKAR EDUCATION HUB Page 42


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
{
struct Student s1;
/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
Output
Name of Student 1: Viraaj
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s1.name);
scanf(" %d ", &s1.age);
Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
DIWAKAR EDUCATION HUB Page 43
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

struct Patient p1 = { 180.75 , 73, 23 }; //initialization


or,
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using the
structure as given below.
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printing the details....\n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Output
Enter the name, id, and marks of student 1 James 90 90

DIWAKAR EDUCATION HUB Page 44


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we will have
to declare 20 different structure variables and store 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 variables is 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 of different data types. The array of
structures is also known as the collection of structures.

an example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
DIWAKAR EDUCATION HUB Page 45
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
DIWAKAR EDUCATION HUB Page 46
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Rollno:5, Name:Sarfraz
Nested Structure in C
Nesting of structures, is also permitted in C language. Nested structures means, 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 store the 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 the address of the employee, we need to store the
address of the employee into a separate structure and nest the structure address into the
structure employee. Consider the following program.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add
.pin,emp.add.phone);
}
Output
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....

DIWAKAR EDUCATION HUB Page 47


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
The structure can be nested in the following ways.
o By separate structure
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.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
As We can see, doj (date of joining) is the variable of type Date. Here doj is used as 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.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure

DIWAKAR EDUCATION HUB Page 48


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
C Nested Structure example
a simple example of the nested structure in C language.
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.
doj.yyyy);
return 0;
}
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
DIWAKAR EDUCATION HUB Page 49
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Passing structure to function
Just like other variables, a structure can also be passed to a function. We may pass the
structure members into the function or pass the structure variable at once. Consider the
following example to pass the structure variable employee to a function display() which is used
to display the details of an employee.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void display(struct employee);
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
display(emp);
}
void display(struct employee emp)
{
printf("Printing the details....\n");
printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
Structure as Function Arguments
We can pass a structure as a function argument just like we pass any other variable or an array
as a function argument.
Example:
#include<stdio.h>
struct Student
{
char name[10];
int roll;

DIWAKAR EDUCATION HUB Page 50


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
};
void show(struct Student st);
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}
C Unions
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 size of its largest data member.

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 declared using the union keyword.
union item
{
int m;
float x;
char c;

DIWAKAR EDUCATION HUB Page 51


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
}It1;
This declares a variable It1 of type union item. This union contains three members each 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 all the union variables, irrespective of their size. The
compiler allocates the storage that 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 share the same memory address.
Accessing a Union Member in C
Syntax for accessing any union member is similar to accessing structure members,
union test
{
int a;
float b;
char c;
}t;
t.a; //to access members of union t
t.b;
t.c;
Time for an Example
#include <stdio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z'
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
}
Output

DIWAKAR EDUCATION HUB Page 52


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
-26426
20.1999
z
As we can see here, the values of a and b get corrupted and only variable c prints 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 will have the memory.
In the above example, value of the variable c was stored at last, hence the value of other
variables is lost.
Advantage of union over structure
It occupies less memory because it occupies the size of the largest member only.
Disadvantage of union over structure
Only the last entered data can be stored in the union. It overwrites the data previously stored
in the union.
String
String is nothing but a collection of characters in a linear sequence. 'C' always treats a string a
single data even though it contains whitespaces. A single character is defined using single
quote representation. A string is represented using double quote marks.
Example, "Welcome to the world of programming!"
'C' provides standard library <string.h> that contains many functions which can be used 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 directly support string
as a data type. Hence, to display a string in 'C', We need to make use of a character array.
The general syntax for declaring a variable as a string is as follows,
char string_variable_name [array_size];
The classic string declaration can be done as follow:
char string_name[string_length] = "string";
The size of an array must be defined while declaring a string variable because it used to
calculate how many characters are going to be stored inside the string variable. Some valid
examples of string declaration are as follows,
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 the initialization of a
string variable,
char first_name[15] = "ANTHONY";

DIWAKAR EDUCATION HUB Page 53


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0' is required at end in
this declaration
char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */
char string2 [ ] = "world"; /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */
char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size 6*/
In string3, the NULL character must be added explicitly, and the characters are enclosed in
single quotation marks.
'C' also allows us to initialize a string variable without defining the size of the character array. It
can be done in the following way,
char first_name[ ] = "NATHAN";
The name of a string acts as a pointer because it is basically an array.
String Input: Read a String
When writing interactive programs which ask the user for input, C provides the scanf(), gets(),
and fgets() functions to find a line of text entered from the user.
When we use scanf() to read, we use the "%s" format specifier without using the "&" to access
the variable address because an array name acts as a pointer. For example:
#include <stdio.h>
int main() {
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", name, &age);
printf("You entered: %s %d",name,age);
}
Output:
Enter your first name and age:
John_Smith 48
The problem with the scanf function is that it never reads an entire string. It will halt the
reading process as soon as whitespace, form feed, vertical tab, newline or a 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 ignores the
whitespaces. It stops reading when a newline is reached (the Enter key is pressed).For
example:
#include <stdio.h>
int main() {
char full_name[25];
printf("Enter your full name: ");

DIWAKAR EDUCATION HUB Page 54


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
gets(full_name);
printf("My full name is %s ",full_name);
return 0;
}
Output:
Enter your full name: Dennis Ritchie
My full name is Dennis Ritchie
Another safer alternative to gets() is fgets() function which reads a specified number of
characters. For example:
#include <stdio.h>
int main() {
char name[10];
printf("Enter your name plz: ");
fgets(name, 10, stdin);
printf("My name is %s ",name);
return 0;}
Output:
Enter your name plz: Carlos
My name is Carlos
The fgets() arguments are :
 the string name,
 the number of characters to read,
 stdin means to read from the standard input which is the keyboard.
String Output: Print/Display a String
The standard printf function is used for printing or displaying a string on an output device. The
format specifier used is %s
Example,
printf("%s", name);
String output is done with the fputs() and printf() functions.
fputs() function
The fputs() needs the name of the string and a pointer to where We want to display the text.
We use stdout which refers to the standard output in order to print to the screen.For example:
#include <stdio.h>
int main()
{char town[40];
printf("Enter your town: ");
gets(town);
fputs(town, stdout);

DIWAKAR EDUCATION HUB Page 55


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
return 0;}
Output:
Enter your town: New York
New York
puts function
The puts function prints the string on an output device and moves the cursor back to the first
position. A puts function can be used in the following way,
#include <stdio.h>
int main() {
char name[15];
gets(name); //reads a string
puts(name); //displays a string
return 0;}
The syntax of this function is comparatively simple than other functions.
The string library
The standard 'C' library provides various functions to manipulate the strings within a program.
These functions are also called as string handlers. All these handlers are present inside
<string.h> header file.

Function Purpose

strlen() This function is used for finding a


length of a string. It returns how many
characters are present in a string
excluding the NULL character.

strcat(str1, str2) This function is used for combining two


strings together to form a single string.
It Appends or concatenates str2 to the
end of str1 and returns a pointer to
str1.

strcmp(str1, str2) This function is used to compare two


strings with each other. It returns 0 if
str1 is equal to str2, less than 0 if str1 <
str2, and greater than 0 if str1 > str2.
The program below which demonstrates string library functions:
#include <stdio.h>
#include <string.h>
int main () {

DIWAKAR EDUCATION HUB Page 56


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
//string initialization
char string1[15]="Hello";
char string2[15]=" World!";
char string3[15];
int val;
//string comparison
val= strcmp(string1,string2);
if(val==0){
printf("Strings are equal\n");
}
else{
printf("Strings are not equal\n");
}
//string concatenation
printf("Concatenated string:%s",strcat(string1,string2)); //string1 contains hello world!
//string length
printf("\nLength of first string:%d",strlen(string1));
printf("\nLength of second string:%d",strlen(string2));
//string copy
printf("\nCopied string is:%s\n",strcpy(string3,string1)); //string1 is copied into string3
return 0;
}
Output:
Strings are not equal
Concatenated string:Hello World!
Length of first string:12
Length of second string:7
Copied string is:Hello World!
Other important library functions are:
 strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal to the first n
characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
 strncpy(str1, str2, n) This function is used to copy a string from another string. Copies
the first n characters of str2 to str1
 strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, or NULL if
character not found.
 strrchr(str1, c): it searches str1 in reverse and returns a pointer to the position of char c
in str1, or NULL if character not found.
 strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2
not found.

DIWAKAR EDUCATION HUB Page 57


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
 strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to the end of str1
and returns a pointer to str1.
 strlwr() :to convert string to lower case
 strupr() :to convert string to upper case
 strrev() : to reverse string
Converting a String to a Number
In C programming, we can convert a string of numeric characters to a numeric value to
prevent a run-time error. The stdio.h library contains the following functions for converting a
string to a number:
 int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is
returned if the first character is not a number or no numbers are encountered.
 double atof(str) Stands for ASCII to float, it converts str to the equivalent double value.
0.0 is returned if the first character is not a number or no numbers are encountered.
 long int atol(str) Stands for ASCII to long int, Converts str to the equivalent long integer
value. 0 is returned if the first character is not a number or no numbers are
encountered.
The following program demonstrates atoi() function:
#include <stdio.h>
int main()
{char *string_id[10];
int ID;
printf("Enter a number: ");
gets(string_id);
ID = atoi(string_id);
printf("you enter %d ",ID);
return 0;}
Output:
Enter a number: 221348
you enter 221348
 A string pointer declaration such as char *string = "language" is a constant and cannot
be modified.
Summary
 A string is a sequence of characters stored in a character array.
 A string is a text enclosed in double quotation marks.
 A character such as 'd' is not a string and it is indicated by single quotation marks.
 'C' provides standard library functions to manipulate strings in a program. String
manipulators are stored in <string.h> header file.
 A string must be declared or initialized before using into a program.
 There are different input and output string functions, each one among them has its
features.

DIWAKAR EDUCATION HUB Page 58


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
 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 very
useful 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 also be used to
refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to
the next/ previous memory location. The purpose of pointer is to save memory space and
achieve faster execution time.
How does Pointer Work?
If we declare a variable v of type int, v will actually store a value.

v is equal to zero now.


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 an ampersand (&) before the
variable name.

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

The output of this program is -480613588.


Now, what is a pointer? Instead of storing a value, a pointer will y store the address of a
variable.
Int *y = &v;

VARIABLE POINTER

A value stored in A variable that points to the


a named storage/memory address storage/memory address
of another variable
Declaring a pointer
DIWAKAR EDUCATION HUB Page 59
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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's naming rules. A pointer declaration
has the following form.
data_type * pointer_variable_name;
Here,
 data_type is the pointer's base type of C's variable types and indicates the type of the
variable that the pointer points to.
 The asterisk (*: the same asterisk used for multiplication) which is indirection operator,
declares a pointer.
Some valid pointer declarations
int *ptr_thing; /* pointer to an integer */
int *ptr1,thing;/* ptr1 is a pointer to type integer and thing is an integer variable */
double *ptr2; /* pointer to a double */
float *ptr3; /* pointer to a float */
char *ch1 ; /* pointer to a character */
float *ptr, variable;/*ptr is a pointer to type float and variable is an ordinary float variable */
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 is done with the following syntax.
pointer = &variable;
A simple program for pointer illustration is given below:
#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
}
Output:
Address stored in a variable p is:60ff08
Value stored in a variable p is:10

Operator Meaning

DIWAKAR EDUCATION HUB Page 60


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

* Serves 2 purpose
 Declaration of a pointer
 Returns the value of the
referenced variable

& Serves only 1 purpose


 Returns the address of a
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 to the 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()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d\n",sizeof(p));
return 0;
}
Output:
The size of pointer is:4

DIWAKAR EDUCATION HUB Page 61


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Wild pointer
A pointer is said to be a wild pointer if it is not being initialized to anything. These types of
pointers are not efficient because they may point to some unknown memory location which
may cause problems in our program and it may lead to crashing of the program. One should
always be careful while working with wild pointers.
Following program illustrates the use of wild pointer:
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("\n%d",*p);
return 0;
}
Output
timeout: the monitored command dumped core
sh: line 1: 95298 Segmentation fault timeout 10s main
Other types of pointers in 'c' are as follows:
 Dangling pointer
 Complex pointer
 Near pointer
 Far pointer
 Huge pointer
Direct and Indirect Access Pointers
In C, there are two equivalent ways to access and manipulate a variable content
 Direct access: we use directly the variable name
 Indirect access: we use a pointer to the variable
understand this with the help of program below
#include <stdio.h>
/* Declare and initialize an int variable */
int var = 1;
/* Declare a pointer to int */
int *ptr;
int main( void )
{
/* Initialize ptr to point to var */
ptr = &var;
/* Access var directly and indirectly */
printf("\nDirect access, var = %d", var);
printf("\nIndirect access, var = %d", *ptr);

DIWAKAR EDUCATION HUB Page 62


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
/* Display the address of var two ways */
printf("\n\nThe address of var = %d", &var);
printf("\nThe address of var = %d\n", ptr);
/*change the content of var through the pointer*/
*ptr=48;
printf("\nIndirect access, var = %d", *ptr);
return 0;}
After compiling the program without any errors, the result is:
Direct access, var = 1
Indirect access, var = 1
The address of var = 4202496
The address of var = 4202496
Indirect access, var = 48
Pointers Arithmetic
The pointer operations are summarized in the following figure

Pointer Operations

DIWAKAR EDUCATION HUB Page 63


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Priority operation (precedence)
When working with pointers, we must observe the following priority rules:
 The operators * and & have the same priority as the unary operators (the negation!,
the incrementation++, decrement--).
 In the same expression, the unary operators *, &,!, ++, - are evaluated from right to
left.
If a P pointer points to an X variable, then * P can be used wherever X can be written.
The following expressions are equivalent:

int X =10

int *P = &Y;

For the above code, below expressions are true

Expression Equivalent Expression

Y=*P+1 Y=X+1

*P=*P+10 X=X+10

*P+=2 X+=2

++*P ++X

(*P)++ X++
In the latter case, parentheses are needed: as the unary operators * and ++ are evaluated
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 when dealing with
pointers

Operation Explanation

Assignment int *P1,*P2 P1=P2; P1 and P2 point to


the same integer variable

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

DIWAKAR EDUCATION HUB Page 64


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Adding an offset (Constant) This allows the pointer to move N


elements in a table. The pointer will be
increased or decreased by N times the
number of byte (s) of the type of the
variable. P1+5;
Pointers and Arrays
Traditionally, we access the array elements using its index, but this method can be eliminated
by using pointers. Pointers make it easy to access each array element.
#include <stdio.h>
int main()
{
int a[5]={1,2,3,4,5}; //array initialization
int *p; //pointer declaration
/*the ptr points to the first element of the array*/

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

printf("Printing the array elements using pointer\n");


for(int i=0;i<5;i++) //loop for traversing array elements
{
printf("\n%x",*p); //printing array elements
p++; //incrementing to the next element, you can also write p=p+1
}
return 0;
}
Output
1
2
3
4
5
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 then it will execute in this manner:

Pointer Addition/Increment

DIWAKAR EDUCATION HUB Page 65


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Since p currently points to the location 0 after adding 1, the value will become 1, and hence
the pointer will point to the memory location 1.
Pointers and Strings
A string is an array of char objects, ending with a null character '\ 0'. We can manipulate
strings using pointers. Here is an example that explains this section
#include <stdio.h>
#include <string.h>
int main()
{
char str[]="Hello Manish99";
char *p;
p=str;
printf("First character is:%c\n",*p);
p =p+1;
printf("Next character is:%c\n",*p);
printf("Printing all the characters in a string\n");
p=str; //reset the pointer
for(int i=0;i<strlen(str);i++)
{
printf("%c\n",*p);
p++;
}
return 0;
}
Output
First character is:H
Next character is:e
Printing all the characters in a string
H
e
l
l
o

M
a
n
i
s
DIWAKAR EDUCATION HUB Page 66
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
h
9
9
Another way to deal strings is with an array of pointers like in the following program:
#include <stdio.h>
int main(){
char *materials[ ] = { "iron", "copper", "gold"};
printf("Please remember these materials :\n");
int i ;
for (i = 0; i < 3; i++) {
printf("%s\n", materials[ i ]);}
return 0;}
Output:
Please remember these materials:
iron
copper
gold
Advantages of Pointers
 Pointers are useful for accessing memory locations.
 Pointers provide an efficient way for accessing the elements of an array structure.
 Pointers are used for dynamic memory allocation as well as deallocation.
 Pointers are used to form complex data structures such as linked list, graph, tree, etc.
Disadvantages of Pointers
1. Pointers are a little complex to understand.
2. Pointers can lead to various errors such as segmentation faults or can access a memory
location which is not required at all.
3. If an incorrect value is provided to a pointer, it may cause memory corruption.
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, void pointer and
other types of pointers.
o Pointers can be used with array and string to access elements more efficiently.
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.

DIWAKAR EDUCATION HUB Page 67


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
o Pointers can also point to function which make it easy to call different functions in the
case of defining an array of pointers.
o When We want to deal different variable data type, We can use a typecast void pointer.
Functions in C
A function is a block of code that performs a particular task.
There are many situations where we might need to write same line of code for more than
once in a program. This may lead to unnecessary repetition of code, bugs and even becomes
boring for the programmer. So, C language provides an approach in which We can declare and
define a group of statements once in the form of a function and it can be called and used
whenever required.
These functions defined by the user are also know as User-defined Functions
C functions can be classified into two categories,
 Library functions
 User-defined functions

Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. We just need to include appropriate header files to use
these functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user
at the time of writing program. These functions are made for code reusability and for saving
time and space.
Benefits of Using Functions
1. It provides modularity to Wer program's structure.
2. It makes our code reusable. We just have to call the function by its name to use it,
wherever required.
3. In case of large programs with thousands of code lines, debugging and editing
becomes easier if We use functions.
4. It makes the program more readable and easy to understand.
Function Declaration
General syntax for function declaration is,

DIWAKAR EDUCATION HUB Page 68


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
returntype functionName(type1 parameter1, type2 parameter2,...);
Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its
return type. The actual body of the function can be defined separately. It's also called
as Function Prototyping. Function declaration consists of 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 operation and 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 the type 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 would be void.
functionName
Function name is an identifier and it specifies the name of the function. The function 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 function expects when
it is called. Also, the parameters in the parameter list receives the argument 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 multiply two numbers,
which will be called from the main() function.
#include<stdio.h>

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


int main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);
result = multiply(i, j); // function call
printf("The result of muliplication is: %d", result);
return 0;
}
int multiply(int a, int b)
{

DIWAKAR EDUCATION HUB Page 69


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
return (a*b); // function defintion, this can be done in one line
}
Function definition Syntax
Just like in the example above, the general syntax of function definition is,
returntype functionName(type1 parameter1, type2 parameter2,...)
{
// function body goes here
}
The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known
as function header and the statement(s) within curly braces is called function body.
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function
header, unlike while declaring the function or calling the function.
functionbody
The function body contains the declarations and the statements(algorithm) necessary for
performing the required task. The body is enclosed within curly braces { ... } 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 return type 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 is function call.
Passing Arguments to a function
Arguments are the values specified during the function call, for which the formal parameters
are declared while defining the function.

DIWAKAR EDUCATION HUB Page 70


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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.

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 the variables while declaring, calling and defining a function can be different.
Returning a value from function
A function may or may not return a result. But if it does, we must use the return statement to
output the result. return statement also ends the function execution, hence it must be the last
statement of any function. If We write any statement after the return statement, it won't be
executed.

DIWAKAR EDUCATION HUB Page 71


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

The datatype of the value returned using the return statement should be same as the 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 in recursion.
Type of User-defined Functions in C
There can be 4 different types of user-defined functions, they are:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
Below, about all these types, along with program examples.
Function with no arguments and no return value
Such functions can either be used to display information or they are completely dependent on
user inputs.
Below is an example of a function, which takes 2 numbers as input from user, and display
which is the greater number.
#include<stdio.h>
void greatNum(); // function declaration
int main()
{
greatNum(); // function call
return 0;
}
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
DIWAKAR EDUCATION HUB Page 72
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
}
else {
printf("The greater number is: %d", j);
}
}
Function with no arguments and a return value
We have modified the above example to make the function greatNum() return the number
which is greater amongst the 2 input numbers.
#include<stdio.h>
int greatNum(); // function declaration
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum() // function definition
{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}
Function with arguments and no return value
We are using the same function as example again and again, to demonstrate that to 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 returning anything.
#include<stdio.h>
void greatNum(int a, int b); // function declaration
int main()
DIWAKAR EDUCATION HUB Page 73
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}
void greatNum(int x, int y) // function definition
{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}
Function with arguments and a return value
This is the best type, as this makes the function completely independent of inputs and
outputs, and only the logic is defined inside the function body.
#include<stdio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}
DIWAKAR EDUCATION HUB Page 74
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Nesting of Functions
C language also allows nesting of functions i.e to use/call one function inside another
function's body. We must be careful while using nested functions, because it may lead to
infinite nesting.
function1()
{
// function1 body here
function2();
// function1 body here
}
If function2() also has a call for function1() inside it, then in that case, it will lead to an infinite
nesting. They will keep calling each other and the program will never terminate.
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 go on for infinite times, until We forcefully exit
from program execution.
Recursion
Recursion is a special way of nesting functions, where a function calls itself inside it. We must
have certain conditions in the function to break out of the recursion, otherwise recursion will
occur infinite times.
function1()
{
// function1 body
function1();
// function1 body
}
Example: Factorial of a number using Recursion
#include<stdio.h>
int factorial(int x); //declaring the function
void main()
{
int a, b;
printf("Enter a number...");
scanf("%d", &a);
b = factorial(a); //calling the function named factorial
printf("%d", b);
}
int factorial(int x) //defining the function

DIWAKAR EDUCATION HUB Page 75


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
{
int r = 1;
if(x == 1)
return 1;
else
r = x*factorial(x-1); //recursion, since the function calls itself

return r;
}
Similarly, there are many more applications of recursion in C language. Go to the programs
section, to find out more programs using recursion.
File Handling in C
In programming, we may require some specific input data to be generated several numbers 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 of data 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 is volatile and can be accessed every time. Here, comes the need of file
handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.
i. Creation of the new file
ii. Opening an existing file
iii. Reading from the file
iv. Writing to the file
v. Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

DIWAKAR EDUCATION HUB Page 76


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

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

Opening File: fopen()


We must open a file before it can be read, write, or update. The fopen() function is used to
open a file. The syntax of the fopen() is given below.
o FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
 The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
 The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

DIWAKAR EDUCATION HUB Page 77


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

The fopen function works in the following way.


i. Firstly, It searches the file to be opened.
ii. Then, it loads the file from the disk and place it into the buffer. The buffer is used to
provide efficiency for the read operations.
iii. It sets up a character pointer which points to the first character of the file.
Consider the following example which opens a file in write mode.
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Output
The content of the file will be printed.
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
DIWAKAR EDUCATION HUB Page 78
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it. The syntax of fclose() function is given below:
1. int fclose( FILE *fp );
C fprintf() and fscanf()
C fprintf() and fscanf() example

C fputc() and fgetc()


C fputc() and fgetc() example

C fputs() and fgets()


C fputs() and fgets() example

C fseek()
C fseek() example
C fprintf() and fscanf()
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading File : fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
DIWAKAR EDUCATION HUB Page 79
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Hello file by fprintf...
C File Example: Storing employee information
A file handling example to store employee information as entered by user from console. We
are going to store id, name and salary of the employee.
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
Output:
Enter the id

DIWAKAR EDUCATION HUB Page 80


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin directory,
We will see emp.txt file. It will have following information.
emp.txt
Id= 1
Name= sonoo
Salary= 120000
Command Line Arguments in C
The arguments passed from command line are called command line arguments. These
arguments are handled by main() function.
To support command line argument, We need to change the structure of main() function as
given below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always.
Example
the example of command line arguments where we are passing one argument with file name.
#include <stdio.h>
void main(int argc, char *argv[] ) {

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

if(argc < 2){


printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
Run this program as follows in Linux:
./program hello
Run this program as follows in Windows from command line:
program.exe hello
Output:

DIWAKAR EDUCATION HUB Page 81


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Program name is: program
First argument is: hello
If we pass many arguments, it will print only one.
./program hello c how r u
Output:
Program name is: program
First argument is: hello
But if we pass many arguments within double quote, all arguments will be treated as a single
argument only.
./program "hello c how r u"
Output:
Program name is: program
First argument is: hello c how r u
We can write our program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.
C - Preprocessors
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. We'll refer to the C
Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor directives −
Sr.No. Directive & Description

1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

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

6 #if

DIWAKAR EDUCATION HUB Page 82


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Tests if a compile time condition is true.

7 #else
The alternative for #if.

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

9 #endif
Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11 #pragma
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.
Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
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 the local directory and add
the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if We
pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG,
so We can turn debugging on and off on the fly during compilation.

DIWAKAR EDUCATION HUB Page 83


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in programming,
the predefined macros should not be directly modified.
Sr.No. Macro & Description

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

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

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

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

5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.
try the following example −
#include <stdio.h>

int main() {

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


printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );

}
When the above code in a file test.c is compiled and executed, it produces the following
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
DIWAKAR EDUCATION HUB Page 84
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 −
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
The Stringize (#) Operator
The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a
macro parameter into a string constant. This operator may be used only in a macro having a
specified argument or parameter list. For example −
#include <stdio.h>

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

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

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

int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
When the above code is compiled and executed, it produces the following result −
token34 = 40
It happened so because this example results in the following actual output from the
preprocessor −
printf ("token34 = %d", token34);

DIWAKAR EDUCATION HUB Page 85


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 is not defined, the value is false (zero). The defined operator is specified
as follows −
#include <stdio.h>

#if !defined (MESSAGE)


#define MESSAGE "You wish!"
#endif

int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Here is the message: You wish!
Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a number as follows

int square(int x) {
return x * x;
}
We can rewrite above the code using a macro as follows −
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #define directive before they can be used.
The argument list is enclosed in parentheses and must immediately follow the macro name.
Spaces are not allowed between the macro name and open parenthesis. For example −
#include <stdio.h>

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

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

DIWAKAR EDUCATION HUB Page 86


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
}
When the above code is compiled and executed, it produces the following result −
Max between 20 and 10 is 20

Midpoint Ellipse Algorithm:


This is an incremental method for scan converting an ellipse that is centered at the origin in
standard position i.e., with the major and minor axis parallel to coordinate system axis. It is
very similar to the midpoint circle algorithm. Because of the four-way symmetry property we
need to consider the entire elliptical curve in the first quadrant.
first rewrite the ellipse equation and define the function f that can be used to decide if the
midpoint between two candidate pixels is inside or outside the ellipse:

Now divide the elliptical curve from (0, b) to (a, 0) into two parts at point Q where the slope of
the curve is -1.

Slope of the curve is defined by the f(x, y) = 0 is where fx & fy are partial derivatives of
f(x, y) with respect to x & y.

We have fx = 2b2 x, fy=2a2 y & Hence we can monitor the slope value during 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 i are (xi,yi).
We are to select either T (xi+1),yi) or S (xi+1,yi-1) to be the next pixel. The midpoint of T & S is
used to define the following decision parameter.

pi = f(xi+1),yi- )
pi=b2 (xi+1)2+a2 (yi- )2-a2 b2
If pi<0, the midpoint is inside the curve and we choose pixel T.
DIWAKAR EDUCATION HUB Page 87
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
If pi>0, the midpoint is outside or on the curve and we choose pixel S.
Decision parameter for the next step is:

pi+1=f(xi+1+1,yi+1- )
= b2 (xi+1+1)2+a2 (yi+1- )2-a2 b2
Since xi+1=xi+1,we have
pi+1-pi=b2[((xi+1+1)2+a2 (yi+1- )2-(yi - )2]
pi+1= pi+2b2 xi+1+b2+a2 [(yi+1- )2-(yi - )2]
If T is chosen pixel (pi<0), we have yi+1=yi.
If S is chosen pixel (pi>0) we have yi+1=yi-1. Thus we can express
pi+1in terms of pi and (xi+1,yi+1): pi+1= pi+2b2 xi+1+b2 if pi<0 = pi+2b2 xi+1+b2-
2a2 yi+1 if pi>0
The initial value for the recursive expression can be obtained by the evaluating the original
definition of pi with (0, b):

p1 = (b2+a2 (b- )2-a2 b2


= b2-a2 b+a2/4
Suppose the pixel (xj yj) has just been scan converted upon entering step j. The next pixel is
either U (xj ,yj-1) or V (xj+1,yj-1). The midpoint of the horizontal line connecting U & V is used
to define the decision parameter:

qj=f(xj+ ,yj-1)
qj=b2 (xj+ )2+a2 (yj -1)2-a2 b2
If qj<0, the midpoint is inside the curve and we choose pixel V.
If qj≥0, the midpoint is outside the curve and we choose pixel U.Decision parameter for the
next step is:

qj+1=f(xj+1+ ,yj+1-1)
= b2 (xj+1+ )2+ a2 (yj+1-1)2- a2 b2
Since yj+1=yj-1,we have
qj+1-qj=b2 [(xj+1+ )2-(xj + )2 ]+a2 (yj+1-1)2-( yj+1)2 ]
qj+1=qj+b2 [(xj+1+ )2-(xj + )2]-2a2 yj+1+a2
If V is chosen pixel (qj<0), we have xj+1=xj.
If U is chosen pixel (pi>0) we have xj+1=xj. Thus we can express
qj+1in terms of qj and (xj+1,yj+1 ):
qj+1=qj+2b2 xj+1-2a2 yj+1+a2 if qj < 0
2 2
=qj-2a yj+1+a 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 part 1 of the curve:
DIWAKAR EDUCATION HUB Page 88
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

q1 = f(xk+ ,yk-1)=b2 (xk+ )2-a2 (yk-1)2- a2 b2


Algorithm:
int x=0, y=b; [starting point]
int fx=0, fy=2a2 b [initial partial derivatives]
int p = b2-a2 b+a2/4
while (fx<="" 1="" {="" set="" pixel="" (x,="" y)="" x++;="" fx="fx" +="" 2b2;
if (p<0)
p = p + fx +b2;
else
{
y--;
fy=fy-2a2
p = p + fx +b2-fy;
}
}
Setpixel (x, y);
p=b2(x+0.5)2+ a2 (y-1)2- a2 b2
while (y>0)
{
y--;
fy=fy-2a2;
if (p>=0)
p=p-fy+a2
else
{
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

DIWAKAR EDUCATION HUB Page 89


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 view the object
from different angles, enlarging or reducing the scale or shape of object called as
Transformation.
Two essential aspects of transformation are given below:
1. Each transformation is a single entity. It can be denoted by a unique name or symbol.
2. It is possible to combine two transformations, after connecting a single transformation
is obtained, e.g., A is a transformation for translation. The B transformation performs
scaling. The combination of two is C=AB. So C is obtained by concatenation property.
There are two complementary points of view for describing object 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 of the object.
2. Coordinate Transformation: The object is held stationary while the coordinate system is
transformed relative to the object. This effect is attained through the application of
coordinate transformations.
An example that helps to distinguish these two viewpoints:
The movement of an automobile against a scenic background we can simulate this by
o Moving the automobile while keeping the background fixed-(Geometric Transformation)
o We can keep the car fixed while moving the background scenery- (Coordinate
Transformation)
Types of Transformations:
1. Translation
2. Scaling
3. Rotating
4. Reflection
5. Shearing
Note: Translation, Scaling, and Rotation are also called as Basic Transformations.
Translation
It is the straight line movement of an object from one position to another is called Translation.
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+Tx
y1=y+Ty
The translation pair (Tx,Ty) is called as shift vector.

DIWAKAR EDUCATION HUB Page 90


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Translation is a movement of objects without deformation. Every position or point is
translated by the same amount. When the straight line is translated, then it will be drawn
using endpoints.
For translating polygon, each vertex of the polygon is converted to a new position. Similarly,
curved objects are translated. To change the position of the circle or ellipse its center
coordinates are transformed, then the object is drawn using new coordinates.
Let P is a point with coordinates (x, y). It will be translated as (x1 y1).

Matrix for Translation:

Scaling:
It is used to alter or change the size of objects. The change is done using scaling factors. 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 of coordinates 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 are not equal
then scaling will occur but it will elongate or distort the picture.

DIWAKAR EDUCATION HUB Page 91


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
If scaling factors are less than one, then the size of the object will be reduced. If scaling factors
are higher than one, then the size of the object will be enlarged.
If Sxand Syare equal it is also called as Uniform Scaling. If not equal then called as Differential
Scaling. If scaling factors with values less than one will move the object closer to coordinate
origin, while a value higher than one will move coordinate position farther from origin.

Enlargement: If T1= ,If (x1 y1)is original position and T1is translation vector then (x2 y2) are
coordinated after scaling

The image will be enlarged two times

Reduction: If T1= . If (x1 y1) is original position and T1 is translation vector, then (x2 y2)
are coordinates after scaling

DIWAKAR EDUCATION HUB Page 92


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Matrix for Scaling:

Example: Prove that 2D Scaling transformations are commutative i.e, S1 S2=S2 S1.
Solution: S1 and S2 are scaling matrices

DIWAKAR EDUCATION HUB Page 93


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 rotation point. 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 a counter-clockwise
(anti-clockwise) direction.
The negative value of the pivot point (rotation angle) rotates an object in a clockwise 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 and redrawing the
line between new endpoints.
Polygon: Polygon is rotated by shifting every vertex using the same rotational angle.
Curved Lines: Curved Lines are rotated by repositioning of all points and drawing of the curve
at new positions.
Circle: It can be obtained by center position by the specified angle.
Ellipse: Its rotation can be obtained by rotating major and minor axis of an ellipse by the
desired angle.

DIWAKAR EDUCATION HUB Page 94


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Matrix for rotation is a clockwise direction.

Matrix for rotation is an anticlockwise direction.

DIWAKAR EDUCATION HUB Page 95


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Matrix for homogeneous co-ordinate rotation (clockwise)

Matrix for homogeneous co-ordinate rotation (anticlockwise)

Rotation about an arbitrary point: If we want to rotate an object or point about an arbitrary
point, first of all, we translate the point about which we want to rotate to the origin. Then
rotate point or object about the origin, and at the end, we again translate it to the original
place. We get rotation about an arbitrary point.
Example: The point (x, y) is to be rotated
The (xc yc) is a point about which counterclockwise rotation is done
Step1: Translate point (xc yc) to origin

Step2: Rotation of (x, y) about the origin

DIWAKAR EDUCATION HUB Page 96


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Step3: Translation of center of rotation back to its original position

DIWAKAR EDUCATION HUB Page 97


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Example1: Prove that 2D rotations about the origin are commutative i.e. R1 R2=R2 R1.
Solution: R1 and R2are rotation matrices

Example2: Rotate a line CD whose endpoints are (3, 4) and (12, 15) about origin through a 45°
anticlockwise direction.
Solution: The point C (3, 4)

DIWAKAR EDUCATION HUB Page 98


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

DIWAKAR EDUCATION HUB Page 99


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Example3: Rotate line AB whose endpoints are A (2, 5) and B (6, 12) about origin through a 30°
clockwise direction.
Solution: For rotation in the clockwise direction. The matrix is

Step1: Rotation of point A (2, 5). Take angle 30°

Step2: Rotation of point B (6, 12)

DIWAKAR EDUCATION HUB Page 100


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Reflection:
It is a transformation which produces a mirror image of an object. The mirror image can be
either about x-axis or y-axis. The object is rotated by180°.
Types of Reflection:
1. Reflection about the x-axis
2. Reflection about the y-axis
3. Reflection about an axis perpendicular to xy plane and passing through the origin
4. Reflection about line y=x
1. Reflection about x-axis: The object can be reflected about x-axis with the help of the
following matrix

In this transformation value of x will remain same whereas the value of y will become
negative. Following figures shows the reflection of the object axis. The object will lie another
side of the x-axis.

DIWAKAR EDUCATION HUB Page 101


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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

3. Reflection about an axis perpendicular to xy plane and passing through origin:


In the matrix of this transformation is given below

DIWAKAR EDUCATION HUB Page 102


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

In this value of x and y both will be reversed. This is also called as half revolution about the
origin.
4. Reflection about line y=x: The object may be reflected about line y = x with the help of
following transformation matrix

First of all, the object is rotated at 45°. The direction of rotation is clockwise. After it 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:

DIWAKAR EDUCATION HUB Page 103


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

The a point coordinates after reflection

The b point coordinates after reflection

The coordinate of point c after reflection

a (3, 4) becomes a1 (3, -4)


b (6, 4) becomes b1 (6, -4)
c (4, 8) becomes c1 (4, -8)
Program to perform Mirror Reflection about a line:
#include <iostream.h>
#include <conio.h>
#include <graphics.h>
DIWAKAR EDUCATION HUB Page 104
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
#include <math.h>
#include <stdlib.h>
#define pi 3.14
class arc
{
float x[10],y[10],theta,ref[10][10],ang;
float p[10][10],p1[10][10],x1[10],y1[10],xm,ym;
int i,k,j,n;
public:
void get();
void cal ();
void map ();
void graph ();
void plot ();
void plot1();
};
void arc::get ()
{
cout<<"\n ENTER ANGLE OF LINE INCLINATION AND Y INTERCEPT";
cin>> ang >> b;
cout <<"\n ENTER NO OF VERTICES";
cin >> n;
cout <<"\n ENTER";
for (i=0; i<n; i++)
{
cout<<"\n x["<<i<<"] and y["<<i<<"]";
}
theta =(ang * pi)/ 180;
ref [0] [0] = cos (2 * theta);
ref [0] [1] = sin (2 * theta);
ref [0] [2] = -b *sin (2 * theta);
ref [1] [0] = sin (2 * theta);
ref [1] [1] = -cos (2 * theta);
ref [1] [2] = b * (cos (2 * theta)+1);
ref [2] [0]=0;
ref [2] [1]=0;
ref [2] [2] = 1;
}
void arc :: cal ()
DIWAKAR EDUCATION HUB Page 105
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
{
for (i=0; i < n; i++)
{
p[0] [i] = x [i];
p [1] [i] = y [i];
p [2] [i] = 1;
}
for (i=0; i<3;i++)
{
for (j=0; j<n; j++)
{
p1 [i] [j]=0;
for (k=0;k<3; k++)
}
p1 [i] [j] + = ref [i] [k] * p [k] [j];
}
for (i=0; i<n; i++)
{
x1 [i]=p1[0] [i];
y1 [i] = p1 [1] [i];
}
}
void arc :: map ()
{
int gd = DETECT,gm;
initgraph (&gd, &gm, " ");
int errorcode = graphresult ();
/* an error occurred */
if (errorcode ! = grOK)
{
printf ("Graphics error: %s \n", grapherrormsg (errorcode));
printf ("Press any key to halt:");
getch ();
exit (1); /* terminate with an error code */
}
}
void arc :: graph ()
{
xm=getmaxx ()/2;
DIWAKAR EDUCATION HUB Page 106
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
ym=getmaxy ()/2;
line (xm, 0, xmm 2*ym);
}
void arc :: plot 1 ()
{
for (i=0; i <n-1; i++)
{
circle (x1[i]+xm, (-y1[i]+ym), 2);
line (x1[i]+xm, (-y1[i]+ym), x1[i+1]+xm, (-y1[i+1]+ym));
}
line (x1[n-1)+xm, (-y1[n-1]+ym), x1[0]+xm, (-y1[0]+ym));
getch();
}
void arc :: plot ()
{
for (i=0; i <n-1; i++)
{
circle (x1[i]+xm, (-y1[i]+ym, 2);
line (x1[i]+xm, (-y1[i]+ym), x[i+1]+xm, (-y1[i+1]+ym));
}
line (x[n-1]+xm, (-y1[n-1]+ym), x[0]+xm, (-y[0]+ym));
getch();
}
void main ()
{
class arc a;
clrscr();
a.map();
a.graph();
a.get();
a.cal();
a.plot();
a.plot1();
getch();
}
Output:

DIWAKAR EDUCATION HUB Page 107


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Shearing:
It is transformation which changes the shape of object. The sliding of layers of object 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. The
homogeneous matrix for shearing in the x-direction is shown below:

Shearing in the Y-direction: Here shearing is done by sliding along vertical or y-axis.

Shearing in X-Y directions: Here layers will be slided in both x as well as y direction. The sliding
will be in horizontal as well as vertical direction. The shape of the object will be distorted. The
matrix of shear in both directions is given by:

Matrix Representation of 2D Transformation

DIWAKAR EDUCATION HUB Page 108


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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, the amount, by which picture
is required to be shifted.
Translation of point by the change of coordinate cannot be combined with other
transformation by using simple matrix application. Such a combination is essential if 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 picture into 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-

DIWAKAR EDUCATION HUB Page 109


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
zero value. For our convenience take it as one. Each two-dimensional position is then
represented with homogeneous coordinates (x, y, 1).
Following are matrix for two-dimensional transformation in homogeneous coordinate:

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
1. Translation
2. Rotation
3. Reverse Translation

DIWAKAR EDUCATION HUB Page 110


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
The ordering sequence of these numbers of transformations must not be changed. If a matrix
is represented in column form, then the composite transformation is performed by multiplying
matrix in order from right to left side. The output obtained from the previous matrix is
multiplied with the new coming matrix.
Example showing composite transformations:
The enlargement is with respect to center. For this following sequence of transformations will
be performed and all will be combined to a single one
Step1: The object is kept at its position as in fig (a)
Step2: The object is translated so that its center coincides with the origin as in fig (b)
Step3: Scaling of an object by keeping the object at origin is done in fig (c)
Step4: Again translation is done. This second translation is called a reverse translation. It will
position the object at the origin location.
Above transformation can be represented as TV.STV-1

DIWAKAR EDUCATION HUB Page 111


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Note: Two types of rotations are used for representing matrices one is column method.
Another is the row method.

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 obtained after multiplication.

Above resultant matrix show that two successive translations are additive.
Composition of two Rotations: Two Rotations are also additive
Composition of two Scaling: The composition of two scaling is multiplicative. Let S11 and S12are
matrix to be multiplied.

Computer Graphics Window to Viewport Co-ordinate Transformation

DIWAKAR EDUCATION HUB Page 112


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Once object description has been transmitted to the viewing reference frame, we choose the
window extends in viewing coordinates and selects the viewport limits in 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) in window mapped
into position (xv, yv) in the associated viewport.

In order to maintain the same relative placement of the point in the viewport as in the
window, we require:

Solving these impressions for the viewport position (xv, yv), we have
xv=xvmin+(xw-xwmin)sx
yv=yvmin+(yw-ywmin)sy ...........equation 2
Where scaling factors are

DIWAKAR EDUCATION HUB Page 113


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 screen coordinate area. This
conversation is performed with the following sequence of transformations:
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. Relative proportions
of objects are maintained if the scaling factors are the same (sx=sy).
From normalized coordinates, object descriptions are mapped to the various display 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 output device.
This mapping called workstation transformation (It is accomplished by selecting a window 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 of normalized
space can be displayed on various output devices).

DIWAKAR EDUCATION HUB Page 114


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Matrix Representation of the above three steps of Transformation:

Step1:Translate window to origin 1


Tx=-Xwmin Ty=-Ywmin
Step2:Scaling of the window to match its size to the viewport
Sx=(Xymax-Xvmin)/(Xwmax-Xwmin)
Sy=(Yvmax-Yvmin)/(Ywmax-Ywmin)

DIWAKAR EDUCATION HUB Page 115


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Step3:Again translate viewport to its correct position on screen.
Tx=Xvmin
Ty=Yvmin
Above three steps can be represented in matrix form:
VT=T * S * T1
T = Translate window to the origin
S=Scaling of the window to viewport size
T1=Translating viewport on screen.

Viewing Transformation= T * S * T1
Advantage of Viewing Transformation:
We can display picture at device or display system according to our need and choice.
Note:
 World coordinate system is selected suits according to the application program.
 Screen coordinate system is chosen according to the need of design.
 Viewing transformation is selected as a bridge between the world and screen
coordinate.
Line Clipping:
It is performed by using the line clipping algorithm. The line clipping algorithms are:
1. Cohen Sutherland Line Clipping Algorithm
2. Midpoint Subdivision Line Clipping Algorithm
3. Liang-Barsky Line Clipping Algorithm
Cohen Sutherland Line Clipping Algorithm:
In the algorithm, first of all, it is detected whether line lies inside the screen or it is outside the
screen. All lines come under any one of the following categories:
1. Visible
2. Not Visible
3. Clipping Case
1. Visible: If a line lies within the window, i.e., both endpoints of the line lies within the
window. A line is visible and will be displayed as it is.

DIWAKAR EDUCATION HUB Page 116


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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, then the line is considered
invisible. Let A (x1,y2) and B (x2,y2) are endpoints of line.
xmin,xmax are coordinates of the window.
ymin,ymax are also coordinates of the window.
x1>xmax
x2>xmax
y1>ymax
y2>ymax
x1<xmin
x2<xmin
y1<ymin
y2<ymin
3. Clipping Case: If the line is neither visible case nor invisible case. It is considered to be
clipped case. First of all, the category of a line is found based on nine regions given below. All
nine regions are assigned codes. Each code is of 4 bits. If both endpoints of the line have end
bits zero, then the line is considered to be visible.

The center area is having the code, 0000, i.e., region 5 is considered a rectangle window.
Following figure show lines of various types

DIWAKAR EDUCATION HUB Page 117


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 candidate
Line CD are clipping candidate
Advantage of Cohen Sutherland Line Clipping:
1. It calculates end-points very quickly and rejects and accepts lines quickly.
2. It can clip pictures much large than screen size.
Algorithm of Cohen Sutherland Line Clipping:
Step1:Calculate positions of both endpoints of the line
Step2:Perform OR operation on both of these end-points
Step3:If the OR operation gives 0000
Then
line is considered to be visible
else
Perform AND operation on both endpoints
If And ≠ 0000
then the line is invisible
else
And=0000
Line is considered the clipped case.
Step4:If a line is clipped case, find an intersection with boundaries of the window
m=(y2-y1 )(x2-x1)
(a) If bit 1 is "1" line intersects with left boundary of rectangle window
y3=y1+m(x-X1)
where X = Xwmin
where Xwminis the minimum value of X co-ordinate of window
(b) If bit 2 is "1" line intersect with right boundary
y3=y1+m(X-X1)
where X = Xwmax
where X more is maximum value of X co-ordinate of the window
(c) If bit 3 is "1" line intersects with bottom boundary
X3=X1+(y-y1)/m
where y = ywmin
ywmin is the minimum value of Y co-ordinate of the window
(d) If bit 4 is "1" line intersects with the top boundary
X3=X1+(y-y1)/m
where y = ywmax
ywmax is the maximum value of Y co-ordinate of the window
Example of Cohen-Sutherland Line Clipping Algorithm:

DIWAKAR EDUCATION HUB Page 118


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Let R be the rectangular window whose lower left-hand corner is at L (-3, 1) and upper right-
hand corner is at R (2, 6). Find the region codes for the endpoints in fig:

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

So
A (-4, 2)→ 0001 F (1, 2)→ 0000
B (-1, 7) → 1000 G (1, -2) →0100
C (-1, 5)→ 0000 H (3, 3) → 0100
D (3, 8) → 1010 I (-4, 7) → 1001
E (-2, 3) → 0000 J (-2, 10) → 1000
We place the line segments in their appropriate categories by testing the region codes found
in the problem.
Category1 (visible): EF since the region code for both endpoints is 0000.
Category2 (not visible): IJ since (1001) AND (1000) =1000 (which is not 0000).
Category 3 (candidate for clipping): AB since (0001) AND (1000) = 0000, CD since (0000) AND
(1010) =0000, and GH. since (0100) AND (0010) =0000.
The candidates for clipping are AB, CD, and GH.
DIWAKAR EDUCATION HUB Page 119
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 3 since (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 remaining segment 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
3. Hexagon
4. Pentagon
Following figures shows some polygons.

DIWAKAR EDUCATION HUB Page 120


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 concave polygon has one interior angle
greater than 180°. So that it can be clipped into similar polygons.

DIWAKAR EDUCATION HUB Page 121


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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.

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 the clipping 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 the following figure.

DIWAKAR EDUCATION HUB Page 122


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 −

3-D 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

DIWAKAR EDUCATION HUB Page 123


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
 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 to determine
their response to stress and temperature etc.
Polygon Surfaces
Objects are represented as a collection of surfaces. 3D object representation is divided into
two categories.
 Boundary Representations B−repsB−reps − It describes a 3D object as a set of surfaces
that 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 set of 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 use this 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 of surface structure.
Then realistic scenes are produced by interpolating shading patterns across polygon surface to
illuminate.

Curved Surfaces

1. Regular curved surfaces can be generated as


- Quadric Surfaces, eg. Sphere, Ellipsoid, or
- Superquadrics, eg. Superellipsoids

DIWAKAR EDUCATION HUB Page 124


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

2. Irregular
surfaces can also be generated
using some special formulating approach,
to form a kind of blobby objects -- The
shapes 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 the length 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 line segment in
three dimensional space about the Z axis. The axis of rotation is always the z axis. Each quadric
DIWAKAR EDUCATION HUB Page 125
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
routine has a sweep parameter, specifying the angular extent to which the quadric is swept
about z axis. Sweeping a quadric by less 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 modeling applications.
All the following quadrics are rotationally symmetric about the z axis. In all the
quadrics 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 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:

DIWAKAR EDUCATION HUB Page 126


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Note that if zmin > -radius or zmax < radius, the bottom or top of the sphere is open, and that
if thetamax is not equal to 360 degrees, the sides are also open.
RIB BINDING
Sphere radius zmin zmax thetamax parameterlist
Sphere [radius zmin zmax thetamax] parameterlist
EXAMPLE
RiSphere(0.5, 0.0, 0.5, 360.0, RI_NULL);
RiCone( height, radius, thetamax, parameterlist )
RtFloat height;
RtFloat radius;
RtFloat thetamax;
Requests a cone defined by the following equations:

Note that the bottom of the cone is open, and if thetamax is not equal to 360 degrees, the
sides are open.
RIB BINDING
Cone height radius thetamax parameterlist
Cone [height radius thetamax] parameterlist
EXAMPLE
RtColor four_colors[4];
RiCone(0.5, 0.5, 270.0, "Cs", (RtPointer)four_colors, RI_NULL);
RiCylinder( radius, zmin, zmax, thetamax, parameterlist )
RtFloat radius;
RtFloat zmin, zmax;
RtFloat thetamax;
Requests a cylinder defined by the following equations:

Note that the cylinder is open at the top and bottom, and if thetamax is not equal to 360
degrees, the sides also are open.
RIB BINDING

DIWAKAR EDUCATION HUB Page 127


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Cylinder radius zmin zmax thetamax parameterlist


Cylinder [radius zmin zmax thetamax] parameterlist
Bezier Curves
Bezier curve is discovered by the French engineer Pierre Bézier. These curves can be
generated under the control of other points. Approximate tangents by using control points are
used to generate curve. The Bezier curve can be represented mathematically as −

Where pipi is the set of points and Bni(t)Bin(t) represents the Bernstein polynomials which are
given by −

Where n is the polynomial degree, i is the index, and t is the variable.


The simplest Bézier curve is the straight line from the point P0P0 to P1P1. A quadratic Bezier
curve is determined by three control points. A cubic Bezier curve is determined by four control
points.

Properties of Bezier Curves


Bezier curves have the following properties −
 They generally follow the shape of the control polygon, which consists of the 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, the degree of the polynomial is
3, i.e. cubic polynomial.
 A Bezier curve generally follows the shape of the defining polygon.

DIWAKAR EDUCATION HUB Page 128


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
 The direction of the tangent vector at the end points is same as that of the vector
determined by first and last segments.
 The convex hull property for a Bezier curve ensures that the polynomial smoothly
follows the control points.
 No straight line intersects a Bezier curve more times than it intersects its control
polygon.
 They are invariant under an affine transformation.
 Bezier curves exhibit global control means moving a control point alters the shape 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 parameter value 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 the resulting
polynomial which defines the curve.
 The second limiting characteristic is that the value of the blending function is nonzero
for all parameter values over the entire curve.
The B-spline basis contains the Bernstein basis as the special case. The B-spline basis 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,

DIWAKAR EDUCATION HUB Page 129


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 of defining polygon.
 The degree of B-spline polynomial is independent on the number of vertices of defining
polygon.
 B-spline allows the local control over the curve surface because each vertex affects the
shape of a curve only over a range of parameter values where its associated 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 the vertices of
defining polygon.
 The curve line within the convex hull of its defining polygon.
Bezier and B-spline Surfaces
Bezier Surfaces.
Like the Bezier curves, the Bezier surfaces use the Bernstein polynomials as blending functions.
We now have the control points being points on a design net, which is again a rectangular
mesh spread over area of interest. The x and y coordinates of the control points are fixed and
the shape of the surface varies as the control points are moved up or down. The figure below
shows a Bezier surface with an associated control net of 3 points by 4 points. The values of the
points are stored in an array B(4,3) and the blending functions are obtained from the
equations of the Bezier curves.

DIWAKAR EDUCATION HUB Page 130


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Bezier Surface and Control Net


Thus, the three point Bezier curve is given by :
B(v) = (1-v)2B(I,1) + 2v(1-v)B(I,2) + v2B(I,3)
or
B(v) = b(20)(v) B(I,1) + b(21)(v) B(I,2) + b(22)(v) B(I,3)
and the 4-point Bezier curve needed in the u-direction has the form:
B(u) = (1-u)3B(1,J) + 3u(1-u)2B(2,J) + 3u2(1-u)B(3,J) + u3B(4,J)
or B(u) = b{30}(u)B(1,J) + b{31}(u) B(2,J) + b{32}(u) B(3,J) + b{33}(u) B(4,J)
These must be combined together in the matrix equation to calculate any point on the surface.
The equation of a point on the Bezier surface is given by:
r(u,v) = [b{30}(u) b{31}(u) b{32}(u) b{33}(u)] B(1,1)B(1,2) B(1,3) b{20}(v)
B(2,1) B(2,2) B(2,3) b{21}(v)
B(3,1) B(3,2) B(3,3) b{22}(v)
B(4,1) B(4,2) B(4,3)
To obtain the equation of one of the edge-curves, e.g. when u=0, we must substitute in the
matrix equation:
r(0,v) = B(1,1) B(1,2) B(1,3) (1-v)(1-v)
2v(1-v)
v*v
which becomes r(0,v) = (1-v)(1-v)B(1,1) + 2v(1-v)B(1,2) + v*vB(1,3) and similarly for the other
edge curves. This form of the Bezier curve assumes a rectangular mesh with m+1 points in the
one direction and n+1 points in the other. It requires the 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'. This included 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
DIWAKAR EDUCATION HUB Page 131
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 extra smoothness of functions which
can only be guaranteed by bicubic or higher-order patches.
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 or three C.A.D. programs to use, and
there was very 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 a
mistake 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 local control of the
shape. The equation of this surface is given by
Q(u,v) = sum{i=0 to m} sum{j=0 to n} B(i+1,j+1) N{i,k}(u) M{j,l}(v)
In the x-direction, x(i) are the elements of the k-knot vector and

N{i,1}(u) = 1 if x(i) <= u <= x(i+1)


= 0 otherwise
and
N{i.k}(u) = (u-x(i)) * N{i,k-1}(u) + (x(i+k)-u) * N{i+1,k-1}(u)
--------------------- -------------------------
(x(i+k-1)-x(i)) (x(i+k)-x(i+1))

In the y-direction, the y(j) are elements of the l-knot vector and we have similar expressions
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 curves are 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. There are three factors on which
lightning effect depends on:
1. Light Source :
Light source is the light emitting source. There are three types of light sources:
1. Point Sources – The source that emit rays in all directions (A bulb in a room).
2. Parallel Sources – Can be considered as a point source which is far from the
surface (The sun).
3. Distributed Sources – Rays originate from a finite area (A tubelight).
Their position, electromagnetic spectrum and shape determine the lightning effect.

DIWAKAR EDUCATION HUB Page 132


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
2. Surface :
When light falls on a surface part of it is reflected and part of it is absorbed. Now the
surface structure decides the amount of reflection and absorption of light. The position
of the surface and positions of all the nearby surfaces also determine the lightning
effect.
3. Observer :
The observer’s position and sensor spectrum sensitivities also affect the lightning effect.
1. Ambient Illumination :
Assume We are standing on a road, facing a building with glass exterior and sun
rays are falling on that building reflecting back from it and the falling on the
object under observation. This would be Ambient Illumination. In simple words,
Ambient Illumination is the one where source of light is indirect.
The reflected intensity Iamb of any point on the surface is:

2. Diffuse Reflection :
Diffuse reflection occurs on the surfaces which are rough or grainy. In this reflection the
brightness of a point depends upon the angle made by the light source and the surface.
The reflected intensity Idiff of a point on the surface is:

3. Specular Reflection:
When light falls on any shiny or glossy surface most of it is reflected back, such reflection is
known as Specular Reflection.
Phong Model is an empirical model for Specular Reflection which provides us with the formula
for calculation the reflected intensity Ispec:

DIWAKAR EDUCATION HUB Page 133


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

Polygen Rending Methods

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 the following
calculations:
1. Determining the average unit normal vector at each polygon vertex.
DIWAKAR EDUCATION HUB Page 134
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
2. Apply an illumination model to each vertex to determine the vertex intensity.
3. Linear interpolate the vertex intensities over the surface of the polygon.
At each polygon vertex, we obtain a normal vector by averaging the surface normals of all
polygons staring that vertex as shown in fig:

Thus, for any vertex position V, we acquire the unit vertex normal with the calculation

Once we have the vertex normals, we can determine the intensity at the vertices from a
lighting model.
Following figures demonstrate the next step: Interpolating intensities along the polygon
edges. For each scan line, the intensities at the intersection of the scan line with a polygon
edge are linearly interpolated from the intensities at the edge endpoints. For example: In fig,
the polygon edge with endpoint vertices at position 1 and 2 is intersected by the scanline at
point 4. A fast method for obtaining the intensities at point 4 is to interpolate between
intensities I1 and I2 using only the vertical displacement of the scan line.

DIWAKAR EDUCATION HUB Page 135


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 the previous fig) is interpolated from the
bounding intensities at point 4 and 5 as

Incremental calculations are used to obtain successive edge intensity values between scan
lines and to obtain successive intensities along a scan line as shown in fig:

DIWAKAR EDUCATION HUB Page 136


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

If the intensity at edge position (x, y) is interpolated as

Then we can obtain the intensity along this edge for the next scan line, Y-1 as

Similar calculations are used to obtain intensities at successive horizontal pixel positions along
each scan line.
When surfaces are to be rendered in color, the intensities of each color component is
calculated at the vertices. Gouraud Shading can be connected with a 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 following figure:

DIWAKAR EDUCATION HUB Page 137


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 into a 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., of the camera) an additional
projection step is done, which is the reduction of 3D-data onto a projection plane:

This projection step can be arbitrarily complex, depending on which 3D-viewing concepts
should be used.
Viewing-Coordinates
Similar to photography there are certain degrees of freedom when specifying the camera:
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 (viewing coordinates). Usually
the xy-plane of
this viewing-coordinate system is orthogonal to the main viewing direction and the viewing
direction is in the direction of the negative z-axis.
Based on the camera position the usual way to define the viewing-coordinate system is:

DIWAKAR EDUCATION HUB Page 138


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
1. Choose a camera position (also called eye-point, or view-point).
2. Choose a viewing direction = Choose the z– direction of the viewing-coordinates.
3. Choose a direction „upwards“. From this, the x-axis and y-axis can be calculated: the
image-plane is orthogonal to the viewing direction. The parallel projection of the „view-up
vector“ onto this image plane defines the y-axis of the viewing coordinates.
4. Calculate the x-axis as vector-product of the z- and y-axis.
5. The distance of the image-plane from the eye-point defines the viewing angle, which is the
size of the scene to be displayed.
In animations the camera-definition is often automatically calculated according to certain
conditions, e.g. when the camera moves around an object or in flight-simulations, such that
desired effects can be achieved in an uncomplicated way.
To convert world-coordinates to viewing-coordinates a series of simple transformations is
needed: mainly a translation of the coordinate origins onto each other and afterwards 3
rotations, such that the coordinate-axes also coincide (two rotations for the first axis, one for
the second axis, and the third axis is already correct then). Of course, all these
transformations can be merged by multiplication into one matrix, which looks about like this:
MWC,VC = Rz· Ry· Rx· T

Projection
It is the process of converting a 3D object into a 2D object. It is also defined as mapping or
transformation of the object in projection plane or view plane. The view plane is displayed
surface.

DIWAKAR EDUCATION HUB Page 139


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 the center of projection. More
we increase 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, two point, 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 in the y -direction
as shown in fig (b)

DIWAKAR EDUCATION HUB Page 140


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
Three Points: There are three vanishing points. One is x second in y and third in two 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 plane of 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.
Anomalies in Perspective Projection
It introduces several anomalies due to these object shape and appearance gets affected.
1. Perspective foreshortening: The size of the object will be small of its distance from the
center 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 is appearing to
six rollers.

DIWAKAR EDUCATION HUB Page 141


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 a y-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 is the projection of vertex.
Parallel projections are used by architects and engineers for creating working drawing of the
object, for complete representations require two or more views of an object using different
planes.

DIWAKAR EDUCATION HUB Page 142


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

1. Isometric Projection: All projectors make equal angles generally angle is of 30°.
2. Dimetric: In these two projectors have equal angles. With respect to two principle axis.
3. Trimetric: The direction of projection makes unequal angle with their principle axis.
4. Cavalier: All lines perpendicular to the projection plane are projected with no change in
length.
5. Cabinet: All lines perpendicular to the projection plane are projected to one half of their
length. These give a realistic appearance of object.

DIWAKAR EDUCATION HUB Page 143


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

DIWAKAR EDUCATION HUB Page 144


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

DIWAKAR EDUCATION HUB Page 145


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

DIWAKAR EDUCATION HUB Page 146


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

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 computer with 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:
[−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 world space 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 we are 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 resolutions changes. Although we might want to
change that also.
There are actually many frames of references and transformations between our vertices and
what we see on the screen. look at them one at a time.
World Space

DIWAKAR EDUCATION HUB Page 147


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3

First, our vertices are usually defined in the object space. We will try to center our object
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

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 will be 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

DIWAKAR EDUCATION HUB Page 148


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
convenience function that underneath will construct the corresponding matrix that will do the
camera transformation in this step. see, how this can be done.
We know:
 Camera's position in world space. Call it pp.
 Camera's up-vector. Call it uu.
 Camera's looking direction. Call it ll.
Well, the first step would be to align the origins. So we want to move all our objects 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 be just −p.
So the first transformations would be:

Next we need to align the axes. Now, the vector ll shows the direction we are facing, but
because the z-axis should be in the negative direction, we will reverse it: w=−l. We assume
that vectors uu and ww are orthogonal to each other and of unit length. We still need one
orthogonal vector, the right vector, in order to have the camera basis. We could use the Gram-
Schmidt process here, but a more simpler way to find an orthogonal unit vector, given already
two, would be to use the 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 cross product, 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 of reference. The
transformation that would transform the camera basis from the world basis (ignoring the
translation for now) would be:

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
transpose of it. All rotation matrices are orthogonal matrices and a multiplication of two

DIWAKAR EDUCATION HUB Page 149


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
rotation matrices is a rotation matrix. Our camera basis will differ from the world basis only by
a number of rotations. So in order to find out how to transform the world so that the camera
basis would be aligned with the world basis, we only need to take the inverse of those
rotation. That is the inverse of the matrix we just found. The inverse is currently just the
transpose of it.
The total view transformation would be then:

In some sources the view transformation is called the inverse of the camera transformation.
There the camera transformation is the transformation that transforms the actual camera as
an object. In other sources the camera transformation is the transformation that transforms
all the vertices into the camera space. One should explain what is actually meant when using
those terms. The term view transformation (the view matrix) is generally more common.
Clip Space

Third step is to construct the clip space. This is the space that should be seen from the camera.
In our illustration here there is a 2D projection of it. In 3D We will also have a top and a
bottom plane. 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.
DIWAKAR EDUCATION HUB Page 150
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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, are ignored. 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, then we can put every vertex in the
plane equation and see which side of the plane a vertex lies.
We will look this and the next step in more detail when talking about different projections.
Canonical View Volume

Fourth step is to transform everything so that the clip space will form a canonical view 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 we had 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 transformations and 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 even
something else. After this transformation, there is a need for the perspective division, because
the value of w will usually 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 we see the world.
DIWAKAR EDUCATION HUB Page 151
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
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 be of the same length as the final
range, and then translate it so that they cover each other.

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 seem to be reversed. This will be
handled later by OpenGL, currently we just assume that the (0,0) in the screen space is at the
DIWAKAR EDUCATION HUB Page 152
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT - 3
bottom-left corner and the positive directions are up and right. Also the z value will later be
normalized to a range [0,1].

DIWAKAR EDUCATION HUB Page 153


DIWAKAR EDUCATION HUB

PROGRAMMING LANGUAGES AND


COMPUTER GRAPHICS UNIT – 3 MCQS

As per updated syllabus


DIWAKAR EDUCATION HUB

THE LEARN WITH EXPERTIES


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
1) What is the 16-bit compiler allowable 4) What will this program print?
range for integer constants? main()
a) -3.4e38 to 3.4e38 {
b) -32767 to 32768 int i = 2;
c) -32668 to 32667 {
d) -32768 to 32767
int i = 4, j = 5;
Answer: (d) -32768 to 32767
printf("%d %d", i, j);
Explanation: In a 16-bit C compiler, we have
}
2 bytes to store the value.
printf("%d %d", i, j);
o The range for signed integers is -32768
to 32767. }
o The range for unsigned integers is 0 to
a. 4525
65535. b. 2525
o The range for unsigned character is 0 c. 4545
to 255. d. None of the these
2) Study the following program: Answer: (a) 4525
main() Explanation: In this program, it will first print
{printf("javatpoint"); the inner value of the function and then print
main();} the outer value of the function.
What will be the output of this program? 5) Which of the following comment is correct
when a macro definition includes arguments?
a. Wrong statement
a. The opening parenthesis should
b. It will keep on printing javatpoint
immediately follow the macro name.
c. It will Print javatpoint once
b. There should be at least one blank
d. None of the these between the macro name and the opening
Answer: (b) It will keep on printing javatpoint parenthesis.
Explanation: In this program, the main c. There should be only one blank
function will call itself again and again. between the macro name and the opening
Therefore, it will continue to print javatpoint. parenthesis.
3) What is required in each C program? d. All the above comments are correct.
a. The program must have at least one Answer: (a) The opening parenthesis should
function. immediately follow the macro name.
b. The program does not require any 6) What is a lint?
function. a. C compiler
c. Input data b. Interactive debugger
d. Output data c. Analyzing tool
Answer: (a) The program must have at least d. C interpreter
one function.
Answer: (c) Analyzing tool
Explanation: Any C program has at least one
Explanation: Lint is an analyzing tool that
function, and even the most trivial programs
analyzes the source code by suspicious
can specify additional functions. A function is
constructions, stylistic errors, bugs, and flag
a piece of code. In other words, it works like a
programming errors. Lint is a compiler-like
sub-program.
tool in which it parses the source files of C
DIWAKAR EDUCATION HUB Page 2
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
programming. It checks the syntactic Explanation: It is an effect of the comma
accuracy of these files. operator.
7) What is the output of this statement a + = (a + = 3, 5, a)
"printf("%d", (a++))"? It first evaluates to "a + = 3" i.e. a = a + 3 then
a. The value of (a + 1) evaluate 5 and then evaluate "a".
b. The current value of a Therefore, we will get the output is 4.
c. Error message Then,
d. Garbage a+=4
Answer: (b) The current value of "a". It gives 8 as the output.
10) What does this declaration mean?
8) Study the following program: int x : 4;
main() a. X is a four-digit integer.
{ b. X cannot be greater than a four-digit
char x [10], *ptr = x; integer.
scanf ("%s", x); c. X is a four-bit integer.
change(&x[4]); d. None of the these
}
change(char a[]) Answer: (c) X is a four-bit integer.
{ Explanation: This means, "X" is a four bit
puts(a); integer.
} 11) Why is a macro used in place of a
If abcdefg is the input, the output will be function?
a. abcd a. It reduces execution time.
b. abc b. It reduces code size.
c. efg c. It increases execution time.
d. Garbage d. It increases code size.
Answer: (c) efg Answer: (d) It reduces code size.
Explanation: Macro is used in place of a
function because it reduces code size, and
9) Study the following program:
very efficient.
main()
12) In the C language, the constant is defined
{ _______.
int a = 1, b = 2, c = 3: a. Before main
printf("%d", a + = (a + = 3, 5, a)) b. After main
} c. Anywhere, but starting on a new line.
What will be the output of this program? d. None of the these.
a. 6 Answer: (c) Anywhere, but starting on a new
b. 9 line.
c. 12 Explanation: In the C language, the constant
d. 8 is defined anywhere, but starting on a new
Answer: (d) 8 line.

DIWAKAR EDUCATION HUB Page 3


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
13) How many times will the following loop will execute the body of a loop; otherwise,
execute? control is transferred out of the loop.
for(j = 1; j <= 10; j = j-1) 17) Which of the following best describes the
a. Forever ordering of destructor calls for stack-resident
b. Never objects in a routine?
c. 0 a. The first object created is the first
d. 1 object destroyed; last created is last
destroyed.
Answer: (a) Forever
b. The first object destroyed is the last
14) A pointer is a memory address. Suppose
object destroyed; last created is first
the pointer variable has p address 1000, and
destroyed.
that p is declared to have type int*, and an
int is 4 bytes long. What address is c. Objects are destroyed in the order
represented by expression p + 2? they appear in memory, the object with the
lowest memory address is destroyed first.
a. 1002
d. The order is undefined and may vary
b. 1004
from compiler to compiler.
c. 1006
Answer: (b) The first object destroyed is the
d. 1008 last object destroyed; last created is first
Answer: (d) 1008 destroyed.
15) What is the result after execution of the
following code if a is 10, b is 5, and c is 10? 18) How many characters can a string hold
If ((a > b) && (a <= c)) when declared as follows?
a = a + 1; char name[20]:
else a. 18
c = c+1; b. 19
a. a = 10, c = 10 c. 20
b. a = 11, c = 10 d. None of the these
c. a = 10, c = 11 Answer: (b) 20
d. a = 11, c = 11 19) Directives are translated by the
Answer: (b) a = 11, c = 10 a. Pre-processor
16) Which one of the following is a loop b. Compiler
construct that will always be executed once? c. Linker
a. for d. Editor
b. while Answer: (a) Pre-processor
c. switch Explanation: In C language, the pre-processor
d. do while is a macro processor that is dynamically used
Answer: (d) do while by the C programmer to modify the program
Explanation: The body of a loop is often before it is properly compiled (Before
executed at least once during the do-while construction, pro-processor directives are
loop. Once the body is performed, the implemented).
condition is tested. If the condition is valid, it 20) How many bytes does "int = D" use?
a. 0

DIWAKAR EDUCATION HUB Page 4


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
b. 1 Explanation: Each instance of the class has a
c. 2 or 4 different set of attribute values
d. 10 25) How many instances of a class can be
Answer: (c) 2 or 4 declared?
Explanation: The int type takes 2 or 4 bytes. a. 1
21) What feature makes C++ so powerful? b. 10
a. Easy implementation c. As per required
b. Reusing the old code d. None of the these
c. Easy memory management Answer: (c) As per required
d. All of the above Explanation: You can always declare multiple
Answer: (d) All of the above instances of a class, as per required. Each
object will hold its own individual inner
variables (unless they are static, in which case
22) Which of the following will copy the null- they are shared).
terminated string that is in array src into
26) What will the result of num variable after
array dest?
execution of the following statements?
a. dest = src;
int num = 58;
b. dest == src;
num % = 11;
c. strcpy(dest, src);
a. 3
d. strcpy(src, dest);
b. 5
Answer: (c) strcpy(dest, src)
c. 8
Explanation: strcpy is a string function that is
d. 11
used to copy the string between the two files.
strcpy(destination, source) Answer: (a) 3
23) In the statement "COUT << "javatpoint" Explanation: num = 58
<< end1;", end1 is a ___. num % = 11
a. Extractor num = num % 11
b. Inserter num = 58 % 11
c. Manipulator num = 3
d. Terminator 27) What is the maximum number of
Answer: (c) Manipulator characters that can be held in the string
variable char address line [40]?
Explanation: End1 is an I/O manipulator that
takes effect in printing a new line '\ n' a. 38
character and then flushing the output b. 39
stream. c. 40
24) Each instance of a class has a different set d. 41
of Answer: (b) 39
a. Class interfaces 28) What will the result of num1 variable
b. Methods after execution of the following statements?
c. Return types int j = 1, num1 = 4;
d. Attribute values while (++j <= 10)
Answer: (d) Attribute values {

DIWAKAR EDUCATION HUB Page 5


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
num1++; b. 102
} c. 104
a. 11 d. 108
b. 12 Answer: (b) 102
c. 13 Explanation: aPtr is an integer pointer which
d. 14 value is 100.
Answer: (c) 13 = *aPtr + 2
29) What will the result of len variable after = 100 + 2
execution of the following statements? = 102
int len; 32) Give the following declarations and an
char str1[] = {"39 march road"}; assignment statement. Which one is
len = strlen(str1); equivalent to the expression str [4]?
a. 11 char str[80];
b. 12 char * p;
c. 13 p = str;
d. 14 a. p+4
Answer: (c) 13 b. *p + 4
Explanation: strlen is a string function that c. *(p + 4)
counts the word and also count the space in d. p [3]
the string. (39 march road) = 13 Answer: (c) *(p + 4)
30) Study the following statement 33) Which one is the correct description for
#include <stdio.h> the variable balance declared below?
int main() 1. int ** balance;
{ a. Balance is a point to an integer
int *ptr, a = 10; b. Balance is a pointer to a pointer to an
ptr = &a; integer
*ptr += 1; c. Balance is a pointer to a pointer to a
printf("%d,%d/n", *ptr, a); pointer to an integer
} d. Balance is an array of integer
What will be the output? Answer: (b) Balance is a pointer to a pointer
to an integer
a. 10, 10
Explanation: This code description states that
b. 10, 11
the remainder is a pointer to a pointer to an
c. 11, 10 integer.
d. 11, 11 34) A class D is derived from a class B, b is an
Answer: (d) 11, 11 object of class B, d is an object of class D, and
31) Given the following statement, what will pb is a pointer to class B object. Which of the
be displayed on the screen? following assignment statement is not valid?
int * aPtr; a. d = d;
*aPtr = 100; b. b = d;
cout << *aPtr + 2; c. d = b;
a. 100
DIWAKAR EDUCATION HUB Page 6
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
d. *pb = d: a. 2001
Answer: (c) d = b; b. 2002
Explanation: A class D is derived from a class c. 2004
B, so "d" is not equal to b. d. 2008
35) Which of the following statement is not Answer: (c) 2004
true? Explanation: The size of one pointer integer
a. A pointer to an int and a pointer to a is 4 bytes. The current value of p1 is 2000.
double are of the same size. p1++ = p1 + 1
b. A pointer must point to a data item on p1++ = 2004
the heap (free store). 39) Let p1 and p2 be integer pointers. Which
c. A pointer can be reassigned to point to one is a syntactically wrong statement?
another data item. a. p1 = p1 + p2;
d. A pointer can point to an array. b. p1 = p1 - 9;
Answer: (b) A pointer must point to a data c. p2 = p2 + 9;
item on the heap (free store).
d. cout << p1 - p2;
Answer: (a) p1 = p1 + p2;
36) Which of the following SLT template class
40) Suppose that cPtr is a character pointer,
is a container adaptor class?
and its current content is 300. What will be
a. Stack the new value in cPtr after the following
b. List assignment?
c. Deque 1. cPtr = cPtr + 5;
d. Vector a. 305
Answer: (a) Stack b. 310
Explanation: Container Adaptors is the c. 320
subset of Containers that provides many d. 340
types interface for sequential containers,
Answer: (a) 305
such as stack and queue.
Explanation: cPtr = cPtr + 5
37) What kinds of iterators can be used with
vectors? cPtr = 300 + 5
a. Forward iterator cPtr = 305
b. Bi-directional iterator 41) Which is valid expression in c language?
c. Random access iterator a. int my_num = 100,000;
d. All of the above b. int my_num = 100000;
Answer: (d) All of the above c. int my num = 1000;
Explanation: An iteration is like a pointer, d. int my num == 10000;
indicating an element inside the container. All Answer: (b) int my_num = 100000;
these types of iterations can be used with Explanation: Special symbol, Space, and
vectors. comma cannot be used in a variable name in
38) Let p1 be an integer pointer with a c language.
current value of 2000. What is the content of 42) If addition had higher precedence than
p1 after the expression p1++ has been multiplication, then the value of the
evaluated?

DIWAKAR EDUCATION HUB Page 7


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
expression (1 + 2 * 3 + 4 * 5) would be which Explanation: All statements are true
of the following? 45) What does this statement mean?
a. 27 x - = y + 1;
b. 47 a. x=x-y+1
c. 69 b. x = -x - y - 1
d. 105 c. x=x+y-1
Answer: (d) 105 d. x=x-y-1
Explanation: (1 + 2 * 3 + 4 * 5) Answer: (d) x = x - y - 1
= (1 + 2) * (3 + 4) * 5 Explanation: x - = y + 1
=3*7*5 x = x - (y + 1)
= 105 So, x = x - y - 1
43) What will be the output of this program? 46) Study the following statement
int main() for (i = 3; i < 15; i + = 3)
{ {printf ("%d", i);
int a=10, b=20; ++i;
printf("a=%d b=%d",a,b); }
a=a+b; What will be the output?
b=a-b; a. 3 6 9 12
a=a-b; b. 3 6 9 12 15
printf("a=%d b=%d",a,b); c. 3 7 11
return 0; d. 3 7 11 15
} Answer: (c) 3 7 15
a. a = 20, b = 20 47) Study the following statement
b. a = 10, b = 20 main()
c. a = 20, b = 10 {
d. a = 10, b = 10 char *s = "Hello,"
Answer: (c) a = 20, b = 10 "World!";
Explanation: This program is a swapping printf("%s", s);
program. }
a = a + b → a = 10 + 20 → a = 30 What will be the output?
b = a - b → b = 30 - 20 → B = 10 a. Hello, World!
a = a - b → a = 30 - 10 → a = 20 b. Hello,
44) The following statements are about EOF. World!
Which of them is true? c. Hello
a. Its value is defined within stdio.h d. Compile error
b. Its value is implementation dependent Answer: (b) Hello, World!
c. Its value can be negative Explanation: The output of this program is
d. Its value should not equal the integer "Hello, World!". This program's output will
equivalent of any character not appear in the new line because the \ n
e. All of the these escape sequence has not been used in this
Answer: (e) All of the these program.
DIWAKAR EDUCATION HUB Page 8
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
48) Study the following array definition {
1. int num[10] = {3, 3, 3}; int i = 065, j = 65;
Which of the following statement is correct? printf ("%d %d", i, j);
a. num[9] is the last element of the array }
num a. 065 65
b. The value of num[8] is 3 b. 53 65
c. The value of num[3] is 3 c. 65 65
d. None of the above d. Syntax error
Answer: (a) num[9] is the last element of the Answer: (b) 53 65
array num Explanation: This value (065) is an octal
Explanation: The num[9] is the last element value, and it equals to the decimal value 53.
of the array number because the total 51. Prolog comes under ___________
element in this array is 10, and the array a) Logic Programming
starts with 0, so the last element of the array b) Procedural Programming
is the num[9]. c) OOP
49) What will the output after execution of d) Functional
the following statements? Answer: a
main() Explanation: Prolog stands for Programming
{ in Logic. The options mentioned are the four
printf ("\\n ab"); categories of programming. Prolog is a type
printf ("\\b si"); of logic programming.
printf ("\\r ha"); 52. Java is procedural programming.
} a) True
b) False
a. absiha
Answer: b
b. asiha
Explanation: The statement is false. Java is a
c. haasi type of object oriented programming
d. hai language. It involves solving real-life
Answer: (d) hai problems as well.
Explanation: 53. A program that can execute high-level
o \\n - newline - printf("\\nab"); - Prints language programs.
'ab' a) Compiler
o \\b - backspace - printf("\\bsi"); - firstly b) Interpreter
'\\b' removes 'b' from 'ab ' and then c) Sensor
prints 'si'. So, after execution of d) Circuitry
printf("\\bsi"); it is 'asi' Answer: b
o \\r - linefeed - printf("\\rha"); - Now Explanation: Interpreter is a program that
here '\\r' moves the cursor to the start can execute high-level language programs
of the current line and then override “directly,” without first being translated into
'asi' to 'hai' machine language.
50) What will the output after execution of 54. Executables might be called ________
the following statements? a) native code
void main() b) executable code

DIWAKAR EDUCATION HUB Page 9


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) complex code Answer: a
d) machine code Explanation: JVM stands for Java Virtual
Answer: a Machine. Other related terms are JRE which
Explanation: The executables are sometimes is java runtime environment and JDK which is
called native code. HLL are translated to java development kit.
Machine language called the native code. 59. A language supported by MS. Net
55. Source program is compiled to an platform.
intermediate form called ___________ a) C
a) Byte Code b) C++
b) Smart code c) java
c) Executable code d) C#
d) Machine code Answer: d
Answer: a Explanation: C# is supported by MS. Net
Explanation: The Source program is compiled platform. JAVA was originally designed for
to an intermediate form called byte code. For web purposes.
each supported platform, write a “virtual 60. Which of the following isn’t a
machine” emulator that reads byte code and characteristic of High level languages?
emulates its execution. a) machine code
56. _______________ is the assembly b) platform independent
language for an imaginary architecture. c) interactive execution
a) Byte code d) user-friendly
b) Machine code Answer: a
c) Native code Explanation: HLL isn’t in machine language. It
d) Executable code is converted to machine language for further
Answer: a processing.
Explanation: Source program is compiled to 61. Which of the following approach help us
an intermediate form – byte code. Byte code understand better about Real time examples,
is the assembly language for an imaginary say Vehicle or Employee of an Organisation?
architecture. a) Procedural approach
57. JIT stands for? b) Object Oriented approach
a) Just in time c) Both a and b
b) Jump in time d) None of the mentioned
c) Jump in text Answer: b
d) Jump in terms Explanation: Object Oriented Programming
Answer: a supports the concept of class and object
Explanation: JIT stands for Just in time. JVMs which help us understand the real time
actually compile each bytecode instruction to examples better. Vehicle is defined to be a
native code the first time it is used. class. Car, truck, bike are defined to be
58. JVM stands for? objects of the class, Vehicle.
a) Java virtual machine 62. Which of the following Paradigm is
b) Java visual machine followed by Object Oriented Language
c) JRE virtual machine Design?
d) JRE visual machine a) Process-Oriented Model
b) Data Controlling access to code.

DIWAKAR EDUCATION HUB Page 10


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) Both a and b int num = 10;
d) None of the mentioned if (NUM < 100) {
Answer: b System.out.println("The value of
Explanation: Object-oriented programming num is"+ num);
organises a program around its data(that is, }
objects) and a set of well-defined interfaces }
to that data.
}
63. Which of the following approach is
a) Compilation error
followed by Object Oriented Language during
b) Run time error
the execution of a program?
c) The value of num is 10
a) Bottom up approach
d) None of the mentioned
b) Top down approach
c) Both a and b Answer: a
d) None of the mentioned Explanation: Java is case-sensitive. The
variable ‘num’ used in print statement is not
Answer: a
same as the variable ‘NUM’ used in the if
Explanation: Bottom up approach begins
conditional statement.
with details and moves to higher conceptual
level there by reducing complexity and 67. Which of the following is called as
making the concept easier to understand. ‘Comiplation unit’?
a) Object file
64. Which of the following is/are advantage
b) Byte code
of using object oriented programming?
c) Source file
a) Code Reusability
d) All of the mentioned
b) Can create more than one instance of a
class without interference Answer: c
c) Platform independent 68. What is the output of this program?
d) All of the mentioned class TypeChecking {
Answer: d public static void main(String args[])
65. Java Compiler translates the source code {
into? int num = 10.5;
a) Machine code System.out.println("Output :The
b) Assembly code value of num is" +num);
c) Byte code }
d) JVM code }
a) Output: The value of num is 10.5
Answer: c b) Run-time error
Explanation: Java program is converted into c) Compilation error
‘byte code’ which makes it easier to run on d) None of the mentioned
wide variety of environments. Only the run-
Answer: c
time package JVM has to be implemented for
Explanation: Java is storngly typed language.
each platform.
The variable num is declared as ‘int’ but the
66. What is the output of this program? value assigned to it is ‘float’, as a result the
class PrintTest { code does not get compiled.
public static void main(String args[]) 69. Which is a named memory location
{ assigned a value by the program?
DIWAKAR EDUCATION HUB Page 11
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
a) variable 75. The idea of overlays is to ____________
b) literal a) data that are needed at any given time
c) identifier b) enable a process to be larger than the
d) None of the mentioned amount of memory allocated to it
Answer: a c) keep in memory only those instructions
70. What is Address Binding? d) all of the mentioned
a) going to an address in memory Answer: d
b) locating an address with the help of 76. The ___________ must design and
another address program the overlay structure.
c) binding two addresses together to form a a) programmer
new address in a different memory space b) system architect
d) a mapping from one address space to c) system designer
another d) none of the mentioned
Answer: d Answer: a
71. Binding of instructions and data to 77. The ___________ swaps processes in and
memory addresses can be done at out of the memory.
____________ a) Memory manager
a) Compile time b) CPU
b) Load time c) CPU manager
c) Execution time d) User
d) All of the mentioned Answer: a
Answer: d 78. If a higher priority process arrives and
72. If the process can be moved during its wants service, the memory manager can
execution from one memory segment to swap out the lower priority process to
another, then binding must be ____________ execute the higher priority process. When
a) delayed until run time the higher priority process finishes, the lower
b) preponed to compile time priority process is swapped back in and
c) preponed to load time continues execution. This variant of swapping
d) none of the mentioned is sometimes called?
Answer: a a) priority swapping
73. What is Dynamic loading? b) pull out, push in
a) loading multiple routines dynamically c) roll out, roll in
b) loading a routine only when it is called d) none of the mentioned
c) loading multiple routines randomly Answer: c
d) none of the mentioned 79. If binding is done at assembly or load
Answer: b time, then the process _____ be moved to
74. What is the advantage of dynamic different locations after being swapped out
loading? and in again.
a) A used routine is used multiple times a) can
b) An unused routine is never loaded b) must
c) CPU utilization increases c) can never
d) All of the mentioned d) may
Answer: b Answer: c

DIWAKAR EDUCATION HUB Page 12


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
80. Which of the following is not the primary 84. _________ defines the properties of a
objectives in the analysis model? data object and take on one of the three
a) describing the customer complaints different characteristics.
b) establishing a basis for the creation of a a) data object
software design b) attributes
c) defining a set of requirements that can be c) relationships
validated once the software is built d) data object and attributes
d) none of the mentioned Answer: b
Answer: d Explanation: They can be used to name an
Explanation: All the options are covered in instance of the data object, describe the
analysis model. instance, or make reference to another
81. A description of each function presented instance in another table.
in the DFD is contained in a ________ 85. Which of the following is not a data type?
a) data flow a) Symbolic Data
b) process specification b) Alphanumeric Data
c) control specification c) Numeric Data
d) data store d) Alphabetic Data
Answer: b Answer: a
82. Which diagram indicates the behaviour of Explanation: Data types are of three basic
the system as a consequence of external types: Numeric, Alphabetic and
events? Alphanumeric. Numeric Data consists of only
a) data flow diagram numbers.
b) state transition diagram Alphabetic Data consists of only letters and a
c) control specification diagram blank character and alphanumeric data
d) workflow diagram consists of symbols.
Answer: b 86. *@Ac# is a type of ________________
Explanation: The state transition diagram data.
represents the various modes of behavior a) Symbolic
(called states) of the system and the manner b) Alphanumeric
in which transitions are made from state to c) Alphabetic
state. d) Numeric
83. A data model contains Answer: b
a) data object Explanation: Alphanumeric data consists of
b) attributes symbols. Alphanumeric data may be a letter,
c) relationships either in uppercase or lowercase or some
d) all of the mentioned special symbols like #,^,*,(, etc.
Answer: d 87. Which of the following is not a valid
Explanation: The data model consists of representation in bits?
three interrelated pieces of information: the a) 8-bit
data object, b) 24-bit
the attributes that describe the data object, c) 32-bit
and the relationships that connect data d) 64-bit
objects to one another. Answer: b
Explanation: There are no criteria like the 24-

DIWAKAR EDUCATION HUB Page 13


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
bit representation of numbers. Numbers can language. It was developed for solving
be written in 8-bit, 16-bit, 32-bit and 64-bit as mathematical and scientific problems. It is
per the IEEE format. very commonly used among the scientific
88. What are the entities whose values can community.
be changed called? 92. The program written by the programmer
a) Constants in high level language is called
b) Variables _____________
c) Modules a) Object Program
d) Tokens b) Source Program
Answer: b c) Assembled Program
Explanation: Variables are the data entities d) Compiled Program
whose values can be changed. Constants Answer: b
have a fixed value. Tokens are the words Explanation: The program written by the
which are easily identified by the compiler. programmer is called a source program. The
89. Which of the following is not a basic data program generated by the compiler after
type in C language? compilation is called an object program. The
a) float object program is in machine language.
b) int 93. A standardized language used for
c) real commercial applications.
d) char a) C
Answer: c b) Java
Explanation: There are 5 basic data types in C c) COBOL
language: int, char, float, double, void. d) FORTRAN
Int is for the representation of integers, char Answer: c
is for strings and characters, float and double Explanation: COBOL is a language used in
are for floating point numbers whereas void business and commercial applications. It
is a valueless special data type. stands for Common Business Oriented
90. BOOLEAN is a type of data type which Language. It is imperative, procedural as well
basically gives a tautology or fallacy. as object oriented language.
a) True 94. ______________ define how the
b) False locations can be used.
Answer: a a) Data types
Explanation: A Boolean representation is for b) Attributes
giving logical values. It returns either true or c) Links
false. If a result gives a truth value, it is called d) Data Objects
tautology whereas if it returns a false term, it Answer: b
is referred to as fallacy. Explanation: Attributes can determine how
91. What does FORTRAN stands for? any location can be used. Attributes can be
a) Formula Transfer type, name, component, etc. Data objects are
b) Formula Transformation the variables and constants in a program.
c) Formula Translation 95. Which was the first purely object oriented
d) Format Transformation programming language developed?
Answer: c a) Java
Explanation: FORTRAN is a type of computer b) C++

DIWAKAR EDUCATION HUB Page 14


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) SmallTalk 99. Which is not feature of OOP in general
d) Kotlin definitions?
Answer: c a) Code reusability
Explanation: SmallTalk was the first b) Modularity
programming language developed which was c) Duplicate/Redundant data
purely object oriented. It was developed by d) Efficient Code
Alan Kay. OOP concept came into the picture Answer: c
in 1970’s. Explanation: Duplicate/Redundant data is
96. Which of the following best defines a dependent on programmer and hence can’t
class? be guaranteed by OOP. Code reusability is
a) Parent of an object done using inheritance. Modularity is
b) Instance of an object supported by using different code files and
c) Blueprint of an object classes. Codes are more efficient because of
d) Scope of an object features of OOP.
Answer: b 100. Pure OOP can be implemented without
Explanation: A class is Blueprint of an object using class in a program. (True or False)
which describes/ shows all the functions and a) True
data that are provided by an object of a b) False
specific class. It can’t be called as parent or Answer: b
instance of an object. Class in general Explanation: It’s false because for a program
describes all the properties of an object. to be pure OO, everything must be written
97. Who invented OOP? inside classes. If this rule is violated, the
a) Alan Kay program can’t be labelled as purely OO.
b) Andrea Ferro 101. Which Feature of OOP illustrated the
c) Dennis Ritchie code reusability?
d) Adele Goldberg a) Polymorphism
Answer: a b) Abstraction
Explanation: Alan Kay invented OOP, Andrea c) Encapsulation
Ferro was a part of SmallTalk Development. d) Inheritance
Dennis invented C++ and Adele Goldberg was Answer: d
in team to develop SmallTalk but Alan Explanation: Using inheritance we can reuse
actually had got rewarded for OOP. the code already written and also can avoid
98. What is the additional feature in classes creation of many new functions or variables,
that was not in structures? as that can be done one time and be reused,
a) Data members using classes.
b) Member functions 102. Which language does not support all 4
c) Static data allowed types of inheritance?
d) Public access specifier a) C++
Answer: b b) Java
Explanation: Member functions are allowed c) Kotlin
inside a class but were not present in d) Small Talk
structure concept. Data members, static data Answer: b
and public access specifiers were present in Explanation: Java doesn’t support all 4 types
structures too. of inheritance. It doesn’t support multiple

DIWAKAR EDUCATION HUB Page 15


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
inheritance. But the multiple inheritance can d) At least one object should be declared in
be implemented using interfaces in Java. code
103. How many classes can be defined in a Answer: b
single program? Explanation: In C++, it’s not necessary to use
a) Only 1 classes, and hence codes can be written
b) Only 100 without using OOP concept. Classes may or
c) Only 999 may not contain member functions, so it’s
d) As many as you want not a necessary condition in C++. And, an
Answer: d object can only be declared in a code if its
Explanation: Any number of classes can be class is defined/included via header file.
defined inside a program, provided that their 107. Which header file is required in C++ to
names are different. In java, if public class is use OOP?
present then it must have the same name as a) iostream.h
that of file. b) stdio.h
104. When OOP concept did first came into c) stdlib.h
picture? d) OOP can be used without using any header
a) 1970’s file
b) 1980’s Answer: d
c) 1993 Explanation: We need not include any
d) 1995 specific header file to use OOP concept in
Answer: a C++, only specific functions used in code need
Explanation: OOP first came into picture in their respective header files to be included or
1970’s by Alan and his team. Later it was classes should be defined if needed.
used by some programming languages and 108. Which of the two features match each
got implemented successfully, SmallTalk was other?
first language to use pure OOP and followed a) Inheritance and Encapsulation
all rules strictly. b) Encapsulation and Polymorphism
105. Why Java is Partially OOP language? c) Encapsulation and Abstraction
a) It supports usual declaration of primitive d) Abstraction and Polymorphism
data types Answer: c
b) It doesn’t support all types of inheritance Explanation: Encapsulation and Abstraction
c) It allows code to be written outside classes are similar features. Encapsulation is actually
d) It does not support pointers binding all the properties in a single class or
Answer: a we can say hiding all the features of object
Explanation: As Java supports usual inside a class. And Abstraction is hiding
declaration of data variables, it is partial unwanted data (for user) and showing only
implementation of OOP. Because according the data required by the user of program.
to rules of OOP, object constructors must be 109. Which feature allows open recursion,
used, even for declaration of variables. among the following?
106. Which concept of OOP is false for C++? a) Use of this pointer
a) Code can be written without using classes b) Use of pointers
b) Code must contain at least one class c) Use of pass by value
c) A class must have member functions d) Use of parameterized constructor

DIWAKAR EDUCATION HUB Page 16


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
Answer: a {
Explanation: Use of this pointer allows an int a;
object to call data and methods of itself public : float a;
whenever needed. This helps us call the };
members of an object recursively, and
a) Error : same variable name can’t be used
differentiate the variables of different scopes.
twice
110. Which of the following is not type of b) Error : Public must come first
class? c) Error : data types are different for same
a) Abstract Class variable
b) Final Class d) It is correct
c) Start Class
Answer: a
d) String Class
Explanation: Same variable can’t be defined
Answer: c twice in same scope. Even if the data types
Explanation: Only 9 types of classes are are different, variable name must be
provided in general, namely, abstract, final, different. There is no rule like Public member
mutable, wrapper, anonymous, input-output, should come first or last.
string, system, network. We may further
114. Which is known as a generic class?
divide the classes into parent class and
a) Abstract class
subclass if inheritance is used.
b) Final class
111. Class is pass by _______ c) Template class
a) Value d) Efficient Code
b) Reference
Answer: c
c) Value or Reference, depending on program
Explanation: Template classes are known to
d) Copy
be generic classes because those can be used
Answer: b for any data type value and the same class
Explanation: Classes are pass by reference, can be used for all the variables of different
and the structures are pass by copy. It data types.
doesn’t depend on the program.
115. Size of a class is _____________
112. What is default access specifier for data a) Sum of the size of all the variables declared
members or member functions declared inside the class
within a class without any specifier, in C++? b) Sum of the size of all the variables along
a) Private with inherited variables in the class
b) Protected c) Size of the largest size of variable
c) Public d) Classes doesn’t have any size
d) Depends on compiler
Answer: d
Answer: a Explanation: Classes doesn’t have any size,
Explanation: The data members and member actually the size of object of the class can be
functions are Private by default in C++ defined. That is done only when an object is
classes, if none of the access specifier is used. created and its constructor is called.
It is actually made to increase the privacy of
116. Which class can have member functions
data.
without their implementation?
113. Which is most appropriate comment on a) Default class
following class definition? b) String class
class Student

DIWAKAR EDUCATION HUB Page 17


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) Template class program can be executed using the derived
d) Abstract class class names also in java.
Answer: d 120. Which definition best describes an
Explanation: Abstract classes can have object?
member functions with no implementation, a) Instance of a class
where the inheriting subclasses must b) Instance of itself
implement those functions. c) Child of a class
117. Which of the following describes a friend d) Overview of a class
class? Answer: a
a) Friend class can access all the private Explanation: An object is instance of its class.
members of the class, of which it is a friend It can be declared in the same way that a
b) Friend class can only access protected variable is declared, only thing is you have to
members of the class, of which it is a friend use class name as the data type.
c) Friend class don’t have any 121. How many objects can be declared of a
implementation specific class in a single program?
d) Friend class can’t access any data member a) 32768
of another class but can use it’s methods b) 127
Answer: a c) 1
Explanation: A friend class can access all the d) As many as you want
private members of another class, of which it Answer: d
is a friend. It is a special class provided to use Explanation: You can create as many objects
when you need to reuse the data of a class of a specific class as you want, provided
but don’t want that class to have those enough memory is available.
special functions. 122. Which among the following is false?
118. What is the scope of a class nested a) Object must be created before using
inside another class? members of a class
a) Protected scope b) Memory for an object is allocated only
b) Private scope after its constructor is called
c) Global scope c) Objects can’t be passed by reference
d) Depends on access specifier and d) Objects size depends on its class data
inheritance used members
Answer: d Answer: c
Explanation: It depends on the access Explanation: Objects can be passed by
specifier and the type of inheritance used reference. Objects can be passed by value
with the class, because if the class is inherited also. If the object of a class is not created, we
then the nested class can be used by subclass can’t use members of that class.
too, provided it’s not of private type. 123. Which of the following is incorrect?
119. Class with main() function can be a) class student{ }s;
inherited. b) class student{ }; student s;
a) True c) class student{ }s[];
b) False d) class student{ }; student s[5];
Answer: a Answer: c
Explanation: The class containing main Explanation: The array must be specified
function can be inherited and hence the with a size. You can’t declare object array, or

DIWAKAR EDUCATION HUB Page 18


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
any other linear array without specifying its is not necessary to use the pointers. We can’t
size. It’s a mandatory field. use the names directly because it may be
124. The object can’t be __________ used outside the class.
a) Passed by reference 128. If a local class is defined in a function,
b) Passed by value which of the following is true for an object of
c) Passed by copy that class?
d) Passed as function a) Object is accessible outside the function
Answer: d b) Object can be declared inside any other
Explanation: Object can’t be passed as function
function as it is an instance of some class, it’s c) Object can be used to call other class
not a function. Object can be passed by members
reference, value or copy. There is no term d) Object can be used/accessed/declared
defined as pass as function for objects. locally in that function
125. What is size of the object of following Answer: d
class (64 bit system)? Explanation: For an object which belongs to a
class student { int rollno; char name[20]; local class, it is mandatory to declare and use
static int studentno; }; the object within the function because the
a) 20 class is accessible locally within the class only.
b) 22 129. Which among the following is wrong?
c) 24 a) class student{ }; student s;
d) 28 b) abstract class student{ }; student s;
Answer: c c) abstract class student{ }s[50000000];
Explanation: The size of any object of student d) abstract class student{ }; class toppers:
class will be of size 4+20=24, because static public student{ }; topper t;
members are not really considered as
property of a single object. So static variables Answer: b
size will not be added. Explanation: We can never create instance of
126. Functions can’t return objects. an abstract class. Abstract classes doesn’t
a) True have constructors and hence when an
b) False instance is created there is no facility to
initialize its members. Option d is correct
Answer: b
because topper class is inheriting the base
Explanation: Functions can always return an
abstract class student, and hence topper class
object if the return type is same as that of
object can be created easily.
object being returned. Care has to be taken
while writing the prototype of the function. 130. Which feature of OOP indicates code
reusability?
127. How members of an object are
a) Encapsulation
accessed?
b) Inheritance
a) Using dot operator/period symbol
c) Abstraction
b) Using scope resolution operator
d) Polymorphism
c) Using member names directly
d) Using pointer only Answer: b
Explanation: Inheritance indicates the code
Answer: a
reusability. Encapsulation and abstraction are
Explanation: Using dot operator after the
meant to hide/group data into one element.
name of object we can access its members. It
DIWAKAR EDUCATION HUB Page 19
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
Polymorphism is to indicate different tasks must have a class defined. If object is not
performed by a single entity. used, it is a violation of pure OOP concept.
131. If a function can perform more than 1 134. Which among the following doesn’t
type of tasks, where the function name come under OOP concept?
remains same, which feature of OOP is used a) Platform independent
here? b) Data binding
a) Encapsulation c) Message passing
b) Inheritance d) Data hiding
c) Polymorphism Answer: a
d) Abstraction Explanation: Platform independence is not
Answer: c feature of OOP. C++ supports OOP but it’s not
Explanation: For the feature given above, the a platform independent language. Platform
OOP feature used is Polymorphism. Example independence depends on programming
of polymorphism in real life is a kid, who can language.
be a student, a son, a brother depending on 135. Which feature of OOP is indicated by the
where he is. following code?
132. If different properties and functions of a class student{ int marks; };
real world entity is grouped or embedded class topper:public student{ int age;
into a single element, what is it called in OOP topper(int age){ this.age=age; } };
language? a) Inheritance
a) Inheritance b) Polymorphism
b) Polymorphism c) Inheritance and polymorphism
c) Abstraction d) Encapsulation and Inheritance
d) Encapsulation
Answer: d
Answer: d Explanation: Encapsulation is indicated by
Explanation: It is Encapsulation, which use of classes. Inheritance is shown by
groups different properties and functions of a inheriting the student class into topper class.
real world entity into single element. Polymorphism is not shown here because we
Abstraction, on other hand, is hiding of have defined the constructor in the topper
functional or exact working of codes and class but that doesn’t mean that default
showing only the things which are required constructor is overloaded.
by the user.
136. Which feature may be violated if we
133. Which of the following is not a feature of don’t use classes in a program?
pure OOP? a) Inheritance can’t be implemented
a) Classes must be used b) Object must be used is violated
b) Inheritance c) Encapsulation only is violated
c) Data may/may not be declared using d) Basically all the features of OOP gets
object violated
d) Functions Overloading
Answer: d
Answer: c Explanation: All the features are violated
Explanation: Data must be declared using because Inheritance and Encapsulation won’t
objects. Object usage is mandatory because it be implemented. Polymorphism and
in turn calls its constructors, which in turn Abstraction are still possible in some cases,
but the main features like data binding,
DIWAKAR EDUCATION HUB Page 20
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
object use and etc won’t be used hence the 140. Which feature in OOP is used to allocate
use of class is must for OOP concept. additional function to a predefined operator
137. How many basic features of OOP are in any language?
required for a programming language to be a) Operator Overloading
purely OOP? b) Function Overloading
a) 7 c) Operator Overriding
b) 6 d) Function Overriding
c) 5 Answer: a
d) 4 Explanation: The feature is operator
Answer: a overloading. There is not a feature named
Explanation: There are 7 basic features that operator overriding specifically. Function
define whether a programing language is overloading and overriding doesn’t give
pure OOP or not. The 4 basic features are addition function to any operator.
inheritance, polymorphism, encapsulation 141. Which among doesn’t illustrates
and abstraction. Further, one is, object use is polymorphism?
must, secondly, message passing and lastly, a) Function overloading
Dynamic binding. b) Function overriding
138. The feature by which one object can c) Operator overloading
interact with another object is d) Virtual function
_____________ Answer: b
a) Data transfer Explanation: Function overriding doesn’t
b) Data Binding illustrate polymorphism because the
c) Message Passing functions are actually different and theirs
d) Message reading scopes are different. Function and operator
Answer: c overloading illustrate proper polymorphism.
Explanation: The interaction between two Virtual functions show polymorphism
object is called the message passing feature. because all the classes which inherit virtual
Data transfer is not a feature of OOP. Also, function, define the same function in
message reading is not a feature of OOP. different ways.
139. ___________ underlines the feature of 142. Exception handling is a feature of OOP.
Polymorphism in a class. a) True
a) Nested class b) False
b) Enclosing class Answer: a
c) Inline function Explanation: Exception handling is a feature
d) Virtual Function of OOP as it includes classes concept in most
Answer: d of the cases. Also it may come handy while
Explanation: Virtual Functions can be defined using inheritance.
in any class using the keyword virtual. All the 143. Which among the following, for a pure
classes which inherit the class containing the OOP language, is true?
virtual function, define the virtual function as a) The language should follow 3 or more
required. Redefining the function on all the features of OOP
derived classes according to class and use b) The language should follow at least 1
represents polymorphism. feature of OOP
c) The language must follow only 3 features

DIWAKAR EDUCATION HUB Page 21


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
of OOP d) If classes are supported, polymorphism will
d) The language must follow all the rules of always be supported
OOP Answer: c
Answer: d Explanation: The languages which support
Explanation: The language must follow all the classes but doesn’t support polymorphism,
rules of OOP to be called a purely OOP are known as object-based languages.
language. Even if a single OOP feature is not Polymorphism is such an important feature,
followed, then it’s known to be a partially that is a language doesn’t support this
OOP language. feature, it can’t be called as a OOP language.
144. Does OOP provide better security than 147. Which among the following is the
POP? language which supports classes but not
a) Always true for any programming language polymorphism?
b) May not be true with respect to all a) SmallTalk
programming languages b) Java
c) It depends on type of program c) C++
d) It’s vice-versa is true d) Ada
Answer: a Answer: d
Explanation: It is always true as we have the Explanation: Ada is the language which
facility of private and protected access supports the concept of classes but doesn’t
specifiers. Also, only the public and global support the polymorphism feature. It is an
data are available globally or else the object-based programming language. Note
program should have proper permission to that it’s not an OOP language.
access the private data. 148. If same message is passed to objects of
145. Which among the following best several different classes and all of those can
describes polymorphism? respond in a different way, what is this
a) It is the ability for a message/data to be feature called?
processed in more than one form a) Inheritance
b) It is the ability for a message/data to be b) Overloading
processed in only 1 form c) Polymorphism
c) It is the ability for many messages/data to d) Overriding
be processed in one way Answer: c
d) It is the ability for undefined message/data Explanation: The feature defined in question
to be processed in at least one way defines polymorphism features. Here the
Answer: a different objects are capable of responding to
Explanation: It is actually the ability for a the same message in different ways, hence
message / data to be processed in more than polymorphism.
one form. The word polymorphism indicates 149. Which type of function among the
many-forms. So if a single entity takes more following shows polymorphism?
than one form, it is known as polymorphism. a) Inline function
146. What do you call the languages that b) Virtual function
support classes but not polymorphism? c) Undefined functions
a) Class based language d) Class member functions
b) Procedure Oriented language Answer: b
c) Object-based language Explanation: Only virtual functions among

DIWAKAR EDUCATION HUB Page 22


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
these can show polymorphism. Class member b) Overloading +=
functions can show polymorphism too but we c) Overloading <<
should be sure that the same function is d) Overloading &&
being overloaded or is a function of abstract Answer: c
class or something like this, since we are not Explanation: Only insertion operator can be
sure about all these, we can’t say whether it overloaded among all the given options. And
can show polymorphism or not. the polymorphism can be illustrated here
150. In case of using abstract class or function only if any of these is applicable of being
overloading, which function is supposed to be overloaded. Overloading is type of
called first? polymorphism.
a) Local function 153. Polymorphism is possible in C language.
b) Function with highest priority in compiler a) True
c) Global function b) False
d) Function with lowest priority because it Answer: a
might have been halted since long time, Explanation: It is possible to implement
because of low priority polymorphism in C language, even though it
Answer: b doesn’t support class. We can use structures
Explanation: Function with highest priority is and then declare pointers which in turn
called. Here, it’s not about the thread points to some function. In this way we
scheduling in CPU, but it focuses on whether simulate the functions like member functions
the function in local scope is present or not, but not exactly member function. Now we
or if scope resolution is used in some way, or can overload these functions, hence
if the function matches the argument implementing polymorphism in C language.
signature. So all these things define which 154. Which problem may arise if we use
function has the highest priority to be called abstract class functions for polymorphism?
in runtime. Local function could be one of the a) All classes are converted as abstract class
answer but we can’t say if someone have b) Derived class must be of abstract type
used pointer to another function or same c) All the derived classes must implement the
function name. undefined functions
151. Which among the following can’t be d) Derived classes can’t redefine the function
used for polymorphism? Answer: c
a) Static member functions Explanation: The undefined functions must
b) Member functions overloading be defined is a problem, because one may
c) Predefined operator overloading need to implement few undefined functions
d) Constructor overloading from abstract class, but he will have to define
Answer: a each of the functions declared in abstract
Explanation: Static member functions are not class. Being useless task, it is a problem
property of any object. Hence it can’t be sometimes.
considered for overloading/overriding. For 155. Which among the following is not true
polymorphism, function must be property of for polymorphism?
object, not only of class. a) It is feature of OOP
152. Which among the following can show b) Ease in readability of program
polymorphism? c) Helps in redefining the same functionality
a) Overloading ||

DIWAKAR EDUCATION HUB Page 23


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
d) Increases overhead of function definition feature have helped us modify the structures
always used in C language to be upgraded into class
Answer: d in C++ and other languages.
Explanation: It never increases function 158. If data members are private, what can
definition overhead, one way or another if we do to access them from the class object?
you don’t use polymorphism, you will use the a) Create public member functions to access
definition in some other way, so it actually those data members
helps to write efficient codes. b) Create private member functions to access
156. If 2 classes derive one base class and those data members
redefine a function of base class, also c) Create protected member functions to
overload some operators inside class body. access those data members
Among these two things of function and d) Private data members can never be
operator overloading, where is polymorphism accessed from outside the class
used?
a) Function overloading only Answer: a
b) Operator overloading only Explanation: We can define public member
c) Both of these are using polymorphism functions to access those private data
d) Either function overloading or operator members and get their value for use or
overloading because polymorphism can be alteration. They can’t be accessed directly but
applied only once in a program is possible to be access using member
Answer: d functions. This is done to ensure that the
Explanation: Both of them are using private data doesn’t get modified
polymorphism. It is not necessary that accidentally.
polymorphism can be used only once in a 159. While using encapsulation, which among
program, it can be used anywhere, any the following is possible?
number of times in a single program. a) Code modification can be additional
157. Which among the following best overhead
describes encapsulation? b) Data member’s data type can be changed
a) It is a way of combining various data without changing any other code
members into a single unit c) Data member’s type can’t be changed, or
b) It is a way of combining various member whole code have to be changed
functions into a single unit d) Member functions can be used to change
c) It is a way of combining various data the data type of data members
members and member functions into a single
unit which can operate on any data Answer: b
d) It is a way of combining various data Explanation: Data member’s data type can be
members and member functions that operate changed without changing any further code.
on those data members into a single unit All the members using that data can continue
in the same way without any modification.
Answer: d Member functions can never change the data
Explanation: It is a way of combining both type of same class data members.
data members and member functions, which 160. Find which of the following uses
operate on those data members, into a single encapsulation?
unit. We call it a class in OOP generally. This a) void main(){ int a; void fun( int a=10;

DIWAKAR EDUCATION HUB Page 24


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
cout<<a); fun(); } b) Using only private members
b) class student{ int a; public: int b;}; c) Using inheritance
c) class student{int a; public: void disp(){ d) Using Abstraction
cout<<a;} };
d) struct topper{ char name[10]; public : int Answer: a
marks; } Explanation: Using access specifiers we can
achieve encapsulation. Using this we can in
Answer: c turn implement data abstraction. It’s not
Explanation: It is the class which uses both necessary that we only use private access.
the data members and member functions 164. Which among the following violates the
being declared inside a single unit. Only data principle of encapsulation almost always?
members can be there in structures also. And a) Local variables
the encapsulation can only be illustrated if b) Global variables
some data/operations are associated within c) Public variables
class. d) Array variables
161. Encapsulation helps in writing
___________ classes in java. Answer: b
a) Mutable Explanation: Global variables almost always
b) Abstract violates the principles of encapsulation.
c) Wrapper Encapsulation says the data should be
d) Immutable accessed only by required set of elements.
But global variable is accessible everywhere,
Answer: d also it is most prone to changes. It doesn’t
Explanation: Immutable classes are used for hide the internal working of program.
caching purpose generally. And it can be 165. Which among the following would
created by making the class as final and destroy the encapsulation mechanism if it
making all its members private. was allowed in programming?
162. Which among the following should be a) Using access declaration for private
encapsulated? members of base class
a) The data which is prone to change is near b) Using access declaration for public
future members of base class
b) The data prone to change in long terms c) Using access declaration for local variable
c) The data which is intended to be changed of main() function
d) The data which belongs to some other d) Using access declaration for global
class variables

Answer: a Answer: a
Explanation: The data prone to change in Explanation: If using access declaration for
near future is usually encapsulated so that it private members of base class was allowed in
doesn’t get changed accidentally. We programming, it would have destroyed whole
encapsulate the data to hide the critical concept of encapsulation. As if it was
working of program from outside world. possible, any class which gets inherited
163. How can Encapsulation be achieved? privately, would have been able to inherit the
a) Using Access Specifiers private members of base class, and hence

DIWAKAR EDUCATION HUB Page 25


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
could access each and every member of base encapsulation. By this code we can get the
class. address of the private member of the class,
166. Which among the following can be a hence we can change the value of private
concept against encapsulation rules? member, which is against the rules.
a) Using function pointers 168. Encapsulation is the way to add
b) Using char* string pointer to be passed to functions in a user defined structure.
non-member function a) True
c) Using object array b) False
d) Using any kind of pointer/array address in
passing to another function Answer: b
Explanation: False, because we can’t call
Answer: d these structures if member functions are
Explanation: If we use any kind of array or involved, it must be called class. Also, it is not
pointer as data member which should not be just about adding functions, it’s about binding
changed, but in some case its address is data and functions together.
passed to some other function or similar 169. Using encapsulation data security is
variable. There are chances to modify its ___________
whole data easily. Hence Against a) Not ensured
encapsulation. b) Ensured to some extent
167. Consider the following code and select c) Purely ensured
the correct option. d) Very low
class student
{ Answer: b
int marks; Explanation: The encapsulation can only
public : int* fun() ensure data security to some extent. If
pointer and addresses are misused, it may
{
violate encapsulation. Use of global variables
return &marks; also makes the program vulnerable, hence
} we can’t say that encapsulation gives pure
}; security.
main() 170. Which among the following best defines
{ abstraction?
student s; a) Hiding the implementation
int *ptr=c.fun(); b) Showing the important data
return 0; c) Hiding the important data
d) Hiding the implementation and showing
}
only the features
a) This code is good to go
Answer: d
b) This code may result in undesirable
Explanation: It includes hiding the
conditions
implementation part and showing only the
c) This code will generate error
required data and features to the user. It is
d) This code violates encapsulation
done to hide the implementation complexity
and details from the user. And to provide a
Answer: d
good interface in programming.
Explanation: This code violates the
DIWAKAR EDUCATION HUB Page 26
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
172. Hiding the implementation complexity can code better. It can’t increase the program
can ____________ complexity, as the feature itself is made to
a) Make the programming easy hide it.
b) Make the programming complex 176. Abstraction can apply to ____________
c) Provide more number of features a) Control and data
d) Provide better features b) Only data
Answer: a c) Only control
Explanation: It can make programming easy. d) Classes
The programming need not know how the Answer: a
inbuilt functions are working but can use Explanation: Abstraction applies to both.
those complex functions directly in the Control abstraction involves use of
program. It doesn’t provide more number of subroutines and control flow abstraction.
features or better features. Data abstraction involves handling pieces of
173. Class is _________ abstraction. data in meaningful ways.
a) Object 177. Which among the following can be
b) Logical viewed as combination of abstraction of data
c) Real and code.
d) Hypothetical a) Class
Answer: b b) Object
Explanation: Class is logical abstraction c) Inheritance
because it provides a logical structure for all d) Interfaces
of its objects. It gives an overview of the Answer: b
features of an object. Explanation: Object can be viewed as
174. Object is ________ abstraction. abstraction of data and code. It uses data
a) Object members and their functioning as data
b) Logical abstraction. Code abstraction as use of object
c) Real of inbuilt class.
d) Hypothetical 178. Abstraction principle
Answer: c includes___________
Explanation: Object is real abstraction a) Use abstraction at its minimum
because it actually contains those features of b) Use abstraction to avoid longer codes
class. It is the implementation of overview c) Use abstraction whenever possible to avoid
given by class. Hence the class is logical duplication
abstraction and its object is real. d) Use abstraction whenever possible to
175. Abstraction gives higher degree of achieve OOP
________ Answer: c
a) Class usage Explanation: Abstraction principle includes
b) Program complexity use of abstraction to avoid duplication
c) Idealized interface (usually of code). It this way the program
d) Unstable interface doesn’t contain any redundant functions and
Answer: c make the program efficient.
Explanation: It is to idealize the interface. In 179. Higher the level of abstraction, higher
this way the programmer can use the are the details.
programming features more efficiently and

DIWAKAR EDUCATION HUB Page 27


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
a) True the display only, and the phone is
b) False represented as a whole. Which among the
Answer: b following have highest level of abstraction?
Explanation: Higher the level of abstraction, a) Motherboard
lower are the details. The best way to b) Display
understand this is to consider a whole system c) Camera
that is highest level of abstraction as it hides d) Phone
everything inside. And next lower level would Answer: d
contain few of the computer components Explanation: Phone as a whole have the
and so on. highest level of abstraction. This is because
180. Encapsulation and abstraction differ as the phone being a single unit represents the
____________ whole system. Whereas motherboard,
a) Binding and Hiding respectively display and camera are its components.
b) Hiding and Binding respectively 184. Which among the following is not a level
c) Can be used any way of abstraction?
d) Hiding and hiding respectively a) Logical level
Answer: a b) Physical level
Explanation: Abstraction is hiding the c) View level
complex code. For example, we directly use d) External level
cout object in C++ but we don’t know how is Answer: d
it actually implemented. Encapsulation is Explanation: Abstraction is generally divided
data binding, as in, we try to combine a into 3 different levels, namely, logical,
similar type of data and functions together. physical and view level. External level is not
182. If two classes combine some private defined in terms of abstraction.
data members and provides public member 185. Using higher degree of abstraction
functions to access and manipulate those __________
data members. Where is abstraction used? a) May get unsafe
a) Using private access specifier for data b) May reduce readability
members c) Can be safer
b) Using class concept with both data d) Can increase vulnerability
members and member functions Answer: c
c) Using public member functions to access Explanation: It will make the code safer. One
and manipulate the data members may think it reduces the readability, but the
d) Data is not sufficient to decide what is fact is, it actually helps us understand the
being used code better. We don’t have to read the
Answer: c complex code which is of no use in
Explanation: It is the concept of hiding understanding the program.
program complexity and actual working in 186. Which among the following best
background. Hence use of public member describes the Inheritance?
functions illustrates abstraction here. a) Copying the code already written
183. A phone is made up of many b) Using the code already written once
components like motherboard, camera, c) Using already defined functions in
sensors and etc. If the processor represents programming language
all the functioning of phone, display shows

DIWAKAR EDUCATION HUB Page 28


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
d) Using the data and functions into derived c) class student{int marks;}; class
segment stream:public student{ };
Answer: d d) class student{ }; class stream{ }; class
Explanation: It can only be indicated by using topper{ };
the data and functions that we use in derived Answer: a
class, being provided by parent class. Copying Explanation: Class topper is getting derived
code is nowhere similar to this concept, also from 2 other classes and hence it is multiple
using the code already written is same as inheritance. Topper inherits class stream and
copying. Using already defined functions is class student publicly and hence can use its
not inheritance as we are not adding any of features. If only few classes are defined,
our own features. there we are not even using inheritance (as in
187. How many basic types of inheritance are option class student{ }; class stream{ }; class
provided as OOP feature? topper{ };).
a) 4 190. Which programming language doesn’t
b) 3 support multiple inheritance?
c) 2 a) C++ and Java
d) 1 b) C and C++
Answer: a c) Java and SmallTalk
Explanation: There are basically 4 types of d) Java
inheritance provided in OOP, namely, single Answer: d
level, multilevel, multiple and hierarchical Explanation: Java doesn’t support multiple
inheritance. We can add one more type as inheritance. But that feature can be
Hybrid inheritance but that is actually the implemented by using the interfaces concept.
combination any types of inheritance from Multiple inheritance is not supported
the 4 basic ones. because of diamond problem and similar
188. Which among the following best defines issues.
single level inheritance? 191. Which among the following is correct for
a) A class inheriting a derived class a hierarchical inheritance?
b) A class inheriting a base class a) Two base classes can be used to be derived
c) A class inheriting a nested class into one single class
d) A class which gets inherited by 2 classes b) Two or more classes can be derived into
Answer: b one class
Explanation: A class inheriting a base class c) One base class can be derived into other
defines single level inheritance. Inheriting an two derived classes or more
already derived class makes it multilevel d) One base class can be derived into only 2
inheritance. And if base class is inherited by 2 classes
other classes, it is multiple inheritance. Answer: c
189. Which among the following is correct for Explanation: One base class can be derived
multiple inheritance? into the other two derived classes or more. If
a) class student{public: int marks;}s; class only one class gets derived by only 2 other
stream{int total;}; class topper:public classes, it is also hierarchical inheritance, but
student, public stream{ }; it is not a mandatory condition, because any
b) class student{int marks;}; class stream{ }; number of derived classes can be there.
class topper: public student{ };

DIWAKAR EDUCATION HUB Page 29


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
192. Which is the correct syntax of 195. If a base class is inherited in protected
inheritance? access mode then which among the following
a) class derived_classname : base_classname{ is true?
/*define class body*/ }; a) Public and Protected members of base
b) class base_classname : derived_classname{ class becomes protected members of derived
/*define class body*/ }; class
c) class derived_classname : access b) Only protected members become
base_classname{ /*define class body*/ }; protected members of derived class
d) class base_classname :access c) Private, Protected and Public all members
derived_classname{ /*define class body*/ }; of base, become private of derived class
Answer: c d) Only private members of base, become
Explanation: Firstly, keyword class should private of derived class
come, followed by the derived class name. Answer: a
Colon is must followed by access in which Explanation: As the programming language
base class has to be derived, followed by the rules apply, all the public and protected
base class name. And finally the body of class. members of base class becomes protected
Semicolon after the body is also must. members of derived class in protected access
193. Which type of inheritance leads to mode. It can’t be changed because it would
diamond problem? hinder the security of data and may add
a) Single level vulnerability in the program.
b) Multi-level 196. How many types of inheritance are
c) Multiple possible in C++?
d) Hierarchical a) 2
Answer: c b) 3
Explanation: When 2 or more classes inherit c) 4
the same class using multiple inheritance and d) 5
then one more class inherits those two base
classes, we get a diamond like structure. Answer: d
Here, ambiguity arises when same function Explanation: There are five types of
gets derived into 2 base classes and finally to inheritance that are possible in C++. Single
3rd level class because same name functions level, Multilevel, multiple, hierarchical and
are being inherited. hybrid. Here we count hybrid also because it
194. Which access type data gets derived as sometimes can bring up a new form of
private member in derived class? inheritance, Like inheritance using multiple
a) Private and hierarchical, which sometimes results in
b) Public diamond problem.
c) Protected 197. Which among the following is true?
d) Protected and Private a) Java supports all types of inheritance
Answer: a b) Java supports multiple inheritance
Explanation: It is a rule, that when a derived c) Java doesn’t support multiple inheritance
class inherits the base class in private access d) Java doesn’t support inheritance
mode, all the members of base class gets
derived as private members of the derived Answer: c
class. Explanation: Java doesn’t support multiple

DIWAKAR EDUCATION HUB Page 30


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
inheritance. This is done to avoid the one class which inherits more than one class
diamond problem that sometimes arises with to be called as multiple inheritance.
inherited functions. Though, multiple 200. How many types of inheritance can be
inheritance can be implemented in java using used at a time in a single program?
interfaces. a) Any two types
198. Which type of inheritance is illustrated b) Any three types
by the following code? c) Any 4 types
class student{ public: int marks; }; d) Any type, any number of times
class topper: public student { public: char
grade; }; Answer: d
class average{ public: int makrs_needed; }; Explanation: Any type of inheritance can be
class section: public average{ public: char used in any program. There is no rule to use
name[10]; }; only few types of inheritance. Only thing that
matters is how the classes are inherited and
class overall: public average{ public: int
used.
students; };
201. Which among the following defines
a) Single level
single level inheritance?
b) Multilevel and single level
a) One base class derives another class
c) Hierarchical
b) One derived class inherits from one base
d) Hierarchical and single level
class
c) One base class inherits from one derived
Answer: c class
Explanation: It is hierarchical inheritance and d) One derived class derives from another
single level inheritance. Since class topper is derived class
inheriting class student, it is single level
inheritance. And then average is inherited by
Answer: b
section and overall, so it is hierarchical
Explanation: If only one base class is used to
inheritance. But both of them are separate.
derive only one subclass, it is known as single
Hence it is not hybrid inheritance.
level inheritance. The reason of this name is
199. Which among the following best that we inherit the base class to one more
describes multiple inheritance? level and stop the inheritance any further.
a) Two classes being parent of any other
202. If class A and class B are derived from
classes
class C and class D, then ________________
b) Three classes being parent of other classes
a) Those are 2 pairs of single inheritance
c) More than one class being parent of other
b) That is multilevel inheritance
child classes
c) Those is enclosing class
d) More than one class being parent of single
d) Those are all independent classes
child
Answer: a
Answer: d
Explanation: Since class A is derived from
Explanation: If a class inherits more than one
class C and then class B is derived from class
class, it is known as multiple inheritance. This
D, there are two pairs of classes which shows
should not be referred with only two or three
single inheritance. Those two pairs are
classes being inherited. But there must be
independent of each other though.

DIWAKAR EDUCATION HUB Page 31


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
203. If single inheritance is used, program will };
contain ________________ class C: private A, public B
a) At least 2 classes {
b) At most 2 classes void avg()
c) Exactly 2 classes
{
d) At most 4 classes
cout&lt;&lt;(a+b)/2;
Answer: a }
Explanation: The program will contain at };
least 2 classes in the sense of base and a) Class A
derived classes. At least one base class and b) Class B
one derived class must be there. Types of c) Class C
inheritance remains the same though. d) None
204. Single level inheritance supports
_____________ inheritance. Answer: b
a) Runtime Explanation: Class B is using single level
b) Compile time inheritance. Class C is using multiple
c) Multiple inheritance inheritance. And class A is parent of other
d) Language independency two classes.
206. If single level inheritance is used and an
Answer: a abstract class is created with some undefined
Explanation: The runtime inheritance is done functions, can its derived class also skip some
when object of a class is created to call a definitions?
method. At runtime the function is searched a) Yes, always possible
if it is in class of object. If not, it will search in b) Yes, possible if only one undefined
its parent classes and hierarchy for that function
method. c) No, at least 2 undefined functions must be
205. Which method in the code below is there
single level inherited? d) No, the derived class must implement
class A those methods
{
Answer: d
protected int a, b;
Explanation: The derived class must
public: void show() implement those methods. This is because
{ the parent class is abstract and hence will
cout&lt;&lt;a&lt;&lt;b; have some undefined functions which has to
} be defined in derived classes. Since we are
}; using single level inheritance, if derived class
class B: public A doesn’t implement those functions then one
{ more class has to be there which will become
multi-level inheritance.
public: void disp()
207. Which among the following is false for
{
single level inheritance?
cout&lt;&lt;a++&lt;&lt;b++; a) There can be more than 2 classes in
} program to implement single inheritance
DIWAKAR EDUCATION HUB Page 32
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
b) There can be exactly 2 classes to of specific idea. And multiple inheritance not
implement single inheritance in a program so safe as it might result in some ambiguity.
c) There can be more than 2 independent 210. Which language doesn’t support single
classes involved in single inheritance level inheritance?
d) The derived class must implement all the a) Java
abstract method if single inheritance is used b) C++
c) Kotlin
Answer: c d) All languages support it
Explanation: If more than 2 independent
classes are involved to implement the single Answer: d
level inheritance, it won’t be possible as Explanation: All the languages support single
there must be only one child and one parent level inheritance. Since any class can inherit
class and none other related class. other classes as required, if single level
208. Which concept will result in derived inheritance was not allowed it would result in
class with more features (consider maximum failing a lot of features of OOP.
3 classes)? 211. Which among the following best defines
a) Single inheritance multilevel inheritance?
b) Multiple inheritance a) A class derived from another derived class
c) Multilevel inheritance b) Classes being derived from other derived
d) Hierarchical inheritance classes
c) Continuing single level inheritance
Answer: b d) Class which have more than one parent
Explanation: If single inheritance is used then Answer: b
only feature of a single class are inherited, Explanation: Only if the class is being derived
and if multilevel inheritance is used, the 2nd from other derived class, it can be called as
class might have use private inheritance. multilevel inheritance. If a class is derived
Hence only multiple inheritance can result in from another class, it is single level
derived class with more features. This is not inheritance. There must be more than one
mandatory but in a case if we consider same level of inheritance.
number of features in each class, it will result 212. If there are 5 classes, E is derived from
the same. D, D from C, C from B and B from A. Which
209. Single level inheritance is safer than class constructor will be called first if the
_____________ object of E or D is created?
a) Multiple inheritance a) A
b) Interfaces b) B
c) Implementations c) C
d) Extensions d) A and B
Answer: a
Answer: a Explanation: A is parent of all other classes
Explanation: Interfaces also represent a way indirectly. Since A is parent of B and B is
of inheritance but is a wide word to decide parent of C and so on till E. Class A
which inheritance we are talking about in it, constructor will be called first always.
hence can’t be considered. Implementation 213. If there are 3 classes. Class C is derived
and extensions also doesn’t match that level from class B and B is derived from A, Which

DIWAKAR EDUCATION HUB Page 33


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
class destructor will be called at last if object class. In turn those won’t be allowed for
of C is destroyed. further inheritance or direct access outside
a) A the class.
b) B 216. Multilevel inheritance allows
c) C _________________ in the program.
d) All together a) Only 7 levels of inheritance
Answer: a b) At least 7 levels of inheritance
Explanation: The destructors are called in the c) At most 16 levels of inheritance
reverse order of the constructors being d) As many levels of inheritance as required
called. Hence in multilevel inheritance, the Answer: d
constructors are created from parent to child, Explanation: The multilevel inheritance
which leads to destruction from child to allows any number of levels of inheritance.
parent. Hence class A destructor will be This is the maximum flexibility feature to
called at last. make the members available to all the new
214. Which Class is having highest degree of classes and to add their own functionalities.
abstraction in multilevel inheritance of 5 The code reusability is used too.
levels? 217. Multiple inheritance is
a) Class at 1st level ____________________
b) Class 2nd last level a) When a class is derived from another class
c) Class at 5th level b) When a class is derived from two or more
d) All with same abstraction classes
Answer: a c) When a class is derived from other two
Explanation: The class with highest degree of derived classes
abstraction will be the class at the 1st level. d) When a class is derived from exactly one
You can look at a simple example like, a CAR class
is more abstract than SPORTS CAR class. The Answer: b
level of abstraction decrease with each level Explanation: The multiple inheritance is used
as more details comes out. when a class is being derived using two base
215. If all the classes use private inheritance classes or more. This way a single class can
in multilevel inheritance then have features of more than one classes
______________ inherited into a single unit. This lets us
a) It will not be called multilevel inheritance combine two class members into a single
b) Each class can access only non-private class.
members of its parent 218. Which problem arises due to multiple
c) Each subsequent class can access all inheritance, if hierarchical inheritance is used
members of previous level parent classes previously for its base classes?
d) None of the members will be available to a) Diamond
any other class b) Circle
Answer: b c) Triangle
Explanation: The classes will be able to d) Loop
access only the non-private members of its Answer: a
parent class. The classes are using private Explanation: The diamond problem arises
inheritance, hence all the members of the when multiple inheritance is used. This
parent class become private in the derived problem arises because the same name

DIWAKAR EDUCATION HUB Page 34


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
member functions get derived into a single 222. How many types of inheritance should
class. Which in turn creates ambiguity in be used for hybrid?
calling those methods. a) Only 1
219. Which among the following is best to b) At least 2
define hierarchical inheritance? c) At most two
a) More than one classes being derived from d) Always more than 2
one class Answer: b
b) More than 2 classes being derived from Explanation: There must be combination of
single base class at least 2 types of inheritance. The
c) At most 2 classes being derived from single inheritance should be of different type.
base class 223. Which of the following is the correct
d) At most 1 class derived from another class syntax of including a user defined header files
Answer: a in C++?
Explanation: When two or more classes get a) #include <userdefined.h>
derived from a single base class, it is known b) #include <userdefined>
as hierarchical inheritance. This gives us c) #include “userdefined”
freedom to use same code with different d) #include [userdefined]
scopes and flexibility into different classes.
220. Do members of base class gets divided Answer: c
among all of its child classes? Explanation: C++ uses double quotes to
a) Yes, equally include a user-defined header file. The
b) Yes, depending on type of inheritance correct syntax of including user-defined is
c) No, it’s doesn’t get divided #include “userdefinedname”.
d) No, it may or may not get divided 224. Which of the following is a correct
Answer: c identifier in C++?
Explanation: The class members doesn’t get a) 7var_name
divided among the child classes. All the b) 7VARNAME
members get derived to each of the c) VAR_1234
subclasses as whole. The only restriction is d) $var_name
from the access specifiers used.
221. Which among the following best defines Answer: c
the hybrid inheritance? Explanation: The rules for writing an
a) Combination of two or more inheritance identifier is as follows:
types i) may contain lowercase/uppercase letters,
b) Combination of same type of inheritance digits or underscore(_) only
c) Inheritance of more than 7 classes ii) should start with a non-digit character
d) Inheritance involving all the types of iii) should not contain any special characters
inheritance like @, $, etc.
Answer: a 225. Which of the following is called address
Explanation: When more than one type of operator?
inheritance are used together, it results in a) *
new type of inheritance which is in general b) &
known as hybrid inheritance. This may of may c) _
not have better capabilities.

DIWAKAR EDUCATION HUB Page 35


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
d) % b) getline(ch)
c) read(ch)
Answer: b d) scanf(ch)
Explanation: & operator is called address
operator and is used to access the address of Answer: a
a variable. Explanation: C++ provides cin.get() function
226. Which of the following is used for to read a single character from console
comments in C++? whereas others are used to read either a
a) // comment single or multiple characters.
b) /* comment */ 230. Which function is used to write a single
c) both // comment or /* comment */ character to console in C++?
d) // comment */ a) cout.put(ch)
b) cout.putline(ch)
Answer: c c) write(ch)
Explanation: Both the ways are used for d) printf(ch)
commenting in C++ programming. // is used
for single line comments and /* … */ is used Answer: a
for multiple line comments. Explanation: C++ provides cout.put() function
227. What are the actual parameters in C++? to write a single character to console
a) Parameters with which functions are called whereas others are used to write either a
b) Parameters which are used in the single or multiple characters.
definition of a function 231. What are the escape sequences?
c) Variables other than passed parameters in a) Set of characters that convey special
a function meaning in a program
d) Variables that are never used in the b) Set of characters that whose use are
function avoided in C++ programs
c) Set of characters that are used in the name
Answer: a of the main function of the program
Explanation: Actual parameters are those d) Set of characters that are avoided in cout
using which a function call is made i.e. which statements
are actually passed in a function when that
function is called. Answer: a
228. What are the formal parameters in C++? Explanation: Escape sequence is a set of
a) Parameters with which functions are called characters that convey a special meaning to
b) Parameters which are used in the the program. They are used to convey a
definition of the function meaning which cannot be conveyed directly.
c) Variables other than passed parameters in 232. Which of the following escape sequence
a function represents carriage return?
d) Variables that are never used in the a) \r
function b) \n
c) \n\r
229. Which function is used to read a single d) \c
character from the console in C++?
a) cin.get(ch)

DIWAKAR EDUCATION HUB Page 36


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
Answer: a or get from operator i.e. extract/get things
Explanation: \r is used to represent carriage from console/files.
return which means move the cursor to the 237. A language which has the capability to
beginning of the next line. generate new data types are called
233. Which of the following escape sequence ________________
represents tab? a) Extensible
a) \t b) Overloaded
b) \t\r c) Encapsulated
c) \b d) Reprehensible
d) \a
Answer: a
Answer: a Explanation: Languages that can
Explanation: \t is used to represent tab which produce/generate new data types are called
means a set of blank spaces in a line. extensible languages as they have the ability
234. Who created C++? to handle new data types.
a) Bjarne Stroustrup 238. What is the size of wchar_t in C++?
b) Dennis Ritchie a) 2
c) Ken Thompson b) 4
d) Brian Kernighan c) 2 or 4
d) Based on the number of bits in the system
Answer: a Answer: d
Explanation: Bjarne Stroustrup is the original Explanation: Compiler wants to make CPU as
creator of C++ during 1979 at AT&T Bell Labs. more efficient in accessing the next value.
235. Which of the following is called 239. Pick the odd one out.
insertion/put to operator? a) array type
a) << b) character type
b) >> c) boolean type
c) > d) integer type
d) < Answer: a
Explanation: Array type is not the basic type
Answer: a and it is constructed using the basic type.
Explanation: << operator is called insertion or 240. Which data type is used to represent the
put to operator i.e. insert/put things to absence of parameters?
console/files. a) int
236. Which of the following is called b) short
extraction/get from operator? c) void
a) << d) float
b) >> Answer: c
c) > Explanation: Because void specifies an empty
d) < set of values/parameters.
241. What does ‘\a’ escape code represent?
Answer: b a) alert
Explanation: >> operator is called extraction b) backslash

DIWAKAR EDUCATION HUB Page 37


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) tab used to position back from the end of file
d) form feed object.
Answer: a 246. How many objects are used for input
Explanation: Because \a is used to produce a and output to a string?
beep sound. a) 1
242. Which type is best suited to represent b) 2
the logical values? c) 3
a) integer d) 4
b) boolean
c) character Answer: c
d) float Explanation: The stringstream,
Answer: b ostringstream, and istringstream objects are
Explanation: Logical values can be either true used for input and output to a string.
or false, so the boolean type is suited for it. 247. What will be the output of the following
243. Identify the user-defined types from the C++ code?
following? 1. #include <iostream>
a) enumeration 2. #include <fstream>
b) classes 3. using namespace std;
c) both enumeration and classes 4. int main ()
d) int
5. {
Answer: c
6. int length;
Explanation: They must be defined by the
users before use, unlike the other types 7. char * buffer;
which are readily available. 8. ifstream is;
244. Which operator is used to insert the 9. is.open ("sample.txt", ios ::
data into file? binary );
a) >> 10. is.seekg (0, ios :: end);
b) << 11. length = is.tellg();
c) < 12. is.seekg (0, ios :: beg);
d) > 13. buffer = new char [length];
14. is.read (buffer, length);
Answer: b 15. is.close();
Explanation: You can write information to a
16. cout.write (buffer, length);
file from your program using the stream
17. delete[] buffer;
insertion operator <<.
18. return 0;
245. Which function is used to position back
from the end of file object? 19. }
a) seekg a) This is sample
b) seekp b) sample
c) both seekg & seekp c) Error
d) seekf d) Runtime error

Answer: a Answer: d
Explanation: The member function seekg is Explanation: In this program, if the file exist,

DIWAKAR EDUCATION HUB Page 38


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
it will read the file. Otherwise it will throw an Answer: c
exception. A runtime error will occur because Explanation: <fstream> header file is needed
the value of the length variable will be “-1” if to use file I/O operations in C++. This header
file doesn’t exist and in line 13 we are trying file contains all the file I/O operations
to allocate an array of size “-1”. definition.
248. What will be the output of the following 250. Which of the following is used to create
C++ code? an output stream?
1. #include <iostream> a) ofstream
2. using namespace std; b) ifstream
3. int main () c) iostream
d) fsstream
4. {
Answer: a
5. char first, second;
Explanation: ofstream is used to create an
6. cout << "Enter a word: "; output stream in C++ file handling
7. first = cin.get(); operations. Ofstream objects are used to
8. cin.sync(); read files.
9. second = cin.get(); 251. Which of the following is used to create
10. cout << first << endl; a stream that performs both input and
11. cout << second << endl; output operations?
12. return 0; a) ofstream
13. } b) ifstream
c) iostream
a) first
d) fstream
b) second
c) returns first 2 letter or number from the Answer: d
entered word Explanation: fstream is used to create a
d) third stream that performs both input and output
operations in C++ file handling.
Answer: c 252. Which of the following is not used as a
Explanation: In this program, We are using file opening mode?
the sync function to return the first two a) ios::trunc
letters of the entered word. b) ios::binary
Output: c) ios::in
d) ios::ate
$ g++ stream.cpp
Answer: a
$ a.out
Explanation: ios::trunc is used to truncate a
Enter a word: steve
file if it exists. It is not a file opening mode.
s
253. Which of the following statements are
t correct?
249. Which header file is required to use file 1) It is not possible to combine two or more
I/O operations? file opening mode in open() method.
a) <ifstream>
2) It is possible to combine two or more file
b) <ostream>
opening mode in open() method.
c) <fstream>
3) ios::in and ios::out are input and output
d) <iostream>
file opening mode respectively.
DIWAKAR EDUCATION HUB Page 39
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
a) 1, 3 Answer: d
b) 2, 3 Explanation: cout, cerr and clog are the
c) 3 only standard objects for the instantiation of
d) 1, 2 output stream class.
Answer: a 258. What is meant by ofstream in c++?
Explanation: C++ allows to use one or more a) Writes to a file
file opening mode in a single open() method. b) Reads from a file
ios::in and ios::out are input and output file c) Writes to a file & Reads from a file
opening mode respectively. d) delete a file
254. By default, all the files in C++ are opened Answer: a
in _________ mode. Explanation: ofstream is a stream class to
a) Text write on files.
b) Binary 259. Which operator is used for input
c) ISCII stream?
d) VTC a) >
Answer: a b) >>
Explanation: By default, all the files in C++ c) <
are opened in text mode. They read the file d) <<
as normal text. Answer: b
255. What is the use of ios::trunc mode? Explanation: The operator of extraction is >>
a) To open a file in input mode and it is used on the standard input stream.
b) To open a file in output mode 260. Where does a cin stops it extraction of
c) To truncate an existing file to half data?
d) To truncate an existing file to zero a) By seeing a blank space
Answer: d b) By seeing (
Explanation: In C++ file handling, ios::trunc c) By seeing a blank space & (
mode is used to truncate an existing file to d) By seeing <
zero length. Answer: a
256. How many groups of output of Explanation: cin will stop its extraction when
operation are there in c++? it encounters a blank space.
a) 1 261. Which of the following is used for
b) 2 generic programming?
c) 3 a) Virtual functions
d) 4 b) Modules
Answer: b c) Templates
Explanation: There are two groups of output d) Abstract Classes
operation in c++. They are formatted output
and unformatted output. Answer: c
257. Pick out the correct objects about the Explanation: Templates are used for generic
instantiation of output stream. programming. They help in making generic
a) cout functions and classes hence achieving the
b) cerr generic codes.
c) clog 262. Which of the following is correct about
d) all of the mentioned templates?
DIWAKAR EDUCATION HUB Page 40
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
a) It is a type of compile time polymorphism function. Hence the call using int takes the
b) It allows the programmer to write one newly defined function.
code for all data types 264. What will be the output of the following
c) Helps in generic programming C++ code?
d) All of the mentioned #include <iostream>
using namespace std;
Answer: d template<int n>
Explanation: Templates are used for generic
struct funStruct
programming hence allowing to write a single
function for all data types. It is a type of {
compile time polymorphism. static const int val = 2*funStruct<n-1>::val;
263. What will be the output of the following };
C++ code? template<>
#include <iostream> struct funStruct<0>
using namespace std; {
template <class T> static const int val = 1 ;
T max (T &a, T &b) };
{
cout << "Template Called "; int main()
return (a > b)? a : b; {
} cout << funStruct<10>::val << endl;
return 0;
template <> }
int max <int> (int &a, int &b) a) 1
{ b) 1024
cout << "Called "; c) Error
d) Segmentation fault
return (a > b)? a : b;
Answer: b
}
Explanation: The above call for struct will call
the first struct for n > 0 and second one when
int main () n = 0. Therefore when value of n = 10 the
{ until n becomes 0 first struct is called so we
int a = 10, b = 20; will call 2*2*2…10 times*1 which will give the
cout << max <int> (a, b); result 210 = 1024.
} 265. What is an exception in C++ program?
a) Template Called 20 a) A problem that arises during the execution
b) Called 20 of a program
c) Error b) A problem that arises during compilation
d) Segmentation fault c) Also known as the syntax error
Answer: b d) Also known as semantic error
Explanation: For T = int we have created a Answer: a
separate definition for the above template Explanation: An exception is defined as the
problem in C++ program that arises during

DIWAKAR EDUCATION HUB Page 41


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
the execution of the program for example c) finally part
divide by zero error. d) throw part
266. By default, what a program does when it Answer: c
detects an exception? Explanation: finally part of the try-catch
a) Continue running block is always executed whether exceptions
b) Results in the termination of the program are caught or not.
c) Calls other functions of the program 270. Which of the following is an exception in
d) Removes the exception and tells the C++?
programmer about an exception a) Divide by zero
Answer: b b) Semicolon not written
Explanation: By default, whenever a program c) Variable not declared
detects an exception the program crashes as d) An expression is wrongly written
it does not know how to handle it hence Answer: a
results in the termination of the program. Explanation: Exceptions are those which are
267. Why do we need to handle exceptions? encountered during run-time of the program.
a) To avoid unexpected behaviour of a semicolon, variable not declared and the
program during run-time wrong expression are compile-time errors,
b) To let compiler remove all exceptions by therefore, they are not exceptions. Divide by
itself zero is the problem that is encountered
c) To successfully compile the program during run-time, therefore, it is an exception.
d) To get correct output 271. Where should we place catch block of
Answer: a the derived class in a try-catch block?
Explanation: We need to handle exceptions a) Before the catch block of Base class
in a program to avoid any unexpected b) After the catch block of Base class
behaviour during run-time because that c) Anywhere in the sequence of catch blocks
behaviour may affect other parts of the d) After all the catch blocks
program. Also, an exception is detected Answer: a
during run-time, therefore, a program may Explanation: C++ asks the programmer to
compile successfully even with some place the catch block of derived class before
exceptions cases in your program. a catch block of the base class, otherwise
268. How Exception handling is implemented derived catch block will never be executed.
in the C++ program? 272. What id the syntax for catching any type
a) Using Exception keyword of exceptions?
b) Using try-catch block a) catch(Exception e)
c) Using Exception block b) catch(…)
d) Using Error handling schedules c) catch(Exception ALL)
Answer: b d) catch(ALL)
Explanation: C++ provides a try-catch block Answer: b
to handle exceptions in your program. Explanation: catch(…) is used in C++ to catch
269. Which part of the try-catch block is all types of exceptions in a single catch block.
always fully executed? 273. The C++ code which causes abnormal
a) try part termination/behaviour of a program should
b) catch part be written under _________ block.
a) try

DIWAKAR EDUCATION HUB Page 42


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
b) catch world
c) finally
d) throw Answer: c
Answer: a Explanation: A constructor is used in classes
Explanation: Code that leads to the abnormal to initialize data members of class in order to
termination of the program should be written avoid errors/segmentation faults.
under the try block. 277. Why constructors are efficient instead of
274. Exception handlers are declared with a function init() defined by the user to
____________ keyword. initialize the data members of an object?
a) try a) Because user may forget to call init() using
b) catch that object leading segmentation fault
c) throw b) Because user may call init() more than
d) finally once which leads to overwriting values
Answer: b c) Because user may forget to define init()
Explanation: C++ uses catch block to handle function
any exceptions that occur during run-time of d) All of the mentioned
the program. Answer: d
275. Which of the following statements are Explanation: We cannot use init() because as
correct about Catch handler? mentioned in options that user may forget to
i. It must be placed immediately after the try initialize the members which will lead to a
block segmentation fault. Also if the user calls the
ii. It can have more than one parameters init() function more than once it may
overwrite the values and may result into
iii. There must be one and only one catch
disastrous results. Also if any user forgets to
handler for every try block
define init() function then no object will be
iv. There can be multiple catch handler for a initialized whereas if any constructor is not
try block defined in any class the class provides a
v. General catch handler can be kept default constructor for initialization.
anywhere after try block. 278. What is a copy constructor?
a) i, iv, v a) A constructor that allows a user to move
b) i, ii, iii data from one object to another
c) i, iv b) A constructor to initialize an object with
d) i, ii the values of another object
Answer: c c) A constructor to check the whether to
Explanation: A catch block should always be objects are equal or not
placed after the try block and there can be d) A constructor to kill other copies of a given
multiple catch block following a try block. object.
276. What is the role of a constructor in Answer: b
classes? Explanation: Copy constructor allows the
a) To modify the data whenever required user to initialize an object with the values of
b) To destroy an object another object instead of supplying the same
c) To initialize the data members of an object set of values again to initialize the object.
when it is created 279. What will be the output of the following
d) To call private functions from the outer C++ code?

DIWAKAR EDUCATION HUB Page 43


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
#include <iostream> #include <string>
#include <string> using namespace std;
using namespace std; class A{
class A{ int a;
int a; public:
public: A(){
A(int i){ cout<<"A's constructor
a = i; called";
} }
void assign(int i){ };
a = i; class B{
} static A a;
int return_value(){ public:
return a; B(){
} cout<<"B's constructor
}; called";
int main(int argc, char const *argv[]) }
{ static A get(){
A obj; return a;
obj.assign(5); }
cout<<obj.return_value(); };
} A B::a;
a) 5 int main(int argc, char const *argv[])
b) 55 {
c) Error B b;
d) Segmentation Fault A a1 = b.get();
Answer: c A a2 = b.get();
Explanation: As we have defined a A a3 = b.get();
constructor which takes an int parameter, so }
when we are trying to declare an object obj
a) 3
of class A without supplying any parameter
b) 4
then as a constructor is overwritten it will
c) 2
give an error saying that no matching
d) 1
function found. So whenever one writes a
constructor then the default constructor is Answer: d
overwritten hence if you want to declare an Explanation: As the object is defined ony
object without parameter then you also have once in the program at line A B::a, so the
to define that constructor. constructor of A is called only once. For
objects a1, a2 and a3 copy constructor is
280. In the following C++ code how many
called so the string will not be printed for
times the string “A’s constructor called” will
them.
be printed?
#include <iostream>

DIWAKAR EDUCATION HUB Page 44


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
281. What happens if a user forgets to define 283. What is the difference between
a constructor inside a class? constructors and destructors?
a) Error occurs a) They have a different function name
b) Segmentation fault b) Constructors does not have return type
c) Objects are not created properly whereas destructors do have
d) Compiler provides a default constructor to c) Constructors allow function parameters
avoid faults/errors whereas destructors do not
Answer: d d) Constructors does not function parameters
Explanation: The C++ compiler always 284. How many Destructors are allowed in a
provides a default constructor if one forgets Class?
to define a constructor inside a class. a) 1
282. How many parameters does a default b) 2
constructor require? c) 3
a) 1 d) Any number
b) 2 Answer: a
c) 0 Explanation: A class in C++ allows only one
d) 3 destructor, which is called whenever the
Answer: c lifetime of an object ends.
Explanation: A default constructor does not 285. Which of the following constructors are
require any parameters for object creation provided by the C++ compiler if not defined
that’s why sometimes we declare an object in a class?
without any parameters. a) Default constructor
283. How constructors are different from b) Assignment constructor
other member functions of the class? c) Copy constructor
a) Constructor has the same name as the d) All of the mentioned
class itself Answer: d
b) Constructors do not return anything Explanation: If a programmer does not define
c) Constructors are automatically called when the above constructors in a class the C++
an object is created compiler by default provides these
d) All of the mentioned constructors to avoid error on basic
Answer: d operations.
Explanation: All the above mention are the 286. When a copy constructor is called?
reasons where constructor differs from other a) When an object of the class is returned by
normal member functions of a class. value
284. How many types of constructors are b) When an object of the class is passed by
there in C++? value to a function
a) 1 c) When an object is constructed based on
b) 2 another object of the same class
c) 3 d) All of the mentioned
d) 4 Answer: d
Answer: c Explanation: Copy constructor is called in all
Explanation: There are three types of the above-mentioned criteria because in all
constructors in C++ namely default, the above cases we are somehow trying to
parameterized and copy constructor. copy one object into another.

DIWAKAR EDUCATION HUB Page 45


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
287. Pick the other name of operator Answer: b
function. Explanation: The overloaded operator must
a) function overloading not have at least one operand of its class
b) operator overloading type.
c) member overloading 291. Operator overloading is ___________
d) object overloading a) making c++ operator works with objects
Answer: b b) giving new meaning to existing operator
Explanation: Operator function means c) making the new operator
operation defined for that operator so if user d) adding operation to the existing operators
defines a function for an operator then that is Answer: d
called operator overloading i.e. overloading Explanation: Operator overloading is the way
already present operator function. adding operation to the existing operators.
288. Which of the following operators can’t 292. Which operator is having the right to left
be overloaded? associativity in the following?
a) :: a) Array subscripting
b) + b) Function call
c) – c) Addition and subtraction
d) [] d) Type cast
Answer: a Answer: d
Explanation: :: operator cannot be Explanation: There are many rights to left
overloaded because this operator operates associativity operators in C++, which means
on names rather than values and C++ has no they are evaluation is done from right to left.
syntax for writing codes that works on names Type Cast is one of them. Here is a link of the
than values so using syntax these operators associativity of operators:
cannot be overloaded. https://github.com/MicrosoftDocs/cpp-
289. How to declare operator function? docs/blob/master/docs/cpp/cpp-built-in-
a) operator sign operators-precedence-and-associativity.md
b) operator 293. Which operator is having the highest
c) name of the operator precedence?
d) name of the class a) postfix
Answer: a b) unary
Explanation: We have to declare the c) shift
operator function by using the operator, d) equality
operator sign. Example “operator +” where Answer: a
the operator is a keyword and + is the symbol Explanation: The operator which is having
need to be overloaded. the highest precedence is postfix and lowest
290. Which of the following statements is is equality.
NOT valid about operator overloading? 294. What is this operator called ?:?
a) Only existing operators can be overloaded a) conditional
b) The overloaded operator must have at b) relational
least one operand of its class type c) casting operator
c) The overloaded operators follow the d) unrelational
syntax rules of the original operator Answer: a
d) None of the mentioned Explanation: In this operator, if the condition

DIWAKAR EDUCATION HUB Page 46


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
is true means, it will return the first operator, int main()
otherwise second operator. {
295. What will be the output of the following int a = 5, b = 6, c, d;
C++ code? c = a, b;
#include <iostream> d = (a, b);
using namespace std; cout << c << ' ' << d;
int main() return 0;
{ }
int a; a) 5
a = 5 + 3 * 5; b) 6
cout << a; c) 6
return 0; d) 6
} Answer: a
a) 35 Explanation: It is a separator here. In C, the
b) 20 value a is stored in c and in d the value b is
c) 25 stored in d because of the bracket.
d) 30 Output:
Answer: b $ g++ op3.cpp
Explanation: Because the * operator is having $ a.out
highest precedence, So it is executed first and 5 6
then the + operator will be executed. 298. What will be the output of the following
Output: C++ code?
$ g++ op1.cpp #include <iostream>
$ a.out using namespace std;
20 int main()
296. What is the use of dynamic_cast {
operator? int i, j;
a) it converts virtual base class to derived j = 10;
class
i = (j++, j + 100, 999 + j);
b) it converts the virtual base object to
derived objects cout << i;
c) it will convert the operator based on return 0;
precedence }
d) it converts the virtual base object to a) 1000
derived class b) 11
Answer: a c) 1010
Explanation: Because the dynamic_cast d) 1001
operator is used to convert from base class to Answer: c
derived class. Explanation: j starts with the value 10. j is
297. What will be the output of the following then incremented to 11. Next, j is added to
C++ code? 100. Finally, j (still containing 11) is added to
#include <iostream> 999 which yields the result 1010.
using namespace std; Output:

DIWAKAR EDUCATION HUB Page 47


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
$ g++ op2.cpp a) 6
$ a.out b) 5
1010 c) 4
299. What will be the output of the following d) 7
C++ code? Answer: a
#include <iostream> Explanation: Here the condition is false on
conditional operator, so the b value is
using namespace std;
assigned to c.
int main () Output:
{ $ g++ op1.cpp
int x, y; $ a.out
x = 5; 6
y = ++x * ++x; 301. What will be the output of the following
cout << x << y; C++ code?
x = 5; #include <iostream>
y = x++ * ++x; using namespace std;
cout << x << y; main()
return 0; {
} double a = 21.09399;
a) 749735 float b = 10.20;
b) 736749 int c ,d;
c) 367497
c = (int) a;
d) 367597
d = (int) b;
Answer: a
Explanation: Because of the precedence the cout << c <<' '<< d;
pre-increment and post increment operator, return 0;
we got the output as 749736. }
Output: a) 20
$ g++ op.cpp b) 10
$ a.out c) 21
749735 d) 10
300. What will be the output of the following Answer: c
C++ code? Explanation: In this program, we are casting
the operator to integer, So it is printing as 21
#include <iostream>
and 10.
using namespace std; Output:
int main() $ g++ op5.cpp
{ $ a.out
int a = 5, b = 6, c; 21 10
c = (a > b) ? a : b; 302. How are many sequences of statements
cout << c; present in c++?
return 0; a) 4
} b) 3

DIWAKAR EDUCATION HUB Page 48


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) 5 c) 5432
d) 6 d) 53
Answer: c Answer: a
Explanation: There are five sequences of Explanation: In this program, We are printing
statements. They are Preprocessor directives, the numbers in reverse order but by using
Comments, Declarations, Function break statement we stopped printing on 3.
Declarations, Executable statements. Output:
303. The if..else statement can be replaced $ g++ stat.cpp
by which operator? $ a.out
a) Bitwise operator 543
b) Conditional operator 306. What will be the output of the following
c) Multiplicative operator C++ code?
d) Addition operator
#include <iostream>
Answer: b
using namespace std;
Explanation: In the conditional operator, it
will predicate the output using the given int main()
condition. {
304. The switch statement is also called as? int a = 10;
a) choosing structure if (a < 15)
b) selective structure {
c) certain structure time:
d) bitwise structure cout << a;
Answer: b goto time;
Explanation: The switch statement is used to }
choose the certain code to execute, So it is
break;
also called as selective structure.
return 0;
305. What will be the output of the following
}
C++ code?
a) 1010
#include <iostream>
b) 10
using namespace std;
c) infinitely print 10
int main () d) compile time error
{ Answer: d
int n; Explanation: Because the break statement
for (n = 5; n > 0; n--) need to be presented inside a loop or a
{ switch statement.
cout << n; 307. What will be the output of the following
if (n == 3) C++ code?
break; #include <iostream>
} using namespace std;
return 0; int main()
} {
a) 543 int n = 15;
b) 54 for ( ; ;)
DIWAKAR EDUCATION HUB Page 49
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
cout << n; c) 3
return 0; d) 1
} Answer: a
a) error Explanation: There are four types of loop.
b) 15 They are the while, do while, nested, for the
c) infinite times of printing n loop.
d) none of the mentioned 310. Which looping process is best used when
Answer: c the number of iterations is known?
Explanation: There is not a condition in the a) for
for loop, So it will loop continuously. b) while
308. What will be the output of the following c) do-while
C++ code? d) all looping processes require that the
iterations be known
#include <iostream>
Answer: a
using namespace std;
Explanation: Because in for loop we are
int main() allowed to provide starting and ending
{ conditions of loops, hence fixing the number
int i; of iterations of loops, whereas no such things
for (i = 0; i < 10; i++); are provided by other loops.
{ 311. Which of the following is the default
cout << i; return value of functions in C++?
} a) int
return 0; b) char
c) float
}
d) void
a) 0123456789
Answer: a
b) 10
Explanation: C++ uses int as the default
c) 012345678910
return values for functions. It also restricts
d) compile time error
that the return type of the main function
Answer: b
must be int.
Explanation: for loop with a semicolon is
312. What happens to a function defined
called as body less for loop. It is used only for
inside a class without any complex operations
incrementing the variable values. So in this
(like looping, a large number of lines, etc)?
program the value is incremented and
a) It becomes a virtual function of the class
printed as 10.
b) It becomes a default calling function of the
Output:
class
$ g++ stat2.cpp
c) It becomes an inline function of the class
$ a.out d) The program gives an error
10 Answer: c
309. How many types of loops are there in Explanation: Any function which is defined
C++? inside a class and has no complex operations
a) 4 like loops, a large number of lines then it is
b) 2 made inline.

DIWAKAR EDUCATION HUB Page 50


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
313. What is an inline function? 317. By default how the value are passed in
a) A function that is expanded at each call c++?
during execution a) call by value
b) A function that is called during compile b) call by reference
time c) call by pointer
c) A function that is not checked for syntax d) call by object
errors Answer: a
d) A function that is not checked for semantic
analysis 318. What will be the output of the following
Answer: a C++ code?
Explanation: Inline function is those which #include <iostream>
are expanded at each call during the using namespace std;
execution of the program to reduce the cost
void copy (int& a, int& b, int& c)
of jumping during execution.
{
314. An inline function is expanded during
______________ a *= 2;
a) compile-time b *= 2;
b) run-time c *= 2;
c) never expanded }
d) end of the program int main ()
Answer: a {
Explanation: An inline function is expanded int x = 1, y = 3, z = 7;
during the compile-time of a program. copy (x, y, z);
315. How many ways of passing a parameter cout << "x =" << x << ", y =" << y <<
are there in c++? ", z =" << z;
a) 1
return 0;
b) 2
}
c) 3
d) 4 a) 2 5 10
b) 2 4 5
Answer: c
c) 2 6 14
Explanation: There are three ways of passing
d) 2 4 9
a parameter. They are pass by value,pass by
reference and pass by pointer. Answer: c
Explanation: Because we multiplied the
316. Which is used to keep the call by
values by 2 in the copy function.
reference value as intact?
Output:
a) static
b) const $ g++ arg6.cpp
c) absolute $ a.out
d) virtual x = 2,y = 6,z = 14
Answer: b 319. What will happen when we use void in
Explanation: Because const will not change argument passing?
the value of the variables during the a) It will not return value to its caller
execution. b) It will return value to its caller
c) Maybe or may not be return any value to

DIWAKAR EDUCATION HUB Page 51


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
its caller existing classes in order to reuse the
d) It will return value with help of object properties of classes defined earlier.
Answer: a 322. How many specifiers are used to derive
Explanation: As void is not having any return a class?
value, it will not return the value to the caller. a) 1
320. What will be the output of the following b) 2
C++ code? c) 3
#include <iostream> d) 4
using namespace std; Answer: c
void Sum(int a, int b, int & c) Explanation: There are 3 specifiers used to
derive a class. They are private, protected
{
and public.
a = b + c;
323. Which specifier makes all the data
b = a + c; members and functions of base class
c = a + b; inaccessible by the derived class?
} a) private
int main() b) protected
{ c) public
int x = 2, y =3; d) both private and protected
Sum(x, y, y); Answer: a
cout << x << " " << y; Explanation: Private access specifier is used
to make all the data members and functions
return 0;
of the base class inaccessible.
}
324. If a class is derived privately from a base
a) 2 3
class then
b) 6 9
______________________________
c) 2 15
a) no members of the base class is inherited
d) compile time error b) all members are accessible by the derived
Answer: c class
Explanation: We have passed three values c) all the members are inherited by the class
and it will manipulate according to the given but are hidden and cannot be accessible
condition and yield the result as 2 15 d) no derivation of the class gives an error
Output:
Answer: c
$ g++ arg.cpp Explanation: Whenever a class is derived, all
$ a.out the members of the base class is inherited by
2 15 the derived class but are not accessible by
321. What is Inheritance in C++? the derived class.
a) Wrapping of data into a single class 325. What is a virtual function in C++?
b) Deriving new classes from existing classes a) Any member function of a class
c) Overloading of classes b) All functions that are derived from the
d) Classes with same names base class
Answer: b c) All the members that are accessing base
Explanation: Inheritance is the concept of class data members
OOPs in which new classes are derived from d) All the functions which are declared in the

DIWAKAR EDUCATION HUB Page 52


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
base class and is re-defined/overridden by b.func();
the derived class return 0;
Answer: d }
Explanation: Virtual function is a function a) Hello this is class B
that is declared inside the base class and is b) Hello this is class A
re-defined inside the derived class. c) Error
326. Which is the correct syntax of declaring d) Segmentation fault
a virtual function? Answer: a
a) virtual int func(); Explanation: Normal execution of the
b) virtual int func(){}; program and object calls func() from class B.
c) inline virtual func(); 328. What will be the output of the following
d) inline virtual func(){}; C++ code?
Answer: a #include <iostream>
Explanation: To make a function virtual
#include <string>
function we just need to add virtual keyword
at the starting of the function declaration. using namespace std;
327. What will be the output of the following class A
C++ code? {
#include <iostream> float d;
#include <string> public:
using namespace std; virtual void func(){
class A{ cout<<"Hello this is class
float d; A\n";
public: }
virtual void func(){ };
cout<<"Hello this is class
A\n"; class B: public A
} {
}; int a = 15;
public:
class B: public A{ void func(){
int a = 15; cout<<"Hello this is class
public: B\n";
void func(){ }
cout<<"Hello this is class };
B\n";
} int main(int argc, char const *argv[])
}; {
A *a;
int main(int argc, char const *argv[]) a->func();
{ return 0;
B b; }

DIWAKAR EDUCATION HUB Page 53


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
a) Hello this is class A derived class
b) Hello this is class B d) Any function that is made virtual
c) Error Answer: b
d) Segmentation Fault Explanation: A virtual function that has no
Answer: d definition relative to the base class is called a
Explanation: As object ‘a’ is a pointer object pure virtual function.
and we know every pointer needs to be 332. Which attribute specifies a unique
initialised memory before use. Hence alphanumeric identifier to be associated with
segmentation fault. Use A *a = new A(); to an element?
initialise memory to the object. a) class
329. Which statement is incorrect about b) id
virtual function. c) article
a) They are used to achieve runtime d) html
polymorphism Answer: b
b) They are used to hide objects Explanation: HTML is Hyper Text Markup
c) Each virtual function declaration starts Language which is used to create web pages
with the virtual keyword and applications. The id attribute is most
d) All of the mentioned used to point to a style in a style sheet, and
Answer: b by JavaScript (via the HTML DOM) to
Explanation: Virtual function are used to manipulate the element with the specific id.
achieve runtime polymorphism by calling the Class is a name given to HTML elements
right function during runtime. Their which can be used by CSS and JavaScript for
declaration starts with a virtual keyword. styling the web pages. A self-contained
330. The concept of deciding which function content is called attribute.
to invoke during runtime is called 333. The _____________ attribute specifies
______________________ an inline style associated with an element,
a) late binding which determines the rendering of the
b) dynamic linkage affected element.
c) static binding a) dir
d) both late binding and dynamic linkage b) style
Answer: d c) class
Explanation: The concept of deciding which d) article
function to invoke during runtime is called Answer: b
late binding or dynamic linkage. Late binding Explanation: Style attribute specifies an inline
because function binding to the object is style for an element. The style attribute will
done during runtime. Dynamic linkage override any style set globally, e.g. styles
because this binding is done during runtime. specified in the style tag or in an external
331. What is a pure virtual function? style sheet. A self-contained content is called
a) A virtual function defined inside the base attribute. Class is a name given to HTML
class elements which can be used by CSS and
b) A virtual function that has no definition JavaScript for styling the web pages. List of
relative to the base class directory files is given by dir tag which is not
c) A virtual function that is defined inside the supported in HTML5.

DIWAKAR EDUCATION HUB Page 54


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
334. Which attribute is used to provide an binding. A Disabled is a boolean attribute
advisory text about an element or its which specifies that <input> element should
contents? be disabled.
a) tooltip 337. Which of the following is the attribute
b) dir that indicates the name of the data source
c) title object that supplies the data that is bound to
d) head this element?
Answer: c a) dataFormatAs
Explanation: The extra information about an b) datafld
element is specified by title tag. The c) disabled
information is most often shown as a tooltip d) datasrc
text when the mouse moves over the Answer: d
element. List of directory files is given by dir Explanation: The identifier for data source is
tag which is not supported in HTML5. Tooltip set by dataSrc. When the dataSrc property is
or else infotip is a graphical user interface of applied to a tabular data consumer, the
an element. Container of metadata is called entire data set is repeated by the consuming
head. elements. DataFormatAs specifies how data
335. The __________ attribute sets the text is rendered. A Disabled is a boolean attribute
direction as related to the lang attribute. which specifies that <input> element should
a) lang be disabled.
b) sub 338. Which of the following is the attribute
c) dir that specifies additional horizontal space, in
d) ds pixels, to be reserved on either side of an
Answer: c embedded item like an iframe, applet, image,
Explanation: The dir attribute specifies the and so on?
text direction of the element’s content. List of a) height
directory files is given by dir tag which is not b) hspace
supported in HTML5. The language of an c) hidefocus
element’s content is given by lang attribute. d) datasrc
The subscript text is defined by sub attribute. Answer: b
336. Which of the following is the attribute Explanation: Height of element is pixels is
that specifies the column name from the data specified by height attribute. The hspace
source object that supplies the bound data? attribute specifies the whitespace on left and
a) dataFormatAs right side of an object. The hidefocus
b) datafld specifies whether a focused rectangle is
c) disabled drawn around an object. The identifier for
d) datasrc data source is set by dataSrc.
Answer: b 339. The accesskey attribute specifies a
Explanation: DataFormatAs specifies how keyboard navigation accelerator for the
data is rendered. The identifier for data element.
source is set by dataSrc. Datafld attribute a) True
specifies the column name from the data b) False
source object that supplies the bound data. Answer: a
This attribute is specific to Microsoft’s data Explanation: The accesskey attribute

DIWAKAR EDUCATION HUB Page 55


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
specifies a shortcut key to activate/focus an 343. JavaScript Code can be called by using
element. It specifies a keyboard navigation ___________
accelerator for the element. We can use a) RMI
accesskey attribute in forms or links. b) Triggering Event
340. Which feature was already introduced c) Preprocessor
before HTML5? d) Function/Method
a) Canvas/SVG Answer: d
b) Video Explanation: JavaScript code can be called by
c) Geolocation making a function call to the element on
d) Frames which JavaScript has to be run. There are
Answer: d many other methods like onclick, onload, and
Explanation: Until recently you could not onsubmit etc.
draw on the web and graphics were not very 344. The type of a variable that is volatile is
interactive but canvas/SVG which were _______________
introduced by HTML5 solved all the a) Volatile variable
problems. Video, Geolocation were also new b) Mutable variable
features introduced by HTML5. Frames were c) Immutable variable
already there before the launch of HTML5. d) Dynamic variable
341. Which tag is used with JavaScript? Answer: b
a) <canvas> Explanation: The variables whose values can
b) <table> be changed are called mutable variable types.
c) <article> In JavaScript, only objects and arrays are
d) <footer> mutable, not primitive values.
Answer: a 345. A hexadecimal literal begins with
Explanation: <canvas> tag is basically used __________
for graphics via scripting i.e. usually with Java a) 00
Script (scripting language, basically used to b) 0x
create animations). Other tags like <table>, c) 0X
<article>, <footer> can be used simply with d) Both 0x and 0X
HTML. Answer: d
342. What application can one create even Explanation: Generally, X or x denotes
before the introduction of HTML5? hexadecimal values. So, any integer literal
a) Web applications that begins with 0X or 0x denotes a
b) Mobile applications hexadecimal number.
c) Forms 346. The generalised syntax for a real number
d) Browser based games representation is __________
Answer: c a) [digits][.digits][(E|e)[(+|-)]digits]
Explanation: With the help of HTML5 and b) [digits][+digits][(E|e)[(+|-)]digits]
JavaScript it became possible to create c) [digits][(E|e)[(+|-)]digits]
excellent mobile applications, browser based d) [.digits][digits][(E|e)[(+|-)]digits]
games, web applications and many more Answer: a
other applications. Forms were already Explanation: Floating-point literals may also
introduced before HTML5. be represented using exponential notation: a
real number followed by the letter e (or E),

DIWAKAR EDUCATION HUB Page 56


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
followed by an optional plus or minus sign, c) \f is not present in JavaScript
followed by an integer exponent. This d) Form feed
notation represents the real number Answer: d
multiplied by 10 to the power of the Explanation: \f is the JavaScript escape
exponent. sequence that stands for Form feed (\u000C).
347. JavaScript _________ when there is an It skips to the start of the next page. (Applies
indefinite or an infinite value during an mostly to terminals where the output device
arithmetic computation. is a printer rather than a VDU).
a) Prints an exception error 350. The snippet that has to be used to check
b) Prints an overflow error if “a” is not equal to “null” is _________
c) Displays “Infinity” a) if(a!=null)
d) Prints the value as such b) if (!a)
Answer: c c) if(a!null)
Explanation: When the result of a numeric d) if(a!==null)
operation is larger than the largest Answer: d
representable number (overflow), JavaScript Explanation: A strict comparison (e.g., ===) is
prints the value as Infinity. Similarly, when a only true if the operands are of the same
negative value becomes larger than the type and the contents match. The more
largest representable negative number, the commonly-used abstract comparison (e.g. ==)
result is negative infinity. The infinite values converts the operands to the same type
behave as you would expect: adding, before making the comparison. The not-equal
subtracting, multiplying, or dividing them by operator !== compares 0 to null and
anything results in an infinite value (possibly evaluates to either true or false.
with the sign reversed). 351. The statement a===b refers to
348. Which of the following is not considered _________
as an error in JavaScript? a) Both a and b are equal in value, type and
a) Syntax error reference address
b) Missing of semicolons b) Both a and b are equal in value
c) Division by zero c) Both a and b are equal in value and type
d) Missing of Bracket d) There is no such statement
Answer: c Answer: c
Explanation: Division by zero is not an error Explanation: ”===” operator is known as the
in JavaScript: it simply returns infinity or strict comparison operator. A strict
negative infinity. There is one exception, comparison (===) is only true if the operands
however: zero divided by zero does not have are of the same type and the contents match.
a well defined value, and the result of this 352. Assume that we have to convert “false”
operation is the special not-a-number value, that is a non-string to string. The command
printed as NaN. that we use is (without invoking the “new”
349. The escape sequence ‘\f’ stands for operator).
_________ a) false.toString()
a) Floating numbers b) String(false)
b) Representation of functions that returns a c) String newvariable=”false”
value d) Both false.toString() and String(false)

DIWAKAR EDUCATION HUB Page 57


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
Answer: d c) OpenOffice
Explanation: The three approaches for d) All of the mentioned
converting to string are: value.toString(),”” + Answer: d
value and String(value). A non-string can be Explanation: More that hundred of
converted in two ways without using a new document formats using XML syntax have
operator false.toString () and String(false). been developed, including RSS, Atom, SOAP
353. XML is a _________ markup language. and XHTML.
a) meta 357. A DTD is associated with a XML file by
b) beta means of ___________
c) octa a) Function
d) peta b) <!DOCTYPE>
Answer: a c) Macros
Explanation: Generally speaking, a meta d) None of the mentioned
language is a language used to describe a Answer: b
language. XML is a metalanguage that is used Explanation: A document type definition
to describe a markup language. defines the legal building blocks of an XML
354. XML uses _________ principle to document .
formally describe the data. 358. Which of the following is not an example
a) DDL of electronic mark up?
b) DTD a) HTML
c) DML b) LaTeX
d) None of the mentioned c) PostScript
Answer: b d) None of the mentioned
Explanation: A document type definition Answer: d
(DTD) is a set of markup declarations that Explanation: There are three categories of
define a document type for an SGML-family electronic markup: presentational,
markup language (SGML, XML, HTML). A procedural, and descriptive markup.
Document Type Definition (DTD) defines the Examples are XML, HTML, LaTeX, etc.
legal building blocks of an XML document. It 359. troff and nroff are _________ in Unix.
defines the document structure with a list of a) functions
legal elements and attributes. b) typesetting tools
355. Which among the following are true for c) System sofwares
an Extensible markup language? d) None of the mentioned
a) Human Readable/ Machine Readable Answer: b
b) Extended from SGML Explanation: Early examples of computer
c) Developed by www consortium markup languages can be found in
d) All of the mentioned typesetting tools like troff and nroff in Unix.
Answer: d 360. Which of the following is not OOPS
Explanation: XML is an open format markup concept in Java?
language with a filename extension of .xml. a) Inheritance
356. Which of them have XML as their default b) Encapsulation
format? c) Polymorphism
a) IWork d) Compilation
b) LibreOffice

DIWAKAR EDUCATION HUB Page 58


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
Answer: d 365. How constructor can be used for a
Explanation: There are 4 OOPS concepts in servlet?
Java. Inheritance, Encapsulation, a) Initialization
Polymorphism and Abstraction. b) Constructor function
361. Which of the following is a type of c) Initialization and Constructor function
polymorphism in Java? d) Setup() method
a) Compile time polymorphism Answer: c
b) Execution time polymorphism Explanation: We cannot declare constructors
c) Multiple polymorphism for interface in Java. This means we cannot
d) Multilevel polymorphism enforce this requirement to any class which
Answer: a implements Servlet interface.
Explanation: There are two types of Also, Servlet requires ServletConfig object for
polymorphism in Java. Compile time initialization which is created by container.
polymorphism (overloading) and runtime 366. Can servlet class declare constructor
polymorphism (overriding). with ServletConfig object as an argument?
362. When does method overloading is a) True
determined? b) False
a) At run time Answer: b
b) At compile time Explanation: ServletConfig object is created
c) At coding time after the constructor is called and before
d) At execution time init() is called. So, servlet init parameters
Answer: b cannot be accessed in the constructor.
Explanation: Overloading is determined at 367. What is the difference between servlets
compile time. Hence, it is also known as and applets?
compile time polymorphism. i. Servlets execute on Server; Applets execute
363. What is the range of short data type in on browser
Java? ii. Servlets have no GUI; Applet has GUI
a) -128 to 127 iii. Servlets creates static web pages; Applets
b) -32768 to 32767 creates dynamic web pages
c) -2147483648 to 2147483647 iv. Servlets can handle only a single request;
d) None of the mentioned Applet can handle multiple requests
Answer: b a) i, ii, iii are correct
Explanation: Short occupies 16 bits in b) i, ii are correct
memory. Its range is from -32768 to 32767. c) i, iii are correct
364. What is the range of byte data type in d) i, ii, iii, iv are correct
Java? Answer: b
a) -128 to 127 Explanation: Servlets execute on Server and
b) -32768 to 32767 doesn’t have GUI. Applets execute on
c) -2147483648 to 2147483647 browser and has GUI.
d) None of the mentioned 368. Which of the following code is used to
Answer: a get an attribute in a HTTP Session object in
Explanation: Byte occupies 8 bits in memory. servlets?
Its range is from -128 to 127. a) session.getAttribute(String name)
b) session.alterAttribute(String name)

DIWAKAR EDUCATION HUB Page 59


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) session.updateAttribute(String name) volatile can be changed unexpectedly by
d) session.setAttribute(String name) other part of the program. Specially used in
Answer: a situations involving multithreading.
Explanation: session has various methods for 373. The most commonly used input device is
use. a) Mouse
369. Which of these functions is called to b) Keyboard
display the output of an applet? c) Scanner
a) display() d) Printer
b) paint() Answer: b
c) displayApplet() Explanation: Keyboard is the most commonly
d) PrintApplet() used input device.
Answer: b 374. Which keys allows user to enter
Explanation: Whenever the applet requires frequently used operations in a single key
to redraw its output, it is done by using stroke?
method paint(). a) Function keys
370. Which of these methods can be used to b) Cursor control keys
output a string in an applet? c) Trackball
a) display() d) Control keys
b) print() Answer: a
c) drawString() Explanation: Function keys are used to access
d) transient() frequently used areas.
Answer: c 375. ________ are used to measure dial
Explanation: drawString() method is defined rotations.
in Graphics class, it is used to output a string a) Potentiometers
in an applet. b) Volta meter
371. Which of these methods is a part of c) Parameter
Abstract Window Toolkit (AWT) ? d) Only a
a) display() Answer: d
b) paint() Explanation: Potentiometer measures the
c) drawString() dial rotations.
d) transient() 376. The device which is used to position the
Answer: b screen cursor is
Explanation: paint() is an abstract method a) Mouse
defined in AWT. b) Joystick
372. Which of these modifiers can be used c) Data glove
for a variable so that it can be accessed from d) Both a and c
any thread or parts of a program? Answer: a
a) transient Explanation: A mouse is small hand-held box
b) volatile used to position the screen cursor.
c) global 377. _________ is used for detecting mouse
d) No modifier is needed motion.
Answer: b a) Optical sensor
Explanation: The volatile modifier tells the b) Rollers on the bottom of mouse
compiler that the variable modified by
DIWAKAR EDUCATION HUB Page 60
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) Both a and b a) Bresenham’s line algorithm
d) Sensor b) Parallel line algorithm
Answer: c c) Mid-point algorithm
Explanation: Rollers and optical sensors are d) DDA line algorithm
used to record the amount and direction of Answer: d
movement. Explanation: The DDA is a faster method for
378. The Cartesian slope-intercept equation calculating pixel positions.
for a straight line is 383. The function which references a single
a) y = m.x + b attribute that specifies how a primitive is to
b) y = b.x + m be displayed with that attribute setting is
c) y = x.x + m called
d) y = b + m.m a) Individual attribute
Answer: a b) Unbundled attribute
Explanation: Equation for a straight line is y = c) Bundled attribute
m.x + b. d) A or B
379. For lines with slope magnitude |m|<1, Answer: d
?x can be_________ Explanation: Individual attribute are also
a) A set corresponding vertical deflection known as unbundled attribute.
b) A set proportional to a small horizontal 384. A particular set of attribute values for a
deflection voltage primitive on each output device is chosen by
c) Only a specifying appropriate table index is known
d) All of the mentioned as?
Answer: b a) Individual attribute
Explanation:?x can be a set proportional to a b) Unbundled attribute
small horizontal deflection voltage only if c) Bundled attribute
slope magnitude |m| < 1. d) A or B
380. On raster system, lines are plotted with Answer: c
a) Lines Explanation: Bundle attributes specifies
b) Dots group of attribute values. And these values
c) Pixels can be bundled into the workstation table.
d) None of the mentioned 385. A table for which, a primitive defines
Answer: c groups of attribute values to be used when
Explanation: Using pixels lines can be displaying that primitive on a particular
plotted. output device is called
381. Expansion of line DDA algorithm is a) Bundle table
a) Digital difference analyzer b) Index table
b) Direct differential analyzer c) Both a and b
c) Digital differential analyzer d) None of these
d) Data differential analyzer Answer: a
Answer: c
Explanation: DDA stands for digital 386. The choice between a bundled attribute
differential analyzer. or an unbundled attribute is made by
382. Which algorithm is a faster method for a) Setting switch
calculating pixel positions? b) Setting bundle table

DIWAKAR EDUCATION HUB Page 61


PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
c) Index table dx and dy to its originsl position (x, y) we can
d) Only a obtain a new position (x’, y’).
Answer: d 391.The two-dimensional translation
Explanation: By setting switch the user can equation in the matrix form is
change their choice between bundled a) P’=P+T
attribute or an unbundled attribute. b) P’=P-T
387. A translation is applied to an object by c) P’=P*T
a) Repositioning it along with straight line d) P’=p
path Answer: a
b) Repositioning it along with circular path Explanation: The 2D translation equation is
c) Only b P’=P+T.
d) All of the mentioned 392. A two dimensional rotation is applied to
Answer: a an object by
Explanation: A translation is applied to an a) Repositioning it along with straight line
object by repositioning it along with straight path
line path from one location to another. b) Repositioning it along with circular path
388. We translate a two-dimensional point by c) Only b
adding d) Any of the mentioned
a) Translation distances Answer: c
b) Translation difference Explanation: A two dimensional rotation is
c) X and Y applied to an object by repositioning it along
d) Only a with circular path.
Answer: d 393. To generate a rotation , we must specify
Explanation: We can translate 2D point by a) Rotation angle ϴ
adding translation distances dx and dy. b) Distances dx and dy
389. The translation distances (dx, dy) is c) Rotation distance
called as d) All of the mentioned
a) Translation vector Answer: a
b) Shift vector Explanation: Generate a rotation, we must
c) Both a and b specify rotation angle ϴ of the rotation point
d) Neither a nor b or pivot point which the object is to be
Answer: c rotated.
Explanation: The translation distances (dx, 394. Positive values for the rotation angle ϴ
dy) from its original position is called as defines
translation vector or shift vector. a) Counterclockwise rotations about the end
390. In 2D-translation, a point (x, y) can move points
to the new position (x’, y’) by using the b) Counterclockwise translation about the
equation pivot point
a) x’=x+dx and y’=y+dx c) Counterclockwise rotations about the pivot
b) x’=x+dx and y’=y+dy point
c) X’=x+dy and Y’=y+dx d) Negative direction
d) X’=x-dx and y’=y-dy Answer: c
Answer: b Explanation: A positive value for the rotation
Explanation: By adding translation distance
DIWAKAR EDUCATION HUB Page 62
PROGRAMMING LANGUAGES AND COMPUTER GRAPHICS UNIT – 3 MCQS
angle ϴ defines counterclockwise rotations a) P’=P+T
about the pivot point. b) P’=S*P
395. The rotation axis that is perpendicular to c) P’=P*R
the xy plane and passes through the pivot d) P’=R+S
point is known as Answer: b
a) Rotation Explanation: The 2d scaling equation is
b) Translation P’=S*P.
c) Scaling 400. Scaling of a polygon is done by
d) Shearing computing
Answer: a a) The product of (x, y) of each vertex
Explanation: The rotation transformation is b) (x, y) of end points
also described as a rotation about a rotation c) Center coordinates
axis that is perpendicular to the xy plane and d) Only a
passes through the pivot point. Answer: d
396. The original coordinates of the point in Explanation: Scaling of a polygon is done by
polor coordinates are computing the product of (x, y) of each vertex
a) X’=r cos (Ф +ϴ) and Y’=r cos (Ф +ϴ) with scaling factor sx and sy to produce the
b) X’=r cos (Ф +ϴ) and Y’=r sin (Ф +ϴ) transformation coordinates ( Xnew, Ynew).
c) X’=r cos (Ф -ϴ) and Y’=r cos (Ф -ϴ) 401. If the scaling factors values sx and sy < 1
d) X’=r cos (Ф +ϴ) and Y’=r sin (Ф -ϴ) then
Answer: b a) It reduces the size of object
Explanation: The original coordinates of the b) It increases the size of object
point in polor coordinates are X’=r cos (Ф +ϴ) c) It stunts the shape of an object
and Y’=r sin (Ф +ϴ). d) None
397. The two-dimensional rotation equation Answer: a
in the matrix form is Explanation: If the scaling factors values sx
a) P’=P+T and sy < 1 then it reduces the size of object.
b) P’=R*P 402. If the scaling factors values sx and sy are
c) P’=P*P assigned to the same value then
d) P’=R+P a) Uniform rotation is produced
Answer: b b) Uniform scaling is produced
Explanation: The 2D translation equation is c) Scaling cannot be done
P’=R*P. d) Scaling can be done or cannot be done
398. The transformation that is used to alter Answer: b
the size of an object is Explanation: When sx and sy are assigned the
a) Scaling same value then uniform scaling is produced
b) Rotation that maintains relative object proportions.
c) Translation
d) Reflection
Answer: a
Explanation: Scaling is used to alter the size
of an object.
399. The two-dimensional scaling equation in
the matrix form is
DIWAKAR EDUCATION HUB Page 63

You might also like