Download CBSE Class 12 Computer Science Useful Resources
Access comprehensive study materials and useful resources for Objective Oriented Programming in C++ using the Class 12 Objective Oriented Programming in C++ Revision Notes. Designed to align with the 2026-27 CBSE academic guidelines, these advanced resources help Class 12 Computer Science students reinforce core concepts beyond standard textbooks.
Access CBSE Study Guides and Summaries
Access the complete useful resource PDF for Class 12 Computer Science below. Regular practice with these targeted academic notes builds familiarity with complex topics and helps secure higher marks in final school evaluations.
Object Oriented Programming in C++ is the first unit of Class 12 Computer Science, and it begins with a revision tour of the Class XI topics. These revision notes cover keywords, identifiers, data types, variables, constants, operators, type conversion, control statements, functions and parameter passing, scope, arrays, structures, pointers, typedef, macros and function overloading, followed by solved board-style questions on header files, error finding, output tracing and random numbers.
KEYWORDS
Keywords are certain reserved words that convey a special meaning to the compiler. They are reserved for a special purpose and must not be used as identifier names, for example for, if, else, this, do.
IDENTIFIERS
Identifiers are programmer-defined names given to the various program elements such as variables, functions, arrays, objects and classes. An identifier may contain digits, letters and the underscore, and must begin with a letter or an underscore. C++ is case sensitive, as it treats upper and lower case letters differently. A keyword cannot be used as an identifier. Some valid identifiers are:
Pen time580 s2e2r3 _dos _HJI3_JK
DATA TYPES IN C++
Data types are means to identify the types of data and the associated operations of handling it. Data types in C++ are of two types.
1. Fundamental or built-in data types: These data types are already known to the compiler and are not composed of other data types. The fundamental data types in C++ are:
(i) int data type (for integers)
(ii) char data type (for characters)
(iii) float data type (for floating point numbers)
(iv) double data type
DATA TYPE MODIFIERS
There are four data type modifiers in C++, which may be used to modify the fundamental data types to fit various situations more precisely: (i) signed, (ii) unsigned, (iii) long and (iv) short.
VARIABLES
A named memory location whose contents can be changed within program execution is known as a variable. In other words, a variable is an identifier that denotes a storage location whose contents can be varied during program execution.
Declaration of variables: The syntax for variable declaration is:
datatype variable_name1, variable_name2, variable_name3, ... ;
A variable can also be initialized at the time of declaration by using the following syntax:
datatype variable_name = value;
In C++ both the declaration and the initialization of a variable can be done simultaneously at the place where the variable is used for the first time. This feature is known as dynamic initialization. For example, the two statements below can be combined into one as float avg = sum/count;.
float avg;
avg = sum/count;
CONSTANTS
A named memory location whose contents cannot be changed within program execution is known as a constant. In other words, a constant is an identifier that denotes a storage location whose contents cannot be varied during program execution. The syntax for constant declaration is:
const datatype constant_name = value;
For example:
const float pi = 3.14f;
CONDITIONAL OPERATOR ( ? : )
The conditional operator (? :) is a ternary operator, that is, it requires three operands. Its general form is:
expression1 ? expression2 : expression3 ;
Here expression1 is a logical expression which is either true or false. If expression1 evaluates to true (1), the value of the whole expression is the value of expression2, otherwise it is the value of expression3. For example:
min = a<b ? a : b ;
Here, if the expression (a
TYPE CONVERSION
The process of converting one predefined data type into another is called type conversion. C++ facilitates type conversion in two forms.
(i) Implicit type conversion: An implicit type conversion is performed by the compiler without the programmer's intervention. It is applied generally whenever different data types are intermixed in an expression. The C++ compiler converts all operands up to the data type of the largest operand, which is called type promotion.
(ii) Explicit type conversion: An explicit type conversion is user-defined and forces an expression to be of a specific data type.
TYPE CASTING
The explicit conversion of an operand to a specific type is called type casting. The type casting operator (type) allows you to convert a data item of a given type to another data type. The expression or identifier must be preceded by the name of the desired data type, enclosed in parentheses:
(data type) expression
Here data type is a valid C++ data type to which the conversion is to be done. For example, to make sure that the expression (x+y/2) evaluates to type float, write it as:
(float) (x+y/2)
SOME IMPORTANT SYNTAX IN C++
1. if statement
if ( <conditional expression> )
{
<statement-1 or block-1>;
// statements to be executed when the conditional expression is true
}
[ else
{
<statement-2 or block-2>;
// statements to be executed when the conditional expression is false
} ]
2. The if-else-if ladder
if ( <condition-1> )
statement-1; // do something if condition-1 is satisfied (True)
else if ( <condition-2> )
statement-2; // do something if condition-2 is satisfied (True)
else if ( <condition-3> )
statement-3; // do something if condition-3 is satisfied (True)
: // many more n-1 else-if ladders may come
else if ( <condition-n> )
statement-n; // do something if condition-n is satisfied (True)
[ else
statement-m; ] // at last do this when none of the above conditions is satisfied
The symbol <> in the syntax is a place holder. It is not a part of the syntax, so do not type it while writing a program. It only signifies that whatever is kept there varies from program to program. The symbol [ ] is also not a part of the syntax. It marks the optional part of the syntax, that is, everything between [ ] is optional.
3. switch statement
switch (expression/variable)
{
case value_1: statement-1;
break;
case value_2: statement-2;
break;
:
case value_n: statement-n;
break;
[ default: statement-m; ]
}
4. The for loop
for (initialization_expression(s); loop_condition; update_expression)
{
Body of loop
}
5. while loop
while (loop_condition)
{
Loop_body
}
6. do-while loop
do
{
Loop_body
} while (loop_condition);
break statement: The break statement enables a program to skip over part of the code. A break statement terminates the smallest enclosing while, do-while, for or switch statement. Execution resumes at the statement immediately following the body of the terminated statement. The following figure explains the working of the break statement.
[Figure: The Working of Break Statement. Three flow diagrams. In the while (test expression) loop, statement1 is followed by if (val>2000) break; and then statement2, and the break arrow jumps out of the loop to statement3. In the for (int; expression; update) loop and in the do { ... } while (expression); loop the same structure is shown, with the break arrow leaving the loop body for statement3 after the loop]
continue statement: The continue statement is another jump statement like the break statement, as both skip over a part of the code. But continue is somewhat different from break. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. The following figure explains the working of the continue statement.
[Figure: The Working of Continue Statement. Three flow diagrams for while (expression), for (int; expression; update) and do { ... } while (expression); loops. Each has statement1, then if (condition) continue; and then statement2, and statement3 after the loop. The continue arrow goes back to the loop test (or the update expression in the for loop) to start the next iteration]
FUNCTIONS
A function is a named group of programming statements which performs a specific task and returns a value.
1. Built-in functions (library functions): The functions which are already defined in the C++ library (in header files) and which a user can directly use without giving their definition are known as built-in or library functions, for example sqrt( ), toupper( ) and isdigit( ). Some important header files and the useful functions within them are:
| Header file | Functions |
|---|---|
| stdio.h (standard I/O functions) | gets( ), puts( ) |
| ctype.h (character type functions) | isalnum( ), isalpha( ), isdigit( ), islower( ), isupper( ), tolower( ), toupper( ) |
| string.h (string related functions) | strcpy( ), strcat( ), strlen( ), strcmp( ), strcmpi( ), strrev( ), strupr( ), strlwr( ) |
| math.h (mathematical functions) | fabs( ), pow( ), sqrt( ), sin( ), cos( ), abs( ) |
| stdlib.h | randomize( ), random( ) |
randomize( ): This function provides the seed value and an algorithm to help the random( ) function in generating random numbers. The seed value may be taken from the current system's time.
random(<int>): This function accepts an integer parameter, say x, and then generates a random value between 0 and x-1. For example, random(7) will generate numbers between 0 and 6.
To generate random numbers between a lower limit L and an upper limit U we can use the formula random(U - L + 1) + L. For example, to find random numbers between 10 and 100 we write:
random(100 - 10 + 1) + 10; // generates a random number between 10 and 100
2. User-defined function: The functions which are defined by the user for a specific purpose are known as user-defined functions. To use a user-defined function it is required to first define it and then use it.
Declaration of a user-defined function:
Return_type function_name(List of formal parameters)
{
Body of the function
}
Calling a function: When a function is called, a list of actual parameters is supplied that should match the formal parameter list in number, type and order of arguments. The syntax for calling a function is:
function_name ( list of actual parameters );
For example:
#include <iostream>
int addition (int a, int b)
{
int r;
r = a + b;
return (r);
}
void main ( )
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
Output: The result is 8
Call by value (passing by value): The call by value method of passing arguments to a function copies the value of the actual parameters into the formal parameters. That is, the function creates its own copy of the argument values and then uses them, hence any change made in the parameters inside the function will not be reflected in the actual parameters. The program above is an example of call by value.
Call by reference (passing by reference): The call by reference method uses a different mechanism. In place of passing a value to the function being called, a reference to the original variable is passed. This means that in the call by reference method the called function does not create its own copy of the original values, rather it refers to the original values only by a different name, that is, a reference. Thus the called function works on the original data and any changes are reflected in the original values.
// passing parameters by reference
#include <iostream.h>
void duplicate (int& a, int& b, int& c)
{
a *= 2;
b *= 2;
c *= 2;
}
void main ()
{
int x = 1, y = 3, z = 7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
}
Output: x=2, y=6, z=14
The ampersand (&) (address of) specifies that the corresponding arguments are to be passed by reference instead of by value.
Constant arguments: In C++ the value of a constant argument cannot be changed by the function. To make an argument constant to a function we can use the keyword const as shown below:
int myFunction( const int x, const int b );
The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated.
Default arguments: C++ allows us to assign default value(s) to a function's parameter(s), which is useful in case a matching argument is not passed in the function call statement. The default values are specified at the time of function definition. For example:
float interest ( float principal, int time, float rate = 0.70f )
Here, if we call this function as below, then rate = 0.7 will be used in the function.
si_int = interest(5600, 4);
Formal parameters: The parameters that appear in a function definition are formal parameters.
Actual parameters: The parameters that appear in a function call statement are actual parameters.
Functions with no return type (the use of void): In this case the void type specifier should be used for the function. It is a special specifier that indicates the absence of a type.
The return statement: On execution of the return statement the function is exited immediately and control passes back to the calling function (or, in the case of main( ), control is transferred back to the operating system). The return statement also returns a value to the calling function. Its syntax is:
return (value);
SCOPE OF AN IDENTIFIER
The part of the program in which an identifier can be accessed is known as the scope of that identifier. There are four kinds of scope in C++.
(i) Local scope: An identifier declared in a block ( { } ) is local to that block and can be used only in it.
(ii) Function scope: An identifier declared in the outermost block of a function has function scope.
(iii) File scope (global scope): An identifier has file scope or global scope if it is declared outside all blocks, that is, it can be used in all blocks and functions.
(iv) Class scope: The name of a class member has class scope and is local to its class.
LIFETIME
The time interval for which a particular identifier or data value lives in the memory is called the lifetime of the identifier or data value.
ARRAYS
Declaration of a one-dimensional array:
Data_type Array_name[size];
Working with a one-dimensional array: The general form of the for loop for reading the elements of a 1-D array and for printing them is given below. Processing may be included within the loop of reading or printing, otherwise a separate loop of the same type may be used for processing.
// reading elements
for (int i = 0; i < size; i++)
{
cout << "Enter Array Element " << i+1;
cin >> Array_Name[i];
}
// printing elements
for (int i = 0; i < size; i++)
{
cout << Array_Name[i] << ", ";
}
Declaration of a 2-D array:
Data_type Array_name [R][C];
Here R represents the number of rows and C the number of columns in the array.
Working with a two-dimensional array: The general form of the for loop for reading and for printing the elements of a 2-D array is given below. Processing may be included within the loop of reading or printing, otherwise a separate nested loop of the same type may be used for processing.
// reading elements
for (int i = 0; i < R; i++)
{
cout << "Enter Row " << i+1;
for (int j = 0; j < C; j++)
cin >> Array_Name[i][j];
}
// printing elements
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
cout << Array_Name[i][j] << '\t';
cout << '\n';
}
STRUCTURES
Defining a structure:
struct <Name of Structure>
{
<datatype> <data-member 1>;
<datatype> <data-member 2>;
<datatype> <data-member 3>;
...
<datatype> <data-member n>;
};
Declaring structure variables: The variables can be declared along with the definition:
struct <Name of Structure>
{
<datatype> <data-member 1>;
...
<datatype> <data-member n>;
} var1, var2, ..., varn;
We can also declare structure type variables separately (after the definition of the structure) using the following syntax:
Structure_name var1, var2, ..., var_n;
Accessing structure elements: To access a structure element the dot operator (.) is used. The general form of accessing a structure element is:
Structure_Variable_Name.element_name
POINTERS
A pointer is a variable that holds the memory address of another variable of the same type.
Declaration and initialization of pointers: The syntax is:
Datatype *variable_name;
// e.g. int *p; float *p1; char *c;
Two special unary operators, * and &, are used with pointers. The & is a unary operator that returns the memory address of its operand. For example:
int a = 10;
int *p;
p = &a;
Pointer arithmetic: Two arithmetic operations, addition and subtraction, may be performed on pointers. When you add 1 to a pointer, you are actually adding the size of whatever the pointer is pointing at. That is, each time a pointer is incremented by 1, it points to the memory location of the next element of its base type. For example:
int *p;
p++;
If the current address of p is 1000, then the statement p++ will increase p to 1002 (taking an int as 2 bytes, as in Turbo C++), not 1001. Adding 1 to a pointer actually adds the size of the pointer's base type.
Base address: A pointer holds the address of the very first memory location of the array it is pointing to. The address of the first memory location of an array is known as the BASE ADDRESS.
Dynamic allocation operators: C++ dynamic allocation operators allocate memory from the free store (heap or pool), the pool of unallocated heap memory provided to the program. C++ defines two operators, new and delete, that perform the task of allocating and freeing memory during runtime.
Pointers and arrays: C++ treats the name of an array as a constant pointer which contains the base address, that is, the address of the first memory location of the array.
TYPEDEF
The typedef keyword allows us to create an alias for a data type. The syntax is:
typedef existing_data_type new_name;
// e.g. typedef int num;
#DEFINE PREPROCESSOR DIRECTIVE
The #define directive creates symbolic constants, that is, constants that are represented as macros.
Macros: Macros are preprocessor directives created using #define that serve as symbolic constants. They are created to simplify and reduce the amount of repetitive coding.
Example 1:
#define PI 3.14
Here PI is defined as a macro. It will replace PI with 3.14 throughout the program.
Example 2:
#define max(a,b) a>b ? a : b
This defines the macro max, taking two arguments a and b. It may be called like any function. Therefore, after preprocessing, the statement A = max(x, y); becomes A = x>y ? x : y;
FUNCTION OVERLOADING
Function overloading is the process of defining and using functions with the same name but a different argument list. These functions are differentiated during the calling process by the number, order and types of arguments passed to them. A difference in the return type alone is not enough to overload a function. Example:
int Add (int, int);
double Add (double, double);
float Add (int, float);
SHORT ANSWER TYPE QUESTIONS (2-MARKS)
1. Define Macro with suitable example. [2 Marks]
Answer:
1. A macro is a preprocessor directive created with #define. Before compilation the preprocessor replaces every use of the macro name by its replacement text.
2. Symbolic constant: #define PI 3.14 replaces PI by 3.14 wherever it appears.
3. Macro with arguments: #define max(a,b) a>b ? a : b, so the call A = max(x, y); becomes A = x>y ? x : y;
Teacher's Note:
a) A macro is only text substitution and does no type checking.
b) Give one example of each kind, with and without arguments.
2. Explain in brief the purpose of function prototype with the help of a suitable example. [2 Marks]
Answer:
1. A function prototype is a declaration of a function before it is used. It tells the compiler the function name, its return type and the number and types of its parameters.
2. The compiler uses it to check that every call has the right number and types of arguments and that the return value is used correctly.
3. Example: int Add(int, int); is written before main( ), and the definition of Add( ) can come after main( ).
Teacher's Note:
a) The names of the parameters in a prototype are optional.
b) A prototype ends with a semicolon, a definition has a body.
3. What is the difference between Global Variable and Local Variable? [2 Marks]
Answer:
1. A global variable is declared outside all functions and blocks. It can be used in all functions and lives for the whole run of the program.
2. A local variable is declared inside a function or block. It can be used only in that block and is destroyed when the block ends.
Teacher's Note:
a) Global variables have file scope, local variables have local scope.
b) If both have the same name, the local variable hides the global one inside its block.
4. What is the difference between Object Oriented Programming and Procedural Programming? [2 Marks]
Answer:
1. Procedural programming is built around functions (procedures). The data and the functions are separate, and data is often global and open to all functions. It follows a top-down approach.
2. Object oriented programming is built around objects that bind data and the functions working on that data into one unit (class). Data can be hidden, and it follows a bottom-up approach.
3. OOP supports encapsulation, data hiding, inheritance and polymorphism, which procedural programming does not support in the same way.
Teacher's Note:
a) Procedural: focus on functions. OOP: focus on objects and data.
b) OOP gives better security of data and easier reuse of code.
5. What is the difference between Global Variable and Local Variable? Also, give a suitable C++ code to illustrate both. [2 Marks]
Answer:
1. A global variable is declared outside all functions and is accessible everywhere in the file. A local variable is declared inside a function or block and is accessible only there.
2. In the code below, g is global and l is local to main( ). g can be used inside show( ) but l cannot.
#include <iostream.h>
int g = 10; // global variable
void show()
{
cout << g << " "; // g is accessible here
}
void main()
{
int l = 20; // local variable of main()
show();
cout << l; // l is accessible only here
}
Teacher's Note:
a) The output of the code is: 10 20
b) This repeats Question 3 with a code example.
6. Differentiate between ordinary function and member functions in C++. Explain with an example. [2 Marks]
Answer:
1. An ordinary function is defined outside any class and is called directly by its name.
2. A member function is defined inside a class (or declared there and defined with the scope resolution operator). It is called with an object and the dot operator, and it can use the private data members of its class.
int sum(int a, int b) // ordinary function
{ return a + b; }
class Box
{
int l;
public:
void set(int x) // member function
{ l = x; }
int get()
{ return l; }
};
void main()
{
Box b;
b.set(5); // called using an object
cout << sum(2, 3) << b.get(); // sum() called directly
}
Teacher's Note:
a) A member function works on the data of the object that calls it.
b) Ordinary functions cannot access private members of a class.
7. What is the difference between call by reference and call by value with respect to memory allocation? Give a suitable example to illustrate using C++ code. [2 Marks]
Answer:
1. In call by value, separate memory is allocated for the formal parameters, and the values of the actual parameters are copied into it. Changes inside the function do not affect the actual parameters.
2. In call by reference, no new memory is allocated for the parameters. The formal parameters are only another name (alias) for the memory of the actual parameters, so changes made inside the function change the original variables.
3. In the code below, swapv( ) works on copies and leaves x and y unchanged, while swapr( ) swaps the originals.
void swapv(int a, int b) // call by value
{ int t = a; a = b; b = t; }
void swapr(int &a, int &b) // call by reference
{ int t = a; a = b; b = t; }
void main()
{
int x = 5, y = 8;
swapv(x, y);
cout << x << " " << y << endl; // 5 8
swapr(x, y);
cout << x << " " << y; // 8 5
}
Teacher's Note:
a) After swapv(x,y) the values stay 5 and 8; after swapr(x,y) they become 8 and 5.
b) Reference parameters use the & sign in the function header.
8. What is the difference between actual and formal parameter? Give a suitable example to illustrate using a C++ code. [2 Marks]
Answer:
1. The parameters that appear in the function call statement are actual parameters. They supply the values (or references) to the function.
2. The parameters that appear in the function definition are formal parameters. They receive the values of the actual parameters.
3. In the code below, x and y are actual parameters and a and b are formal parameters.
int mul(int a, int b) // a and b are formal parameters
{ return a * b; }
void main()
{
int x = 3, y = 4;
cout << mul(x, y); // x and y are actual parameters
}
Teacher's Note:
a) The actual and formal parameters must match in number, type and order.
b) The output of the code is 12.
9. Differentiate between a Logical Error and Syntax Error. Also give suitable examples of each in C++. [2 Marks]
Answer:
1. A syntax error is a violation of the grammar rules of the language. The compiler reports it and the program does not compile. Example: cout << a (semicolon missing).
2. A logical error is a mistake in the logic of the program. The program compiles and runs but gives a wrong result. Example: writing avg = a + b / 2; instead of avg = (a + b) / 2;
Teacher's Note:
a) Syntax errors are found at compile time, logical errors only by testing the output.
b) Logical errors are harder to find than syntax errors.
10. Find the correct identifiers out of the following, which can be used for naming variable, constants or functions in a C++ program:
While, for, Float, new, 2ndName, A%B, Amount2, _Counter [2 Marks]
Answer:
1. Valid identifiers: While, Float, Amount2, _Counter
2. Not valid: for and new are keywords, 2ndName begins with a digit, and A%B contains the character %
Teacher's Note:
a) C++ is case sensitive, so While and Float are different from the keywords while and float.
b) An identifier must begin with a letter or an underscore.
11. Out of the following, find those identifiers, which cannot be used for naming Variable, Constants or Functions in a C++ program:
_Cost, Price*Qty, float, Switch, Address One, Delete, Number12, do [2 Marks]
Answer:
1. Identifiers that cannot be used: Price*Qty (contains *), float (keyword), Address One (contains a space), do (keyword)
2. _Cost, Switch, Delete and Number12 are valid, because Switch and Delete differ from the keywords switch and delete in case
Teacher's Note:
a) Only letters, digits and the underscore are allowed in an identifier.
b) Keywords are in lower case in C++.
12. Find the correct identifiers out of the following, which can be used for naming Variable, Constants or Functions in a C++ program:
For, while, INT, NeW, delete, 1stName, Add+Subtract, name1 [2 Marks]
Answer:
1. Valid identifiers: For, INT, NeW, name1
2. Not valid: while and delete are keywords, 1stName begins with a digit, and Add+Subtract contains the character +
Teacher's Note:
a) For, INT and NeW are valid as they differ from the keywords in case.
b) A name cannot start with a digit.
VERY SHORT ANSWER TYPE QUESTIONS (1-MARK BASED ON HEADER FILES)
1. Which C++ header file(s) will be included to run/execute the following C++ code? [1 Mark]
void main( )
{
int Last = 26.5698742658;
cout << setw(5) << setprecision(9) << Last;
}
Answer: iostream.h, iomanip.h
Teacher's Note:
a) The cout statement needs iostream.h and setw( ) and setprecision( ) need iomanip.h.
b) These are the two header files required.
2. Name the header files that shall be needed for successful compilation of the following C++ code: [1 Mark]
void main()
{
char str[20],str[20];
gets(str);
strcpy(str1,str);
strrev(str);
puts(str);
puts(str1);
}
Answer: stdio.h, string.h
Teacher's Note:
a) gets( ) and puts( ) belong to stdio.h and strcpy( ) and strrev( ) belong to string.h.
b) The declaration char str[20],str[20]; repeats the name str. It should be str[20],str1[20]; for the code to compile.
3. Write the names of the header files to which the following belong:
(i) strcmp() (ii) fabs() [1 Mark]
Answer: (i) strcmp( ): string.h
(ii) fabs( ): math.h
Teacher's Note:
a) strcmp( ) is a string function and fabs( ) is a mathematical function.
b) Match each function to its header file.
4. Write the names of the header files to which the following belong:
(i) frexp() (ii) isalnum() [1 Mark]
Answer: (i) frexp( ): math.h
(ii) isalnum( ): ctype.h
Teacher's Note:
a) frexp( ) splits a number into mantissa and exponent, so it is a mathematical function.
b) isalnum( ) tests a character, so it is in ctype.h.
SHORT ANSWER TYPE QUESTIONS (2-MARKS ERROR FINDING)
1. Rewrite the following program after removing any syntactical errors. Underline each correction made. [2 Marks]
#include<iostream.h>
void main( )
int A[10];
A=[3,2,5,4,7,9,10];
for( p = 0; p<=6; p++)
{ if(A[p]%2=0)
int S = S+A[p]; }
cout<<S;
}
Answer:
1. The declaration void main( ) has no opening brace { before int A[10];
2. The array is assigned with A=[3,2,5,4,7,9,10]; which is wrong. It must be initialized at declaration as int A[10] = {3,2,5,4,7,9,10};
3. The variable p is not declared, and S is declared inside the if body. Declare int S = 0, p; before the loop
4. The test A[p]%2=0 uses assignment. It must be A[p]%2==0
#include<iostream.h>
void main( )
{ int A[10] = {3,2,5,4,7,9,10};
int S = 0, p;
for(p = 0; p<=6; p++)
{ if(A[p]%2==0)
S = S+A[p]; }
cout<<S;
}
Teacher's Note:
a) The corrected program is given below.
b) The program adds the even elements, 2 + 4 + 10, so it prints 16.
2. Deepa has just started working as a programmer in STAR SOFTWARE company. In the company she has got her first assignment to be done using a C++ function to find the smallest number out of a given set of numbers stored in a one-dimensional array. But she has committed some logical mistakes while writing the code and is not getting the desired result. Rewrite the correct code underlining the corrections done. Do not add any additional statements in the corrected code. [2 Marks]
int find(int a[],int n)
{ int s=a[0];
for(int x=1;x<n;x++)
if(a[x]>s)
a[x]=s;
return(s); }
Answer:
1. The comparison if(a[x]>s) finds a larger element. For the smallest number it must be if(a[x]2. The statement a[x]=s; overwrites the array element instead of keeping the smallest. It must be s=a[x];
int find(int a[],int n)
{ int s=a[0];
for(int x=1;x<n;x++)
if(a[x]<s)
s=a[x];
return(s); }
Teacher's Note:
a) Only the condition and the assignment are changed, no statement is added.
b) With the corrections, s holds the smallest element when the loop ends.
3. Rewrite the following program after removing the syntactical errors (if any). Underline each correction. [2 Marks]
#include [iostream.h]
class PAYITNOW
{ int Charge;
PUBLIC:
void Raise(){cin>>Charge;}
void Show{cout<<Charge;}
};
void main()
{
PAYITNOW P;
P.Raise();
Show();
}
Answer:
1. #include [iostream.h] must be #include
2. The keyword is public: in lower case, not PUBLIC:
3. The function header must have brackets: void Show( ) instead of void Show
4. The member function Show( ) must be called with the object: P.Show( ); instead of Show( );
#include <iostream.h>
class PAYITNOW
{ int Charge;
public:
void Raise(){cin>>Charge;}
void Show(){cout<<Charge;}
};
void main()
{
PAYITNOW P;
P.Raise();
P.Show();
}
Teacher's Note:
a) Four corrections are needed in all.
b) A member function is always called through an object and the dot operator.
4. Rewrite the following program after removing the syntactical errors (if any). Underline each correction. [2 Marks]
#include <iostream.h>
struct Pixels
{ int Color,Style;}
void ShowPoint(Pixels P)
{ cout<<P.Color,P.Style<<endl;}
void main()
{
Pixels Point1=(5,3);
ShowPoint(Point1);
Pixels Point2=Point1;
Color.Point1+=2;
ShowPoint(Point2);
}
Answer:
1. A semicolon is missing after the closing brace of the structure: struct Pixels { int Color,Style; };
2. The cout statement must use the insertion operator for both members: cout<
4. The member is accessed as Point1.Color+=2; and not Color.Point1+=2;
#include <iostream.h>
struct Pixels
{ int Color,Style; };
void ShowPoint(Pixels P)
{ cout<<P.Color<<P.Style<<endl; }
void main()
{
Pixels Point1={5,3};
ShowPoint(Point1);
Pixels Point2=Point1;
Point1.Color+=2;
ShowPoint(Point2);
}
Teacher's Note:
a) Four corrections are needed in all.
b) The structure variable comes first, then the dot and the member name.
SHORT ANSWER TYPE QUESTIONS (2-MARKS FINDING OUTPUT)
1. Find output of the following program segment: [2 Marks]
#include<iostream.h>
#include<ctype.h>
void Mycode(char Msg[],char CH)
{ for(int cnt=0;Msg[cnt]!='\0';cnt++)
{ if(Msg[cnt]>='B'&& Msg[cnt]<='G')
Msg[cnt]=tolower(Msg[cnt]);
else
if(Msg[cnt]=='N'||Msg[cnt]=='n'||Msg[cnt]==' ')
Msg[cnt]=CH;
else
if(cnt%2==0)
Msg[cnt]=toupper(Msg[cnt]);
else
Msg[cnt]=Msg[cnt-1]; } }
void main()
{ char MyText[]="Input Raw";
Mycode(MyText,'@');
cout<<"NEW TEXT:"<<MyText<<endl;
}
Answer:
1. Msg = "Input Raw" and CH = @. The letters in the range B to G are changed to lower case, N, n and the space are replaced by CH, other letters at even positions are made upper case, and other letters at odd positions copy the character before them.
2. Positions: I(0) is upper case I, n(1) becomes @, p(2) becomes P, u(3) copies P, t(4) becomes T, space(5) becomes @, R(6) stays R, a(7) copies R, w(8) becomes W
3. The text becomes I@PPT@RRW
NEW TEXT:I@PPT@RRW
Teacher's Note:
a) The if branches are checked in order, so a letter between B and G is handled first.
b) Even positions are tested with cnt%2==0.
2. Find the output of the following C++ program: [2 Marks]
#include<iostream.h>
void repch(char s[])
{
for (int i=0;s[i]!='\0';i++)
{
if(((i%2)!=0) &&(s[i]!=s[i+1]))
{
s[i]='@';
cout<<"Hello";
}
else if (s[i]==s[i+1])
{
s[i+1]='!';
i++;
}
}
}
void main()
{
char str[]="SUCCESS";
cout<<"Original String"<<str
repch(str);
cout<<"Changed String"<<str;
}
Answer:
1. str = "SUCCESS". At i=1: i is odd and s[1]=U differs from s[2]=C, so s[1] becomes @ and Hello is printed
2. At i=2: s[2]=C equals s[3]=C, so s[3] becomes ! and i skips to 4. At i=4: s[4]=E differs from s[5]=S and i is even, so nothing happens
3. At i=5: i is odd but s[5]=S equals s[6]=S, so s[6] becomes ! and i skips on. The string is now S@C!ES!
4. The printed output is Original StringSUCCESSHelloChanged StringS@C!ES!
Original StringSUCCESSHelloChanged StringS@C!ES!
Teacher's Note:
a) The source key leaves out the word Hello, which is printed once when s[1] is changed.
b) The source program also lacks semicolons after two cout statements, which are needed to compile.
3. Find the output of the following program: [2 Marks]
#include <iostream.h>
#include <ctype.h>
void Encrypt(char T[])
{
for (int i=0;T[i]!='\0';i+=2)
if (T[i]=='A' || T[i]=='E') T[i]='#';
else if (islower(T[i])) T[i]=toupper(T[i]);
else T[i]='@';
}
void main()
{
char Text[]="SaVE EArtH";
//The two words in the string Text
//are separated by single space
Encrypt(Text);
cout<<Text<<endl;
}
Answer:
1. Text = "SaVE EArtH", and the loop visits indexes 0, 2, 4, 6, 8.
2. Index 0 S becomes @, index 2 V becomes @, index 4 (the space) becomes @, index 6 A becomes #, index 8 t is lower case so it becomes T
3. The odd positions are not changed, so the string becomes @a@E@E#rTH
@a@E@E#rTH
Teacher's Note:
a) Only every second character is processed because i increases by 2.
b) The comment in the source says the two words are separated by a single space.
4. Find the output of the following program: [2 Marks]
#include <iostream.h>
struct Game
{
char Magic[20];
int Score;
};
void main()
{
Game M={"Tiger",500};
char *Choice;
Choice=M.Magic;
Choice[4]='P';
Choice[2]='L';
M.Score+=50;
cout<<M.Magic<<M.Score<<endl;
Game N=M;
N.Magic[0]='A';N.Magic[3]='J';
N.Score-=120;
cout<<N.Magic<<N.Score<<endl;
}
Answer:
1. M.Magic = "Tiger". Choice points to it, so Choice[4]=P gives TigeP and Choice[2]=L gives TiLeP. M.Score becomes 550
2. The first cout prints TiLeP550
3. N is a copy of M. N.Magic[0]=A and N.Magic[3]=J give AiLJP, and N.Score = 550 - 120 = 430
4. The second cout prints AiLJP430
TiLeP550
AiLJP430
Teacher's Note:
a) The array member is copied when the whole structure is assigned, so M is not changed by the changes to N.
b) The pointer Choice works on the array inside M.
APPLICATION BASED QUESTIONS (3 MARKS FINDING OUTPUT)
1. Find the output of the following: [3 Marks]
#include<iostream.h>
void switchover(int A[ ],int N, int split)
{
for(int K = 0; K<N; K++)
if(K<split)
A[K] += K;
else
A[K]*= K; }
void display(int A[ ] ,int N)
{
for(int K = 0; K<N; K++)
(K%2== 0) ?cout<<A[K]<<"%" : cout<<A[K]<<endl;
}
void main( )
{ int H[ ] = {30,40,50,20,10,5};
switchover(H,6,3);
display(H,6); }
Answer:
1. H = {30,40,50,20,10,5}, N = 6 and split = 3. For K < 3, K is added to the element: 30, 41, 52
2. For K >= 3 the element is multiplied by K: 20 × 3 = 60, 10 × 4 = 40, 5 × 5 = 25
3. display( ) prints an even K with % and an odd K with a new line, so the output is 30%41, 52%60 and 40%25 on three lines
30%41
52%60
40%25
Teacher's Note:
a) The conditional operator chooses the % form for even K and the new line form for odd K.
b) The printed key was checked and is correct.
c) The array after the call is 30, 41, 52, 60, 40, 25.
2. Find the output of the following program: [3 Marks]
#include<iostream.h>
void in(int x,int y, int &z)
{ x+=y;
y--;
z*=(x-y);
}
void out(int z,int y, int &x)
{ x*=y;
y++;
z/=(x+y);
}
void main()
{ int a=20, b=30, c=10;
out(a,c,b);
cout<<a<<"#"<<b<<"#"<<c<<"#"<<endl;
in(b,c,a);
cout<<a<<"@"<<b<<"@"<<c<<"@"<<endl;
out(a,b,c);
cout<<a<<"$"<<b<<"$"<<c<<"$"<<endl; }
Answer:
1. a=20, b=30, c=10. out(a,c,b): z=20, y=10, x is b. x*=y gives b = 30 × 10 = 300. The changes to z and y are lost. Output: 20#300#10#
2. in(b,c,a): x=300, y=10, z is a. x becomes 310, y becomes 9, and a = 20 × (310 - 9) = 6020. Output: 6020@300@10@
3. out(a,b,c): z=6020, y=300, x is c. c = 10 × 300 = 3000. Output: 6020$300$3000$
20#300#10#
6020@300@10@
6020$300$3000$
Teacher's Note:
a) Only the reference parameter keeps its change after the call.
b) The statement y- - in the source is the decrement y--.
3. Find the output of the following program: [3 Marks]
#include <iostream.h>
struct PLAY
{ int Score, Bonus;};
void Calculate(PLAY &P, int N=10)
{
P.Score++;P.Bonus+=N;
}
void main()
{
PLAY PL={10,15};
Calculate(PL,5);
cout<<PL.Score<<":"<<PL.Bonus<<endl;
Calculate(PL);
cout<<PL.Score<<":"<<PL.Bonus<<endl;
Calculate(PL,15);
cout<<PL.Score<<":"<<PL.Bonus<<endl;
}
Answer:
1. PL = {10,15}. Calculate(PL,5): Score = 11, Bonus = 15 + 5 = 20. Output 11:20
2. Calculate(PL) uses the default N = 10: Score = 12, Bonus = 30. Output 12:30
3. Calculate(PL,15): Score = 13, Bonus = 45. Output 13:45
11:20
12:30
13:45
Teacher's Note:
a) The structure is passed by reference, so the changes stay.
b) When no second argument is given, the default value 10 is used.
4. Find the output of the following program: [3 Marks]
#include <iostream.h>
void Changethecontent(int Arr[], int Count)
{
for (int C=1;C<Count;C++)
Arr[C-1]+=Arr[C];
}
void main()
{
int A[]={3,4,5},B[]={10,20,30,40},C[]={900,1200};
Changethecontent(A,3);
Changethecontent(B,4);
Changethecontent(C,2);
for (int L=0;L<3;L++) cout<<A[L]<<'#';
cout<<endl;
for (L=0;L<4;L++) cout<<B[L] <<'#';
cout<<endl;
for (L=0;L<2;L++) cout<<C[L] <<'#';
}
Answer:
1. The function adds each element to the one before it: Arr[C-1] += Arr[C], from left to right.
2. A = {3,4,5}: 3 + 4 = 7, then 4 + 5 = 9, so A = {7,9,5}
3. B = {10,20,30,40}: 30, 50, 70, so B = {30,50,70,40}
4. C = {900,1200}: 2100, so C = {2100,1200} (the third element is not printed because only C[0] and C[1] are)
7#9#5#
30#50#70#40#
2100#1200#
Teacher's Note:
a) In the source, the loop variable L is declared only in the first for loop. This works in old Turbo C++ but needs int L declared once in modern compilers.
b) The last element of each array stays the same.
5. Find the output of the following program: [3 Marks]
#include <iostream.h>
struct GAME
{ int Score, Bonus;};
void Play(GAME &g, int N=10)
{ g.Score++;g.Bonus+=N; }
void main()
{ GAME G={110,50};
Play(G,10);
cout<<G.Score<<":"<<G.Bonus<<endl;
Play(G);
cout<<G.Score<<":"<<G.Bonus<<endl;
Play(G,15);
cout<<G.Score<<":"<<G.Bonus<<endl; }
Answer:
1. G = {110,50}. Play(G,10): Score = 111, Bonus = 60. Output 111:60
2. Play(G) uses the default 10: Score = 112, Bonus = 70. Output 112:70
3. Play(G,15): Score = 113, Bonus = 85. Output 113:85
111:60
112:70
113:85
Teacher's Note:
a) The structure variable is passed by reference.
b) Bonus rises by 10, 10 and 15 from 50 to 85.
APPLICATION BASED QUESTIONS (2 MARKS BASED ON RANDOM FUNCTION)
1. Observe the following C++ code and find out, which out of the given options i) to iv) are the expected correct output. Also assign the maximum and minimum value that can be assigned to the variable Go.
(i) 100$$75 (ii) 75$$10$$125$$ (iii) 75$$10$$ (iv) 10$$125$$ [2 Marks]
void main()
{ int X [4] ={100,75,10,125};
int Go = random(2)+2;
for (int i = Go; i< 4; i++)
cout<<X[i]<<"$$";
}
Answer:
1. random(2) gives 0 or 1, so Go = random(2) + 2 is 2 or 3
2. If Go = 2 the loop prints X[2] and X[3]: 10$$125$$. If Go = 3 it prints X[3] only: 125$$
3. Only option (iv) matches a possible output
4. Minimum value of Go = 2 and maximum value of Go = 3
Teacher's Note:
a) The printed key (iv) is correct.
b) Options (i), (ii) and (iii) cannot occur since the loop starts at index 2 or 3.
2. Write a user defined function DIVT() which takes an integer as parameter and returns whether it is divisible by 13 or not. The function should return 1 if it is divisible by 13, otherwise it should return 0. [2 Marks]
Answer:
1. The function takes an integer n and tests n % 13 == 0.
2. It returns 1 when the remainder is 0 and 0 otherwise.
int DIVT(int n)
{
if (n % 13 == 0)
return 1;
else
return 0;
}
Teacher's Note:
a) The % operator gives the remainder of the division.
b) Example: DIVT(26) returns 1 and DIVT(30) returns 0.
3. In the following program, if the value of N given by the user is 15, what maximum and minimum values the program could possibly display? [2 Marks]
#include <iostream.h>
#include <stdlib.h>
void main()
{
int N,Guessme;
randomize();
cin>>N;
Guessme=random(N)+10;
cout<<Guessme<<endl;
}
Answer:
1. N = 15, so random(15) gives a value from 0 to 14.
2. Guessme = random(15) + 10 therefore ranges from 10 to 24.
3. Minimum value = 10 and maximum value = 24
Teacher's Note:
a) random(N) gives 0 to N-1, then 10 is added.
b) The range is 10 to N + 9.
4. In the following program, if the value of N given by the user is 20, what maximum and minimum values the program could possibly display? [2 Marks]
#include <iostream.h>
#include <stdlib.h>
void main()
{
int N,Guessnum;
randomize();
cin>>N;
Guessnum=random(N-10)+10;
cout<<Guessnum<<endl;
}
Answer:
1. N = 20, so random(N-10) = random(10) gives a value from 0 to 9.
2. Guessnum = random(10) + 10 therefore ranges from 10 to 19.
3. Minimum value = 10 and maximum value = 19
Teacher's Note:
a) Evaluate N-10 first, which is 10.
b) The highest value is 9 + 10 = 19.
5. Read the following C++ code carefully and find out, which out of the given options (i) to (iv) are the expected correct output(s) of it. Also, write the maximum and minimum value that can be assigned to the variable Taker used in the code:
(i) 100# (ii) 50#200# (iii) 100#50#200# (iv) 100#50 [2 Marks]
void main()
{
int GuessMe[4]={100,50,200,20};
int Taker=random(2)+2;
for (int Chance=0;Chance<Taker;Chance++)
cout<<GuessMe[Chance]<<"#";
}
Answer:
1. random(2) gives 0 or 1, so Taker = random(2) + 2 is 2 or 3
2. The loop prints the first Taker elements, each followed by #. If Taker = 2 the output is 100#50#, and if Taker = 3 it is 100#50#200#
3. Option (iii) matches. Options (i) and (ii) cannot start that way, and option (iv) lacks the final #
4. Minimum value of Taker = 2 and maximum value of Taker = 3
Teacher's Note:
a) Always check the # that follows each element.
b) Option (iii) is the only possible output as printed; 100#50# would be correct but is not listed.
Free study material for Computer Science
Computer Science Class 12 Exam Resources: Objective Oriented Programming in C++
Comprehensive Study Resources for Objective Oriented Programming in C++
Review targeted study resources for Objective Oriented Programming in C++ tailored for Class 12 learners. Utilizing these structured notes and quick-revision tools ensures complete alignment with current CBSE evaluation standards.
Understanding Marking Schemes
Built using official NCERT guidelines for Class 12 Computer Science, these materials provide reliable academic support. Integrating past examination questions and step-by-step solutions helps students understand official CBSE grading criteria.
Complete Revision for Computer Science
Wrap up your chapter revision by testing your knowledge against standard objective question formats. Explore our full library of free, up-to-date sample papers and online assessments to secure top grades in your CBSE examinations.
FAQs
Our advanced study package for Objective Oriented Programming in C++ includes detailed concepts, diagrams, Mind Maps, and explanation of complex topics to ensure Class 12 students learn as per syllabus for 2026 exams.
The Mind Maps provided for Objective Oriented Programming in C++ act as visual anchors which will help faster recall during high-pressure exams.
Yes, teachers use our Class 12 Computer Science resources for lesson planning as they are in simple language and have lot of solved examples.
Yes, You can download the complete, mobile-friendly PDF of the Computer Science Objective Oriented Programming in C++ advanced resources for free.
Yes, our subject matter experts have updated the Objective Oriented Programming in C++ material to align with the rationalized NCERT textbooks and have removed deleted topics and added new competency-based questions.