CS UNIT-3 (Ugc Net/set/jrf)
CS UNIT-3 (Ugc Net/set/jrf)
2020
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
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
2
Programming Languages and Computer Graphics Unit - 3
conventional mathematical notation or human language, and its codes vary from
computer to computer.
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.
3
Programming Languages and Computer Graphics Unit - 3
Algorithmic languages
FORTRAN
FORTRAN was also designed to translate into efficient machine language. It was
immediately successful and continues to evolve.
ALGOL
4
Programming Languages and Computer Graphics Unit - 3
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.
LISP
5
Programming Languages and Computer Graphics Unit - 3
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
computer’s internal architecture. C, along with its descendant C++, remains one
of the most common languages.
Business-oriented languages
COBOL
SQL
Education-oriented languages
6
Programming Languages and Computer Graphics Unit - 3
BASIC
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
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.
Logo
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
C++
8
Programming Languages and Computer Graphics Unit - 3
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 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
A programming paradigm is a various system design of ideas that have been used
to guide/implement the programming.
9
Programming Languages and Computer Graphics Unit - 3
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.
Advantage:
10
Programming Languages and Computer Graphics Unit - 3
Disadvantage:
average = sum / 5;
Procedural: Imperative programming with procedure calls something like the re-
use of code.
11
Programming Languages and Computer Graphics Unit - 3
The program is written as a collection of classes and object which are meant for
communication. The smallest and basic entity is object and all kind of
computation is performed on the objects only. More emphasis is on data rather
procedure. It can handle almost all kind of real life problems which are today in
scenario.
Advantages:
1. Data security
2. Inheritance
3. Code reusability
4. Flexible and abstraction is also present
Parallel processing: It is a type of processing that works like a divide and conquer
technique by dividing the task into multiple small processes and processing them
parallel to run a program in the least time.
12
Programming Languages and Computer Graphics Unit - 3
Declarative
Logic (as per defined rules): Specifying a set of rules/business logic in the
programming. It is used to solve logic problems.
13
Programming Languages and Computer Graphics Unit - 3
n1=n-1,
sum(n1, r1),
r=r1+n
Functional (Application-oriented): Expressing the calculations as evaluation of
math-function, Function call programming with to avoid any global state change.
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.
Translation process
15
Programming Languages and Computer Graphics Unit - 3
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
16
Programming Languages and Computer Graphics Unit - 3
storage, but is isolated from other software on the computer. It can easily be
created, modified, or destroyed without affecting the host computer.
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.
years later, the tuition is fully paid up, no matter how high it may be at that
moment.
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.
18
Programming Languages and Computer Graphics Unit - 3
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.
By default early binding happens in C++. Late binding is achieved with the help
of virtual keyword)
// outputs.
#include<iostream>
19
Programming Languages and Computer Graphics Unit - 3
class Base
public:
};
public:
};
int main(void)
// function.
bp->show();
return 0;
Output:
20
Programming Languages and Computer Graphics Unit - 3
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.
#include<iostream>
class Base
public:
};
public:
};
int main(void)
21
Programming Languages and Computer Graphics Unit - 3
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.
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.
22
Programming Languages and Computer Graphics Unit - 3
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?
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.
Basic Syntax
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++
23
Programming Languages and Computer Graphics Unit - 3
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
Human languages have syntax. These rules stipulate word order, punctuation and
sentence structure.
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
24
Programming Languages and Computer Graphics Unit - 3
int main() {
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:
The executed program would display: My first line of code just printed!
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?
25
Programming Languages and Computer Graphics Unit - 3
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.
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.
Type Description
26
Programming Languages and Computer Graphics Unit - 3
27
Programming Languages and Computer Graphics Unit - 3
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.
Attribute of a variable:
y:=9;
The name of the box and its storage location are fixed, but the contents and it
name may vary over time.
28
Programming Languages and Computer Graphics Unit - 3
Data Object:
Definition: A Data object represents a container for data values, a place where
data values may be stored and later retrieved.
29
Programming Languages and Computer Graphics Unit - 3
• Single number
30
Programming Languages and Computer Graphics Unit - 3
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.
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.
31
Programming Languages and Computer Graphics Unit - 3
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.
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.
const PI=3.1415;
real root2=1.4142135;
32
Programming Languages and Computer Graphics Unit - 3
In Ada, provides a uniform notation for setting constants to initial values and for
initializing variables.
X: Constant INTEGER:=17;
In C, there is micro definition which is used for control the execution of program
and can be used for declaring constant.
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.
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.
33
Programming Languages and Computer Graphics Unit - 3
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.
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.
Example
(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 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.
35
Programming Languages and Computer Graphics Unit - 3
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.
For Example:
36
Programming Languages and Computer Graphics Unit - 3
c) set x=-x
Integers
Sub -ranges
Complex numbers
Rational numbers
Enumerations Booleans
Booleans
37
Programming Languages and Computer Graphics Unit - 3
Characters
Integers Specification
Operations:
Sub-ranges Specification:
subtype of integer
Pascal declaration A: 1..10 means that the variable A may be assigned integer
values from 1 through 10.
Implementation
Round-off issues - the check for equality may fail due to round -off
Implementation
38
Programming Languages and Computer Graphics Unit - 3
Implementation :
Complex numbers: software simulated with two storage locations one the real
portion and one for the imaginary portion.
Characters
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.
It is assumed that this literals are distinct and does equality can be directly
defined.
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
39
Programming Languages and Computer Graphics Unit - 3
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.
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};
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
40
Programming Languages and Computer Graphics Unit - 3
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
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}
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.
41
Programming Languages and Computer Graphics Unit - 3
Specification: In Pascal and Ada, the Boolean data type is considered simply a
language - defined enumeration, viz;
Which both defines the names true and false for the values of the types and
define ordering false<true
and : Boolean*Boolean->Boolean(conjunction)
or : Boolean*Boolean->Boolean(inclusive disjunction )
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
42
Programming Languages and Computer Graphics Unit - 3
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'.
• Relational operations
• Assignment and
• To test character for- Letter, Digit, Special Character.
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
char a ; //declaration
44
Programming Languages and Computer Graphics Unit - 3
Character Strings
Pointers and Programmer- Constructed Objects
Files
Fixed declared length : storage allocation at translation time. Strings longer than
the declared length are truncated.
Unbounded length: storage allocation at run time. String can be any length
implementation
Objects
Specification:
C, C++: pointers are data objects and can be manipulated by the program
Pointers - implementation
Absolute addresses stored in the pointer. Allows for storing the new object
anywhere in the memory
46
Programming Languages and Computer Graphics Unit - 3
Characteristics:
Types of Files
Direct Access Files: Any single component can be accessed at random just as in an
array.
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
47
Programming Languages and Computer Graphics Unit - 3
C programming
1. Easy to learn
2. Structured language
3. It produces efficient programs
4. It can handle low-level activities
5. It can be compiled on a variety of computer platforms
Facts about C
48
Programming Languages and Computer Graphics Unit - 3
7. Today's most popular Linux OS and RDBMS MySQL have been written
in C.
#include <stdio.h
int main() {
/* my first program in C */
return 0;
Applications of C Programming
C was initially used for system development work, particularly the programs that
make-up the 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
49
Programming Languages and Computer Graphics Unit - 3
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.
Keywords
do if static while
Identifiers
50
Programming Languages and Computer Graphics Unit - 3
51
Programming Languages and Computer Graphics Unit - 3
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
Keyword Identifier
52
Programming Languages and Computer Graphics Unit - 3
Its meaning is pre-defined in the c Its meaning is not defined in the c compiler.
compiler.
It does not contain the underscore It can contain the underscore character.
character.
an example.
int main()
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
53
Programming Languages and Computer Graphics Unit - 3
Example
#include >stdio.h>
int main() {
char a1 = 'H';
int b = 8;
float d = 5.6;
// declaration of string
if(b<10)
else
54
Programming Languages and Computer Graphics Unit - 3
return 0;
Output
Character Value : H
Data Types in C
A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.
55
Programming Languages and Computer Graphics Unit - 3
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.
56
Programming Languages and Computer Graphics Unit - 3
float 4 byte
double 8 byte
Subprogram
57
Programming Languages and Computer Graphics Unit - 3
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:
(2) The Call Instruction is present in the Main Program and the Return(Ret)
Instruction is present in the subprogram itself.
(3) It is important to note that the Main Program is suspended during the
execution of any subprogram. Moreover, after the completion of the subprogram
the main program executes from the next sequential address present in the
Program Counter .
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.
ARRAY
Introduction
59
Programming Languages and Computer Graphics Unit - 3
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.
Assume We have to store marks of 100 students and then think about the
following:
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.
int marks[100];
Notice square brackets after array name marks. This pair of square brackets
is used to depict array usage.
60
Programming Languages and Computer Graphics Unit - 3
#include<stdio.h>
#include<conio.h>
main()
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();
61
Programming Languages and Computer Graphics Unit - 3
Explanation:
► 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;
62
Programming Languages and Computer Graphics Unit - 3
int a[2][3];
this declaration means, we have an array of 2 arrays containing 3 int blocks each.
#include<conio.h>
#include<stdio.h>
main()
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
63
Programming Languages and Computer Graphics Unit - 3
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf("%d ",c[i][j]);
printf("\n");
getch();
Explanation:
64
Programming Languages and Computer Graphics Unit - 3
3) Lastly sum of corresponding elements of two matrices are added and stored
in third array.
int a[ ]= { 23,45,11,67,55};
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.
int b[ ] [ ] = {12,65,78,45,33,21};
Last two styles are invalid and lead to compile time error.
C Structures
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.
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
...
66
Programming Languages and Computer Graphics Unit - 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];
char gender;
};
Here struct Student declares a structure to hold the details of a student which
consists of 4 data fields, namely name, age, branch and gender. These fields are
called structure elements or members.
Each member can have different datatype, like in this case, name is an array
of char type and age is of int type etc. Student is the name of the structure and is
called as the structure tag.
67
Programming Languages and Computer Graphics Unit - 3
struct Student
char name[25];
int age;
char branch[10];
char gender;
};
struct Student
char name[25];
int age;
char branch[10];
68
Programming Languages and Computer Graphics Unit - 3
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not
much recommended.
For example:
#include<stdio.h>
#include<string.h>
struct Student
char name[25];
int age;
char branch[10];
char gender;
};
int main()
{
69
Programming Languages and Computer Graphics Unit - 3
/*
*/
s1.age = 18;
/*
*/
strcpy(s1.name, "Viraaj");
/*
*/
return 0;
Output
Age of Student 1: 18
We can also use scanf() to give values to structure members through terminal.
70
Programming Languages and Computer Graphics Unit - 3
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;
};
or,
p1.weight = 73;
p1.age = 23;
C 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.
71
Programming Languages and Computer Graphics Unit - 3
#include<stdio.h>
struct student
char name[20];
int id;
float marks;
};
void main()
int dummy;
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
72
Programming Languages and Computer Graphics Unit - 3
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
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
Array of Structures in C
73
Programming Languages and Computer Graphics Unit - 3
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
74
Programming Languages and Computer Graphics Unit - 3
char name[10];
};
int main(){
int i;
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
return 0;
Output:
Enter Rollno:1
75
Programming Languages and Computer Graphics Unit - 3
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
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
Nested Structure in C
76
Programming Languages and Computer Graphics Unit - 3
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];
};
void main ()
77
Programming Languages and Computer Graphics Unit - 3
Output
Arun
Delhi
110001
1234567890
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
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.
78
Programming Languages and Computer Graphics Unit - 3
struct Date
int dd;
int mm;
int yyyy;
};
struct Employee
int id;
char name[20];
}emp1;
As We can see, doj (date of joining) is the variable of type Date. Here doj is 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;
79
Programming Languages and Computer Graphics Unit - 3
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
#include <stdio.h>
#include <string.h>
struct Employee
int id;
80
Programming Languages and Computer Graphics Unit - 3
char name[20];
struct Date
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
e1.id=101;
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
81
Programming Languages and Computer Graphics Unit - 3
return 0;
Output:
employee id : 101
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
82
Programming Languages and Computer Graphics Unit - 3
char name[20];
};
void main ()
display(emp);
printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
We can pass a structure as a function argument just like we pass any other
variable or an array as a function argument.
Example:
#include<stdio.h>
83
Programming Languages and Computer Graphics Unit - 3
struct Student
char name[10];
int roll;
};
void main()
printf("\nStudent name:\t");
scanf("%s", std.name);
scanf("%d", &std.roll);
show(std);
84
Programming Languages and Computer Graphics Unit - 3
C Unions
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;
}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
85
Programming Languages and Computer Graphics Unit - 3
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.
Syntax for accessing any union member is similar to accessing structure members,
union test
int a;
float b;
char c;
}t;
t.b;
t.c;
#include <stdio.h>
union item
int a;
float b;
86
Programming Languages and Computer Graphics Unit - 3
char ch;
};
int main( )
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
-26426
20.1999
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.
87
Programming Languages and Computer Graphics Unit - 3
In the above example, value of the variable c was stored at last, hence the value
of other variables is lost.
It occupies less memory because it occupies the size of the largest member only.
Only the last entered data can be stored in the union. It overwrites the data
previously stored in the union.
String
'C' provides standard library <string.h> that contains many functions which can be
used to perform complicated string operations easily.
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.
88
Programming Languages and Computer Graphics Unit - 3
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 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.
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,
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;
Output:
John_Smith 48
The problem with the scanf function is that it never reads an entire string. It will
halt the reading process as soon as whitespace, form feed, vertical tab, newline 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.
90
Programming Languages and Computer Graphics Unit - 3
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];
gets(full_name);
return 0;
Output:
#include <stdio.h>
int main() {
char name[10];
91
Programming Languages and Computer Graphics Unit - 3
return 0;}
Output:
My name is Carlos
• stdin means to read from the standard input which is the keyboard.
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);
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];
92
Programming Languages and Computer Graphics Unit - 3
gets(town);
fputs(town, stdout);
return 0;}
Output:
New York
puts function
The puts function prints the string on an output device and moves the cursor back
to the first position. A puts function can be used in the following way,
#include <stdio.h>
int main() {
char name[15];
return 0;}
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.
93
Programming Languages and Computer Graphics Unit - 3
Function Purpose
#include <stdio.h>
#include <string.h>
int main () {
//string initialization
char string1[15]="Hello";
char string3[15];
94
Programming Languages and Computer Graphics Unit - 3
int val;
//string comparison
val= strcmp(string1,string2);
if(val==0){
else{
//string concatenation
//string length
//string copy
return 0;
Output:
96
Programming Languages and Computer Graphics Unit - 3
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.
#include <stdio.h>
int main()
{char *string_id[10];
int ID;
gets(string_id);
ID = atoi(string_id);
return 0;}
Output:
97
Programming Languages and Computer Graphics Unit - 3
Summary
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.
98
Programming Languages and Computer Graphics Unit - 3
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).
Now, what is a pointer? Instead of storing a value, a pointer will y store the
address of a variable.
Int *y = &v;
VARIABLE POINTER
Declaring a pointer
99
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.
int *ptr1,thing;/* ptr1 is a pointer to type integer and thing is an integer variable
*/
float *ptr, variable;/*ptr is a pointer to type float and variable is an ordinary float
variable */
Initialize a pointer
100
Programming Languages and Computer Graphics Unit - 3
pointer = &variable;
#include <stdio.h>
int main()
return 0;
Output:
Operator Meaning
* Serves 2 purpose
Declaration of a pointer
101
Programming Languages and Computer Graphics Unit - 3
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.
#include <stdio.h>
int main()
return 0;
Output:
Void Pointer
102
Programming Languages and Computer Graphics Unit - 3
#include <stdio.h>
int main()
return 0;
Output:
Wild pointer
#include <stdio.h>
int main()
103
Programming Languages and Computer Graphics Unit - 3
printf("\n%d",*p);
return 0;
Output
Dangling pointer
Complex pointer
Near pointer
Far pointer
Huge pointer
In C, there are two equivalent ways to access and manipulate a variable content
#include <stdio.h>
int var = 1;
104
Programming Languages and Computer Graphics Unit - 3
int *ptr;
ptr = &var;
*ptr=48;
return 0;}
After compiling the program without any errors, the result is:
105
Programming Languages and Computer Graphics Unit - 3
Pointers Arithmetic
Pointer Operations
When working with pointers, we must observe the following priority rules:
106
Programming Languages and Computer Graphics Unit - 3
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.
int X =10
int *P = &Y;
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.
107
Programming Languages and Computer Graphics Unit - 3
Below table shows the arithmetic and basic operation that can be used when
dealing with pointers
Operation Explanation
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()
108
Programming Languages and Computer Graphics Unit - 3
p++; //incrementing to the next element, you can also write p=p+1
return 0;
Output
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:
109
Programming Languages and Computer Graphics Unit - 3
Pointer Addition/Increment
Since p currently points to the location 0 after adding 1, the value will become 1,
and hence the pointer will point to the memory location 1.
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 *p;
p=str;
p =p+1;
for(int i=0;i<strlen(str);i++)
110
Programming Languages and Computer Graphics Unit - 3
printf("%c\n",*p);
p++;
return 0;
Output
H
e
l
l
o
M
a
n
i
s
h
9
9
Another way to deal strings is with an array of pointers like in the following
program:
#include <stdio.h>
111
Programming Languages and Computer Graphics Unit - 3
int main(){
int i ;
return 0;}
Output:
iron
copper
gold
Advantages of Pointers
Disadvantages of Pointers
Summary
Functions in C
There are many situations where we might need to write same line of code for
more than once in a program. This may lead to unnecessary repetition of code,
bugs and even becomes boring for the programmer. So, C language provides 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
113
Programming Languages and Computer Graphics Unit - 3
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.
2. It makes our code reusable. We just have to call the function by its name to
use it, wherever required.
114
Programming Languages and Computer Graphics Unit - 3
Function Declaration
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
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
115
Programming Languages and Computer Graphics Unit - 3
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 main()
int i, j, result;
return 0;
116
Programming Languages and Computer Graphics Unit - 3
Just like in the example above, the general syntax of function definition is,
functionbody
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
117
Programming Languages and Computer Graphics Unit - 3
In the example above, the statement multiply(i, j); inside the main() function is
function call.
Arguments are the values specified during the function call, for which the formal
parameters are declared while defining the function.
118
Programming Languages and Computer Graphics Unit - 3
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.
119
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.
120
Programming Languages and Computer Graphics Unit - 3
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>
int main()
return 0;
int i, j;
if(i > j) {
121
Programming Languages and Computer Graphics Unit - 3
else {
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 main()
int result;
return 0;
int i, j, greaterNum;
122
Programming Languages and Computer Graphics Unit - 3
if(i > j) {
greaterNum = i;
else {
greaterNum = j;
return greaterNum;
We are using the same function as example again and again, to demonstrate that
to solve a problem there can be many different ways.
#include<stdio.h>
int main()
int i, j;
123
Programming Languages and Computer Graphics Unit - 3
return 0;
if(x > y) {
else {
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 main()
int i, j, result;
124
Programming Languages and Computer Graphics Unit - 3
return 0;
if(x > y) {
return x;
else {
return y;
Nesting of Functions
C language also allows nesting of functions i.e to use/call one function inside
another function's body. We must be careful while using nested functions,
because it may lead to infinite nesting.
function1()
function2();
125
Programming Languages and Computer Graphics Unit - 3
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
#include<stdio.h>
126
Programming Languages and Computer Graphics Unit - 3
void main()
int a, b;
printf("Enter a number...");
scanf("%d", &a);
printf("%d", b);
int r = 1;
if(x == 1)
return 1;
else
return r;
File Handling in C
127
Programming Languages and Computer Graphics Unit - 3
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.
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:
128
Programming Languages and Computer Graphics Unit - 3
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.
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".
129
Programming Languages and Computer Graphics Unit - 3
Mode Description
130
Programming Languages and Computer Graphics Unit - 3
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.
#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
131
Programming Languages and Computer Graphics Unit - 3
#include;
void main( )
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 );
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:
132
Programming Languages and Computer Graphics Unit - 3
C fseek()
C fseek() example
The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
Syntax:
Example:
#include <stdio.h>
main(){
FILE *fp;
133
Programming Languages and Computer Graphics Unit - 3
fclose(fp);//closing file
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:
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "r");
fclose(fp);
Output:
134
Programming Languages and Computer Graphics Unit - 3
#include <stdio.h>
void main()
FILE *fptr;
int id;
char name[30];
float salary;
if (fptr == NULL)
return;
scanf("%d", &id);
scanf("%s", name);
135
Programming Languages and Computer Graphics Unit - 3
scanf("%f", &salary);
fclose(fptr);
Output:
Enter the id
sonoo
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
The arguments passed from command line are called command line arguments.
These arguments are handled by main() function.
136
Programming Languages and Computer Graphics Unit - 3
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>
else{
137
Programming Languages and Computer Graphics Unit - 3
./program hello
program.exe hello
Output:
Output:
But if we pass many arguments within double quote, all arguments will be treated
as a single argument only.
Output:
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
138
Programming Languages and Computer Graphics Unit - 3
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 −
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
Tests if a compile time condition is true.
139
Programming Languages and Computer Graphics Unit - 3
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.
140
Programming Languages and Computer Graphics Unit - 3
#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.
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.
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.
141
Programming Languages and Computer Graphics Unit - 3
5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.
int main() {
}
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 −
142
Programming Languages and Computer Graphics Unit - 3
#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!
int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
143
Programming Languages and Computer Graphics Unit - 3
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);
This example shows the concatenation of token##n into token34 and here we
have used both stringize and token-pasting.
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 −
144
Programming Languages and Computer Graphics Unit - 3
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>
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result
−
Max between 20 and 10 is 20
OOP focuses on the objects that developers want to manipulate rather than the
logic required to manipulate them. This approach to programming is well-suited
for programs that are large, complex and actively updated or maintained.
145
Programming Languages and Computer Graphics Unit - 3
The first step in OOP is to collect all of the objects a programmer wants to
manipulate and identify how they relate to each other -- an exercise often known
as data modeling.
Examples of an object can range from physical entities, such as a human being
who is described by properties like name and address, down to small computer
programs, such as widgets.
Once an object is known, it is labeled with a class of objects that defines the kind
of data it contains and any logic sequences that can manipulate it. Each distinct
logic sequence is known as a method. Objects can communicate with well-
defined interfaces called messages.
Principles of OOP
Encapsulation. The implementation and state of each object are privately held
inside a defined boundary, or class. Other objects do not have access to this
class or the authority to make changes but are only able to call a list of public
functions, or methods. This characteristic of data hiding provides greater
program security and avoids unintended data corruption.
Hiding the implementation details of the class from the user through an
object’s methods is known as data encapsulation. In object oriented
programming, it binds the code and the data together and keeps them safe
from outside interference.
146
Programming Languages and Computer Graphics Unit - 3
Abstraction. Objects only reveal internal mechanisms that are relevant for the
use of other objects, hiding any unnecessary implementation code. This
concept helps developers more easily make changes and additions over time.
Polymorphism. Objects can take on more than one form depending on the
context. The program will determine which meaning or usage is necessary for
each execution of that object, cutting down the need to duplicate code.
Java
JavaScript
Python
C++
Visual Basic .NET
Ruby
Scala
PHP
147
Programming Languages and Computer Graphics Unit - 3
Criticism of OOP
functional programming
structured programming
imperative programming
Programming starts with the concept of real world objects and classes.
Objects
Real-world objects share two characteristics − They all have state and behavior.
see the following pictorial example to understand Objects.
In the above diagram, the object ‘Dog’ has both state and behavior.
An object stores its information in attributes and discloses its behavior through
methods. now discuss in brief the different components of object oriented
programming.
Public Interface
The point where the software entities interact with each other either in a single
computer or in a network is known as pubic interface. This help in data security.
Other objects can change the state of an object in an interaction by using only
those methods that are exposed to the outer world through a public interface.
Class
A class is a group of objects that has mutual methods. It can be considered as the
blueprint using which objects are created.
149
Programming Languages and Computer Graphics Unit - 3
Classes being passive do not communicate with each other but are used to
instantiate objects that interact with each other.
Example
Object oriented interface unites users with the real world manipulating software
objects for designing purpose. see the diagram.
While creating the OOM for interface design, first of all analysis of user
requirements is done. The design specifies the structure and components
150
Programming Languages and Computer Graphics Unit - 3
required for each dialogue. After that, interfaces are developed and tested
against the Use Case. Example − Personal banking application.
The sequence of processes documented for every Use Case are then analyzed for
key objects. This results into an object model. Key objects are called analysis
objects and any diagram showing relationships between these objects is called
object diagram.
C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables,
functions, arrays, or other user-defined data types created by the programmer.
They are the basic requirement of any language. Every language has its own rules
for naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a
program which are given below:
Constants
Variables
Functions
Labels
Defined data types
Some naming rules are common in both C and C++. They are as follows:
Valid Identifiers
Result
Test2
_sum
power
Invalid Identifiers
Note: Identifiers cannot be used as the keywords. It may not conflict with the
keywords, but it is highly recommended that the keywords should not be used as
the identifier name. We should always use a consistent way to name the
identifiers so that our code will be more readable and maintainable.
The major difference between C and C++ is the limit on the length of the name of
the variable. ANSI C considers only the first 32 characters in a name while ANSI
C++ imposes no limit on the length of the name.
Constants are the identifiers that refer to the fixed value, which do not change
during the execution of a program. Both C and C++ support various kinds of literal
constants, and they do have any memory location. For example, 123, 12.34, 037,
0X2, etc. are the literal constants.
152
Programming Languages and Computer Graphics Unit - 3
#include <iostream>
int main()
int a;
int A;
cin>>a;
cin>>A;
return 0;
In the above code, we declare two variables 'a' and 'A'. Both the letters are same
but they will behave as different identifiers. As we know that the identifiers are
the case-sensitive so both the identifiers will have different memory locations.
Output
153
Programming Languages and Computer Graphics Unit - 3
Keywords are the reserved words that have a special meaning to the compiler.
They are reserved for a special purpose, which cannot be used as the identifiers.
For example, 'for', 'break', 'while', 'if', 'else', etc. are the predefined words where
predefined words are those words whose meaning is already known by the
compiler. Whereas, the identifiers are the names which are defined by the
programmer to the program elements such as variables, functions, arrays,
objects, classes.
Identifiers Keywords
Identifiers are the names defined by the Keywords are the reserved words
programmer to the basic elements of a whose meaning is known by the
program. compiler.
It can use both lowercase and uppercase It uses only lowercase letters.
letters.
154
Programming Languages and Computer Graphics Unit - 3
The starting letter of identifiers can be It can be started only with the
lowercase, uppercase or underscore. lowercase letter.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break',
etc.
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
type variable_list;
int x;
float y;
char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
155
Programming Languages and Computer Graphics Unit - 3
float f=30.8;
char c='A';
A variable name can start with alphabet and underscore only. It can't start with
digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
int a;
int _ab;
int a30;
int 4;
int x y;
int double;
A data type specifies the type of data that a variable can store such as integer,
floating, character etc.
156
Programming Languages and Computer Graphics Unit - 3
The memory size of basic data types may change according to 32 or 64 bit
operating system.
157
Programming Languages and Computer Graphics Unit - 3
158
Programming Languages and Computer Graphics Unit - 3
float 4 byte
double 8 byte
C++ Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operator
Unary operator
Ternary or Conditional Operator
Misc Operator
159
Programming Languages and Computer Graphics Unit - 3
The precedence of operator species that which operator will be evaluated first
and next. The associativity specifies the operators direction to be evaluated, it
may be left to right or right to left.
1. int data=5+10*10;
160
Programming Languages and Computer Graphics Unit - 3
161
Programming Languages and Computer Graphics Unit - 3
if statement
switch statement
conditional operator statement
goto statement
1. Simple if statement
2. if....else statement
4. else if statement
Simple if statement
if(expression)
statement-inside;
statement-outside;
162
Programming Languages and Computer Graphics Unit - 3
Example:
#include< iostream.h>
int main( )
int x,y;
x=15;
y=13;
if (x > y )
Output
x is greater than y
y is greater than x
if(expression)
if(expression1)
163
Programming Languages and Computer Graphics Unit - 3
statement-block1;
else
statement-block2;
else
statement-block3;
Example:
void main( )
int a,b,c;
164
Programming Languages and Computer Graphics Unit - 3
if(a > b)
if( a > c)
else
else
if( b> c)
else
165
Programming Languages and Computer Graphics Unit - 3
The above code will print different statements based on the values
of a, b and c variables.
else-if Ladder
if(expression 1)
statement-block1;
else if(expression 2)
statement-block2;
else if(expression 3 )
statement-block3;
else
default-statement;
The expression is tested from the top(of the ladder) downwards. As soon as the
true condition is found, the statement associated with it is executed.
166
Programming Languages and Computer Graphics Unit - 3
Example:
void main( )
int a;
cin >> a;
else if(a%5==0)
else
167
Programming Languages and Computer Graphics Unit - 3
If We enter value 40 for the variable a, then the output will be:
Output
Points to Remember
int a = 5;
if(a > 4)
Output
success
No curly braces are required in the above case, but if we have more than one
statement inside if condition, then we must enclose them inside curly braces
otherwise only the first statement after the if condition will be considered.
int a = 2;
if(a > 4)
Output
168
Programming Languages and Computer Graphics Unit - 3
2. Other than 0(zero), all other positive numeric values are considered as true.
3. if(27)
Output
hello
C++ Functions
To perform any task, we can create function. A function can be called many times.
It provides modularity and code reusability.
Advantage of functions in C
1) Code Reusability
By creating functions in C++, we can call it many times. So we don't need to write
the same code again and again.
2) Code optimization
169
Programming Languages and Computer Graphics Unit - 3
Suppose, we have to check 3 numbers (531, 883 and 781) whether it is prime
number or not. Without using function, we need to write the prime number logic
3 times. So, there is repetition of code.
But if we use functions, we need to write the logic only once and we can reuse it
several times.
Types of Functions
1. Library Functions: are the functions which are declared in the C++ header files
such as ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.
Declaration of a function
//code to be executed
170
Programming Languages and Computer Graphics Unit - 3
#include <iostream>
void func() {
i++;
j++;
int main()
func();
func();
func();
Output:
i= 1 and j= 1
i= 2 and j= 1
171
Programming Languages and Computer Graphics Unit - 3
i= 3 and j= 1
There are two ways to pass value or data to function in C language: call by value
and call by reference. Original value is not modified in call by value but it is
modified in call by reference.
Understand call by value and call by reference in C++ language one by one.
In call by value, value being passed to the function is locally stored by the function
parameter in stack memory location. If We change the value of function
parameter, it is changed for the current function only. It will not change the value
of variable inside the caller method such as main().
The concept of call by value in C++ language by the example given below:
172
Programming Languages and Computer Graphics Unit - 3
#include <iostream>
int main()
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
data = 5;
Output:
Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, value changed inside the
function, is reflected inside as well as outside the function.
173
Programming Languages and Computer Graphics Unit - 3
Note: To understand the call by reference, We must have the basic knowledge of
pointers.
the concept of call by reference in C++ language by the example given below:
#include<iostream>
int swap;
swap=*x;
*x=*y;
*y=swap;
int main()
return 0;
Output:
174
Programming Languages and Computer Graphics Unit - 3
2 Changes made inside the function is Changes made inside the function
not reflected on other functions is reflected outside the function
also
3 Actual and formal arguments will be Actual and formal arguments will
created in different memory be created in same memory
location location
175
Programming Languages and Computer Graphics Unit - 3
#include <iostream>
class A
int x=5;
public:
176
Programming Languages and Computer Graphics Unit - 3
void display()
};
class B: public A
int y = 10;
public:
void display()
};
int main()
A *a;
B b;
a = &b;
a->display();
return 0;
177
Programming Languages and Computer Graphics Unit - 3
Output:
Value of x is : 5
In the above example, * a is the base class pointer. The pointer can only access
the base class members but not the members of the derived class. Although C++
permits the base pointer to point to any object derived from the base class, it
cannot directly access the members of the derived class. Therefore, there is a
need for virtual function which allows the base pointer to access the members of
the derived class.
the simple example of C++ virtual function used to invoked the derived class in a
program.
#include <iostream>
public:
};
class B:public A
public:
178
Programming Languages and Computer Graphics Unit - 3
void display()
};
int main()
a = &b;
Output:
A virtual function is not used for performing any task. It only serves as a
placeholder.
When the function has no definition, such function is known as "do-
nothing" function.
The "do-nothing" function is known as a pure virtual function. A pure
virtual function is a function declared in the base class that has no
definition relative to the base class.
A class containing the pure virtual function cannot be used to declare
the objects of its own, such classes are known as abstract base classes.
179
Programming Languages and Computer Graphics Unit - 3
The main objective of the base class is to provide the traits to the
derived classes and to create the base pointer used for achieving the
runtime polymorphism.
A simple example:
#include <iostream>
class Base
public:
};
public:
void show()
std::cout << "Derived class is derived from the base class." << std::endl;
};
int main()
180
Programming Languages and Computer Graphics Unit - 3
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
Output:
In the above example, the base class contains the pure virtual function. Therefore,
the base class is an abstract base class. We cannot create the object of the base
class.
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, we can reuse, extend or
modify the attributes and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived
class and the class whose members are inherited is called base class. The derived
class is the specialized class for the base class.
Code reusability: Now we can reuse the members of our parent class. So, there is
no need to define the member again. So less code is required in the class.
181
Programming Languages and Computer Graphics Unit - 3
Types Of Inheritance
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
Where,
182
Programming Languages and Computer Graphics Unit - 3
visibility mode: The visibility mode specifies whether the features of the base
class are publicly inherited or privately inherited. It can be public or private.
o When the base class is privately inherited by the derived class, public
members of the base class becomes the private members of the derived
class. Therefore, the public members of the base class are not accessible by
the objects of the derived class only by the member functions of the
derived class.
o When the base class is publicly inherited by the derived class, public
members of the base class also become the public members of the derived
class. Therefore, the public members of the base class are accessible by the
objects of the derived class as well as by the member functions of the base
class.
Note:
183
Programming Languages and Computer Graphics Unit - 3
Where 'A' is the base class, and 'B' is the derived class.
When one class inherits another class, it is known as single level inheritance. the
example of single level inheritance which inherits the fields only.
#include <iostream>
class Account {
public:
};
public:
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
Output:
184
Programming Languages and Computer Graphics Unit - 3
Salary: 60000
Bonus: 5000
#include <iostream>
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
};
public:
void bark(){
cout<<"Barking...";
};
185
Programming Languages and Computer Graphics Unit - 3
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
Output:
Eating...
Barking...
The private member is not inheritable. If we modify the visibility mode by making
it public, but this takes away the advantage of data hiding.
C++ introduces a third visibility modifier, i.e., protected. The member which is
declared as protected will be accessible to all the member functions within the
class as well as the class immediately derived from it.
186
Programming Languages and Computer Graphics Unit - 3
187
Programming Languages and Computer Graphics Unit - 3
When one class inherits another class which is further inherited by another class,
it is known as multi level inheritance in C++. Inheritance is transitive so the last
derived class acquires all the members of all its base classes.
#include <iostream>
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
};
188
Programming Languages and Computer Graphics Unit - 3
public:
void bark(){
cout<<"Barking..."<<endl;
};
public:
void weep() {
cout<<"Weeping...";
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
Output:
189
Programming Languages and Computer Graphics Unit - 3
Eating...
Barking...
Weeping...
Multiple inheritance is the process of deriving a new class that inherits the
attributes from two or more classes.
Ambiguity can be occurred in using the multiple inheritance when a function with
the same name occurs in more than one base class.
The above issue can be resolved by using the class resolution operator
with the function. In the above example, the derived class code can be
rewritten as:
190
Programming Languages and Computer Graphics Unit - 3
void view()
};
class A
public:
void display()
cout<<?Class A?;
};
class B
public:
191
Programming Languages and Computer Graphics Unit - 3
void display()
cout<<?Class B?;
};
In the above case, the function of the derived class overrides the method of the
base class. Therefore, call to the display() function will simply call the function
defined in the derived class. If we want to invoke the base class function, we can
use the class resolution operator.
int main()
B b;
192
Programming Languages and Computer Graphics Unit - 3
Hierarchical inheritance is defined as the process of deriving more than one class
from a base class.
class A
class B : public A
193
Programming Languages and Computer Graphics Unit - 3
// body of class B.
class C : public A
// body of class C.
class D : public A
// body of class D.
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop
etc.
In other words, object is an entity that has state and behavior. Here, state means
data and behavior means functionality.
Object is an instance of a class. All the members of the class can be accessed
through object.
194
Programming Languages and Computer Graphics Unit - 3
In this example, Student is the type and s1 is the reference variable that refers to
the instance of Student class.
C++ Class
In C++, object is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors etc.
class Student
public:
C++ Constructor
Default constructor
Parameterized constructor
#include <iostream>
class Employee
public:
Employee()
};
int main(void)
Employee e2;
return 0;
Output:
196
Programming Languages and Computer Graphics Unit - 3
C++ Destructor
A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).
#include <iostream>
class Employee
public:
Employee()
cout<<"Constructor Invoked"<<endl;
197
Programming Languages and Computer Graphics Unit - 3
~Employee()
cout<<"Destructor Invoked"<<endl;
};
int main(void)
return 0;
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ allows us to specify more than one definition for a function name or
an operator in the same scope, which is called function overloading and operator
overloading respectively.
198
Programming Languages and Computer Graphics Unit - 3
we can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list. We cannot overload function
declarations that differ only by return type.
Following is the example where same function print() is being used to print
different data types −
#include <iostream>
class printData {
public:
void print(int i) {
void print(double f) {
199
Programming Languages and Computer Graphics Unit - 3
void print(char* c) {
};
int main(void) {
printData pd;
pd.print(5);
pd.print(500.263);
pd.print("Hello C++");
return 0;
When the above code is compiled and executed, it produces the following result −
Printing int: 5
200
Programming Languages and Computer Graphics Unit - 3
We can redefine or overload most of the built-in operators available in C++. Thus,
a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined. Like any other function,
an overloaded operator has a return type and a parameter list.
declares the addition operator that can be used to add two Box objects and
returns final Box object. Most overloaded operators may be defined as ordinary
non-member functions or as class member functions. In case we define above
function as non-member function of a class then we would have to pass two
arguments for each operand as follows −
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
201
Programming Languages and Computer Graphics Unit - 3
:: .* . ?:
Templates in C++
A template is a simple and yet very powerful tool in C++. The simple idea is to
pass data type as a parameter so that we don’t need to write the same code for
different data types. For example, a software company may need sort() for
202
Programming Languages and Computer Graphics Unit - 3
different data types. Rather than writing and maintaining the multiple codes, we
can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’.
The second keyword can always be replaced by keyword ‘class’.
Function Templates We write a generic function that can be used for different
data types. Examples of function templates are sort(), max(), min(), printArray().
203
Programming Languages and Computer Graphics Unit - 3
#include <iostream>
// One function works for all data types. This would work
T myMax(T x, T y)
int main()
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char
return 0;
Output:
204
Programming Languages and Computer Graphics Unit - 3
Class Templates Like function templates, class templates are useful when a class
defines something that is independent of the data type. Can be useful for classes
like LinkedList, BinaryTree, Stack, Queue, Array, etc.
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
205
Programming Languages and Computer Graphics Unit - 3
// catch block
} catch( ExceptionName eN ) {
// catch block
We can list down multiple catch statements to catch different type of exceptions
in case our try block raises more than one exception in different situations.
Throwing Exceptions
Exceptions can be thrown anywhere within a code block using throw statement.
The operand of the throw statement determines a type for the exception and can
be any expression and the type of the result of the expression determines the
type of exception thrown.
if( b == 0 ) {
return (a/b);
Catching Exceptions
The catch block following the try block catches any exception. We can specify
what type of exception We want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
206
Programming Languages and Computer Graphics Unit - 3
try {
// protected code
} catch( ExceptionName e ) {
try {
// protected code
} catch(...) {
207
Programming Languages and Computer Graphics Unit - 3
Here is the small description of each exception mentioned in the above hierarchy
−
1 std::exception
2 std::bad_alloc
208
Programming Languages and Computer Graphics Unit - 3
3 std::bad_cast
4 std::bad_exception
5 std::bad_typeid
6 std::logic_error
7 std::domain_error
8 std::invalid_argument
9 std::length_error
10 std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
209
Programming Languages and Computer Graphics Unit - 3
11 std::runtime_error
12 std::overflow_error
13 std::range_error
14 std::underflow_error
another standard C++ library called fstream, which defines three new data types −
1 ofstream
This data type represents the output file stream and is used to create files
and to write information to files.
2 ifstream
This data type represents the input file stream and is used to read
information from files.
210
Programming Languages and Computer Graphics Unit - 3
3 fstream
This data type represents the file stream generally, and has the capabilities
of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be
included in our C++ source file.
Opening a File
Here, the first argument specifies the name and location of the file to be opened
and the second argument of the open() member function defines the mode in
which the file should be opened.
1 ios::app
2 ios::ate
Open a file for output and move the read/write control to the end of the
file.
211
Programming Languages and Computer Graphics Unit - 3
3 ios::in
4 ios::out
5 ios::trunc
If the file already exists, its contents will be truncated before opening the
file.
we can combine two or more of these values by ORing them together. For
example if We want to open a file in write mode and want to truncate it in case
that already exists, following will be the syntax −
ofstream outfile;
Similar way, We can open a file for reading and writing purpose as follows −
fstream afile;
Closing a File
When a C++ program terminates it automatically flushes all the streams, release
all the allocated memory and close all the opened files. But it is always a good
practice that a programmer should close all the opened files before program
termination.
void close();
212
Programming Languages and Computer Graphics Unit - 3
Writing to a File
While doing C++ programming, We write information to a file from our program
using the stream insertion operator (<<) just as We use that operator to output
information to the screen. The only difference is that We use
an ofstream or fstream object instead of the cout object.
We read information from a file into our program using the stream extraction
operator (>>) just as We use that operator to input information from the
keyboard. The only difference is that We use an ifstream or fstream object
instead of the cin object.
Both istream and ostream provide member functions for repositioning the file-
position pointer. These member functions are seekg ("seek get") for istream
and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument
can be specified to indicate the seek direction. The seek direction can
be ios::beg (the default) for positioning relative to the beginning of a
stream, ios::cur for positioning relative to the current position in a stream
or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as
a number of bytes from the file's starting location. Some examples of positioning
the "get" file-position pointer are −
fileObject.seekg( n );
213
Programming Languages and Computer Graphics Unit - 3
fileObject.seekg( n, ios::cur );
fileObject.seekg( n, ios::end );
fileObject.seekg( 0, ios::end );
C++ Exceptions
C++ Exceptions
When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The
technical term for this is: C++ will throw an exception (throw an error).
Exception handling in C++ consist of three keywords: try, throw and catch:
The try statement allows We to define a block of code to be tested for errors
while it is being executed.
The throw keyword throws an exception when a problem is detected, which lets
us create a custom error.
Example
214
Programming Languages and Computer Graphics Unit - 3
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Web Programming
Web programming refers to the writing, markup and coding involved in Web
development, which includes Web content, Web client and server scripting and
network security. The most common languages used for Web programming are
XML, HTML, JavaScript, Perl 5 and PHP. Web programming is different from just
programming, which requires interdisciplinary knowledge on the application area,
client and server scripting, and database technology.
Web programming can be briefly categorized into client and server coding. The
client side needs programming related to accessing data from users and providing
information. It also needs to ensure there are enough plug ins to enrich user
experience in a graphic user interface, including security measures.
The server side needs programming mostly related to data retrieval, security and
performance. Some of the tools used here include ASP, Lotus Notes, PHP, Java
and MySQL. There are certain tools/platforms that aid in both client- and server-
side programming. Some examples of these are Opa and Tersus.
215
Programming Languages and Computer Graphics Unit - 3
Hypertext markup language (HTML) is the major markup language used to display
Web pages on the Internet. In other words, Web pages are composed of HTML,
which is used to display text, images or other resources through a Web browser.
All HTML is plain text, meaning it is not compiled and may be read by humans.
The file extension for an HTML file is .htm or .html.
New Web developers may mistake HTML for a programming language when it is
actually a markup language. HTML is used with other technologies because all
HTML really does is organize documents. On the client side, JavaScript (JS) is used
to provide interactivity. On the server side, a Web development platform like
Ruby, PHP or ASP.NET is used.
HTML was never designed for the Web that exists today, as it is just a markup
language with severe limitations, in terms of control and design. Numerous
technologies have been used to work around this issue - the most significant
being cascading style sheet (CSS).
The long term solution is (or hopefully will be) HTML5, which is the next
generation of HTML and allows for more control and interactivity. As with any
development on the Web, the move to standards is a slow and arduous process,
and Web developers and designers have to make due with current and supported
technologies, which means that basic HTML will continue to be used for some
time.
Applications of HTML
As mentioned before, HTML is one of the most widely used language over the
web. I'm going to list few of them here:
216
Programming Languages and Computer Graphics Unit - 3
Internet Navigation - HTML provides tags which are used to navigate from
one page to another and is heavily used in internet navigation.
Offline support HTML pages once loaded can be made available offline on
the machine without any need of internet.
Game development- HTML5 has native support for rich experience and is
now useful in gaming developent arena as well.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>
217
Programming Languages and Computer Graphics Unit - 3
HTML Tags
As told earlier, HTML is a markup language and makes use of various tags to
format the content. These tags are enclosed within angle braces <Tag Name>.
Except few tags, most of the tags have their corresponding closing tags. For
example, <html> has its closing tag </html> and <body> tag has its closing
tag </body> tag etc.
1 <!DOCTYPE...>
2 <html>
This tag encloses the complete HTML document and mainly comprises of
document header which is represented by <head>...</head> and
document body which is represented by <body>...</body> tags.
3 <head>
This tag represents the document's header which can keep other HTML
tags like <title>, <link> etc.
4 <title>
The <title> tag is used inside the <head> tag to mention the document
title.
5 <body>
This tag represents the document's body which keeps other HTML tags
218
Programming Languages and Computer Graphics Unit - 3
6 <h1>
7 <p>
To learn HTML, we will need to study various tags and understand how they
behave, while formatting a textual document. Learning HTML is simple as users
have to learn the usage of different tags in order to format the text or images to
make a beautiful webpage.
World Wide Web Consortium (W3C) recommends to use lowercase tags starting
from HTML 4.
<html>
<head>
</head>
<body>
</body>
</html>
219
Programming Languages and Computer Graphics Unit - 3
The <!DOCTYPE> declaration tag is used by the web browser to understand the
version of the HTML used in the document. Current version of HTML is 5 and it
makes use of the following declaration −
<!DOCTYPE html>
There are many other declaration types which can be used in HTML document
depending on what version of HTML is being used.
XML is designed to describe data but is not concerned with the data’s
visualization. The tags created in XML are self explanatory and the user is free to
define their own tags — hence the “extensible.”
XML has been the main source of motivation for development of service oriented
architecture (SOA) platforms such as web services that are not tied to any
particular language and collaborate effectively in heterogeneous environments.
RSS, Atom, SOAP and XHTML are some of the standards influenced by XML.
220
Programming Languages and Computer Graphics Unit - 3
JavaScript (JS)
HTML pages are fine for displaying static content, e.g. a simple image or text.
However, most pages nowadays are rarely static. Many of today’s pages have
menus, forms, slideshows and even images that provide user interaction.
Javascript is the language employed by web developers to provide such
interaction. Since JavaScript works with HTML pages, a developer needs to know
HTML to harness this scripting language’s full potential. While there are other
languages that can be used for scripting on the Web, in practice it is essentially all
Javascript.
There are two ways to use JavaScript in an HTML file. The first one involves
embedding all the JavaScript code in the HTML code, while the second method
makes use of a separate JavaScript file that’s called from within a Script element,
i.e., enclosed by Script tags. JavaScript files are identified by the .js extension.
Although JavaScript is mostly used to interact with HTML objects, it can also be
made to interact with other non-HTML objects such as browser plugins, CSS
(Cascading Style Sheets) properties, the current date, or the browser itself. To
write JavaScript code, all We need is a basic text editor like Notepad in Windows,
Gimp in Linux, or BBEdit. Some text editors, like BBEdit feature syntax highlighting
for JavaScript. This will allow We easily identify elements of JavaScript code. The
latest versions of Internet Explorer, Firefox, and Opera all support JavaScript.
Java
bytecode) runs on most operating systems (OS), including Windows, Linux and
Mac OS. Java derives much of its syntax from the C and C++ programming
languages.
Java applets run in a Web browser with Java Virtual Machine (JVM), which
translates Java bytecode into native processor instructions and allows indirect OS
or platform program execution. JVM provides the majority of components needed
to run bytecode, which is usually smaller than executable programs written
through other programming languages. Bytecode cannot run if a system lacks
required JVM.
Java program development requires a Java software development kit (SDK) that
typically includes a compiler, interpreter, documentation generator and other
tools used to produce a complete application.
Java programs are found in desktops, servers, mobile devices, smart cards and
Blu-ray Discs (BD).
222
Programming Languages and Computer Graphics Unit - 3
Java is −
223
Programming Languages and Computer Graphics Unit - 3
While DHTML enhances the website user’s experience, the technology may also
be frustrating for users when it is used incorrectly. For example, a website menu
with flashy DHTML animations can easily confuse user navigation. Another
DHTML issue occurs when Web developers attempt to create cross-browser
DHTML, which is very difficult.
224
Programming Languages and Computer Graphics Unit - 3
HTML 4.0
CSS
JavaScript
DOM.
HTML 4.0
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers
for controlling the style and layout of the HTML elements on the web pages.
JavaScript
225
Programming Languages and Computer Graphics Unit - 3
DOM
Uses of DHTML
o It is used for designing the animated and interactive web pages that are
developed in real-time.
o DHTML helps users by animating the text and images in their documents.
o It also allows the page authors for including the drop-down menus or
rollover buttons.
o It is also used to add the ticker on various websites, which needs to refresh
their content automatically.
Features of DHTML
o Its simplest and main feature is that we can create the web page
dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size,
color, and content of a web page.
o It provides the facility for using the events, methods, and properties. And,
also provides the feature of code reusability.
226
Programming Languages and Computer Graphics Unit - 3
o Using DHTML, users can easily create dynamic fonts for their web sites or
web pages.
o With the help of DHTML, users can easily change the tags and their
properties.
o The web page functionality is enhanced because the DHTML uses low-
bandwidth effect.
2. It is used for developing and 2. It is used for creating and designing the
creating web pages. animated and interactive web sites or
pages.
3. This markup language creates static 3. This concept creates dynamic web
web pages. pages.
4. It does not contain any server-side 4. It may contain the code of server-side
scripting code. scripting.
5. The files of HTML are stored with 5. The files of DHTML are stored with the
the .html or .htm extension in a .dhtm extension in a system.
227
Programming Languages and Computer Graphics Unit - 3
system.
DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page
as dynamic. We can easily type the JavaScript code within the <head> or <body>
tag of a HTML page. If we want to add the external source file of JavaScript, we
can easily add using the <src> attribute.
Following are the various examples, which describes how to use the JavaScript
technology with the DHTML:
Scripting Language
In that sense, they are modernizations of a system that previously used compilers
to interpret inputs.
228
Programming Languages and Computer Graphics Unit - 3
Example: Python
Interpreted Languages
The interpreter is responsible to interpret the source code for program execution.
We could say that in a scripting language with an interpreter, the code is the
language itself, and it gets interpreted relatively on-the-fly. Other kinds of
systems like just-in-time compiling can also apply.
Hybrids
code syntax is used and implemented. If We, for example, have a virtual machine
friendly language like ByteCode interpreting Java script for a compiler, that would
be an interpreted language.
There are various benefits and disadvantages associated with the use of
interpreted languages over compiler languages. The uniqueness of domain-
specific scripting languages and their use in various runtime environments has
been discussed. There's also the idea that interpreted language systems can help
when distributed systems have different machine languages in play that make it
difficult for compiled languages to bridge these cross-platform gaps.
On the other hand, some experts talk about latency with interpreted programs,
just because the code has to run through an interpreter instead of being
traditionally compiled. Experts have to assess these sorts of trade-offs as they
consider whether using a scripting language makes sense in a given project
environment.
Java Servlet
Java Servlets are server-side Java program modules that process and answer client
requests and implement the servlet interface. It helps in enhancing Web server
functionality with minimal overhead, maintenance and support.
A servlet acts as an intermediary between the client and the server. As servlet
modules run on the server, they can receive and respond to requests made by the
client. Request and response objects of the servlet offer a convenient way to
handle HTTP requests and send text data back to the client.
Since a servlet is integrated with the Java language, it also possesses all the Java
features such as high portability, platform independence, security and Java
database connectivity.
230
Programming Languages and Computer Graphics Unit - 3
When an HTML form is submitted, the servlet processes and stores the data.
When a client supplies a database query, the results are provided to the
client by the servlet.
In most cases, the server uses the common gateway interface (CGI).
A servlet runs in the same process, eliminating the need to create a new
process for every request.
The CGI program must be reloaded for each CGI request. A servlet, however,
does not require reloading and remains in the memory between requests.
The servlet life cycle is the Java servlet processing event sequence that occurs
from servlet instance creation to destruction. The servlet life cycle is controlled by
the container that deploys the servlet.
Instantiation
Initialization
Destruction
231
Programming Languages and Computer Graphics Unit - 3
When a servlet request is mapped, the servlet container checks for the existence
of a servlet class instance. If an instance does not exist, the Web container loads
the servlet class, creates an instance of this class and initializes this instance by
calling the init() method.
Applications of Servlet
Read the explicit data sent by the clients (browsers). This includes an
HTML form on a Web page or it could also come from an applet or a
custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression schemes the browser
understands, and so forth.
Process the data and generate the results. This process may require
talking to a database, executing an RMI or CORBA call, invoking a Web
service, or computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or
XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being
returned (e.g., HTML), setting cookies and caching parameters, and
other such tasks.
Java Applet
232
Programming Languages and Computer Graphics Unit - 3
A Java applet is a small dynamic Java program that can be transferred via the
Internet and run by a Java-compatible Web browser. The main difference
between Java-based applications and applets is that applets are typically executed
in an AppletViewer or Java-compatible Web browser. All applets import
the java.awt package.
Any browser with Java Virtual Machine (JVM) can execute bytecode, which is the
output of a Java compiler and can be run only in a JVM. Bytecode is Java’s
solution for security and portability.
It is easy to convert a graphical Java application (that is, an application that uses
the AWT and that We can start with the Java program launcher) into an applet
that We can embed in a web page.
Make an HTML page with the appropriate tag to load the applet code.
Supply a subclass of the JApplet class. Make this class public. Otherwise,
the applet cannot be loaded.
Eliminate the main method in the application. Do not construct a frame
window for the application. Our application will be displayed inside the
browser.
Move any initialization code from the frame window constructor to the
init method of the applet. We don't need to explicitly construct the
applet object. The browser instantiates it for We and calls the init
method.
233
Programming Languages and Computer Graphics Unit - 3
Remove the call to setSize; for applets, sizing is done with the width and
height parameters in the HTML file.
Remove the call to setDefaultCloseOperation. An applet cannot be
closed; it terminates when the browser exits.
If the application calls setTitle, eliminate the call to the method. Applets
cannot have title bars. (You can, of course, title the web page itself,
using the HTML title tag.)
Don't call setVisible(true). The applet is displayed automatically.
Computer Graphics
Computer Graphics is the creation of pictures with the help of a computer. The
end product of the computer graphics is a picture it may be a business graph,
drawing, and engineering.
Today computer graphics is entirely different from the earlier one. It is not
possible. It is an interactive user can control the structure of an object of various
input devices.
Suppose a shoe manufacturing company want to show the sale of shoes for five
years. For this vast amount of information is to store. So a lot of time and memory
will be needed. This method will be tough to understand by a common man. In
this situation graphics is a better alternative. Graphics tools are charts and graphs.
Using graphs, data can be represented in pictorial form. A picture can be
understood easily just with a single look.
The display device is an output device used to represent the information in the
form of images (visual form). Display systems are mostly called a video
monitor or Video display unit (VDU).
Display devices are designed to model, display, view, or display information. The
purpose of display technology is to simplify information sharing.
1. Cathode-Ray Tube(CRT)
235
Programming Languages and Computer Graphics Unit - 3
6. Plasma Display
7. 3D Display
1. Cathode-ray Tube (CRT): Here, CRT stands for Cathode ray tube. It is a
technology which is used in traditional computer monitor and television.
Cathode ray tube is a particular type of vacuum tube that displays images when
an electron beam collides on the radiant surface.
Component of CRT:
The electron gun is a source of electrons focused on a narrow beam facing the
CRT.
236
Programming Languages and Computer Graphics Unit - 3
Horizontal & Vertical Deflection Plates: These plates are used to guide the
path of the electron the beam. The plates produce an electromagnetic field
that bends the electron beam through the area as it travels.
A raster scan is based on pixel intensity control display as a rectangular box on the
screen called a raster.
Frame buffer is also known as Raster or Bitmap. Raster scan provides the refresh
rate of 60 to 80 frames per second.
1. Horizontal Retracing
2. Vertical Retracing
When the beam starts from the top left corner and reaches bottom right, and
again return to the top left, it is called the vertical retrace.
It will call back from top to bottom more horizontally as a horizontal reversal.
237
Programming Languages and Computer Graphics Unit - 3
Advantages:
1. Real image
Disadvantages:
1. Less resolution
3. More costly
It uses an electron beam like a pencil to make a line image on the screen. The
image is constructed from a sequence of straight-line segments. On the screen,
each line segment is drawn by the beam to pass from one point on the screen to
the other, where its x & y coordinates define each point.
238
Programming Languages and Computer Graphics Unit - 3
After compilation of picture drawing, the system cycle back to the first line and
create all the lines of picture 30 to 60 times per second.
Fig: A Random Scan display draws the lines of an object in a specific order
Advantages:
1. High Resolution
Disadvantages:
The basic idea behind the color CRT monitor is to combine three basic colors- Red,
Green, and Blue. By using these three colors, we can produce
239
Programming Languages and Computer Graphics Unit - 3
A powerful electron beam penetrates the CRT, it passes through the red layer and
excites the green layer within.
A beam with the medium speed of electrons, a mixture of red and green light is
emitted to display two more colors- orange and yellow.
Advantages:
1. Better Resolution
2. Half cost
3. Inexpensive
Disadvantages:
2. Time Consuming
240
Programming Languages and Computer Graphics Unit - 3
Structure:
3. It also has a shadow grid just behind the phosphorus coated screen with
tiny holes in a triangular shape.
Working: A Shadow Mask is a metal plate with tiny holes present inside a color
monitor.
A Shadow Mask directs the beam by consuming the electrons so that the beam
hits only the desired point and displays a resulting picture.
It has three different guns. These guns direct their beams to shadow mask, which
allows them to pass. It is a task of a shadow mask to direct the beam on its
particular dot on the screen and produce a picture on the screen.
A Shadow Mask can display a wider range of pictures than beam penetration.
241
Programming Languages and Computer Graphics Unit - 3
Advantages:
Disadvantages:
Poor Resolution.
3.Liquid crystal display (LCD): The LCD depends upon the light modulating
properties of liquid crystals.
LCD is used in watches and portable computers. LCD requires an AC power supply
instead of DC, so it is difficult to use it in circuits.
It generally works on flat panel display technology. LCD consumes less power than
LED. The LCD screen uses the liquid crystal to turn pixels on or off.
Liquid Crystals are a mixture of solid and liquid. When the current flows inside it,
its position changes into the desired color.
242
Programming Languages and Computer Graphics Unit - 3
Advantages:
2. Energy efficient
Disadvantages:
Lower Contrast
More Expensive
4.Light Emitting Diode (LED): LED is a device which emits when current passes
through it. It is a semiconductor device.
The size of the LED is small, so we can easily make any display unit by arranging a
large number of LEDs.
LED consumes more power compared to LCD. LED is used on TV, smartphones,
motor vehicles, traffic light, etc.
Advantages:
Disadvantages:
5.Direct View Storage Tube (DVST): It is used to store the picture information as a
charge distribution behind the phosphor-coated screen.
Advantages:
2. No Refreshing Required
3. High-Resolution
4. Less Cost
Disadvantages:
244
Programming Languages and Computer Graphics Unit - 3
6.Plasma Display: It is a type of flat panel display which uses tiny plasma cells. It is
also known as the Gas-Discharge display.
1.Anode: It is used to deliver a positive voltage. It also has the line wires.
2.Cathode: It is used to provide negative voltage to gas cells. It also has fine wires.
3.Gas Plates: These plates work as capacitors. When we pass the voltage, the cell
lights regularly.
4.Fluorescent cells: It contains small pockets of gas liquids when the voltage is
passed to this neon gas. It emits light.
Advantages:
1. Wall Mounted
2. Slim
3. Wider angle
245
Programming Languages and Computer Graphics Unit - 3
Disadvantages:
Large Size
Advantages:
High Definition
Motion Communicates
Disadvantage:
Expensive
Binocular Fusion
Raster Scan
In a raster scan system, the electron beam is swept across the screen, one row at
a time from top to bottom. As the electron beam moves across each row, the
beam intensity is turned on and off to create a pattern of illuminated spots.
246
Programming Languages and Computer Graphics Unit - 3
Frame Buffer is also known as Raster or bit map. In Frame Buffer the positions are
called picture elements or pixels. Beam refreshing is of two types. First is
horizontal retracing and second is vertical retracing. When the beam starts from
the top left corner and reaches the bottom right scale, it will again return to the
top left side called at vertical retrace. Then it will again more horizontally from
top to bottom call as horizontal retracing shown in fig:
1. Interlaced Scanning
2. Non-Interlaced Scanning
In Interlaced scanning, each horizontal line of the screen is traced from top to
bottom. Due to which fading of display of object may occur. This problem can be
solved by Non-Interlaced scanning. In this first of all odd numbered lines are
traced or visited by an electron beam, then in the next circle, even number of
lines are located.
For non-interlaced display refresh rate of 30 frames per second used. But it gives
flickers. For interlaced display refresh rate of 60 frames per second is used.
Picture definition is stored in memory area called the Refresh Buffer or Frame
Buffer. This memory area holds the set of intensity values for all the screen
points. Stored intensity values are then retrieved from the refresh buffer and
“painted” on the screen one row scanlinescanline at a time as shown in the
following illustration.
247
Programming Languages and Computer Graphics Unit - 3
Advantages:
1. Realistic image
Disadvantages:
1. Low Resolution
2. Expensive
In this technique, the electron beam is directed only to the part of the screen
where the picture is to be drawn rather than scanning from left to right and top to
bottom as in raster scan. It is also called vector display, stroke-writing
display, or calligraphic display.
Random Scan System uses an electron beam which operates like a pencil to
create a line image on the CRT screen. The picture is constructed out of a
sequence of straight-line segments. Each line segment is drawn on the screen by
directing the beam to move from one point on the screen to the next, where its x
& y coordinates define each point. After drawing the picture. The system cycles
248
Programming Languages and Computer Graphics Unit - 3
back to the first line and design all the lines of the image 30 to 60 time each
second. The process is shown in fig:
Random-scan displays are designed to draw all the component lines of a picture
30 to 60 times each second.
Advantages:
1. A CRT has the electron beam directed only to the parts of the screen where
an image is to be drawn.
3. High Resolution
Disadvantages:
250
Programming Languages and Computer Graphics Unit - 3
applications
Input Devices
The Input Devices are the hardware that is used to transfer transfers input to the
computer. The data can be in the form of text, graphics, sound, and text. Output
device display data from the memory of the computer. Output can be text,
numeric data, line, polygon, and other objects.
1. Keyboard
2. Mouse
251
Programming Languages and Computer Graphics Unit - 3
3. Trackball
4. Spaceball
5. Joystick
6. Light Pen
7. Digitizer
8. Touch Panels
9. Voice Recognition
Keyboard:
The most commonly used input device is a keyboard. The data is entered by
pressing the set of keys. All keys are labeled. A keyboard with 101 keys is called a
QWERTY keyboard.
The keyboard has alphabetic as well as numeric keys. Some special keys are also
available.
1. Numeric Keys: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Function of Keyboard:
252
Programming Languages and Computer Graphics Unit - 3
3. Special purpose keyboards are available having buttons, dials, and switches.
Dials are used to enter scalar values. Dials also enter real numbers. Buttons
and switches are used to enter predefined function values.
Advantage:
2. Function keys are a fast and effective method of using commands, with
fewer errors.
Disadvantage:
Mouse:
A Mouse is a pointing device and used to position the pointer on the screen. It is a
small palm size box. There are two or three depression switches on the top. The
movement of the mouse along the x-axis helps in the horizontal movement of the
cursor and the movement along the y-axis helps in the vertical movement of the
cursor on the screen. The mouse cannot be used to enter text. Therefore, they
are used in conjunction with a keyboard.
253
Programming Languages and Computer Graphics Unit - 3
Advantage:
1. Easy to use
Region filling is the process of filling image or region. Filling can be of boundary or
interior region as shown in fig. Boundary Fill algorithms are used to fill the
boundary and flood-fill algorithm are used to fill the interior.
254
Programming Languages and Computer Graphics Unit - 3
This algorithm lines interior points of a polygon on the scan line and these points
are done on or off according to requirement. The polygon is filled with various
colors by coloring various pixels.
In above figure polygon and a line cutting polygon in shown. First of all, scanning
is done. Scanning is done using raster scanning concept on display device. The
beam starts scanning from the top left corner of the screen and goes toward the
bottom right corner as the endpoint. The algorithms find points of intersection of
the line with polygon while moving from left to right and top to bottom. The
various points of intersection are stored in the frame buffer. The intensities of
such points is keep high. Concept of coherence property is used. According to this
property if a pixel is inside the polygon, then its next pixel will be inside the
polygon.
1. Staircase or Jagged: Staircase like appearance is seen while the scan was
converting line or circle.
255
Programming Languages and Computer Graphics Unit - 3
In this method, a point or seed which is inside region is selected. This point is
called a seed point. Then four connected approaches or eight connected
approaches is used to fill with specified color.
The flood fill algorithm has many characters similar to boundary fill. But this
method is more suitable for filling multiple colors boundary. When boundary is of
many colors and interior is to be filled with one color we use this algorithm.
In fill algorithm, we start from a specified interior point (x, y) and reassign all pixel
values are currently set to a given interior color with the desired color. Using
256
Programming Languages and Computer Graphics Unit - 3
Disadvantage:
Algorithm:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
257
Programming Languages and Computer Graphics Unit - 3
#include<dos.h>
void flood(int,int,int,int);
void main()
intgd=DETECT,gm;
initgraph(&gd,&gm,"C:/TURBOC3/bgi");
rectangle(50,50,250,250);
flood(55,55,10,0);
getch();
if(getpixel(x,y)==defaultColor)
delay(1);
putpixel(x,y,fillColor);
flood(x+1,y,fillColor,defaultColor);
flood(x-1,y,fillColor,defaultColor);
flood(x,y+1,fillColor,defaultColor);
flood(x,y-1,fillColor,defaultColor);
258
Programming Languages and Computer Graphics Unit - 3
Output:
This algorithm uses the recursive method. First of all, a starting pixel called as the
seed is considered. The algorithm checks boundary pixel or adjacent pixels are
colored or not. If the adjacent pixel is already filled or colored then leave it,
otherwise fill it. The filling is done using four connected or eight connected
approaches.
259
Programming Languages and Computer Graphics Unit - 3
1. Four connected approaches: In this approach, left, right, above, below pixels
are tested.
2. Eight connected approaches: In this approach, left, right, above, below and
four diagonals are selected.
Boundary can be checked by seeing pixels from left and right first. Then pixels are
checked by seeing pixels from top to bottom. The algorithm takes time and
memory because some recursive calls are needed.
It may not fill regions sometimes correctly when some interior pixel is already
filled with color. The algorithm will check this boundary pixel for filling and will
found already filled so recursive process will terminate. This may vary because of
another interior pixel unfilled.
Algorithm:
int c;
if (c!=color) (c!=color1)
260
Programming Languages and Computer Graphics Unit - 3
It is based on the following function for testing the spatial relationship between
the arbitrary point (x, y) and a circle of radius r centered at the origin:
Now, consider the coordinates of the point halfway between pixel T and pixel S
If Pi is+ve ⟹midpoint is outside the circle (or on the circle)and we choose pixel S.
We have yi+1=yi
We have yi+1=yi-1
262
Programming Languages and Computer Graphics Unit - 3
We can put ≅1
∴r is an integer
So, P1=1-r
Algorithm:
Step3: End
#include <graphics.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
class bresen
263
Programming Languages and Computer Graphics Unit - 3
float x, y,a, b, r, p;
public:
};
void main ()
bresen b;
b.get ();
b.cal ();
getch ();
cin>>a>>b;
cout<<"ENTER r";
cin>>r;
264
Programming Languages and Computer Graphics Unit - 3
getch ();
x=0;
y=r;
265
Programming Languages and Computer Graphics Unit - 3
p=5/4)-r;
while (x<=y)
If (p<0)
p+= (4*x)+6;
else
p+=(2*(x-y))+5;
y--;
x++;
266
Programming Languages and Computer Graphics Unit - 3
Output:
This algorithm is used for scan converting a line. It was developed by Bresenham.
It is an efficient method because it involves only integer addition, subtractions,
and multiplication operations. These operations can be performed very rapidly so
lines can be generated quickly.
In this method, next pixel selected is that one who has the least distance from
true line.
267
Programming Languages and Computer Graphics Unit - 3
The line is best approximated by those pixels that fall the least distance from the
path between P1',P2'.
To chooses the next one between the bottom pixel S and top pixel T.
If S is chosen
We have xi+1=xi+1 and yi+1=yi
If T is chosen
We have xi+1=xi+1 and yi+1=yi+1
268
Programming Languages and Computer Graphics Unit - 3
This difference is
s-t = (y-yi)-[(yi+1)-y]
= 2y - 2yi -1
di=△x (2 (xi+1)+2b-2yi-1)
=2△xyi-2△y-1△x.2b-2yi△x-△x
di=2△y.xi-2△x.yi+c
We can write the decision variable di+1 for the next slip on
di+1=2△y.xi+1-2△x.yi+1+c
di+1-di=2△y.(xi+1-xi)- 2△x(yi+1-yi)
Special Cases
269
Programming Languages and Computer Graphics Unit - 3
Finally, we calculate d1
d1=△x[2m(x1+1)+2b-2y1-1]
d1=△x[2(mx1+b-y1)+2m-1]
Advantage:
Disadvantage:
1. This algorithm is meant for basic line drawing only Initializing is not a part of
Bresenham's line algorithm. So to draw smooth lines, We should want to look into
a different algorithm.
270
Programming Languages and Computer Graphics Unit - 3
Step5: Consider (x, y) as starting point and xendas maximum possible value of x.
If dx < 0
Then x = x2
y = y2
xend=x1
If dx > 0
Then x = x1
y = y1
xend=x2
Step9: Increment x = x + 1
271
Programming Languages and Computer Graphics Unit - 3
Step11: Go to step 7
Example: Starting and Ending position of the line are (1, 1) and (8, 5). Find
intermediate points.
Solution: x1=1
y1=1
x2=8
y2=5
dx= x2-x1=8-1=7
dy=y2-y1=5-1=4
I1=2* ∆y=2*4=8
I2=2*(∆y-∆x)=2*(4-7)=-6
d = I1-∆x=8-7=1
x y d=d+I1 or I2
1 1 d+I2=1+(-6)=-5
2 2 d+I1=-5+8=3
3 2 d+I2=3+(-6)=-3
4 3 d+I1=-3+8=5
5 3 d+I2=5+(-6)=-1
6 4 d+I1=-1+8=7
272
Programming Languages and Computer Graphics Unit - 3
7 4 d+I2=7+(-6)=1
8 5
#include<stdio.h>
#include<graphics.h>
dx=x1-x0;
dy=y1-y0;
x=x0;
y=y0;
p=2*dy-dx;
while(x<x1)
273
Programming Languages and Computer Graphics Unit - 3
if(p>=0)
putpixel(x,y,7);
y=y+1;
p=p+2*dy-2*dx;
else
putpixel(x,y,7);
p=p+2*dy;}
x=x+1;
int main()
274
Programming Languages and Computer Graphics Unit - 3
return 0;
Output:
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:
275
Programming Languages and Computer Graphics Unit - 3
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- )
276
Programming Languages and Computer Graphics Unit - 3
pi+1=f(xi+1+1,yi+1- )
The initial value for the recursive expression can be obtained by the evaluating
the original definition of pi with (0, b):
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)
277
Programming Languages and Computer Graphics Unit - 3
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)
The initial value for the recursive expression is computed using the original
definition of qj. And the coordinates of (x k yk) of the last pixel choosen for the part
1 of the curve:
Algorithm:
while (fx<="" 1="" {="" set="" pixel="" (x,="" y)="" x++;="" fx="fx" +="" 2b 2;
if (p<0)
278
Programming Languages and Computer Graphics Unit - 3
p = p + fx +b2;
else
y--;
fy=fy-2a2
p = p + fx +b2-fy;
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;
279
Programming Languages and Computer Graphics Unit - 3
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
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.
280
Programming Languages and Computer Graphics Unit - 3
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
281
Programming Languages and Computer Graphics Unit - 3
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:
x1=x+Tx
y1=y+Ty
Let P is a point with coordinates (x, y). It will be translated as (x1 y1).
282
Programming Languages and Computer Graphics Unit - 3
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. S x in x direction Sy in y-direction. If the
283
Programming Languages and Computer Graphics Unit - 3
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 S x = Sy =2. If Sxand Sy are
not equal then scaling will occur but it will elongate or distort the picture.
If scaling factors are less than one, then the size of the object will be reduced. If
scaling factors are higher than one, then the size of the object will be enlarged.
If Sxand Syare equal it is also called as Uniform Scaling. If not equal then called as
Differential Scaling. If scaling factors with values less than one will move the
object closer to coordinate origin, while a value higher than one will move
coordinate position farther from origin.
Enlargement: If T1= ,If (x1 y1)is original position and T1is translation vector
then (x2 y2) are coordinated after scaling
284
Programming Languages and Computer Graphics Unit - 3
285
Programming Languages and Computer Graphics Unit - 3
Example: Prove that 2D Scaling transformations are commutative i.e, S 1 S2=S2 S1.
286
Programming Languages and Computer Graphics Unit - 3
Rotation:
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.
287
Programming Languages and Computer Graphics Unit - 3
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.
Ellipse: Its rotation can be obtained by rotating major and minor axis of an ellipse
by the desired angle.
288
Programming Languages and Computer Graphics Unit - 3
289
Programming Languages and Computer Graphics Unit - 3
290
Programming Languages and Computer Graphics Unit - 3
291
Programming Languages and Computer Graphics Unit - 3
Example1: Prove that 2D rotations about the origin are commutative i.e.
R1 R2=R2 R1.
292
Programming Languages and Computer Graphics Unit - 3
Example2: Rotate a line CD whose endpoints are (3, 4) and (12, 15) about origin
through a 45° anticlockwise direction.
293
Programming Languages and Computer Graphics Unit - 3
294
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.
295
Programming Languages and Computer Graphics Unit - 3
Reflection:
296
Programming Languages and Computer Graphics Unit - 3
Types of Reflection:
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.
297
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.
298
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.
299
Programming Languages and Computer Graphics Unit - 3
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°.
A (3 4)
B (6 4)
C (4 8)
Solution:
300
Programming Languages and Computer Graphics Unit - 3
301
Programming Languages and Computer Graphics Unit - 3
#include <iostream.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#include <stdlib.h>
#define pi 3.14
class arc
float x[10],y[10],theta,ref[10][10],ang;
float p[10][10],p1[10][10],x1[10],y1[10],xm,ym;
int i,k,j,n;
public:
void get();
302
Programming Languages and Computer Graphics Unit - 3
void plot1();
};
void arc::get ()
cin >> n;
303
Programming Languages and Computer Graphics Unit - 3
p [2] [i] = 1;
p1 [i] [j]=0;
304
Programming Languages and Computer Graphics Unit - 3
x1 [i]=p1[0] [i];
int gd = DETECT,gm;
/* an error occurred */
if (errorcode ! = grOK)
getch ();
305
Programming Languages and Computer Graphics Unit - 3
xm=getmaxx ()/2;
ym=getmaxy ()/2;
getch();
306
Programming Languages and Computer Graphics Unit - 3
getch();
void main ()
class arc a;
clrscr();
a.map();
a.graph();
a.get();
a.cal();
a.plot();
a.plot1();
getch();
Output:
307
Programming Languages and Computer Graphics Unit - 3
Shearing:
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:
308
Programming Languages and Computer Graphics Unit - 3
309
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.
310
Programming Languages and Computer Graphics Unit - 3
311
Programming Languages and Computer Graphics Unit - 3
Composite Transformation:
312
Programming Languages and Computer Graphics Unit - 3
1. Translation
2. Rotation
3. Reverse Translation
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)
313
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.
314
Programming Languages and Computer Graphics Unit - 3
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.
315
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.
Fig shows the window to viewport mapping. A point at position (xw, yw) in
window mapped into position (xv, yv) in the associated viewport.
316
Programming Languages and Computer Graphics Unit - 3
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
317
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:
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).
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.
318
Programming Languages and Computer Graphics Unit - 3
319
Programming Languages and Computer Graphics Unit - 3
Viewing Transformation= T * S * T1
We can display picture at device or display system according to our need and
choice.
Note:
320
Programming Languages and Computer Graphics Unit - 3
Line Clipping:
It is performed by using the line clipping algorithm. The line clipping algorithms
are:
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.
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.
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.
322
Programming Languages and Computer Graphics Unit - 3
1. It calculates end-points very quickly and rejects and accepts lines quickly.
323
Programming Languages and Computer Graphics Unit - 3
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
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:
324
Programming Languages and Computer Graphics Unit - 3
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
325
Programming Languages and Computer Graphics Unit - 3
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.
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 y max=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.
326
Programming Languages and Computer Graphics Unit - 3
Polygon:
Example of Polygon:
1. Triangle
2. Rectangle
3. Hexagon
4. Pentagon
327
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.
328
Programming Languages and Computer Graphics Unit - 3
329
Programming Languages and Computer Graphics Unit - 3
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.
330
Programming Languages and Computer Graphics Unit - 3
331
Programming Languages and Computer Graphics Unit - 3
9. 3D Object Representations
Methods:
332
Programming Languages and Computer Graphics Unit - 3
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
333
Programming Languages and Computer Graphics Unit - 3
Curved Surfaces
334
Programming Languages and Computer Graphics Unit - 3
3. Spline Representations
Quadric Surfaces
335
Programming Languages and Computer Graphics Unit - 3
angular extent to which the quadric is swept about z axis. Sweeping a quadric by
less than 360 degrees leaves an open surface.
Quadrics
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.
RtFloat radius;
336
Programming Languages and Computer Graphics Unit - 3
RtFloat thetamax;
Note that if zmin > -radius or zmax < radius, the bottom or top of the sphere is
open, and that if thetamax is not equal to 360 degrees, the sides are also open.
RIB BINDING
EXAMPLE
RtFloat height;
RtFloat radius;
RtFloat thetamax;
337
Programming Languages and Computer Graphics Unit - 3
Note that the bottom of the cone is open, and if thetamax is not equal to 360
degrees, the sides are open.
RIB BINDING
EXAMPLE
RtColor four_colors[4];
RtFloat radius;
RtFloat thetamax;
338
Programming Languages and Computer Graphics Unit - 3
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
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 −
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.
339
Programming Languages and Computer Graphics Unit - 3
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.
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.
340
Programming Languages and Computer Graphics Unit - 3
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.
Where,
341
Programming Languages and Computer Graphics Unit - 3
The sum of the B-spline basis functions for any parameter value is 1.
Each basis function has precisely one maximum value, except for k=1.
342
Programming Languages and Computer Graphics Unit - 3
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 line within the convex hull of its defining polygon.
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.
343
Programming Languages and Computer Graphics Unit - 3
or
and the 4-point Bezier curve needed in the u-direction has the form:
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:
To obtain the equation of one of the edge-curves, e.g. when u=0, we must
substitute in the matrix equation:
344
Programming Languages and Computer Graphics Unit - 3
2v(1-v)
v*v
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 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
345
Programming Languages and Computer Graphics Unit - 3
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
In the x-direction, x(i) are the elements of the k-knot vector and
= 0 otherwise
and
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
346
Programming Languages and Computer Graphics Unit - 3
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. 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.
347
Programming Languages and Computer Graphics Unit - 3
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.
3. Specular Reflection :
348
Programming Languages and Computer Graphics Unit - 3
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 I spec:
349
Programming Languages and Computer Graphics Unit - 3
Gouraud shading
3. Linear interpolate the vertex intensities over the surface of the polygon.
350
Programming Languages and Computer Graphics Unit - 3
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 I 1 and
I2 using only the vertical displacement of the scan line.
351
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
352
Programming Languages and Computer Graphics Unit - 3
Then we can obtain the intensity along this edge for the next scan line, Y-1 as
353
Programming Languages and Computer Graphics Unit - 3
Viewing-Pipeline
Viewing-Coordinates
Similar to photography there are certain degrees of freedom when specifying the
camera:
Based on the camera position the usual way to define the viewing-coordinate
system is:
3. Choose a direction „upwards“. From this, the x-axis and y-axis can be
calculated: the image-plane is orthogonal to the viewing direction. The parallel
projection of the „view-up vector“ onto this image plane defines the y-axis of
the viewing coordinates.
5. The distance of the image-plane from the eye-point defines the viewing angle,
which is the size of the scene to be displayed.
355
Programming Languages and Computer Graphics Unit - 3
Projection
356
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.
357
Programming Languages and Computer Graphics Unit - 3
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)
Three Points: There are three vanishing points. One is x second in y and third in
two directions.
3. Projectors: It is also called a projection vector. These are rays start from the
object scene and are used to create an image of the object on viewing or
view plane.
358
Programming Languages and Computer Graphics Unit - 3
It introduces several anomalies due to these object shape and appearance gets
affected.
2. Vanishing Point: All lines appear to meet at some point in the view plane.
359
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.
360
Programming Languages and Computer Graphics Unit - 3
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.
361
Programming Languages and Computer Graphics Unit - 3
2. Dimetric: In these two projectors have equal angles. With respect to two
principle axis.
362
Programming Languages and Computer Graphics Unit - 3
4. Cavalier: All lines perpendicular to the projection plane are projected with
no change in length.
363
Programming Languages and Computer Graphics Unit - 3
364
Programming Languages and Computer Graphics Unit - 3
365
Programming Languages and Computer Graphics Unit - 3
Frames of Reference
366
Programming Languages and Computer Graphics Unit - 3
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:
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
367
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
368
Programming Languages and Computer Graphics Unit - 3
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 convenience function that underneath will construct the
corresponding matrix that will do the camera transformation in this step. see,
how this can be done.
We know:
Well, the first step would be to align the origins. So we want to move all 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.
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
369
Programming Languages and Computer Graphics Unit - 3
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
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.
370
Programming Languages and Computer Graphics Unit - 3
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
371
Programming Languages and Computer Graphics Unit - 3
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.
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.
372
Programming Languages and Computer Graphics Unit - 3
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.
373
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.
374
Programming Languages and Computer Graphics Unit - 3
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 bottom-left corner and the positive
directions are up and right. Also the z value will later be normalized to a
range [0,1].
375
DIWAKAR EDUCATION HUB
2020
c. Input data
Answer: (d) -32768 to 32767
d. Output data
Explanation: In a 16-bit C compiler, we have
2 bytes to store the value. Answer: (a) The program must have at least
one function.
o The range for signed integers is -
32768 to 32767. Explanation: Any C program has at least
o The range for unsigned integers is 0 one function, and even the most trivial
to 65535. programs can specify additional functions. A
o The range for unsigned character is function is a piece of code. In other words,
0 to 255. it works like a sub-program.
1. main() 1. main()
2. {printf("javatpoint");
2. {
3. main();}
3. int i = 2;
What will be the output of this program?
4. {
a. Wrong statement
5. int i = 4, j = 5;
b. It will keep on printing javatpoint
6. printf("%d %d", i, j);
c. It will Print javatpoint once
7. }
d. None of the these
8. printf("%d %d", i, j);
Answer: (b) It will keep on printing
javatpoint 9. }
2
Programming Languages and Computer Graphics Unit – 3 MCQs
a. C compiler 6. }
c. Analyzing tool 8. {
d. C interpreter 9. puts(a);
Explanation: Lint is an analyzing tool that If abcdefg is the input, the output will be
analyzes the source code by suspicious
a. abcd
3
Programming Languages and Computer Graphics Unit – 3 MCQs
b. abc a+=4
4
Programming Languages and Computer Graphics Unit – 3 MCQs
Answer: (c) Anywhere, but starting on a 1. If ((a > b) && (a <= c))
new line.
2. a = a + 1;
Explanation: In the C language, the
3. else
constant is defined anywhere, but starting
on a new line. 4. c = c+1;
13) How many times will the following loop a. a = 10, c = 10
execute?
b. a = 11, c = 10
1. for(j = 1; j <= 10; j = j-1)
c. a = 10, c = 11
a. Forever
d. a = 11, c = 11
b. Never
Answer: (b) a = 11, c = 10
c. 0
Explanation: None
d. 1
16) Which one of the following is a loop
Answer: (a) Forever construct that will always be executed
once?
Explanation: None
a. for
14) A pointer is a memory address. Suppose
the pointer variable has p address 1000, b. while
and that p is declared to have type int*, and
an int is 4 bytes long. What address is c. switch
represented by expression p + 2?
d. do while
a. 1002
Answer: (d) do while
b. 1004
Explanation: The body of a loop is often
c. 1006 executed at least once during the do-while
loop. Once the body is performed, the
d. 1008 condition is tested. If the condition is valid,
it will execute the body of a loop;
5
Programming Languages and Computer Graphics Unit – 3 MCQs
otherwise, control is transferred out of the 19) Directives are translated by the
loop.
a. Pre-processor
17) Which of the following best describes
b. Compiler
the ordering of destructor calls for stack-
resident objects in a routine? c. Linker
a. The first object created is the first d. Editor
object destroyed; last created is last
destroyed. Answer: (a) Pre-processor
b. The first object destroyed is the last Explanation: In C language, the pre-
object destroyed; last created is first processor is a macro processor that is
destroyed. dynamically used by the C programmer to
modify the program before it is properly
c. Objects are destroyed in the order compiled (Before construction, pro-
they appear in memory, the object with the processor directives are implemented).
lowest memory address is destroyed first.
20) How many bytes does "int = D" use?
d. The order is undefined and may vary
from compiler to compiler. a. 0
a. 18 a. Easy implementation
6
Programming Languages and Computer Graphics Unit – 3 MCQs
d. strcpy(src, dest); a. 1
7
Programming Languages and Computer Graphics Unit – 3 MCQs
8
Programming Languages and Computer Graphics Unit – 3 MCQs
a. 10, 10 2. char * p;
b. 10, 11 3. p = str;
c. 11, 10 a. p+4
d. 11, 11 b. *p + 4
9
Programming Languages and Computer Graphics Unit – 3 MCQs
10
Programming Languages and Computer Graphics Unit – 3 MCQs
c. 320 Explanation: (1 + 2 * 3 + 4 * 5)
d. 340 = (1 + 2) * (3 + 4) * 5
11
Programming Languages and Computer Graphics Unit – 3 MCQs
8. printf("a=%d b=%d",a,b); 1. x - = y + 1;
9. return 0; a. x=x-y+1
10. } b. x = -x - y - 1
a. a = 20, b = 20 c. x=x+y-1
b. a = 10, b = 20 d. x=x-y-1
d. a = 10, b = 10 Explanation: x - = y + 1
12
Programming Languages and Computer Graphics Unit – 3 MCQs
13
Programming Languages and Computer Graphics Unit – 3 MCQs
14
Programming Languages and Computer Graphics Unit – 3 MCQs
15
Programming Languages and Computer Graphics Unit – 3 MCQs
supports the concept of class and object 65. Java Compiler translates the source
which help us understand the real time code into?
examples better. Vehicle is defined to be a a) Machine code
class. Car, truck, bike are defined to be b) Assembly code
objects of the class, Vehicle. c) Byte code
d) JVM code
62. Which of the following Paradigm is
followed by Object Oriented Language Answer: c
Design? Explanation: Java program is converted into
a) Process-Oriented Model ‘byte code’ which makes it easier to run on
b) Data Controlling access to code. wide variety of environments. Only the run-
c) Both a and b time package JVM has to be implemented
d) None of the mentioned for each platform.
16
Programming Languages and Computer Graphics Unit – 3 MCQs
17
Programming Languages and Computer Graphics Unit – 3 MCQs
b) An unused routine is never loaded the higher priority process finishes, the
c) CPU utilization increases lower priority process is swapped back in
d) All of the mentioned and continues execution. This variant of
swapping is sometimes called?
Answer: b
a) priority swapping
Explanation: None.
b) pull out, push in
75. The idea of overlays is to ____________ c) roll out, roll in
a) data that are needed at any given time d) none of the mentioned
b) enable a process to be larger than the
Answer: c
amount of memory allocated to it
Explanation: None.
c) keep in memory only those instructions
d) all of the mentioned 79. If binding is done at assembly or load
time, then the process _____ be moved to
Answer: d
different locations after being swapped out
Explanation: None.
and in again.
76. The ___________ must design and a) can
program the overlay structure. b) must
a) programmer c) can never
b) system architect d) may
c) system designer
Answer: c
d) none of the mentioned
Explanation: None.
Answer: a
80. Which of the following is not the
Explanation: None.
primary objectives in the analysis model?
77. The ___________ swaps processes in a) describing the customer complaints
and out of the memory. b) establishing a basis for the creation of a
a) Memory manager software design
b) CPU c) defining a set of requirements that can
c) CPU manager be validated once the software is built
d) User d) none of the mentioned
Answer: a Answer: d
Explanation: None. Explanation: All the options are covered in
analysis model.
78. If a higher priority process arrives and
wants service, the memory manager can 81. A description of each function
swap out the lower priority process to presented in the DFD is contained in a
execute the higher priority process. When ________
18
Programming Languages and Computer Graphics Unit – 3 MCQs
Answer: b Answer: b
Explanation: None. Explanation: They can be used to name an
instance of the data object, describe the
82. Which diagram indicates the behaviour
instance, or make reference to another
of the system as a consequence of external
instance in another table.
events?
a) data flow diagram 85. Which of the following is not a data
b) state transition diagram type?
c) control specification diagram a) Symbolic Data
d) workflow diagram b) Alphanumeric Data
c) Numeric Data
Answer: b
d) Alphabetic Data
Explanation: The state transition diagram
represents the various modes of behavior Answer: a
(called states) of the system and the Explanation: Data types are of three basic
manner in which transitions are made from types: Numeric, Alphabetic and
state to state. Alphanumeric. Numeric Data consists of
only numbers.
83. A data model contains
Alphabetic Data consists of only letters and
a) data object
a blank character and alphanumeric data
b) attributes
consists of symbols.
c) relationships
d) all of the mentioned 86. *@Ac# is a type of ________________
data.
Answer: d
a) Symbolic
Explanation: The data model consists of
b) Alphanumeric
three interrelated pieces of information:
c) Alphabetic
the data object,
d) Numeric
the attributes that describe the data object,
and the relationships that connect data Answer: b
objects to one another. Explanation: Alphanumeric data consists of
symbols. Alphanumeric data may be a
84. _________ defines the properties of a
letter, either in uppercase or lowercase or
data object and take on one of the three
some special symbols like #,^,*,(, etc.
different characteristics.
19
Programming Languages and Computer Graphics Unit – 3 MCQs
87. Which of the following is not a valid whereas void is a valueless special data
representation in bits? type.
a) 8-bit
90. BOOLEAN is a type of data type which
b) 24-bit
basically gives a tautology or fallacy.
c) 32-bit
a) True
d) 64-bit
b) False
Answer: b
Answer: a
Explanation: There are no criteria like the
Explanation: A Boolean representation is for
24-bit representation of numbers. Numbers
giving logical values. It returns either true or
can be written in 8-bit, 16-bit, 32-bit and
false. If a result gives a truth value, it is
64-bit as per the IEEE format.
called tautology whereas if it returns a false
88. What are the entities whose values can term, it is referred to as fallacy.
be changed called?
91. What does FORTRAN stands for?
a) Constants
a) Formula Transfer
b) Variables
b) Formula Transformation
c) Modules
c) Formula Translation
d) Tokens
d) Format Transformation
Answer: b
Answer: c
Explanation: Variables are the data entities
Explanation: FORTRAN is a type of
whose values can be changed. Constants
computer language. It was developed for
have a fixed value. Tokens are the words
solving mathematical and scientific
which are easily identified by the compiler.
problems. It is very commonly used among
89. Which of the following is not a basic the scientific community.
data type in C language?
92. The program written by the
a) float
programmer in high level language is called
b) int
_____________
c) real
a) Object Program
d) char
b) Source Program
Answer: c c) Assembled Program
Explanation: There are 5 basic data types in d) Compiled Program
C language: int, char, float, double, void.
Answer: b
Int is for the representation of integers,
Explanation: The program written by the
char is for strings and characters, float and
programmer is called a source program. The
double are for floating point numbers
program generated by the compiler after
20
Programming Languages and Computer Graphics Unit – 3 MCQs
21
Programming Languages and Computer Graphics Unit – 3 MCQs
22
Programming Languages and Computer Graphics Unit – 3 MCQs
104. When OOP concept did first came into use classes, and hence codes can be written
picture? without using OOP concept. Classes may or
a) 1970’s may not contain member functions, so it’s
b) 1980’s not a necessary condition in C++. And, an
c) 1993 object can only be declared in a code if its
d) 1995 class is defined/included via header file.
23
Programming Languages and Computer Graphics Unit – 3 MCQs
109. Which feature allows open recursion, 112. What is default access specifier for
among the following? data members or member functions
a) Use of this pointer declared within a class without any
specifier, in C++?
b) Use of pointers
a) Private
c) Use of pass by value b) Protected
d) Use of parameterized constructor c) Public
d) Depends on compiler
Answer: a
Explanation: Use of this pointer allows an Answer: a
object to call data and methods of itself Explanation: The data members and
whenever needed. This helps us call the member functions are Private by default in
members of an object recursively, and C++ classes, if none of the access specifier is
differentiate the variables of different used. It is actually made to increase the
privacy of data.
scopes.
113. Which is most appropriate comment
110. Which of the following is not type of on following class definition?
class?
a) Abstract Class
b) Final Class class Student
c) Start Class {
d) String Class int a;
public : float a;
Answer: c };
Explanation: Only 9 types of classes are a) Error : same variable name can’t be used
provided in general, namely, abstract, final, twice
mutable, wrapper, anonymous, input- b) Error : Public must come first
output, string, system, network. We may c) Error : data types are different for same
further divide the classes into parent class variable
and subclass if inheritance is used. d) It is correct
111. Class is pass by _______
Answer: a
a) Value
Explanation: Same variable can’t be defined
b) Reference
twice in same scope. Even if the data types
c) Value or Reference, depending on
are different, variable name must be
program
different. There is no rule like Public
d) Copy
member should come first or last.
Answer: b 114. Which is known as a generic class?
Explanation: Classes are pass by reference, a) Abstract class
and the structures are pass by copy. It b) Final class
doesn’t depend on the program. c) Template class
24
Programming Languages and Computer Graphics Unit – 3 MCQs
26
Programming Languages and Computer Graphics Unit – 3 MCQs
c) Using member names directly 130. Which feature of OOP indicates code
d) Using pointer only reusability?
a) Encapsulation
Answer: a
b) Inheritance
Explanation: Using dot operator after the
name of object we can access its members. c) Abstraction
It is not necessary to use the pointers. We d) Polymorphism
can’t use the names directly because it may
Answer: b
be used outside the class.
Explanation: Inheritance indicates the code
128. If a local class is defined in a function, reusability. Encapsulation and abstraction
which of the following is true for an object are meant to hide/group data into one
of that class?
element. Polymorphism is to indicate
a) Object is accessible outside the function
b) Object can be declared inside any other different tasks performed by a single entity.
function
131. If a function can perform more than 1
c) Object can be used to call other class
members type of tasks, where the function name
d) Object can be used/accessed/declared remains same, which feature of OOP is used
locally in that function here?
a) Encapsulation
Answer: d b) Inheritance
Explanation: For an object which belongs to c) Polymorphism
a local class, it is mandatory to declare and
d) Abstraction
use the object within the function because
the class is accessible locally within the class Answer: c
only.
Explanation: For the feature given above,
129. Which among the following is wrong? the OOP feature used is Polymorphism.
a) class student{ }; student s; Example of polymorphism in real life is a
b) abstract class student{ }; student s; kid, who can be a student, a son, a brother
c) abstract class student{ }s[50000000];
depending on where he is.
d) abstract class student{ }; class toppers:
public student{ }; topper t; 132. If different properties and functions of
a real world entity is grouped or embedded
Answer: b
into a single element, what is it called in
Explanation: We can never create instance
of an abstract class. Abstract classes doesn’t OOP language?
have constructors and hence when an a) Inheritance
instance is created there is no facility to b) Polymorphism
initialize its members. Option d is correct c) Abstraction
because topper class is inheriting the base d) Encapsulation
abstract class student, and hence topper
class object can be created easily.
27
Programming Languages and Computer Graphics Unit – 3 MCQs
28
Programming Languages and Computer Graphics Unit – 3 MCQs
29
Programming Languages and Computer Graphics Unit – 3 MCQs
142. Exception handling is a feature of OOP. specifiers. Also, only the public and global
a) True data are available globally or else the
b) False program should have proper permission to
access the private data.
Answer: a
Explanation: Exception handling is a feature 145. Which among the following best
of OOP as it includes classes concept in describes polymorphism?
most of the cases. Also it may come handy a) It is the ability for a message/data to be
while using inheritance. processed in more than one form
b) It is the ability for a message/data to be
143. Which among the following, for a pure
processed in only 1 form
OOP language, is true?
c) It is the ability for many messages/data
a) The language should follow 3 or more
to be processed in one way
features of OOP
d) It is the ability for undefined
b) The language should follow at least 1
message/data to be processed in at least
feature of OOP
one way
c) The language must follow only 3 features
of OOP Answer: a
d) The language must follow all the rules of Explanation: It is actually the ability for a
OOP message / data to be processed in more
than one form. The word polymorphism
Answer: d
indicates many-forms. So if a single entity
Explanation: The language must follow all
takes more than one form, it is known as
the rules of OOP to be called a purely OOP
polymorphism.
language. Even if a single OOP feature is not
followed, then it’s known to be a partially 146. What do you call the languages that
OOP language. support classes but not polymorphism?
a) Class based language
144. Does OOP provide better security than
b) Procedure Oriented language
POP?
c) Object-based language
a) Always true for any programming
d) If classes are supported, polymorphism
language
will always be supported
b) May not be true with respect to all
programming languages Answer: c
c) It depends on type of program Explanation: The languages which support
d) It’s vice-versa is true classes but doesn’t support polymorphism,
are known as object-based languages.
Answer: a
Polymorphism is such an important feature,
Explanation: It is always true as we have the
that is a language doesn’t support this
facility of private and protected access
30
Programming Languages and Computer Graphics Unit – 3 MCQs
31
Programming Languages and Computer Graphics Unit – 3 MCQs
32
Programming Languages and Computer Graphics Unit – 3 MCQs
33
Programming Languages and Computer Graphics Unit – 3 MCQs
167. Consider the following code and select 169. Using encapsulation data security is
the correct option. ___________
a) Not ensured
class student b) Ensured to some extent
{ c) Purely ensured
int marks; d) Very low
public : int* fun()
{ Answer: b
return &marks; Explanation: The encapsulation can only
} ensure data security to some extent. If
}; pointer and addresses are misused, it may
main() violate encapsulation. Use of global
{ variables also makes the program
student s; vulnerable, hence we can’t say that
int *ptr=c.fun(); encapsulation gives pure security.
return 0;
170. Which among the following best
}
defines abstraction?
a) Hiding the implementation
35
Programming Languages and Computer Graphics Unit – 3 MCQs
Answer: b Answer: a
Explanation: Class is logical abstraction Explanation: Abstraction applies to both.
because it provides a logical structure for all Control abstraction involves use of
of its objects. It gives an overview of the subroutines and control flow abstraction.
features of an object.
36
Programming Languages and Computer Graphics Unit – 3 MCQs
38
Programming Languages and Computer Graphics Unit – 3 MCQs
level, multilevel, multiple and hierarchical inheritance (as in option class student{ };
inheritance. We can add one more type as class stream{ }; class topper{ };).
Hybrid inheritance but that is actually the
190. Which programming language doesn’t
combination any types of inheritance from
support multiple inheritance?
the 4 basic ones.
a) C++ and Java
188. Which among the following best b) C and C++
defines single level inheritance? c) Java and SmallTalk
a) A class inheriting a derived class d) Java
b) A class inheriting a base class
Answer: d
c) A class inheriting a nested class
Explanation: Java doesn’t support multiple
d) A class which gets inherited by 2 classes
inheritance. But that feature can be
Answer: b implemented by using the interfaces
Explanation: A class inheriting a base class concept. Multiple inheritance is not
defines single level inheritance. Inheriting supported because of diamond problem
an already derived class makes it multilevel and similar issues.
inheritance. And if base class is inherited by
191. Which among the following is correct
2 other classes, it is multiple inheritance.
for a hierarchical inheritance?
189. Which among the following is correct a) Two base classes can be used to be
for multiple inheritance? derived into one single class
a) class student{public: int marks;}s; class b) Two or more classes can be derived into
stream{int total;}; class topper:public one class
student, public stream{ }; c) One base class can be derived into other
b) class student{int marks;}; class stream{ }; two derived classes or more
class topper: public student{ }; d) One base class can be derived into only 2
c) class student{int marks;}; class classes
stream:public student{ };
Answer: c
d) class student{ }; class stream{ }; class
Explanation: One base class can be derived
topper{ };
into the other two derived classes or more.
Answer: a If only one class gets derived by only 2
Explanation: Class topper is getting derived other classes, it is also hierarchical
from 2 other classes and hence it is multiple inheritance, but it is not a mandatory
inheritance. Topper inherits class stream condition, because any number of derived
and class student publicly and hence can classes can be there.
use its features. If only few classes are
192. Which is the correct syntax of
defined, there we are not even using
inheritance?
39
Programming Languages and Computer Graphics Unit – 3 MCQs
it sometimes can bring up a new form of are separate. Hence it is not hybrid
inheritance, Like inheritance using multiple inheritance.
and hierarchical, which sometimes results
in diamond problem. 199. Which among the following best
describes multiple inheritance?
197. Which among the following is true? a) Two classes being parent of any other
a) Java supports all types of inheritance classes
b) Java supports multiple inheritance b) Three classes being parent of other
c) Java doesn’t support multiple inheritance classes
d) Java doesn’t support inheritance c) More than one class being parent of
other child classes
Answer: c d) More than one class being parent of
Explanation: Java doesn’t support multiple single child
inheritance. This is done to avoid the
diamond problem that sometimes arises Answer: d
with inherited functions. Though, multiple Explanation: If a class inherits more than
inheritance can be implemented in java one class, it is known as multiple
using interfaces. inheritance. This should not be referred
with only two or three classes being
198. Which type of inheritance is illustrated inherited. But there must be one class
by the following code? which inherits more than one class to be
called as multiple inheritance.
class student{ public: int marks; };
class topper: public student { public: char 200. How many types of inheritance can be
grade; }; used at a time in a single program?
class average{ public: int makrs_needed; }; a) Any two types
class section: public average{ public: char b) Any three types
name[10]; }; c) Any 4 types
class overall: public average{ public: int d) Any type, any number of times
students; };
Answer: d
a) Single level Explanation: Any type of inheritance can be
b) Multilevel and single level used in any program. There is no rule to use
c) Hierarchical only few types of inheritance. Only thing
d) Hierarchical and single level that matters is how the classes are
inherited and used.
Answer: c
Explanation: It is hierarchical inheritance 201. Which among the following defines
and single level inheritance. Since class single level inheritance?
topper is inheriting class student, it is single a) One base class derives another class
level inheritance. And then average is b) One derived class inherits from one base
inherited by section and overall, so it is class
hierarchical inheritance. But both of them c) One base class inherits from one derived
class
d) One derived class derives from another
41
Programming Languages and Computer Graphics Unit – 3 MCQs
42
Programming Languages and Computer Graphics Unit – 3 MCQs
inheritance. And class A is parent of other 208. Which concept will result in derived
two classes. class with more features (consider
maximum 3 classes)?
206. If single level inheritance is used and a) Single inheritance
an abstract class is created with some b) Multiple inheritance
undefined functions, can its derived class c) Multilevel inheritance
also skip some definitions? d) Hierarchical inheritance
a) Yes, always possible
b) Yes, possible if only one undefined Answer: b
function Explanation: If single inheritance is used
c) No, at least 2 undefined functions must then only feature of a single class are
be there inherited, and if multilevel inheritance is
d) No, the derived class must implement used, the 2nd class might have use private
those methods inheritance. Hence only multiple
inheritance can result in derived class with
Answer: d more features. This is not mandatory but in
Explanation: The derived class must a case if we consider same number of
implement those methods. This is because features in each class, it will result the
the parent class is abstract and hence will same.
have some undefined functions which has
to be defined in derived classes. Since we 209. Single level inheritance is safer than
are using single level inheritance, if derived _____________
class doesn’t implement those functions a) Multiple inheritance
then one more class has to be there which b) Interfaces
will become multi-level inheritance. c) Implementations
d) Extensions
207. Which among the following is false for
single level inheritance? Answer: a
a) There can be more than 2 classes in Explanation: Interfaces also represent a way
program to implement single inheritance of inheritance but is a wide word to decide
b) There can be exactly 2 classes to which inheritance we are talking about in it,
implement single inheritance in a program hence can’t be considered. Implementation
c) There can be more than 2 independent and extensions also doesn’t match that
classes involved in single inheritance level of specific idea. And multiple
d) The derived class must implement all the inheritance not so safe as it might result in
abstract method if single inheritance is used some ambiguity.
43
Programming Languages and Computer Graphics Unit – 3 MCQs
46
Programming Languages and Computer Graphics Unit – 3 MCQs
operator and is used to access the address 229. Which function is used to read a single
of a variable. character from the console in C++?
a) cin.get(ch)
226. Which of the following is used for b) getline(ch)
comments in C++? c) read(ch)
a) // comment d) scanf(ch)
b) /* comment */
c) both // comment or /* comment */ Answer: a
d) // comment */ Explanation: C++ provides cin.get() function
to read a single character from console
Answer: c whereas others are used to read either a
Explanation: Both the ways are used for single or multiple characters.
commenting in C++ programming. // is used
for single line comments and /* … */ is used 230. Which function is used to write a single
for multiple line comments. character to console in C++?
a) cout.put(ch)
227. What are the actual parameters in b) cout.putline(ch)
C++? c) write(ch)
a) Parameters with which functions are d) printf(ch)
called
b) Parameters which are used in the Answer: a
definition of a function Explanation: C++ provides cout.put()
c) Variables other than passed parameters function to write a single character to
in a function console whereas others are used to write
d) Variables that are never used in the either a single or multiple characters.
function
231. What are the escape sequences?
Answer: a a) Set of characters that convey special
Explanation: Actual parameters are those meaning in a program
using which a function call is made i.e. b) Set of characters that whose use are
which are actually passed in a function avoided in C++ programs
when that function is called. c) Set of characters that are used in the
name of the main function of the program
228. What are the formal parameters in d) Set of characters that are avoided in cout
C++? statements
a) Parameters with which functions are
called Answer: a
b) Parameters which are used in the Explanation: Escape sequence is a set of
definition of the function characters that convey a special meaning to
c) Variables other than passed parameters the program. They are used to convey a
in a function meaning which cannot be conveyed
d) Variables that are never used in the directly.
function
232. Which of the following escape
sequence represents carriage return?
47
Programming Languages and Computer Graphics Unit – 3 MCQs
48
Programming Languages and Computer Graphics Unit – 3 MCQs
49
Programming Languages and Computer Graphics Unit – 3 MCQs
50
Programming Languages and Computer Graphics Unit – 3 MCQs
51
Programming Languages and Computer Graphics Unit – 3 MCQs
52
Programming Languages and Computer Graphics Unit – 3 MCQs
263. What will be the output of the static const int val = 2*funStruct<n-
following C++ code? 1>::val;
};
#include <iostream>
using namespace std; template<>
template <class T> struct funStruct<0>
T max (T &a, T &b) {
{ static const int val = 1 ;
cout << "Template Called "; };
return (a > b)? a : b;
} int main()
{
template <> cout << funStruct<10>::val << endl;
int max <int> (int &a, int &b) return 0;
{ }
cout << "Called "; a) 1
return (a > b)? a : b; b) 1024
} c) Error
d) Segmentation fault
int main ()
{ Answer: b
int a = 10, b = 20; Explanation: The above call for struct will
cout << max <int> (a, b); call the first struct for n > 0 and second one
} when n = 0. Therefore when value of n = 10
a) Template Called 20 the until n becomes 0 first struct is called so
b) Called 20 we will call 2*2*2…10 times*1 which will
c) Error give the result 210 = 1024.
d) Segmentation fault
265. What is an exception in C++ program?
Answer: b a) A problem that arises during the
Explanation: For T = int we have created a execution of a program
separate definition for the above template b) A problem that arises during compilation
function. Hence the call using int takes the c) Also known as the syntax error
newly defined function. d) Also known as semantic error
264. What will be the output of the Answer: a
following C++ code?
Explanation: An exception is defined as the
problem in C++ program that arises during
#include <iostream>
the execution of the program for example
using namespace std;
template<int n> divide by zero error.
struct funStruct
{
53
Programming Languages and Computer Graphics Unit – 3 MCQs
55
Programming Languages and Computer Graphics Unit – 3 MCQs
56
Programming Languages and Computer Graphics Unit – 3 MCQs
280. In the following C++ code how many objects a1, a2 and a3 copy constructor is
times the string “A’s constructor called” will called so the string will not be printed for
be printed? them.
57
Programming Languages and Computer Graphics Unit – 3 MCQs
58
Programming Languages and Computer Graphics Unit – 3 MCQs
289. How to declare operator function? 292. Which operator is having the right to
a) operator sign left associativity in the following?
b) operator a) Array subscripting
b) Function call
c) name of the operator
c) Addition and subtraction
d) name of the class d) Type cast
Answer: a
Answer: d
Explanation: We have to declare the
Explanation: There are many rights to left
operator function by using the operator, associativity operators in C++, which means
operator sign. Example “operator +” where they are evaluation is done from right to
the operator is a keyword and + is the left. Type Cast is one of them. Here is a link
symbol need to be overloaded. of the associativity of operators:
https://github.com/MicrosoftDocs/cpp-
290. Which of the following statements is docs/blob/master/docs/cpp/cpp-built-in-
NOT valid about operator overloading? operators-precedence-and-associativity.md
a) Only existing operators can be 293. Which operator is having the highest
overloaded precedence?
b) The overloaded operator must have at a) postfix
least one operand of its class type b) unary
c) The overloaded operators follow the c) shift
syntax rules of the original operator d) equality
d) None of the mentioned
Answer: a
Answer: b Explanation: The operator which is having
the highest precedence is postfix and
Explanation: The overloaded operator must
lowest is equality.
not have at least one operand of its class
type. 294. What is this operator called ?:?
a) conditional
59
Programming Languages and Computer Graphics Unit – 3 MCQs
b) relational precedence
c) casting operator d) it converts the virtual base object to
d) unrelational derived class
Answer: a Answer: a
Explanation: In this operator, if the Explanation: Because the dynamic_cast
condition is true means, it will return the operator is used to convert from base class
first operator, otherwise second operator. to derived class.
295. What will be the output of the 297. What will be the output of the
following C++ code? following C++ code?
296. What is the use of dynamic_cast 298. What will be the output of the
operator? following C++ code?
a) it converts virtual base class to derived
class 1. #include <iostream>
b) it converts the virtual base object to 2. using namespace std;
derived objects 3. int main()
c) it will convert the operator based on 4. {
60
Programming Languages and Computer Graphics Unit – 3 MCQs
5. int i, j; Answer: a
6. j = 10; Explanation: Because of the precedence the
7. i = (j++, j + 100, 999 + j); pre-increment and post increment
8. cout << i; operator, we got the output as 749736.
9. return 0; Output:
10. } $ g++ op.cpp
$ a.out
a) 1000 749735
b) 11
c) 1010 300. What will be the output of the
d) 1001 following C++ code?
61
Programming Languages and Computer Graphics Unit – 3 MCQs
543 a) error
b) 15
306. What will be the output of the c) infinite times of printing n
following C++ code? d) none of the mentioned
63
Programming Languages and Computer Graphics Unit – 3 MCQs
c) 3 the class
d) 1 c) It becomes an inline function of the class
d) The program gives an error
Answer: a
Explanation: There are four types of loop. Answer: c
They are the while, do while, nested, for the Explanation: Any function which is defined
loop.
inside a class and has no complex
310. Which looping process is best used operations like loops, a large number of
when the number of iterations is known? lines then it is made inline.
a) for
b) while 313. What is an inline function?
c) do-while a) A function that is expanded at each call
d) all looping processes require that the during execution
iterations be known b) A function that is called during compile
time
Answer: a
Explanation: Because in for loop we are c) A function that is not checked for syntax
allowed to provide starting and ending errors
conditions of loops, hence fixing the d) A function that is not checked for
number of iterations of loops, whereas no semantic analysis
such things are provided by other loops.
Answer: a
311. Which of the following is the default Explanation: Inline function is those which
return value of functions in C++? are expanded at each call during the
a) int execution of the program to reduce the cost
b) char of jumping during execution.
c) float
d) void 314. An inline function is expanded during
______________
Answer: a a) compile-time
Explanation: C++ uses int as the default b) run-time
return values for functions. It also restricts c) never expanded
that the return type of the main function d) end of the program
must be int.
Answer: a
312. What happens to a function defined Explanation: An inline function is expanded
inside a class without any complex during the compile-time of a program.
operations (like looping, a large number of
lines, etc)? 315. How many ways of passing a
a) It becomes a virtual function of the class parameter are there in c++?
b) It becomes a default calling function of a) 1
b) 2
64
Programming Languages and Computer Graphics Unit – 3 MCQs
c) 3 10. {
d) 4 11. int x = 1, y = 3, z = 7;
12. copy (x, y, z);
Answer: c 13. cout << "x =" << x << ", y ="
Explanation: There are three ways of << y << ", z =" << z;
passing a parameter. They are pass by 14. return 0;
value,pass by reference and pass by 15. }
pointer.
a) 2 5 10
316. Which is used to keep the call by b) 2 4 5
reference value as intact? c) 2 6 14
a) static d) 2 4 9
b) const
c) absolute Answer: c
d) virtual Explanation: Because we multiplied the
values by 2 in the copy function.
Answer: b Output:
Explanation: Because const will not change $ g++ arg6.cpp
the value of the variables during the $ a.out
execution. x = 2,y = 6,z = 14
317. By default how the value are passed in 319. What will happen when we use void in
c++? argument passing?
a) call by value a) It will not return value to its caller
b) call by reference b) It will return value to its caller
c) call by pointer c) Maybe or may not be return any value to
d) call by object its caller
d) It will return value with help of object
Answer: a
Explanation: None. Answer: a
Explanation: As void is not having any
318. What will be the output of the return value, it will not return the value to
following C++ code? the caller.
65
Programming Languages and Computer Graphics Unit – 3 MCQs
8. } Answer: c
9. int main() Explanation: There are 3 specifiers used to
10. { derive a class. They are private, protected
11. int x = 2, y =3;
and public.
12. Sum(x, y, y);
13. cout << x << " " << y; 323. Which specifier makes all the data
14. return 0;
members and functions of base class
15. }
inaccessible by the derived class?
a) 2 3 a) private
b) 6 9 b) protected
c) 2 15 c) public
d) compile time error
d) both private and protected
Answer: c Answer: a
Explanation: We have passed three values
Explanation: Private access specifier is used
and it will manipulate according to the
given condition and yield the result as 2 15 to make all the data members and functions
Output: of the base class inaccessible.
$ g++ arg.cpp
$ a.out 324. If a class is derived privately from a
2 15 base class then
______________________________
321. What is Inheritance in C++?
a) no members of the base class is inherited
a) Wrapping of data into a single class
b) all members are accessible by the
b) Deriving new classes from existing classes
derived class
c) Overloading of classes
c) all the members are inherited by the class
d) Classes with same names
but are hidden and cannot be accessible
Answer: b d) no derivation of the class gives an error
Explanation: Inheritance is the concept of
Answer: c
OOPs in which new classes are derived from
Explanation: Whenever a class is derived, all
existing classes in order to reuse the
the members of the base class is inherited
properties of classes defined earlier.
by the derived class but are not accessible
322. How many specifiers are used to derive by the derived class.
a class?
325. What is a virtual function in C++?
a) 1 a) Any member function of a class
b) 2 b) All functions that are derived from the
c) 3 base class
d) 4 c) All the members that are accessing base
class data members
d) All the functions which are declared in
66
Programming Languages and Computer Graphics Unit – 3 MCQs
67
Programming Languages and Computer Graphics Unit – 3 MCQs
68
Programming Languages and Computer Graphics Unit – 3 MCQs
70
Programming Languages and Computer Graphics Unit – 3 MCQs
c) Forms a) 00
d) Browser based games b) 0x
c) 0X
Answer: c
d) Both 0x and 0X
Explanation: With the help of HTML5 and
JavaScript it became possible to create Answer: d
excellent mobile applications, browser Explanation: Generally, X or x denotes
based games, web applications and many hexadecimal values. So, any integer literal
more other applications. Forms were that begins with 0X or 0x denotes a
already introduced before HTML5. hexadecimal number.
343. JavaScript Code can be called by using 346. The generalised syntax for a real
___________ number representation is __________
a) RMI a) [digits][.digits][(E|e)[(+|-)]digits]
b) Triggering Event b) [digits][+digits][(E|e)[(+|-)]digits]
c) Preprocessor c) [digits][(E|e)[(+|-)]digits]
d) Function/Method d) [.digits][digits][(E|e)[(+|-)]digits]
Answer: d Answer: a
Explanation: JavaScript code can be called Explanation: Floating-point literals may also
by making a function call to the element on be represented using exponential notation:
which JavaScript has to be run. There are a real number followed by the letter e (or
many other methods like onclick, onload, E), followed by an optional plus or minus
and onsubmit etc. sign, followed by an integer exponent. This
notation represents the real number
344. The type of a variable that is volatile is
multiplied by 10 to the power of the
_______________
exponent.
a) Volatile variable
b) Mutable variable 347. JavaScript _________ when there is an
c) Immutable variable indefinite or an infinite value during an
d) Dynamic variable arithmetic computation.
a) Prints an exception error
Answer: b
b) Prints an overflow error
Explanation: The variables whose values can
c) Displays “Infinity”
be changed are called mutable variable
d) Prints the value as such
types. In JavaScript, only objects and arrays
are mutable, not primitive values. Answer: c
Explanation: When the result of a numeric
345. A hexadecimal literal begins with
operation is larger than the largest
__________
representable number (overflow),
71
Programming Languages and Computer Graphics Unit – 3 MCQs
JavaScript prints the value as Infinity. the output device is a printer rather than a
Similarly, when a negative value becomes VDU).
larger than the largest representable
350. The snippet that has to be used to
negative number, the result is negative
check if “a” is not equal to “null” is
infinity. The infinite values behave as you
_________
would expect: adding, subtracting,
a) if(a!=null)
multiplying, or dividing them by anything
b) if (!a)
results in an infinite value (possibly with the
c) if(a!null)
sign reversed).
d) if(a!==null)
348. Which of the following is not
Answer: d
considered as an error in JavaScript?
Explanation: A strict comparison (e.g., ===)
a) Syntax error
is only true if the operands are of the same
b) Missing of semicolons
type and the contents match. The more
c) Division by zero
commonly-used abstract comparison (e.g.
d) Missing of Bracket
==) converts the operands to the same type
Answer: c before making the comparison. The not-
Explanation: Division by zero is not an error equal operator !== compares 0 to null and
in JavaScript: it simply returns infinity or evaluates to either true or false.
negative infinity. There is one exception,
351. The statement a===b refers to
however: zero divided by zero does not
_________
have a well defined value, and the result of
a) Both a and b are equal in value, type and
this operation is the special not-a-number
reference address
value, printed as NaN.
b) Both a and b are equal in value
349. The escape sequence ‘\f’ stands for c) Both a and b are equal in value and type
_________ d) There is no such statement
a) Floating numbers
Answer: c
b) Representation of functions that returns
Explanation: ”===” operator is known as the
a value
strict comparison operator. A strict
c) \f is not present in JavaScript
comparison (===) is only true if the
d) Form feed
operands are of the same type and the
Answer: d contents match.
Explanation: \f is the JavaScript escape
352. Assume that we have to convert
sequence that stands for Form feed
“false” that is a non-string to string. The
(\u000C). It skips to the start of the next
command that we use is (without invoking
page. (Applies mostly to terminals where
the “new” operator).
72
Programming Languages and Computer Graphics Unit – 3 MCQs
73
Programming Languages and Computer Graphics Unit – 3 MCQs
a) HTML Answer: a
b) LaTeX Explanation: There are two types of
c) PostScript polymorphism in Java. Compile time
d) None of the mentioned polymorphism (overloading) and runtime
polymorphism (overriding).
Answer: d
Explanation: There are three categories of 362. When does method overloading is
electronic markup: presentational, determined?
procedural, and descriptive markup. a) At run time
Examples are XML, HTML, LaTeX, etc. b) At compile time
c) At coding time
359. troff and nroff are _________ in Unix.
d) At execution time
a) functions
b) typesetting tools Answer: b
c) System sofwares Explanation: Overloading is determined at
d) None of the mentioned compile time. Hence, it is also known as
compile time polymorphism.
Answer: b
Explanation: Early examples of computer 363. What is the range of short data type in
markup languages can be found in Java?
typesetting tools like troff and nroff in Unix. a) -128 to 127
b) -32768 to 32767
360. Which of the following is not OOPS
c) -2147483648 to 2147483647
concept in Java?
d) None of the mentioned
a) Inheritance
b) Encapsulation Answer: b
c) Polymorphism Explanation: Short occupies 16 bits in
d) Compilation memory. Its range is from -32768 to 32767.
74
Programming Languages and Computer Graphics Unit – 3 MCQs
75
Programming Languages and Computer Graphics Unit – 3 MCQs
in Graphics class, it is used to output a 374. Which keys allows user to enter
string in an applet. frequently used operations in a single key
stroke?
371. Which of these methods is a part of
a) Function keys
Abstract Window Toolkit (AWT) ?
b) Cursor control keys
a) display()
c) Trackball
b) paint()
d) Control keys
c) drawString()
d) transient() Answer: a
Explanation: Function keys are used to
Answer: b
access frequently used areas.
Explanation: paint() is an abstract method
defined in AWT. 375. ________ are used to measure dial
rotations.
372. Which of these modifiers can be used
a) Potentiometers
for a variable so that it can be accessed
b) Volta meter
from any thread or parts of a program?
c) Parameter
a) transient
d) Only a
b) volatile
c) global Answer: d
d) No modifier is needed Explanation: Potentiometer measures the
dial rotations.
Answer: b
Explanation: The volatile modifier tells the 376. The device which is used to position
compiler that the variable modified by the screen cursor is
volatile can be changed unexpectedly by a) Mouse
other part of the program. Specially used in b) Joystick
situations involving multithreading. c) Data glove
d) Both a and c
373. The most commonly used input device
is Answer: a
a) Mouse Explanation: A mouse is small hand-held
b) Keyboard box used to position the screen cursor.
c) Scanner
377. _________ is used for detecting mouse
d) Printer
motion.
Answer: b a) Optical sensor
Explanation: Keyboard is the most b) Rollers on the bottom of mouse
commonly used input device. c) Both a and b
d) Sensor
76
Programming Languages and Computer Graphics Unit – 3 MCQs
77
Programming Languages and Computer Graphics Unit – 3 MCQs
78
Programming Languages and Computer Graphics Unit – 3 MCQs
Answer: a Answer: c
Explanation: The 2D translation equation is Explanation: A positive value for the
P’=P+T. rotation angle ϴ defines counterclockwise
rotations about the pivot point.
392. A two dimensional rotation is applied
to an object by 395. The rotation axis that is perpendicular
a) Repositioning it along with straight line to the xy plane and passes through the
path pivot point is known as
b) Repositioning it along with circular path a) Rotation
c) Only b b) Translation
d) Any of the mentioned c) Scaling
d) Shearing
Answer: c
Explanation: A two dimensional rotation is Answer: a
applied to an object by repositioning it Explanation: The rotation transformation is
along with circular path. also described as a rotation about a
rotation axis that is perpendicular to the xy
393. To generate a rotation , we must
plane and passes through the pivot point.
specify
a) Rotation angle ϴ 396. The original coordinates of the point in
b) Distances dx and dy polor coordinates are
c) Rotation distance a) X’=r cos (Ф +ϴ) and Y’=r cos (Ф +ϴ)
d) All of the mentioned b) X’=r cos (Ф +ϴ) and Y’=r sin (Ф +ϴ)
c) X’=r cos (Ф -ϴ) and Y’=r cos (Ф -ϴ)
Answer: a
d) X’=r cos (Ф +ϴ) and Y’=r sin (Ф -ϴ)
Explanation: Generate a rotation, we must
specify rotation angle ϴ of the rotation Answer: b
point or pivot point which the object is to Explanation: The original coordinates of the
be rotated. point in polor coordinates are X’=r cos (Ф
+ϴ) and Y’=r sin (Ф +ϴ).
394. Positive values for the rotation angle ϴ
defines 397. The two-dimensional rotation equation
a) Counterclockwise rotations about the in the matrix form is
79
Programming Languages and Computer Graphics Unit – 3 MCQs
80
Programming Languages and Computer Graphics Unit – 3 MCQs
a) P’=S*P Answer: d
b) P’=R*P Explanation: Successive translations are
c) P’=dx+dy additive.
d) P’=S*S P’= T(tx1, ty1) .[T(tx2, ty2)] P
= {T(tx1, ty1). T(tx2, ty2)}.P
Answer: a
Or T(tx1, ty1). T(tx2, ty2) = T(tx1+tx2 , ty1 +
Explanation: The matrix representation for
ty2).
scaling is P’=S*P.
408. Two successive translations are not
405. The matrix representation for rotation
commutative.
in homogeneous coordinates is
a) True
a) P’=T+P
b) False
b) P’=S*P
c) P’=R*P Answer: b
d) P’=dx+dy Explanation: According to commutative
property, the order does not matter. Same
Answer: c
as in the case of successive translations.
Explanation: The matrix representation for
Hence we can say that two successive
rotation is P’=R*P.
translations are commutative.
406. What is the use of homogeneous
409. General pivot point rotation can be
coordinates and matrix representation?
expressed as _____________________
a) To treat all 3 transformations in a
a) T(zr,yr).R(θ).T(-zr,-yr) = R(xr,yr,θ)
consistent way
b) T(xr,yr).R(θ).T(-xr,-yr) = R(xr,yr,θ)
b) To scale
c) T(xr,yr).R(θ).T(-xr,-yr) = R(zr,yr,θ)
c) To rotate
d) T(xr,yr).R(θ).T(-xr,-yr) = R(xr,yr,Q)
d) To shear the object
Answer: b
Answer: a
Explanation: Since the first two parameters
Explanation: To treat all 3 transformations
are in 2D, hence only ‘x’ and ‘y’ can be
in a consistent way, we use homogeneous
variable along with ‘θ’. In other options,
coordinates and matrix representation.
there is one more parameter ‘z’.
407. Two successive translations
410. Which of the following is NOT correct?
are___________________
(A, B and C are matrices)
a) Multiplicative
a) A.B = B.A
b) Inverse
b) A.B.C = (A.B).C = A.(B.C)
c) Subtractive
c) C(A+B) = C.A + C.B
d) Additive
d) 1 A = A 1
81
Programming Languages and Computer Graphics Unit – 3 MCQs
82
Programming Languages and Computer Graphics Unit – 3 MCQs
other preserves its values, that’s why it is 420. Co-ordinates are ranging according to
also called skewing. the screen resolution.
a) True
417. Shearing and reflection are types of
b) False
translation.
a) True Answer: a
b) False Explanation: When we display a scene, only
those objects which have a particular
Answer: b
window are displayed. So for that
Explanation: Shearing and reflection are not
mechanism to work, co-ordinates are made
types of translation. They are types of
to range themselves according to the
transformation. Even translation is also a
screen resolution.
type of transformation.
422. Any convenient co-ordinate system or
418. Which of this is compulsory for 2D
Cartesian co-ordinates which can be used to
reflection.
define the picture is called ___________
a) Reflection plane.
a) spherical co-ordinates
b) Origin
b) vector co-ordinates
c) Reflection axis
c) viewport co-ordinates
d) Co-ordinate axis.
d) world co-ordinates
Answer: c
Answer: d
Explanation: Reflection axis is the axis with
Explanation: World Coordinate Systems
respect to which reflection is done. In 3D, it
(WCS) are the type of coordinate systems
is reflection plane rather than reflection
which describe the physical coordinates
axis.
associated with a data array, such as sky
419. A view is selected by specifying a sub- coordinates. It is also used to denote
area of the __________ picture area. wavelengths of a spectrum and to draw
a) half astronomical images.
b) total
423. The object space or the space in which
c) full
the application model is defined is called
d) quarter
____________
Answer: b a) World co-ordinate system
Explanation: We consider a formal b) Screen co-ordinate system
mechanism of view, that is, which part of c) World window
the picture is to be displayed. That’s why d) Interface window
we select a view by specifying a sub-area of
Answer: a
the total picture area.
Explanation: World Coordinate System also
83
Programming Languages and Computer Graphics Unit – 3 MCQs
84
Programming Languages and Computer Graphics Unit – 3 MCQs
Answer: c Answer: a
Explanation: There are three methods for Explanation: Line clipping follows the same
text clipping which are − algorithm that is in the case of point
1) All or none string clipping 2) All or none clipping. So, in line clipping also, we will cut
character clipping 3) Text clipping. the portion of the line which is outside of
the window and keep only the portion that
430. A bitmap is collection of
is inside the window.
___________________ that describes an
image. 433. Cohen-Sutherland clipping is an
a) bits example of _________________
b) colors a) polygon clipping
c) algorithms b) text clipping
d) pixels c) line clipping
d) curve clipping
Answer: d
Explanation: A bitmap is a collection of Answer: c
pixels that describe an image. It is a type of Explanation: It is a type of algorithm which
computer graphics that the computer uses is used for line clipping or in other words it
to store and display pictures. is line clipping algorithm. Other examples of
line clipping algorithms are a Liang-Barsky
431. We can change the size or resize the
algorithm and Cyrus-Beck algorithm.
bitmap image.
a) True 434. The Cohen-Sutherland algorithm
b) False divides the region into _____ number of
spaces.
Answer: b
a) 8
Explanation: We can’t resize the bitmap
b) 6
image. When the bitmap image is resized,
c) 7
the image pixels get distorted. It is one of
d) 9
the main disadvantages of the bitmap.
Answer: d
432. In line clipping, the portion of line
Explanation: The Cohen-Sutherland
which is _____________ of window is cut
algorithm divides a two-dimensional space
and the portion that is _____________ the
into 9 regions and then efficiently
window is kept.
determines the lines and portions of lines
a) outside, inside
that are visible. The portions are visible in
b) inside, outside
the central region of interest.
c) exact copy, different
d) different, an exact copy 435. What is the name of the small integer
which holds a bit for the result of every
85
Programming Languages and Computer Graphics Unit – 3 MCQs
plane test?
a) setcode
b) outcode
c) incode
d) bitcode
Answer: b
Explanation: A small integer holding a bit
for the result of every plane test failed in
clipping is termed as outcode. Primitives
may be trivially rejected if the bitwise of all
its vertices outcodes is non zero.
Answer: a
Explanation: The outcode will have 4 bits
for two-dimensional clipping, or 6 bits in the
three-dimensional case. The first bit is set
to 1 if the point is above the viewport. The
bits in the 2D outcode represent: top,
bottom, right, left.
86