0% found this document useful (0 votes)
13 views219 pages

Programming Languages and Computer Graphics New

The document provides an overview of programming concepts in C, including tokens, data types, functions, storage classes, arrays, and pointers. It categorizes tokens into keywords, identifiers, constants, strings, special symbols, and operators, and explains their usage and rules. Additionally, it covers type casting, function aspects, and the differences between call by value and call by reference, along with examples for clarity.

Uploaded by

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

Programming Languages and Computer Graphics New

The document provides an overview of programming concepts in C, including tokens, data types, functions, storage classes, arrays, and pointers. It categorizes tokens into keywords, identifiers, constants, strings, special symbols, and operators, and explains their usage and rules. Additionally, it covers type casting, function aspects, and the differences between call by value and call by reference, along with examples for clarity.

Uploaded by

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

RAAJ ACADEMY

COMPUTER SCIENCE & APPLICATIONS


PAPER-II

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 begin with a letter or underscore(_).

• They must consist of only letters, digits, or underscore. No other special character is allowed.

• It should not be a keyword.

• It must not contain white space.

• It should be up to 31 characters long as only the first 31 characters are significant.


C Token – Constants
The constants refer to the variables with fixed values. They are like normal
variables but with the difference that their values can not be modified in the
program once they are defined.
Constants may belong to any of the data types.

const int c_var = 20;


const int* const ptr = &c_var;

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

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

long int 4 -2,147,483,648 to 2,147,483,647 %ld

unsigned long int 4 0 to 4,294,967,295 %lu

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

long double 16 3.4E-4932 to 1.1E+4932 %Lf


Type Casting in C
Data types are crucial in determining the nature and behavior of variables in the realm of programming.
Typecasting allows us to convert one data type into another. This procedure is called type casting, and the C
programming language offers it as a useful tool. In this blog, we will examine the syntax, practical applications,
and advantages of typecasting in C.

Types of Type Casting


Type casting may be done in several ways in C, including implicit and explicit casting.

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

There are three aspects of a C function.


• Function declaration A function must be declared globally in a c program to tell the compiler about the function name,
function parameters, and return type.

Function call Function can be called from anywhere in the program. The parameter list must not differ in function
calling and function declaration. We must pass the same number of functions as it is declared in the function declaration.
• Function definition It contains the actual statements which are to be executed. It is the most important aspect to
which the control comes when the function is called. Here, we must notice that only one value can be returned from the
function.
Types of Functions

There are two types of functions in C programming:


1.Library Functions: are the functions which are declared in the C header files such as scanf(), printf(),
gets(), puts(), ceil(), floor() 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 the complexity of a big program and optimizes the code.

#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

Storage Classes Storage Place Default Value Scope Lifetime

auto RAM Garbage Local Within function


Value
extern RAM Zero Global Till the end of the main
program Maybe declared
anywhere in the program

static RAM Zero Local Till the end of the main


program, Retains value
between multiple functions
call
register Register Garbage Local Within the function
Value
Automatic

• Automatic variables are allocated memory automatically at runtime.


• The visibility of the automatic variables is limited to the block in which they are defined.
• The scope of the automatic variables is limited to the block in which they are defined.The automatic variables are initialized
to garbage by default.
• The memory assigned to automatic variables gets freed upon exiting from the block.
• The keyword used for defining automatic variables is auto.
• Every local variable is automatic in C by default.

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;

printf("Size of the structure Person is: %d bytes\n", sizeof(p));

return 0;
}

Size of the structure Person is: 40 bytes


Sizeof() for Unions

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

In programming, we may require some specific input data to be generated several


numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.

•Creation of the new file


•Opening an existing file
•Reading from the file
•Writing to the file
•Deleting the file
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the
file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given
position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the
beginning of the file
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
fseek() function

#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);
}

This is sonoo jaiswal


C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.

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.

No. Macro Description


1 _DATE_ represents current date in
"MMM DD YYYY" format.

2 _TIME_ represents current time in


"HH:MM:SS" format.

3 _FILE_ represents current file name.

4 _LINE_ represents current line


number.
5 _STDC_ It is defined as 1 when
compiler complies with the
ANSI standard.
#include<stdio.h>
int main(){
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ ); File :simple.c
Date :Dec 6 2015
return 0; Time :12:28:46
} Line :6
STDC :1
Advantages of Using Macros:

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

What is the output of this statements “printf(“%d”,(a++)”)?


e) The value of (a++)
f) The current value of a
g) Error Message
h) Garbage
What is the value of the arithmetic expression?
2*3/4-3/4*2
A)0
B)1
C)1.5
D)None

Consider the following statements.


Int i=4,j=3,k=0;
K=++i---j+i++---j+j++;
What will be the values of i ,j and k after the statement?
a) 7,2,8
b) 5,2,10
c) 6,2,8
d) 4,2,8
What is printed by the following C program?

Int f(int x, int *py, int **ppz)

Int y,z);

**ppz+=1;

Z=**ppz;

*py+=2;

U=*py;

X+=3;

Return x+y+z;

Void main()

Int c, *b, **a;

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

What will be the program print?


Main()
{
i=2;
{
Int i=4,j=5;
Print(“%d%d”,i,j);
}
Print(“%d%d”,, i,j);
}
a)4525 b) 2525 c) 4545 d) None
Suppose you are compiling on a machine with 1-byte chars, 2-byte shorts, 4-byte ints, and 8-byte doubles, and with alignment
rules that require the address of every primitive data element to be an integer multiple of the element’s size. Suppose further that
the compiler is not permitted to reorder fields; padding is used to ensure alignment. How much space will be consumed by the
following array?

struct {

short s;

char c;

short t;

char d;

double r;

int i;

} A[10]; /*10 element array of structs */

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.

(3) Class friendship is reciprocal to each other.

(4) There is no such concept.

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;

Choose the correct option:

A. (a) and (b)

B. (b) and (c)

C. (b) and (d)

D. (a) and (d)


Consider the C/C++ function f() given below:
void f(char w[])
{
int x=strlen(w); //length of a string
char c;
for (int i=0; i<x; i++)
{
c=w[i];
w[i]=w[x-i-1];
w[x-i-1] =c;
}
}

Which of the following is the purpose of f() ?


A. It outputs the contents of the array in reverse order
B. It outputs the contents of the array in the original order
C. It outputs the contents of the array with the characters shifted over by one position
D. It outputs the contents of the array with the characters rearranged so they are no longer recognized as the words in the
original phrase
What is the output of the following ‘C’ program? (Assuming little – endian representation of multi-byte data in which Least
Significant Byte (LSB) is stored at the lowest memory address.)
#include<stdio.h>
#include<stdlib.h>
/* Assume short int occupies two bytes of storage */
int main ()
{
union saving
{
short int one;
char two[2];
};
union saving m;
m.two [0] =5;
m.two [1] =2;
printf(“%d, %d, %d\n”, m.two[0], m.two[1], m.one);
}/* end of main */
A. 5, 2, 1282
B. 5, 2, 52
C. 5, 2, 25
D. 5, 2, 517
The following statement in ‘C’
int (*f())[ ];
declares
(1) a function returning a pointer to an array of integers.
(2) a function returning an array of pointers to integers.
(3) array of functions returning pointers to integers.
(4) an illegal statement.

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

*f() shows that function f is returning a pointer


then we went to [] a/c to associativity then complete declaration put together becomes

A function f returning a pointer to an array of integers


OOPs (Object Oriented Programming System)

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.

What is a destructor in C++?

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:

class derived_class_name :: visibility-mode base_class_name


{
// body of the derived class.
}
Multi Level Inheritance Example

#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout<<"Eating..."<<endl;
}
};

class Dog: public Animal


{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};

class BabyDog: public Dog


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

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 also known as overloading, early It is also known as overriding, Dynamic


binding and static binding. binding and late binding.

Overloading is a compile time polymorphism Overriding is a run time polymorphism


where more than one method is having the where more than one method is having the
same name but with the different number of same name, number of parameters and the
parameters or the type of the parameters. type of the parameters.

It is achieved by function overloading and It is achieved by virtual functions and


operator overloading. pointers.

It provides fast execution as it is known at It provides slow execution as it is known at


the compile time. the 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.

Operator that cannot be overloaded are as follows:

• Scope operator (::)

• Sizeof

• member selector(.)

• member pointer 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.

Rules of Virtual Function

• Virtual functions must be members of some class.


• Virtual functions cannot be static members.
• They are accessed through object pointers.
• They can be a friend of another class.
• A virtual function must be defined in the base class, even though it is not used.
• The prototypes of a virtual function of the base class and all the derived classes must be identical. If the two functions
with the same name but different prototypes, C++ will consider them as the overloaded functions.
• We cannot have a virtual constructor, but we can have a virtual destructor
• Consider the situation when we don't use the virtual keyword.
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
Match List I with List II
List I List II
a) Localization i) Encapsulation
b) Packaging or binding of a
collection of item ii)Abstraction
c) Mechanism that enables
designer to focus on
essential details of a paradigm
component iii) Characteristics of software that indicates the manner in
which information is concentrated in program
d) Information hiding iv) Supressing the operational details of a program component
Choose the correct answer given below:
c) A-I,B-II,C-III,D-IV
d) A-II,B-I,C-III,D-IV
e) A-III,B-I,C-II,D-IV
f) A-III,B-I,C-IV,D-II
What is the value returned by the function f given below when n = 100 ?

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

b. Inheritance in object oriented programming provides support to reusability

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

d. Overloading is a type of polymorphism

Choose the correct option from those given below:

A. (a) and (b) only

B. (a), (b) and (c) only

C. (a), (b) and (d) only

D. (b), (c) and (d) only


Consider the following two C++ programs P1 and P2 and two statements S1 and S2 about these
programs:

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 }

D. Neither S1 nor S2 is true


Which of the following is false regarding the evaluation of computer programming languages ?

(1) Application oriented features

(2) Efficiency and Readability

(3) Software development

(4) Hardware maintenance cost

Implicit return type of a class constructor is :

(1) not of class type itself

(2) class type itself

(3) a destructor of class type

(4) a destructor not of class type

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()

C. int get ServerPort()

D. void set ContextType(String Type)


Methods Description
It returns the name of the MIME charset that was used in the body of the client
String getCharacterEncoding()
response.

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 setContentType(String type) Sets the type of the response data.

void setBufferSize(int size) specifies the recommended buffer size for the response’s body.

int getBufferSize() Returns the buffer size

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

Study the following:


Main()
{
Printf(“Java Point”);
Main();
}
What will be the output of this program?
e) Wrong Statement
f) It will keep on printing Java Point
g) It will print Java Point once
h) None of the above
In a system for a restaurant, the main scenario for placing order is given below:
a. Customer reads menu
b. Customer places order
c. Order is sent to kitchen for preparation
d. Ordered items are served
e. Customer requests for a bill for the order
f. Bill is prepared for this order
g. Customer is given the bill
h. Customer pays the bill

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.

Object-oriented C++ is an object-oriented Java is also an object-oriented language. However,


this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference
variable that refers to the current object.

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

1.this can be used to refer current class instance variable.


2.this can be used to invoke current class method (implicitly)
3.this() can be used to invoke current class constructor.
4.this can be passed as an argument in the method call.
5.this can be passed as argument in the constructor call.
6.this can be used to return the current class instance from the method.
Method Overloading

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).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final
variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}

Compile by: javac Bike9.java


.95.165/Bike9.java:4: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will
focus on runtime polymorphism in java.

Java Runtime Polymorphism Example: Bank


Consider a scenario where Bank is a class that provides a method to get the rate of interest. However,
the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are
providing 8.4%, 7.3%, and 9.7% rate of interest.
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Why use Java interface?


• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Example of package that import the packagename.*

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.

There are four types of Java access modifiers:

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

Which one of the following is correct?


A. Java applets cannot be written in any programming language
B. An applet is not a small program
C. An applet can be run on its own
D. Applets are embedded in another applications
Consider the following program:
#include<stdio.h>
main()
{
int i, inp;
float x, term=1, sum=0;
scanf("%d %f", &inp, &x);
for(i=1;i<=inp;i++)
{
term=term*x/i;
sum=sum+term;
}
printf("Result=%f\n", sum);
}
The program computes the sum of which of the following series?
A. x+x2/2+x3/3+x4/4+…
B. x+x2/2!+x3/3!+x4/4!+…
C. 1+x2/2+x3/3+x4/4+…
D. 1+x2/2!+x3/3!+x4/4!+…
Which of the following statements is/are true?
P: C programming language has a weak type system with static types.
Q: Java programming language has a string type system with static types
Code:
A. P only
B. Q only
C. Both P and Q
D. Neither P nor Q
What is the output of the following JAVA program?
class simple
{
public static void main(String[ ] args)
{
simple obj = new simple();
obj.start();
}
void start()
{
long [] P = {3, 4, 5};
long [] Q = method (P);
System.out.print (P[0] + P[1] +P[2]+”:”);
System.out.print (Q[0] + Q[1] + Q[2]);
}
long [ ] method (long [ ] R)
{
R[1] = 7;
return R;
}
} //end of class
A. 12:15
B. 15:12
C. 12:12
D. 15:15
In Java, which of the following statements is/are TRUE?

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

D. All of S1, S2 and S3


Which one of the following is correct for overloaded functions in C++?

A. Compiler sets up a separate function for every definition of function.

B. Compiler does not set up a separate function for every definition of function.

C. Overloaded functions cannot handle different types of objects.

D. Overloaded functions cannot have same number of arguments.

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.

Which of the following storage classes have global visibility in C/C++?

E. Auto

F. Extern

G. Static

H. Register

Which of the following cannot be passed to a function in C++?

A. Constant

B. Structure

C. Array

D. Header file
Which of the following is not correct for virtual function in C++?

A. Must be declared in public section of class

B. Virtual function can be static

C. Virtual function should be accessed using pointers

D. Virtual function is defined in base class

A member function can always access the data in, (in C++)

A. the class of which it is member

B. the object of which it is a member

C. the public part of its class

D. the private part of its class

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

prtdata is a pointer to a data type. The expression ∗prtdata++ is evaluated as (in C+


+)
5.∗(prtdata++)
6.(∗prtdata)++
7.∗(prtdata)++
8.Depends on compiler
What is the output of the following JAVA program?
Class Test
{
public static void main (String [] args)
{
Test obj=new Test ();
obj.start ();
}
void start()
{
String stra="do";
String strb=method (stra);
System.out.print(":" +stra +strb);
}
String method (String stra)
{
stra=stra+"good";
System.out.print(stra);
return "good";
}
}
A. dogood : dogoodgood
B. dogood : gooddogood
C. dogood : dodogood
D. dogood : dogood
Which of the following statements is/are TRUE regarding JAVA?
a. Constants that cannot be changed are declared using ‘static’ keyword.
b. A class can only inherit one class but can implement multiple interfaces.
A. Only (a) is TRUE
B. Only (b) is TRUE
C. Both (a) and (b) are TRUE
D. Neither (a) nor (b) is TRUE

Which of the following statements is/are TRUE?


a. In HTML, character entitites are used to incorporate external content into a web page, such as images.
b. Once a web server returns a cookie to a browser, the cookie will be included in all future requests from
the browser to the same server.
A. Only (a) is TRUE
B. Only (b) is TRUE
C. Both (a) and (b) are TRUE
D. Neither (a) nor (b) is TRUE
Which of the following statement(s) is/are TRUE regarding Java Servelets?

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.

A. Only (a) is TRUE

B. Only (b) is TRUE

C. Both (a) and (b) are TRUE

D. Neither (a) nor (b) is TRUE

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:

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;

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;
}

Which of the following integers best approximates the value of f(2,3)?


A. 0
B. 1
C. 2
D. 3
HTML
HTML stands for Hyper Text Markup Language, which is the most widely used
language on Web to develop web pages. HTML was created by Berners-Lee in late 1991
but "HTML 2.0" was the first standard HTML specification which was published in 1995.
HTML 4.01 was a major version of HTML and it was published in late 1999. Though HTML
4.01 version is widely used but currently we are having HTML-5 version which is an
extension to HTML 4.01, and this version was published in 2012.

• 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>

<body bgcolor=“red” text=“white”>


<center><h1> RAAJ Academy</h1></center>
<p></p>
<b></b>
<i></i>
<img src=“logo.jpg” align=“center” width=200 height=100>
<table>
<tr><th><td>
List tags
<ol><ul><dl>
Link tags
<a href>
<marquee>
Frame tags
Form tags
DHTML

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic


HTML.
Dynamic HTML is not a markup or programming language but it is a term that
combines the features of various web development technologies for creating
the web pages dynamic and interactive.
Components of Dynamic HTML
•HTML 4.0
•CSS
•JavaScript
•DOM.
HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It defines the
structure of a web page with various defined basic elements or tags.

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)

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


technologies of web development.

2. It is used for developing and creating web 2. It is used for creating and designing 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.

Applications of JavaScript Programming

• 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?

A - JavaScript is a lightweight, interpreted programming language.


B - JavaScript has object-oriented capabilities that allows you to
build interactivity into otherwise static HTML pages.
C - The general-purpose core of the language has been embedded
in Netscape, Internet Explorer, and other web browsers.
D - All of the above.
<html>
<body>
<script>
function getSum(first, second)
{
var sum = first * second;
document.write("The sum of " + first + " and " + second + " is " + sum);
}
let first = 3;
const second = 4;
getSum(first, second);
</script>
</body>
</html>
<html>
<body>
<div id="output">
</div>
<script>
let res1 = 4 + 5 * 6;
let res2 = (4 + 5) * 6; document.getElementById("output").innerHTML
= "Result 1: " + res1 + "<br>" + "Result 2: " + res2;
</script>
</body>
</html>
JavaScript - Operator
Precedence

n JavaScript, operator precedence ensures the priority of the operators to be


executed when a single expression contains multiple operators. So, whatever
expressions have higher priority, the compiler executes it first over other operators
and then executes the operators with the lower precedence.
Whenever you write any JavaScript expression with only 1 or 2 operators, you can
easily understand the output of the expression. But when the expression contains
multiple operators, you should know the concept of operator precedence to evaluate
the expression correctly.
The best example of operator precedence is that in traditional mathematics, the
multiplication operator has higher precedence over the addition or subtraction
operator. So, if any mathematical expression contains the multiplication and addition
of both operators, you need to perform the multiplication first.
Associativity
The term associativity refers to the direction compiler should follow while
evaluating the expression. In many situations, operators have the same
precedence. In such cases, ambiguity occurs that which operation the compiler
should perform first. So, the compiler takes the help of associativity. It can be
from left to right or right to left.
Operator
Operator Description Associativity Example
Precedence
1 () Grouping L -> R (expression)
2 . Member of object L -> R Object_name.property
2 () Function call L -> R Demo()
2 new To create objects R -> L New test()
2 [] Member of object L -> R Object["property"]
3 -- Postfix decrement - p--;
3 ++ Postfix increment - p++
4 -- Prefix decrement R -> L --p;
4 ++ Prefix increment R -> L ++p;
4 typeof To get the variable type R -> L typeof a;
4 ! Logical not R -> L !a;
4 ~ Bitwise not R -> L ~p
4 - Unary minus R -> L -p
4 + Unary plus R -> L +p
To delete object
4 delete R -> L Delete arr[0]
property
4 void Evaluates void R -> L Void(1)
Exponentiation
5 ** R -> L p ** q
operator
6 * Multiplication L -> R p*q
6 / Division L -> R p/q
6 % modulo L -> R p%q
Addition or plus
7 + L -> R p+q
operator
7 - Subtraction operator L -> R p-q
8 << Left shift L -> R p << 2
8 >> Signed right shift L -> R p >> 2
8 >>> Unsigned right shift L -> R p >>> 2

9 in Property in object L -> R x in y

9 instanceof Instance of object L -> R p instanceof Object

9 < Less than L -> R p<q

9 <= Less than or equal to L -> R p <= q

9 > Greater than L -> R p>q

Greater than or
9 >= L -> R p >= q
equal to

10 == Equality L -> R p == q

10 != Inequality L -> R p != q

10 === Strict equality L -> R p === q


10 !== Strict inequality L -> R p !== q

11 & Bitwise AND L -> R p&q

12 ^ Bitwise XOR L -> R p^q

13 | Bitwise OR L -> R p|q

14 && Logical AND L -> R p && q

15 || Logical OR L -> R p || q

16 ?? Nullish Coalescing R -> L p ?? q

17 = Assignment R -> L p=q

17 : Colon assignment R -> L p:q

17 += Addition assignment R -> L p += q


17 -= Subtraction assignment R -> L p -= q

17 *= Multiplication assignment R -> L p *= q

17 /= Division assignment R -> L p /= q

17 %= Modulo assignment R -> L p %= q

17 **= Exponentiation assignment R -> L p **= q

17 <<= Left shift assignement R -> L p <<= q

17 >>= Right shift assignment R -> L p >>= q

Unsigned right shift


17 >>>= R -> L p >>>= q
assignment

17 &= Bitwise AND assignment R -> L p &= q

17 ^= Bitwise XOR assignment R -> L p ^= q


Bitwise OR
17 |= R -> L p |= q
assignment
Logical AND
17 &&= R -> L p &&= q
assignment
Logical OR
17 ||= R -> L p ||= q
assignement
(a, b )=> { //
17 => Arrow operator -
function code}
17 … Spread operator - [… arr]
18 yield Pause / Resume R -> L yield p;
19 , Comma operator L -> R (10, 20, 30)
<html>
body>
<div id = "output">
</div>
<script>
const first = 30 / ((15 % 3) * 2);
const second = (2 ** 3) ** 2;
document.getElementById("output").innerHTML = "The value of first
expression is : " + first + "<br>" + "The value of second expression
is : " + second;
</script>
</body>
</html>
Consider the following conditional code, which returns a Boolean values
If((x>25)&&(y>100)
Return ‘false’;
Else if((x<=25)&&(y<=100))
Return ‘true’;
Else if(x>25)&&(y<=100))
Return ‘false’;
Else
Return ‘true’;
Simplify it by filling in the following blank with a single Boolean expression without changing the behavior of the conditional code.
If(……………..)
Return ‘true’;
Else
Return ‘false’;

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. defining a path between two nodes in an image

B. defining clickable region in an image

C. highlighting an area in an image

D. defining the site-map of a web-site

Which of the following UML diagrams has a static view?

A. Collaboration diagram

B. Use-Case diagram

C. State chart 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

c. <Letter>, <LETTER> and <letter> are three different tags in XML

Choose the correct answer from the options given below:

A. (a) and (b) only

B. (a) and (c) only

C. (b) and (c) only

D. (a) (b) and (c)


Consider the following C++ function f():
unsigned int f(unsigned int n) {
unsigned int b=0;
while (n) {
b+=n & 1;
n>>1;
}
return b;
}

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.

Select the correct answer from the options given below:

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”.

R : <xml version=”1.0” encoding =”UTF-8”>

is syntactly correct declaration for the version of an XML document.

Select the correct answer from the options given below:

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?

A. Member function of class B can access protected data of class A

B. Member function of class B can access public data of class A

C. Member function of class B cannot access private data of class A

D. Object of derived class B can access public base class data

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

(a)Frame attribute (i)to create link in HTML

(b)<tr> tag (ii)for vertical alignment of content in cell

(c)Valign attribute (iii)to enclose each row in table

(d)<a> tag (iv)to specify the side of the table frame that display border

Choose the correct option from those given below:

A. (a)-(i) , (b)-(ii), (c)-(iii), (d)-(iv)

B. (a)-(ii) , (b)-(i), (c)-(iii), (d)-(iv)

C. (a)-(iv) , (b)-(iii), (c)-(ii), (d)-(i)

D. (a)-(iii) , (b)-(iv), (c)-(ii), (d)-(i)


Consider the JavaScript Code:
var y=”12”
function f() {
var y=”6”;
alert (this.y);
function g() {alert (y); }
g();
}
f();

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 :

(a) Static variables (i) Local variables in Pascal

(b) Stack dynamic (ii) All variables in APL

(c) Explicit heap dynamic (iii) Fortran 77

(d) Implicit heap dynamic (iv) All objects in JAVA Codes :

(a) (b) (c) (d)

(1) (i) (iii) (iv) (ii)

(2) (iv) (i) (iii) (ii)

(3) (iii) (i) (iv) (ii)

(4) (ii) (i) (iii) (iv)


It is possible to define a class within a class termed as nested class. There are _____ types of nested classes.

(1) 2

(2) 3

(3) 4

(4) 5

Which of the following statements is correct ?

(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.

(2) Abstract class cannot be directly initiated with ‘new’ operator.

(3) Abstract class cannot be initiated.

(4) Abstract class contains definition of implementation.

Which of the following statements is not correct ?

(1) HTML is not screen precise formatting language.

(2) HTML does not specify a logic.

(3) DHTML is used for developing highly interactive web pages.

(4) HTML is a programming language.


When one object reference variable is assigned to another object reference variable then

(1) a copy of the object is created.

(2) a copy of the reference is created.

(3) a copy of the reference is not created.

(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 ?

(1) Quad Tree

(2) Projections

(3) Run length coding

(4) Chain codes


In XML we can specify the frequency of an element by using the symbols:

A. +*!

B. #*!

C. +*?

D. -*?

In XML, DOCTYPE declaration specifies to include a reference to ____ file

A. Document type Definition

B. Document type declaration

C. Document transfer definition

D. Document type language


Which of the following is/are correct with reference to Abstract class and interface?

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

C. Both a and b are true

D. Neitehr a nor b are true

Which of the following statements are true with reference to the way of describing XML data?

c. XML uses DTD to describe the data

d. XML uses XSL to describe the data

e. XML uses a description node to describe the 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

(b)Inheritance (ii)Hiding implementation details ofmethods from users of objects

(c)Encapsulation (iii)Using similar operationsto do similar things

(d)Abstraction (iv) Create new classes fromexisting class

Codes:

A. (a)-(iv), (b)-(iii), (c)-(i), (d)-(ii)

B. (a)-(iii), (b)-(iv), (c)-(i), (d)-(ii)

C. (a)-(iii), (b)-(i), (c)-(ii), (d)-(iv)

D. (a)-(iv), (b)-(iii), (c)-(ii), (d)-(i)


Which of the following is used to make an Abstract class?

A. Making at least one member function as pure virtual function

B. Making at least one member function as virtual function

C. Declaring as Abstract class using virtual keyword

D. Declaring as Abstract class using static keyword

__________ 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

(a)JAVA (i)Dynamically object oriented

(b)Phython (ii)Statistically non-object oriented

(c)Prolog (iii)Statistically object oriented

(d)ADA (iv)Dynamically non-object oriented

Codes :

A. (a)-(iii), (b)-(i), (c)-(ii), (d)-(iv)

B. (a)-(i), (b)-(iii), (c)-(ii), (d)-(iv)

C. (a)-(i), (b)-(iii), (c)-(iv), (d)-(ii)

D. (a)-(ii), (b)-(iv), (c)-(i), (d)-(iii)


Match List I with List II
List I List II
A. If the implementation of
generated or derived classes
differ only through a parameter
we have i)To use class hierarchy
B. If the actual type of objects used
cannot be known at compile time
then we have ii) Improved run time efficiency
C. If online operation are essential and templates
are used then we have iii) To use templates
D. To gain access to differing instances for
derived classes through base we have iv) To use explicit casting
Choose the correct answer from the options given
a) A-I, B-II, C-IV, D-III
b) A-III, B-I, C-II, D-IV
c) A-I, B-III, C-II, D-IV
Introduction to Computer Graphics
Graphics are defined as any sketch or a drawing or a special network that pictorially represents some meaningful
information. Computer Graphics is used where a set of images needs to be manipulated or the creation of the
image in the form of pixels and is drawn on the computer. Computer Graphics can be used in digital photography,
film, entertainment, electronic gadgets, and all other core technologies which are required. It is a vast subject and
area in the field of computer science. Computer Graphics can be used in UI design, rendering, geometric objects,
animation, and many more. In most areas, computer graphics is an abbreviation of CG. There are several tools
used for the implementation of Computer Graphics. The basic is the <graphics.h> header file in Turbo-C, Unity for
advanced and even OpenGL can be used for its Implementation. It was invented in 1960 by great researchers
Verne Hudson and William Fetter from Boeing.
Computer Graphics refers to several things:
• The manipulation and the representation of the image or the data in a graphical manner.
• Various technology is required for the creation and manipulation.
• Digital synthesis and its manipulation.

Types of Computer Graphics


• Raster Graphics: In raster, graphics pixels are used for an image to be drawn. It is also known as a bitmap
image in which a sequence of images is into smaller pixels. Basically, a bitmap indicates a large number of pixels
together.
• Vector Graphics: In vector graphics, mathematical formulae are used to draw different types of shapes, lines,
objects, and so on.
Applications
•Computer Graphics are used for an aided design for engineering and
architectural system- These are used in electrical automobiles, electro-
mechanical, mechanical, electronic devices. For example gears and bolts.
•Computer Art – MS Paint.
•Presentation Graphics – It is used to summarize financial statistical scientific
or economic data. For example- Bar chart, Line chart.
•Entertainment- It is used in motion pictures, music videos, television gaming.
•Education and training- It is used to understand the operations of complex
systems. It is also used for specialized system such for framing for captains,
pilots and so on.
•Visualization- To study trends and patterns.For example- Analyzing satellite
photo of earth.
Display Devices in Computer Graphics

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.

Today, the demand for high-quality displays is increasing.

There are some display devices given below:


1.Cathode-Ray Tube(CRT)
2.Color CRT Monitor
3.Liquid crystal display(LCD)
4.Light Emitting Diode(LED)
5.Direct View Storage Tubes(DVST)
6.Plasma Display
7.3D Display

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

•Electron Gun: The electron gun is made up of several elements, mainly a


heating filament (heater) and a cathode. The electron gun is a source of
electrons focused on a narrow beam facing the 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.

•Phosphorus-coated Screen: The phosphorus coated screen is used to produce


bright spots when the high-velocity electron beam hits it.
There are two ways to represent an object on the screen

1.Raster Scan: It is a scanning technique in which the electron beam moves along the screen. It moves from top to bottom,
covering one line at a time.
A raster scan is based on pixel intensity control display as a rectangular box on 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.

For Example: Television

The beam refreshing has two types:


1.Horizontal Retracing
2.Vertical Retracing

When the beam starts from the top left corner and reaches bottom right, 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:

1.It does only the wireframe.


2.It creates complex scenes due to flicker.
Color CRT Monitor: It is similar to a CRT monitor.
The basic idea behind the color CRT monitor is to combine three basic colors- Red, Green, and Blue. By using these three
colors, we can produce millions of different colors.

The two basic color display producing techniques are:


1.Beam-Penetration Method: It is used with a random scan monitor for displaying pictures. There are two phosphorus
layers- Red and Green are coated inside the screen. The color shown depends on how far the electron beam penetrates
the phosphorus surface.
A powerful electron beam penetrates the CRT, it passes through the red layer and excites the green layer within.
A beam with slow electrons excites only the red layer.
A beam with the medium speed of electrons, a mixture of red and green light is emitted to display two more colors-
orange and yellow.

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.

For Example: TFT (Thin Film Transistor)

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:

1.The Intensity of light can be controlled.


2.Low operational Voltage.
3.Capable of handling the high temperature.

Disadvantages:

4.More Power Consuming than LCD.


Direct View Storage Tube (DVST): It is used to store the picture information as a charge
distribution behind the phosphor-coated screen.

There are two guns used in DVST:


1.Primary Gun: It is used to store the picture information.
2.Flood / Secondary Gun: It is used to display a picture on the screen.

Advantages:
3.Less Time Consuming
4.No Refreshing Required
5.High-Resolution
6.Less Cost

Disadvantages:

• The specific part of the image cannot be erased.


• They do not display color.
Plasma Display: It is a type of flat panel display which uses tiny plasma cells. It is also known as the Gas-
Discharge display.

Components of Plasma display


1.Anode: It is used to deliver a positive voltage. It also has the line wires.
2.Cathode: It is used to provide negative voltage to gas cells. It also has fine wires.
3.Gas Plates: These plates work as capacitors. When we pass the voltage, the 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:
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.

For Example: Fog Display, Holographic Display, Retina Display Etc.

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

Matrix for Scaling:


Rotation:
It is a process of changing the angle of the object. Rotation can be clockwise or
anticlockwise. For rotation, we have to specify the angle of rotation and rotation
point. Rotation point is also called a pivot point. It is print about which object is
rotated.

Types of Rotation:
1.Anticlockwise
2.Counterclockwise

The positive value of the pivot point (rotation angle) rotates an object in a counter-
clockwise (anti-clockwise) direction.
The negative value of the pivot point (rotation angle) rotates an object in a clockwise
direction.
When the object is rotated, then every point of the object is rotated by the same
angle.
Matrix for rotation is a clockwise direction.

Matrix for rotation is an anticlockwise direction.

Rotation about an arbitrary point: If we want to rotate an object or point


about an arbitrary point, first of all, we translate the point about which we want to
rotate to the origin. Then rotate point or object about the origin, and at the end,
we again translate it to the original place. We get rotation about an arbitrary
point.
Reflection:
It is a transformation which produces a mirror image of an object. The mirror
image can be either about x-axis or y-axis. The object is rotated by180°.

Types of Reflection:
1.Reflection about the x-axis
2.Reflection about the y-axis
3.Reflection about an axis perpendicular to xy plane and passing through the
origin
4.Reflection about line y=x
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.
Reflection about y-axis: The object can be reflected about y-axis
with the help of following transformation matrix

Here the values of x will be reversed, whereas the value of y will


remain the same. The object will lie another side of the y-axis.
The following figure shows the reflection about the y-axis
Shearing:
It is transformation which changes the shape of object. The sliding of layers of
object occur. The shear can be in one direction or in two directions.
Shearing in the X-direction: In this horizontal shearing sliding of layers occur.
The homogeneous matrix for shearing in the x-direction is shown below:
Shearing in the Y-direction: Here shearing is done by sliding
along vertical or y-axis.

Shearing in X-Y directions: Here layers will be slided in both x as


well as y direction. The sliding will be in horizontal as well as
vertical direction. The shape of the object will be distorted. The
matrix of shear in both directions is given by:
Matrix
Representation
of 2D
Transformation
Homogeneous Coordinates
The rotation of a point, straight line or an entire image on the screen, about a point other
than origin, is achieved by first moving the image until the point of rotation occupies the
origin, then performing rotation, then finally moving the image to its original position.
The moving of an image from one place to another in a straight line is called a translation. A
translation may be done by adding or subtracting to each point, the amount, by which
picture is required to be shifted.
Translation of point by the change of coordinate cannot be combined with other
transformation by using simple matrix application. Such a combination is essential if we
wish to rotate an image about a point other than origin by translation, rotation again
translation.
To combine these three transformations into a single transformation, homogeneous
coordinates are used. In homogeneous coordinate system, two-dimensional coordinate
positions (x, y) are represented by triple-coordinates.
Homogeneous coordinates are generally used in design and construction applications. Here
we perform translations, rotations, scaling to fit the picture into proper position.
Example of representing coordinates into a homogeneous coordinate system: For
two-dimensional geometric transformation, we can choose homogeneous parameter h to
any non-zero value. For our convenience take it as one. Each two-dimensional position is
then represented with homogeneous coordinates (x, y, 1).
Following are matrix for
two-dimensional
transformation in
homogeneous coordinate:
Clipping:
When we have to display a large portion of the picture, then not only scaling &
translation is necessary, the visible part of picture is also identified. This process is
not easy. Certain parts of the image are inside, while others are partially inside. The
lines or elements which are partially visible will be omitted.
For deciding the visible and invisible portion, a particular process called clipping is
used. Clipping determines each element into the visible and invisible portion. Visible
portion is selected. An invisible portion is discarded.

Types of Lines:

Lines are of three types:


1.Visible: A line or lines entirely inside the window is considered visible
2.Invisible: A line entirely outside the window is considered invisible
3.Clipped: A line partially inside the window and partially outside is clipped. For
clipping point of intersection of a line with the window is determined.
Applications of clipping:

1.It will extract part we desire.


2.For identifying the visible and invisible area in the 3D object.
3.For creating objects using solid modeling.
4.For drawing operations.
5.Operations related to the pointing of an object.
6.For deleting, copying, moving part of an object.
Clipping can be applied to world co-ordinates. The contents inside the window will be mapped to
device co-ordinates. Another alternative is a complete world co-ordinates picture is assigned to
device co-ordinates, and then clipping of viewport boundaries is done.

Types of Clipping:

1.Point Clipping
2.Line Clipping
3.Area Clipping (Polygon)
4.Curve Clipping
5.Text Clipping
6.Exterior Clipping
Line Clipping:

It is performed by using the line clipping algorithm.


The line clipping algorithms are:
1.Cohen Sutherland Line Clipping Algorithm
2.Midpoint Subdivision Line Clipping Algorithm
3.Liang-Barsky Line Clipping Algorithm

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.

Uses of Exterior Clipping:


1.It is used for displaying properly the pictures which overlap each other.
2.It is used in the concept of overlapping windows.
3.It is used for designing various patterns of pictures.
4.It is used for advertising purposes.
5.It is suitable for publishing.
6.For designing and displaying of the number of maps and charts, it is also used.

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:

It is performed by processing the boundary of polygon against each window corner or


edge. First of all entire polygon is clipped against one edge, then resulting polygon is
considered, then the polygon is considered against the second edge, so on for all four
edges.

Four possible situations while processing

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.

The formula for a slope line interception is:

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

These Algorithm has the following characteristics.

• Input: At least one or more inputs must be accept a good algorithm.


• Output: At least one output must produced an algorithm.
• An algorithm should be precise: The algorithm’s each step must well-define.
• Finiteness: Finiteness is require in an algorithm. It signifies that the algorithm will come to a halt once all of the steps
have been complete.
• Correctness: An algorithm must implemented correctly.
• Uniqueness: The result of an algorithm should be based on the given input, and all steps of the algorithm should be
clearly and uniquely defined.
• Effectiveness: An algorithm’s steps must be correct and efficient.
• Easy to understand: Learners must be able to understand the solution in a more natural way thanks to an algorithm.

Types of Line Drawing Algorithm


For drawing a line, the following algorithms are use:
• DDA (Digital Differential Analyzer) Line Drawing Algorithm
• Bresenham’s Line Drawing Algorithm
Digital Differential Algorithm ( DDA)

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.

Advantages of Digital Differential Analyzer

• Firstly, It’s a straightforward algorithm to implement.


• The direct line equation is a slower algorithm.
• In the Digital Differential Analyzer, we are unable to apply the multiplication approach.
• When a point changes its location, the Digital Differential Analyzer method alerts us about the overflow.

DDA Algorithm Limitations

• 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.

Advantages of Bresenham’s Line Drawing Algorithm

The following are the benefits of the Bresenham line algorithm:


• An incremental algorithm that is quick.
• Only integer computations are use in this.

Disadvantages of Bresenham’s Line Drawing Algorithm

• 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.

Side effects of Scan Conversion:

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.

Flood-fill algorithm is comparatively slower than the


Boundary-fill algorithm. Boundary-fill algorithm is faster than the Flood-fill algorithm.

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.

Memory consumption is relatively low in Boundary-fill


It requires huge amount of memory. algorithm.

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 :

Line AB : A (– 6, 2) and B (–1, 8)

Line CD : C (– 1, 5) and D (4, 8)

Line EF : E (–2, 3) and F (1, 2)

Which of the following line(s) is/are candidate for clipping ?

(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

R : Perspective projections do not preserve straight lines.

Choose the correct answer from the code given below:

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. (0,1) and (3,3)

B. (0,1) and (2,3)

C. (0,1) and (4,5)

D. (0,1) and (3,5)


Which of the following colour models are defined with three primary colours?
a) RGB and HSV colour models
b) CMY and HSV colour models
c) HSV and HLS colour models
d) RGB and CMY colour models
Which of the following is not a component of memory tube display?
a) Flooding gun
b) Collector
c) Ground
d) Liquid Crystal
Which of the following is/are the principle components of a memory-tube display?

a. Flooding gun

b. Collector

c. Phosphorus grains

d. Ground

A. a and b

B. c only

C. d only

D. All of the above


Find the equation of the circle x2+y2=1 in terms of x′y′ coordinates, assuming that the xy coordinate system
results from a scaling of 3 units in the x′ direction and 4 units in the y′ direction.

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

With respect to CRT, the horizontal retrace is defined as

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

C. The technique of turning, the electron beam off while retracing

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?

a. Gouraud shading requires more computation than phong shading

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

Choose the correct answer from the options given below:

A. (a) and (b) only

B. (a) and (c) only

C. (b) and (c) only

D. (a),(b) and (c)


In the context of 3D Computer graphics, which of the following statements is/are correct?

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

c. Perspective transformation is a linear transformation

Choose the correct answer from the options given below:

A. (a) and (b) only

B. (a) and (c) only

C. (b) and (c) only

D. (a), (b) and (c)


Match List I with List II. List I gives 3×3 matrices representing 2D transformations and List II shows the
corresponding transformation diagrams.

Choose the correct answer from the options given below:

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. Straight lines are mapped to straight lines

b. Distances and angles are (in general) preserved

c. Far away objects appear the same size as closer ones

d. Requires homogeneous coordinates in order for it to be encoded into a linear transformation

Choose the correct answer from the options given below:

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?

A. Class loader only

B. Class loader and Java Interpreter

C. Class loader, Java Interpreter and API

D. Java Interpreter only

You might also like