Programming Languages and Computer Graphics New
Programming Languages and Computer Graphics New
UNIT – 3
PROGRAMMING LANGUAGE AND
COMPUTER GRAPHICS
Tokens in C
The tokens of C language can be classified into six types based on the functions they are used to perform.
1.Keywords
2.Identifiers
3.Constants
4.Strings
5.Special Symbols
6.Operators
C auto
Token – Keywords
double int struct break else long switch case enum register typedef char extern
return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
C Token – Identifiers
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
• They must consist of only letters, digits, or underscore. No other special character is allowed.
C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double quotes. Whereas, a character is enclosed in single quotes in C and C++.
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”; char string [] = “geeksforgeeks”;
C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The data
items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified as
follows:
• Unary Operators: Those operators that require only a single operand to act upon are known as
unary operators . For Example increment and decrement operators
• Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
• Arithmetic operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the ternary operator.
Conditional Operator(?) is also called the ternary operator.
enum
The enum keyword is used to declare an enum (short for enumeration). An enum is a user-
defined datatype, which holds a list of user-defined integer constants. By default, the
value of each constant is it’s index (starting at zero), though this can be changed. You can
declare an object of an enum and can set it’s value to one of the constants you declared
before. Here is an example of how an enum might be used:
#include<stdio.h>
// enum declaration:
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
// Driver code
int main()
{
//object of the enum (week), called day
enum week day;
day = Wed;
printf("%d", day);
return 0;
}
Data Type Memory (bytes) Range Format Specifier
Implicit Casting:
When the compiler automatically transforms the data from one type to another, it is referred to as implicit
casting or automated type conversion. This casting is based on a set of guidelines that outline how various
kinds of data can coexist. As an illustration, the automated conversion of an integer to a float, which occurs
without any explicit instructions, is an example of an implicit cast.
1.#include <stdio.h>
2.int main() {
3.int num1 = 10;
4.float num2 = 5.5;
5.float result;
6.result = num1 + num2; // Implicit cast from int to float
7.printf("The result is: %f\n", result);
8.return 0;
9.}
Explicit Casting:
Using the cast operator, explicit casting entails explicitly changing one data
type to another. It needs explicit instructions in the code and allows the
programmer control over type conversion.
#include <stdio.h>
int main() {
float num1 = 15.6;
int num2;
num2 = (int) num1;
printf("The result is: %d\n", num2);
return 0;
}
C Functions
In c, we can divide a large program into the basic building blocks known as function. The function contains the set of
programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to
the C program. In other words, we can say that the collection of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.
• By using functions, we can avoid rewriting same logic/code again and again in a program.
• We can call C functions any number of times in a program and from any place in a program.
• We can track a large C program easily when it is divided into multiple functions.
• Reusability is the main achievement of C functions.
• However, Function calling is always a overhead in a C program.
Function Aspects
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
SN Header file Description
1 stdio.h This is a standard input/output header file. It contains all the
library functions regarding standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(),
puts(),etc.
4 stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related
functions like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.
Call by value in C
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);
printf("After function call x=%d \n", x);
return 0;
}
Call by reference in C
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\
n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10
}
Storage Classes in C
Example 1
#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c);
return 0;
}
Static
• The variables defined as static specifier can hold their value between the multiple function calls.
• Static local variables are visible only to the function or the block in which they are defined.
• A same static variable can be declared many times but can be assigned at only one time.
• Default initial value of the static integral variable is 0 otherwise null.
• The visibility of the static global variable is limited to the file in which it has declared.
• The keyword used to define static variable is static.
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}
Register
• The variables defined as the register is allocated the memory into the CPU registers depending upon the size of
the memory remaining in the CPU.
• We can not dereference the register variables, i.e., we can not use &operator for the register variable.
• The access time of the register variables is faster than the automatic variables.
• The initial default value of the register local variables is 0.
• The register keyword is used for the variable which should be stored in the CPU register. However, it is compiler?
s choice whether or not; the variables can be stored in the register.
• We can store pointers into the register, i.e., a register can store the address of a variable.
• Static variables can not be stored into the register since we can not use more than one storage specifier for the
same variable.
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
printf("%d",a);
}
External
• The external storage class is used to tell the compiler that the variable defined as extern is declared with an
external linkage elsewhere in the program.
• The variables declared as extern are not allocated any memory. It is only declaration and intended to specify that
the variable is declared elsewhere in the program.
• The default initial value of external integral type is 0 otherwise null.
• We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block
or method.
• An external variable can be declared many times but can be initialized at only once.
• If a variable is declared as external then the compiler searches for that variable to be initialized somewhere in the
program which may be extern or static. If it is not, then the compiler will show an error.
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pogram or not.
printf("%d",a);
}
int a = 20;
Array
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data such
as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data element can be randomly
accessed by using its index number.
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}
}
return 0;
}
Pointers
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function,
or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n;
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printing p gives the address of number.
printf("Value of p variable is %d \
n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by
p.
return 0;
}
1.#include<stdio.h>
2.int main(){
3.int number=50;
4.printf("value of number is %d, address of number is %u",number,&number);
5.return 0;
6.}
Double Pointer (Pointer to Pointer)
As we know that, a pointer is used to store the address of a variable in C. Pointer reduces the access time of a
variable. However, In C, we can also define a pointer to store the address of another pointer. Such pointer is
known as a double pointer (pointer to pointer). The first pointer is used to store the address of a variable
whereas the second pointer is used to store the address of the first pointer. Let's understand it by the diagram
given below.
#include<stdio.h>
void main ()
{
int a = 10;
int *p;
int **pp;
p = &a; // pointer p is pointing to the address of a
pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
printf("address of a: %x\n",p); // Address of a will be printed
printf("address of p: %x\n",pp); // Address of p will be printed
printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer stoyred at pp
}
Pointer Addition
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
sizeof() operator in C
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type
specified in the number of char-sized storage units. The sizeof() operator contains a single operand
which can be either an expression or a data typecast where the cast is data type enclosed within
parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but
it can also be pointer data types and compound data types such as unions and structs.
#include <stdio.h>
int main()
{
int x=89; // variable declaration.
printf("size of the variable x is %d", sizeof(x)); // Displaying the size of ?x? variable.
printf("\nsize of the integer data type is %d",sizeof(int)); //Displaying the size of integer data type.
printf("\nsize of the character data type is %d",sizeof(char)); //
Displaying the size of character data type.
printf("\nsize of the floating data type is %d",sizeof(float)); //Displaying the size of floating data type.
return 0;
}
Using Structure
#include <stdio.h>
struct Person {
char name[30];
int age;
float salary;
};
int main() {
struct Person p;
return 0;
}
Unions and the sizeof() operator are compatible. Unions are comparable
to structures, except only one member can be active at once, and all its members share
memory.
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
printf("Size of the union Data is: %d bytes\n", sizeof(data));
return 0;
Size of the union Data is: 20 bytes
}
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime. Dynamic memory allocation in c
language is possible by 4 functions of stdlib.h header file.
1.malloc()
2.calloc() static memory dynamic malloc allocates single block
allocation memory () of requested memory.
3.realloc()
allocation
4.free() memory is memory is
calloc( allocates multiple
) block of requested
allocated at allocated at
memory.
compile time. run time.
reallo reallocates the
memory can't be memory can
c() memory occupied by
increased while be increased
malloc() or calloc()
executing while
functions.
program. executing
program. free() frees the dynamically
used in array. used in linked allocated memory.
list.
File Handling in C
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);
fseek( fp, 7, SEEK_SET );
fputs("sonoo jaiswal", fp);
fclose(fp);
}
include
#define
#undef
#ifdef
#ifndef
#if
#else
#elif
#endif
#error
#pragma
Predefined Macros
ANSI C defines many predefined macros that can be used in c program.
There are various advantages of Macros in C. Some main advantages of C macros are as
follows:
Code reuse: By allowing developers to declare a piece of code just once and use it
several times, macros help to promote modular programming and minimize code
duplication.
Code abbreviation: Macros make it possible to write clear, expressive code that is
simpler to read and comprehend the intentions of the programmer.
Performance Optimization: By minimizing function call overhead, macros may be
utilized to optimize code execution. For instance, it is possible to inline brief pieces of
code using function-like macros.
Using macros, conditional compilation enables distinct sections of the code to
be included or removed based on predetermined circumstances.
Debugging or platform-specific code both benefit from this functionality.
What will be the output of the following code?
#include<stdio.h>
Int main()
{
Int a,b,c;
A=ox10;
B=o10;
C=a+b;
Printf(“”%d”, c);
Return 0;
}
a) 20
b) 24
c) Garbage
d) Error
Ans : 2.) 24
a = 0x10 → 10 in hexadecimal = 16 in Decimal
b = 010 → 10 in octal = 8 in decimal
c = a+b = 16+8 = 24.
Suppose X and Y are wo integer variables having values 0x5AB6 and 0x61CD respectively. The result
(in hex) of applying bitwise operator and to X and Y will be?
a) X5089
b) 0x4084
c) 0x78A4
d) 0x3AD1
Int y,z);
**ppz+=1;
Z=**ppz;
*py+=2;
U=*py;
X+=3;
Return x+y+z;
Void main()
C=4;
B=&c;
A=&b;
Print(“%d”, f(c,b,a);
Getchar();
a) 18 b) 19 c) 21 d) 22
#include<stdio.h>
Int main()
{
Int x,y=5,z=5;
X=y==z;
Printf(“%d”,x);
Getchar();
Return 0;
}
a) 0
b) 1
c) 5
d) Compile Error
Int main()
{
Int i=1,2,3;
Printf(“%d”, i);
Return 0;
}
a) 1
b) 3
c) Garbage value
d) Compile Time Error
Int main()
{
int x=10;
int y=20;
X+=y+=10;
print(“X and Y values”, x,y);
return 0;
}
a) 40 20
b) 40 30
c) 30 30
d) 30 40
The value of the following expression (13/4*3)%5+1 is
a) 5.75
b) 2.95
c) 1.4875
d) 5
Given that x=7.5, j=-1.0, n=1.0, m=2.0 the value of
--x+j==x>n>=m is:
a) 0
b) 1
c) 2
d) 3
Given i=0, j=1, k=-1, x=0.5, y=0.0 . What is the output of the following expression in C language
X*y<i+j||k
a) -1
b) 0
c) 1
d) 2
What will be the output of the following code:
Int main()
{
Int a,b,c;
a=oX10;
b=o10;
c=a+b;
printf(“”%d”, c);
return 0;
}
a) 20
b) 24
c) Garbage
d) Error
What is a lint?
a) C Compiler
b) Interactive Debugger
c) Analyzing tool
d) C Interpreter
struct {
short s;
char c;
short t;
char d;
double r;
int i;
A. 150 bytes
B. 320 bytes
C. 240 bytes
D. 200 bytes
Which one of the following is correct, when a class grants friend status to another class ?
(1) The member functions of the class generating friendship can access the members of the friend class.
(2) All member functions of the class granted friendship have unrestricted access to the members of the class granting the friendship.
When a method in a subclass has the same name and type signatures as a method in the superclass, then the method in the subclass _____
the method in the superclass.
(1) Overloads
(2) Friendships
(3) Inherits
(4) Overrides
What is Override :
When it defines a function of the base class in a derived class with the same signature ie. Name, return type, and parameter but with a
different definition.
What is the output of the following C program?
# include <stdio.h>
main ()
{
int i, j, x=0;
for (i=0; i<5; ++i)
for (j=0; j<i; ++j)
{
x+=(i+j-1);
break;
}
printf(“%d”, x);
}
A. 6
B. 5
C. 4
D. 3
Which of the following are legal statements in C programming language?
int *P=&44;
int *P=&r;
int P=&a;
int P=a;
int (*f())[ ];
[] it represents Array Subscript
() it represents function Subscript
* it represents pointer
[ and () has same precedence and they are Left to right associative .
so a/c to precedence and associative f first becomes function
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It simplifies the software development and maintenance by
providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be
physical and logical.
Class
Collection of objects is called class. It is a logical entity.
A Class in C++ is the foundational element that leads to Object-Oriented programming. A class instance must be created in
order to access and use the user-defined data type's data members and member functions. An object's class acts as its
blueprint. Take the class of cars as an example. Even if different names and brands may be used for different cars, all of
them will have some characteristics in common, such as four wheels, a speed limit, a range of miles, etc. In this case, the
class of car is represented by the wheels, the speed limitations, and the mileage.
Inheritance
When one object acquires all the properties and behaviors of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
1.Sub class - Subclass or Derived Class refers to a class that receives properties from another
class.
2.Super class - The term "Base Class" or "Super Class" refers to the class from which a subclass
inherits its properties.
3.Reusability - As a result, when we wish to create a new class, but an existing class already
contains some of the code we need, we can generate our new class from the old class thanks to
inheritance. This allows us to utilize the fields and methods of the pre-existing class.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Different situations may cause an operation to behave differently. The type of data utilized in the
operation determines the behavior.
Abstraction
Hiding internal details and showing functionality is known as abstraction. Data abstraction is the
process of exposing to the outside world only the information that is absolutely necessary while
concealing implementation or background information.For example: phone call, we don't know the
internal processing.
In C++, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
Encapsulation is typically understood as the grouping of related pieces of information and data into a
single entity. Encapsulation is the process of tying together data and the functions that work with it in
object-oriented programming.
Take a look at a practical illustration of encapsulation: at a company, there are various divisions, including
the sales division, the finance division, and the accounts division. All financial transactions are handled by
the finance sector, which also maintains records of all financial data. In a similar vein, the sales section is
in charge of all tasks relating to sales and maintains a record of each sale. Now, a scenario could occur
when, for some reason, a financial official requires all the information on sales for a specific month. Under
the umbrella term "sales section," all of the employees who can influence the sales section's data are
grouped together. Data abstraction or concealing is another side effect of encapsulation. In the same way
that encapsulation hides the data. In the aforementioned example, any other area cannot access any of
the data from any of the sections, such as sales, finance, or accounts.
Dynamic Binding - In dynamic binding, a decision is made at runtime regarding the code that will be run
in response to a function call. For this, C++ supports virtual functions.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
Constructor
In C++, constructor is a special method which is invoked automatically at the
time of object creation. It is used to initialize the data members of new object
generally. The constructor in C++ has the same name as class or structure.
Default Constructor
A constructor which has no argument is known as default constructor. It is
invoked at the time of creating object.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct
objects.
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{ id = i;
name = n;
salary = s; }
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
} };
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
What is a copy constructor?
A member function known as a copy constructor initializes an item using another object from the same class-an in-
depth discussion on Copy Constructors.
Every time we specify one or more non-default constructors (with parameters) for a class, we also need to include a
default constructor (without parameters), as the compiler won't supply one in this circumstance. The best practice is
to always declare a default constructor, even though it is not required.
A reference to an object belonging to the same class is required by the copy constructor.
An equivalent special member function to a constructor is a destructor. The constructor creates class objects, which
are destroyed by the destructor. The word "destructor," followed by the tilde () symbol, is the same as the class
name. You can only define one destructor at a time. One method of destroying an object made by a constructor is to
use a destructor. Destructors cannot be overloaded as a result. Destructors don't take any arguments and don't give
anything back. As soon as the item leaves the scope, it is immediately called. Destructors free up the memory used
by the objects the constructor generated. Destructor reverses the process of creating things by destroying them.
~ <class-name>()
}
Friend function
If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using
the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the
keyword friend.
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
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, you can reuse, extend or modify the attributes and behaviors which are defined in
other class.
• 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.
The Syntax of Derived class:
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"Eating..."<<endl;
}
};
int main(void)
{
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Hierarchical Inheritance
#include <iostream>
using namespace std;
class Shape
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
Compile time polymorphism Run time polymorphism
The function to be invoked is known at the The function to be invoked is known at the
compile time. run time.
It is less flexible as mainly all the things It is more flexible as all the things execute
execute at the compile time. at the run time.
Types of overloading in C++ are:
• Function overloading
• Operator overloading
Function Overloading
Function Overloading is defined as the process of having two or more function with the same name, but
different in parameters is known as function overloading in C++. In function overloading, the function is
redefined by using either different types of arguments or a different number of arguments. It is only
through these differences compiler can differentiate between the functions.
Operators Overloading
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special
meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators
available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the
ability to add the variables of the user-defined data type that is applied to the built-in data types.
• Sizeof
• member selector(.)
• ternary operator(?:)
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b)
{
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C;
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Operators Overloading Example
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
virtual function
• A virtual function is a member function in the base class that you redefine in a derived class. It is declared using the
virtual keyword.
• It is used to tell the compiler to perform dynamic linkage or late binding on the function.
• There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create the pointer
to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived
class object, always executes the base class function. This issue can only be resolved by using the 'virtual' function.
int f (int n)
{ if (n = = 0) then return n;
Else
return n + f(n-2);
(1) 2550
(2) 2556
(3) 5220
(4) 5520
Which of the following statements are true regarding C++?
a. Overloading gives the capability to an existing operator to operate on other data types
c. When object of a derived class is defined, first the constructor of derived class is excecuted
then constructor of a base class is executed
S1 : P1 prints out 3. P1 P2
void f(int a, int *b, int &c)
double a=1, b=2;
S2 : P2 prints out 4:2 {
double &f(double &d)
a=1;
{
What can you say about the statements S1 and S2? *b=2;
d=4;
c=3;
return b;
Code: }
}
int main()
int main()
A. Only S1 is true {
{
int i=0;
f(a)=5;
B. Only S2 is true f(i, &i, i);
count < < a< < “:” < < b;
count <<i;
}
C. Both S1 and S2 are true }
The implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialise the
internal state of an object so that the code creating an instance will have a fully initialised, usable object immediately
When the inheritance is private, the private methods in base class are _____ in the derived class (in C+
+)
A. inaccessible
B. accessible
C. protected
D. public
The Servlet Response interface enables a servlet to formulate a response for a client using the method
A. void log(Exception e, String s)
B. void destroy()
String getContentType() It returns the response content type. e.g. text, HTML etc.
This method returns a ServletOutputStream that may be used to write binary data
ServletOutputStream getOutputStream()
to the response.
PrintWriter getWriter() The PrintWriter object is used to transmit character text to the client.
Sets the length of the response’s content body. This function sets the HTTP Content-
void setContentLength(int len)
Length header in HTTP servlets.
void setBufferSize(int size) specifies the recommended buffer size for the response’s body.
void flushBuffer() Any material in the buffer will be forced to be written to the client.
boolean isCommitted() If the response has been committed, this method returns a boolean.
void setLocale(Locale loc) If the answer hasn’t been committed yet, it sets the response’s location.
Clears the buffer’s data, as well as the headers and status code. To acquire a
void reset()
comprehensive list of ways, go here.
In what sequence the initialization, testing and execution of body is done while using do while loop?
a)Commenting
b)Execution of the body
c)Initialization
d)Testing the condition
Choose the correct answer from the following:
a)D,B,C
b)D,C,B
c)C,A,B
d)C,B,D
Which statement is false?
a) All function calls in C pass arguments using call by value
b) Call by reference enables a called function jto modify a variable in calling function
c) Call by value always more efficient then call by reference
d) Programmers use pointers and indirection operation to simulate call by references.
What is required in each C program?
a) The program must have atleast one function
b) The program does not require any function
c) Input Data
d) Output Data
A sequence diagram for the scenario will have at least how many objects among whom the messages will
be exchanged
A. 3
B. 4
C. 5
D. 6
Comparison C++ Java
Index
Platform- C++ is platform-dependent. Java is platform-independent.
independen
t
Mainly used C++ is mainly used for Java is mainly used for application programming.
for system programming. It is widely used in Windows-based, web-based,
enterprise, and mobile applications.
Design Goal C++ was designed for Java was designed and created as an interpreter
systems and applications for printing systems but later extended as a
programming. It was an support network computing. It was designed to be
extension of the easy to use and accessible to a broader audience.
C programming language.
Goto C++ supports the goto Java doesn't support the goto statement.
statement.
Multiple C++ supports multiple Java doesn't support multiple inheritance through
inheritance inheritance. class. It can be achieved by using
interfaces in java.
Operator C++ supports Java doesn't support operator overloading.
Overloading operator overloading.
Pointers C++ supports pointers. You Java supports pointer internally. However, you
Compiler and C++ uses compiler only. C++ Java uses both compiler and interpreter. Java
Interpreter is compiled and run using the source code is converted into bytecode at
compiler which converts compilation time. The interpreter executes this
source code into machine code bytecode at runtime and produces output. Java is
so, C++ is platform interpreted that is why it is platform-independent.
dependent.
Call by Value and C++ supports both call by value Java supports call by value only. There is no call by
Call by reference and call by reference. reference in java.
Structure and C++ supports structures and Java doesn't support structures and unions.
Union unions.
Thread Support C++ doesn't have built-in support Java has built-in thread support.
for threads. It relies on third-party
libraries for thread support.
Documentation C++ doesn't support Java supports documentation comment (/** ... */) to
comment documentation comments. create documentation for java source code.
Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can override all non-
that we can decide whether or not static methods by default. In other words, non-static
to override a function. methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift >>> operator that fills
shift >>> operator. zero at the top for the negative numbers. For positive
numbers, it works same like >> operator.
Inheritance Tree C++ always creates a new Java always uses a single inheritance tree because all
inheritance tree. classes are the child of the Object class in Java. The
Object class is the root of the inheritance tree in java.
Hardware C++ is nearer to hardware. Java is not so interactive with hardware.
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c){return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Super Keyword in Java
The super keyword in Java is a reference variable which is used to
refer immediate parent class object.
Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
Usage of Java super Keyword
1.super can be used to refer immediate parent class instance
variable.
2.super can be used to invoke immediate parent class method.
3.super() can be used to invoke immediate parent class constructor.
class Animal
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}
Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Access Modifiers in Java
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can
change the access level of fields, constructors, methods, and class by applying the access modifier on it.
1.Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the
class.
2.Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the default.
3.Protected: The access level of a protected modifier is within the package and outside the package through child
class. If you do not make the child class, it cannot be accessed from outside the package.
4.Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
Access Modifier within class within package outside package by outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
In Java, when we implement an interface method, it must be declared as
A. Private
B. Protected
C. Public
D. Friend
S1: The ‘final’ keyword applied to a class definition prevents the class form being extended through
derivation
S2: A class can only inherit one class but can implement multiple interfaces
S3: Java permits a class to replace the implementation of a method that it has inherited. It is called method
overloading
Code:
A. S1 and S2 only
B. S1 and S3 only
C. S2 and S3 only
B. Compiler does not set up a separate function for every definition of function.
When you call an overloaded function or operator, the compiler determines the most appropriate definition to use by comparing the argument types
you used to call the function or operator with the parameter types specified in the definitions. The process of selecting the most appropriate
overloaded function or operator is called overload resolution.
E. Auto
F. Extern
G. Static
H. Register
A. Constant
B. Structure
C. Array
D. Header file
Which of the following is not correct for virtual function in C++?
A member function can always access the data in, (in C++)
A member function can access it’s class member variables, irrespective of the
access specifier in which the member variable is declared.So, a member
function can always access the data in the class of which it is a member.
The associativity of which of the following operators is Left to Right, in C++?
1.Unary Operator
2.Logical not
3.Array element access
4.Addressof
a. A Java Servelet is a server-side component that runs on the web server and extends the capabilities of a server.
b. A servelet can use the user interface classes like AWT or Swing.
An XML document that adheres to syntax rules specified by XML 1.0 specification in that it must satisfy both
physical and logical structured, is called
E. Well-formed
F. Reasonable
G. Valid
H. Sophisticated
Consider the following recursive Java function f that takes two long arguments and returns a float value:
return result;
Which of the following real values best approximates the value of f(1,3)?
A. 0.2
B. 0.4
C. 0.6
D. 0.8
Consider the following recursive Java function f that takes two long arguments and returns a float
value :
public static float f(long m, long n)
{
float result = (float) m / (float) n;
if (m<0 || n <0)
return 0.0f;
else
result +=f(m*2, n*3);
return result;
}
• Create Web site - You can create a website or customize an existing web template if you know HTML well.
• Become a web designer - If you want to start a carrer as a professional web designer, HTML and CSS designing is a must skill.
• Understand web - If you want to optimize your website, to boost its speed and performance, it is good to know HTML to yield best
results.
• Learn other languages - Once you understands the basic of HTML then other related technologies like javascript, php, or angular are
become easier to understand.
HTML
<html>
<head>
<title>
Home Page
</title
</head>
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
JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell the
browser for performing an action.
DOM
DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all elements in
HTML.
Features of DHTML
•Its simplest and main feature is that we can create the web page dynamically.
•Dynamic Style is a feature, that allows the users to alter the font, size, color,
and content of a web page.
•It provides the facility for using the events, methods, and properties. And, also
provides the feature of code reusability.
•It also provides the feature in browsers for data binding.
•Using DHTML, users can easily create dynamic fonts for their web sites or web
pages.
•With the help of DHTML, users can easily change the tags and their properties.
•The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.
HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup language)
2. It is used for developing and creating web 2. It is used for creating and designing the
pages. animated and interactive web sites or pages.
3. This markup language creates static web pages. 3. This concept creates dynamic web pages.
4. It does not contain any server-side scripting 4. It may contain the code of server-side scripting.
code.
5. The files of HTML are stored with the .html 5. The files of DHTML are stored with the .dhtm
or .htm extension in a system. extension in a system.
6. A simple page which is created by a user 6. A page which is created by a user using the
without using the scripts or styles called as an HTML, CSS, DOM, and JavaScript technologies
HTML page. called a DHTML page.
7. This markup language does not need database 7. This concept needs database connectivity
connectivity. because it interacts with users.
What is xml
•Xml (eXtensible Markup Language) is a mark up language.
•XML is designed to store and transport data.
•Xml was released in late 90’s. it was created to provide an easy to use and
store self describing data.
•XML became a W3C Recommendation on February 10, 1998.
•XML is not a replacement for HTML.
•XML is designed to be self-descriptive.
•XML is designed to carry data, not to display data.
•XML tags are not predefined. You must define your own tags.
•XML is platform independent and language independent.
JAVASCRIPT
JavaScript is a lightweight, interpreted programming language. It is commonly used to create dynamic and
interactive elements in web applications. JavaScript is very easy to implement because it is integrated with HTML.
It is open and cross-platform.
• Client side validation − This is really important to verify any user input before submitting it to the server and
JavaScript plays an important role in validating those inputs at front-end itself.
• Manipulating HTML Pages − JavaScript helps in manipulating HTML page on the fly. This helps in adding and
deleting any HTML tag very easily using JavaScript and modify your HTML to change its look and feel based on
different devices and requirements.
• User Notifications − You can use JavaScript to raise dynamic pop-ups on the webpages to give different types of
notifications to your website visitors.
• Back-end Data Loading − JavaScript provides Ajax library which helps in loading back-end data while you are
doing some other processing. This really gives an amazing experience to your website visitors.
• Presentations − JavaScript also provides the facility of creating presentations which gives website look and feel.
JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide presentation.
• Server Applications − Node JS is built on Chrome's JavaScript runtime for building fast
and scalable network applications. This is an event based library which helps in
developing very sophisticated server applications including Web Servers.
• Machine learning − Developers can use the ML5.js library to complete the task related
to machine learning.
• Game Developments − JavaScript contains multiple libraries and NPM packages to
design graphics for the game. We can use HTML, CSS, and JavaScript with libraries to
develop the games.
• Mobile applications − We can use frameworks like React Native to build feature-rich
mobile applications.
• Internet of Things (IoT) − JavaScript is used to add functionality to devices like
smartwatches, earbuds, etc.
• Data visualization − JavaScript contains the libraries like D3.js to visualize the data
efficiently. The D3.js is also used to prepare high-quality charts to visualize the data.
• Cloud computing − We can use JavaScript in serverless computing platforms like
Cloudflare and AWS lambda to write and deploy functions on the cloud.
Which of the following is correct about JavaScript?
Greater than or
9 >= L -> R p >= q
equal to
10 == Equality L -> R p == q
10 != Inequality L -> R p != q
15 || Logical OR L -> R p || q
a)x>25
b) x<=25
c) x>100
d) y<=100
Match List I with List II
List I List II
a) Apache kafka i) Platform for constructing data flows for extract, transform and load (ETL)
processing
and analysis of large datasets
b) Pig ii) General-purpose computing model and
runtime system for distributed data analytics.
c) Apache Mahout iii) Open-source platform that was created by
LinkedIn
d) Map reduce iv) Open-source platform used for creating
scalable machine learning algorithms
Choose the correct answer given below:
b) A-II, B-IV, C-I, D-III
c) A-II, B-I, C-IV, D-III
d) A-III, B-I, C-IV, D-II
e) A-I, B-II, C-IV, D-III
In HTML, <map> tag is used for
A. Collaboration diagram
B. Use-Case diagram
D. Activity diagram
Which of the following statements regarding XML is/are True?
a. XML is a set of tags designed to tell browsers how to display text and images in a web page
b. XML defines a syntax for representing data, but the meaning of data varies from application to
application
The function f() returns the int that represents the ____P____ in the binary representation of positive
integer n, where P is
A. number of 0’s
B. number of bits
C. number of consecutive 1’s
D. number of 1’s
Which of the following statements is/are true?
P : In a scripting language like JacaScript, types are typically associated with values, not variables.
Q : It is not possible to show images on a web page without the <img> tag of HTML.
A. P only
B. Q only
C. Both P and Q
D. Neither P nor Q
Which of the following statements is/are true?
P : An XML document with correct syntax as specified by W3C is called “Well Formed”.
Q : An XML documented validated against a DTD is both “Well formed” and “valid”.
A. P and Q only
B. P and R only
C. Q and R only
D. All of P, Q and R
Let A be the base class in C++ and B be the derived class from A with protected inheritance. Which of the
following statement is false for class B?
Which tag is used to enclose any number of javascript statements in HTML document?
E. <code>
F. <script>
G. <title>
H. <body>
Match List – I with List-II:
List I List II
(d)<a> tag (iv)to specify the side of the table frame that display border
If M is the number of alert dialog boxes generated by this JavaScript code and D1,
D2, …, DM represents the content displayed in the each of the M dialog boxes, then:
A. M=3; D1 displays “12”; D2 displays “6”; D3 displays “12”
B. M=3; D1 displays”6”; D2 displays “12”; D3 displays “6”
C. M=2; D1 displays”6”; D2 displays “12”.
D. M=3; D1 displays”12”; D2 displays “6”
Match the following types of variables with the corresponding programming languages :
(1) 2
(2) 3
(3) 4
(4) 5
(1) Aggregation is a strong type of association between two classes with full ownership.
(2) Aggregation is a strong type of association between two classes with partial ownership.
(3) Aggregation is a weak type of association between two classes with partial ownership.
(4) Aggregation is a weak type of association between two classes with full ownership.
Which of the following statements is correct ?
(1) Every class containing abstract method must not be declared abstract.
(4) it is illegal to assign one object reference variable to another object reference variable.
Which of the following is used for the boundary representation of an image object ?
(2) Projections
A. +*!
B. #*!
C. +*?
D. -*?
a. A class can inherit only one Abstract class but may inherit several interfaces
b. An abstract class can provide complete and default code but an interface has no code
A. a is true
B. b is true
Which of the following statements are true with reference to the way of describing XML data?
A. a only
B. b only
C. a and b
D. a and c
Match the following with reference to object oriented modelling :
List-I List-II
(a)Polymorphism (i)Picking both operator and attributes withoperations appropriate to model an object
Codes:
__________ tag is an extension to HTML that can enclose any number of Javascript statements.
E. <SCRIPT>
F. <BODY>
G. <HEAD>
H. <TITLE>
Match the following w.r.t. programming languages :
List – I List – II
Codes :
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.
8.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
•Focusing & Accelerating Anodes: These anodes are used to produce a narrow
and sharply focused beam of electrons.
•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.
1.Raster Scan: It is a scanning technique in which the electron beam moves along the screen. It moves from top to bottom,
covering one line at a time.
A raster scan is based on pixel intensity control display as a rectangular box on the screen called a raster.
Picture description is stored in the memory area called as Refresh buffer, or Frame Buffer.
Frame buffer is also known as Raster or Bitmap. Raster scan provides the refresh rate of 60 to 80 frames per second.
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.
Advantages:
1.Real image
2.Many colors to be produced
3.Dark scenes can be pictured
Disadvantages:
1.Less resolution
2.Display picture line by line
3.More costly
Random Scan (Vector scan): It is also known as stroke-writing display or calligraphic display. In this, the
electron beam points only to the area in which the picture is to be drawn.
It uses an electron beam like a pencil to make a line image on the screen. The image is constructed from a
sequence of straight-line segments. On the screen, each line segment is drawn by the beam to pass from one
point on the screen to the other, where its x & y coordinates define each point.
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.
Advantages:
1.High Resolution
2.Draw smooth line Drawing
Disadvantages:
Advantages:
1.Better Resolution
2.Half cost
3.Inexpensive
Disadvantages:
1.Only four possible colors
2.Time Consuming
Shadow-Mask Method: It is used with a raster scan monitor for displaying pictures. It has more range of color than the beam
penetration method. It is used in television sets and monitors.
Structure:
1.It has three phosphorus color dots at each position of the pixel.
First Dot: Red color
Second Dot: Green color
Third Dot: Blue color
1.It has three different guns. Each for one color.
2.It has a metal screen or plate just before the phosphorus screen, named “Shadow-Mask.”
3.It also has a shadow grid just behind the phosphorus coated screen 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.
Advantages:
1.Display a wider range picture.
2.Display realistic images.
3.In-line arrangement of RGB color.
Disadvantages:
4.Difficult to cover all three beams on the same hole.
5.Poor Resolution.
Shadow-Mask Method: It is used with a raster scan monitor for displaying pictures. It has more range of color than the beam
penetration method. It is used in television sets and monitors.
Structure:
1.It has three phosphorus color dots at each position of the pixel.
First Dot: Red color
Second Dot: Green color
Third Dot: Blue color
1.It has three different guns. Each for one color.
2.It has a metal screen or plate just before the phosphorus screen, named “Shadow-Mask.”
3.It also has a shadow grid just behind the phosphorus coated screen 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.
Advantages:
1.Display a wider range picture.
2.Display realistic images.
3.In-line arrangement of RGB color.
Disadvantages:
4.Difficult to cover all three beams on the same hole.
5.Poor Resolution.
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.
Advantages:
1.Produce a bright image
2.Energy efficient
3.Completely flat screen
Disadvantages:
4.Fixed aspect ratio & Resolution
5.Lower Contrast
6.More Expensive
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.
LEDs are powerful in structure, so they are capable of withstanding mechanical pressure. LED also works at
high temperatures.
Advantages:
Disadvantages:
Advantages:
3.Less Time Consuming
4.No Refreshing Required
5.High-Resolution
6.Less Cost
Disadvantages:
Advantages:
5.Wall Mounted
6.Slim
7.Wider angle
Disadvantages:
8.Phosphorus loses luminosity over time.
9.It consumes more electricity than LCD.
10.Large Size
Display: It is also called stereoscope display technology. This technology is
capable of bringing depth perception to the viewer.
It is used for 3D gaming and 3D TVs.
Advantages:
• Impressive Picture Quality
• Impressive Picture Quality
• Impressive Picture Quality
Disadvantage:
• Expensive
• Binocular Fusion
Introduction of Transformations
Computer Graphics provide the facility of viewing object from different angles. The
architect can study building from different angles i.e.
1.Front Evaluation
2.Side elevation
3.Top plan
A Cartographer can change the size of charts and topographical maps. So if graphics
images are coded as numbers, the numbers can be stored in memory. These numbers
are modified by mathematical operations called as Transformation.
The purpose of using computers for drawing is to provide facility to user to view the
object from different angles, enlarging or reducing the scale or shape of object called as
Transformation.
Types of Transformations:
1.Translation
2.Scaling
3.Rotating
4.Reflection
5.Shearing
Translation
It is the straight line movement of an object from one position to another is called
Translation. Here the object is positioned from one coordinate location to another.
Translation of point:
To translate a point from coordinate position (x, y) to another (x 1 y1), we add
x1=x+Tx y1=y+Ty
algebraically the translation distances T x and Ty to original coordinate.
Matrix for Translation:
Scaling:
It is used to alter or change the size of objects. The change is done using scaling factors.
There are two scaling factors, i.e. Sx in x direction Sy in y-direction. If the original position
is x and y. Scaling factors are Sx and Sy then the value of coordinates after scaling will be
x1 and y1.
If the picture to be enlarged to twice its original size then 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
Types of Rotation:
1.Anticlockwise
2.Counterclockwise
The positive value of the pivot point (rotation angle) rotates an object in a counter-
clockwise (anti-clockwise) direction.
The negative value of the pivot point (rotation angle) rotates an object in a clockwise
direction.
When the object is rotated, then every point of the object is rotated by the same
angle.
Matrix for rotation is a clockwise direction.
Types of Reflection:
1.Reflection about the x-axis
2.Reflection about the y-axis
3.Reflection about an axis perpendicular to xy plane and passing through the
origin
4.Reflection about line y=x
Reflection about x-axis: The object can be reflected about x-axis
with the help of the following matrix
Types of Lines:
Types of Clipping:
1.Point Clipping
2.Line Clipping
3.Area Clipping (Polygon)
4.Curve Clipping
5.Text Clipping
6.Exterior Clipping
Line Clipping:
Text Clipping:
Several methods are available for clipping of text. Clipping method is dependent on the method of
generation used for characters. A simple method is completely considered, or nothing considers
method. This method is also called as all or none. If all characters of the string are inside window,
then we will keep the string, if a string character is outside then whole string will be discarded in
fig (a).
Another method is discarded those characters not completely inside the window. If a character
overlap boundary of window. Those will be discarded in fig (b).
In fig (c) individual character is treated. Character lies on boundary is discarded as which it is
outside the window.
Curve Clipping:
Curve Clipping involves complex procedures as compared to line clipping. Curve clipping requires more
processing than for object with linear boundaries. Consider window which is rectangular in shape. The circle is
to consider against rectangle window. If circle is completely inside boundary of the window, it is considered
visible. So save the circle. If a circle is in outside window, discard it. If circle cut the boundary then consider it
to be clipping case.
Exterior Clipping:
It is opposite to previous clipping. Here picture which is outside the window is considered. The picture inside
the rectangle window is discarded. So part of the picture outside the window is saved.
Polygon Clipping:
Polygon clipping is applied to the polygons. The term polygon is used to define objects having outline of solid.
These objects should maintain property and shape of polygon after clipping.
Sutherland-Hodgeman Polygon Clipping:
1.If the first vertex is an outside the window, the second vertex is inside the window.
Then second vertex is added to the output list. The point of intersection of window
boundary and polygon side (edge) is also added to the output line.
2.If both vertexes are inside window boundary. Then only second vertex is added to the
output list.
3.If the first vertex is inside the window and second is an outside window. The edge
which intersects with window is added to output list.
4.If both vertices are the outside window, then nothing is added to output list.
Line Drawing Algorithm
The Line Drawing Algorithm is a graphical algorithm for representing line segments on discrete graphical
media, such as printers and pixel-based media.”
A line drawing algorithm is a method for estimating a line segment on discrete graphical media such as
pixel-based screens and printers in computer graphics. Line sketching on such media necessitates an
approximation (in nontrivial cases). Lines are rasterise in one colour using basic methods. Spatial anti-
aliasing is a sophisticated approach that allows for a better representation of numerous colour gradations.
To draw a line on a continuous medium, however, no algorithm is require. Cathode-ray oscilloscopes, for
example, use analogue phenomena to create lines and curves.
Y = mx + b
In this formula, m is the slope line and b is the line’s intercept of y. Two endpoints for the line segment are
supplied in coordinates (x1, y1) and (x2, y2).
Properties of a Line Drawing Algorithm
A DDA Algorithm, also known as a Digital Differential Algorithm, is an incremental conversion method.
Moreover, The usage of the results from the preceding stage in each calculation distinguishes this
method.
• Firstly, It takes a long time to do floating point arithmetic and rounding points.
• A round-off mistake may cause the measured pixel location to deviate from the true long-line segment
path.
The Bresenham Line Algorithm
In 1962, “Jack Elton Bresenham” proposed this algorithm. This algorithm aids in the conversion of a line’s
scan. It’s a strong, useful, and precise method. Furthermore, To draw a line, we employ incremental integer
calculations. Addition, subtraction, and multiplication are among the integer calculations.
In addition, We must determine the slope (m) between the starting point and the final point in Bresenham’s
Line Drawing procedure.
• Bresenham’s Line Drawing Algorithm only aids in the creation of fundamental lines.
• The drawn line is not smooth as a result.
Scan Line Polygon Fill Algorithm:
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.
2. Unequal Intensity: It deals with unequal appearance of the brightness of different lines. An inclined line
appears less bright as compared to the horizontal and vertical line.
Flood-fill Algorithm Boundary-fill Algorithm
It can process the image containing more than one boundary It can only process the image containing single boundary
colours. colour.
In Flood-fill algorithm a random colour can be used to paint In Boundary-fill algorithm Interior points are painted by
the interior portion then the old one is replaced with a new continuously searching for the boundary colour.
one.
Flood-fill algorithms are simple and efficient. The complexity of Boundary-fill algorithm is high.
Consider a raster system with resolution 640 by 480. What size is frame
buffer (in bytes) for this system to store 12 bits per pixel?
A. 450 kilobytes
B. 500 kilobytes
C. 350 kilobytes
D. 400 kilobytes
A graphic display system has a frame buffer that is 640 pixels high , 480 pixels high
and 1 bit of color depth. If the access time for each pixel on the average is 200
nanoseconds, then the refresh rate of this frame buffer is approximately:
A. 16 frames per second
B. 19 frames per second
C. 21 frames per second
D. 23 frames per second
If we want to resize a 1024×768 pixels image to one that is 640 pixels wide with the
same aspect ratio, what would be the height of the resized image?
A. 420 Pixels
B. 460 Pixels
C. 480 Pixels
D. 540 Pixels
Which of the following algorithms is not used for line clipping?
A. Cohen-Sutherland algorithm
B. Sutherland-Hodgeman algorithm
C. Liang-Barsky algorithm
D. Nicholl-Lee-Nicholl algorithm
In the context of 3D computer graphics, which of the following statements is/are true?
P : Orthographic transformations keep parallel lines parallel.
Q : Orthographic transformations are affine transformations.
Select the correct answer from the options given below:
A. Both P and Q
B. Neither P nor Q
C. Only P
D. Only Q
A point P(5, 1) is rotated by 90° about a pivot point (2, 2). What is the coordinate of
new transformed point P′ ?
(1) (3, 5)
(2) (5, 3)
(3) (2, 4)
(4) (1, 5)
Let R be the rectangular window against which the lines are to be clipped using 2D Sutherland-Cohen line
clipping algorithm. The rectangular window has lower left-hand corner at (– 5, 1) and upper right-hand corner
at (3, 7). Consider the following three lines for clipping with the given end point co-ordinates :
(1) AB
(2) CD
(3) EF
(4) AB and CD
The end points of a given line are (0,0) and (6,18). Compute each value
of y as x steps from 0 to 3, by using equation of straight line:
A. For x=0,y=0;x=1,y=3;x=2,y=6;x=3,y=9
B. For x=0,y=1;x=1,y=3;x=2,y=4;x=3,y=9
C. For x=0,y=2;x=1,y=3;x=2,y=6;x=3,y=9
D. For x=0,y=0;x=1,y=3;x=2,y=4;x=3,y=6
Which of the following graphic primitives are considered as the basic building blocks
of computer graphics?
a. Points
b. Lines
c. Polylines
d. Polygons
A. a only
B. a, b, and c
C. a and b
D. a and c
Which of the following is not a basic primitive of the
Graphics Kernel System (GKS)?
A. POLYLINE
B. POLYDRAW
C. FILL AREA
D. POLYMARKER
In 3D Graphics, which of the following statements about perspective and parallel projection is/are
true?
P : In a perspective projection, the farthest an object is from the center of projection, the smaller it appears
Q : Parallel projection is equivalent to a perspective projection where the viewer is standing infinitely far away
Code:
A. P and Q only
B. P and R only
C. Q and R only
D. P, Q and R
Beam penetration and Shadow mask method are the two basic techniques for producing colour
display with a CRT. Which of the following is not true?
I) The beam penetration is used with random scan monitors
II) Shadow-mask is used in raster-scan system.
III) Beam penetration method is better than shadow mask method.
IV) Shadow mask method is better than beam penetration method.
Choose the correct answer from gien below:
a) I & II
b) II & III
c) III only
d) IV only
Line caps are used for adjusting the shape of the line ends to give them a better appearance. Various
kinds of line caps are used are
a) Butt cap and Sharp cap
b) Butt cap and round cap
c) Butt cap, Sharp cap and round cap
d) Butt cap, round cap and projecting square cap
Given below are certain output primitives and their associated attributes. Match each primitive with
its corresponding attributes:
Line I Line II
a) Line i) Type, Size, Colour
b) Fill Area ii)Colour, Size, Font
c) Text iii)Style, Colour, Pattern
d) Marker iv)Type, width, colour
a b c d
1) I ii iii iv
2) Ii I iii iv
3) Iv iii ii I
4) Iii I iv ii
A rectangle is bound by the lines x=0;y=0;x=5 and y=3. The line segment joining (−1,0) and (4,5),
if clipped against this window will connect the points __________.
a. Flooding gun
b. Collector
c. Phosphorus grains
d. Ground
A. a and b
B. c only
C. d only
A. 3(x′)2+4(y′)2=1
B. (x′3)2+(y′4)2=1
C. (3x′)2+(4y′)2=1
D. 13(x′)2+14(y′)2=1
A. The path an electron beam takes when returning to the left side of the CRT
B. The path an electron beam takes when returning to the right side of the CRT
D. The technique of turning, the electron beam on/ off while retracing
Using the phong reflectance model, the strength of the specular highlight is determined by the
angle between
A. the view vector and the normal vector
B. the light vector and the normal vector
C. the light vector and the reflected vector
D. the reflected vector and the view vector
Which of the following is correct?
a) Persistence is the term used to describe the direction of phosphorescent.
b) The control electrode is used to turn the electron beam on or off.
c) The electron gun creates a source of electrons which are focused into a narrow beam directed as
the face of CRT.
Choose the correct answer:
1) A&b
2) b&c
3) A&c
4) A, b & c
Concerning phong shading and Gouraud shading in a 3D scene, which of the following statements
are true?
b. Gouraud shading linearly interpolates the color of an interior pixel from the color at the vertices
c. Phong shading interpolates over the normal vectors specified at the vertices
a. Under perspective projection, each set of parallel lines in the object do not stay parallel in the image (except
those that are parallel to the viewplane to start with).
b. Applying a perspective transformation in the graphics pipeline to a vertex involves dividing by its ′z′ coordinate
A. A−IV,B−II,C−III,D−I
B. A−IV,B−III,C−II,D−I
C. A−III,B−II,C−IV,D−I
D. A−II,B−IV,C−III,D−I
Given below are different properties of 3D projections from A−D. Identify the correct order on the basis of property
true of (i) a perspective projection only, (ii) an orthographic projection only, (iii) both orthographic and projective
transformations and (iv) neither orthographic nor projective transformation, respectively.
A. d,c,b,a
B. b,c,d,a
C. d,c,a,b
D. c,d,b,a
Java Virtual Machine (JVM) is used to execute architectural neutral byte code. Which of the
following is needed by the JVM for execution of Java Code?