Chapter-wise Worksheets for Class 12 Computer Science: Pointer
Access comprehensive chapter-wise worksheets for Pointer using the CBSE Class 12 Computer Science Pointer Worksheet. Designed to align with the 2026-27 academic syllabus for Class 12 Computer Science, these printable practice sets help students reinforce key concepts and improve their overall exam readiness.
Practice Class 12 Computer Science Worksheets: Pointer
Navigate directly to the solved Computer Science worksheets using the digital viewer below. Each practice set includes detailed step-by-step solutions, allowing students to instantly cross-check their work and identify areas requiring further revision.
POINTERS Pointers :
- Pointer is a variable that holds a memory address of another variable.
- It supports dynamic allocation routines.
- It can improve the efficiency of certain routines. C++ Memory Map :
- Program Code : It holds the compiled code of the program.
- Global Variables : They remain in the memory as long as program continues.
- Stack : It is used for holding return addresses at function calls, arguments passed to the functions, local variables for functions. It also stores the current state of the CPU.
- Heap : It is a region of free memory from which chunks of memory are allocated via DMA functions.
Static Memory Allocation : The amount of memory to be allocated is known in advance and it allocated during compilation, it is referred to as Static Memory Allocation.
Eg. Int a; // This will allocate 2 bytes for a during compilation. Dynamic Memory Allocation : The amount of memory to be allocated is not known beforehand rather it is required to allocated as and when required during runtime, it is referred to as dynamic memory allocation.
C++ offers two operator for DMA – new and delete
Q) Find the output of the following program:
#include<iostream.h>
void main()
{ int Array[]={4,6,10,12};
int *pointer=Array;
for(int I=1;I<=3;I++)
{ cout<<*pointer<<”#”;
pointer++;
}
cout<<endl;
for(I=1;I<=4;I++)
{ (*pointer)*=3;
--pointer;
}
for(I=1;I<5;I++)
cout<<Array[I-1]<<”@”;
cout<<endl;
}
Q) Find the output of the following program:
#include<iostream.h>
void main( )
{ int Numbers[]={2,4,8,10};
int *ptr=Numbers;
for(int C=1;C<3;C++)
{ cout<<*ptr<<”@”;
ptr++;
}
cout<<endl;
for(C=0;C<4;C++)
{ (*ptr)*=2;
--ptr;
}
for(C=0;C<4;C++)
cout<<Numbers[C]<<”#”;
cout<<endl; }
Q) Find the output of the following program:
#include<iostream.h>
#include<string.h>
class state
{ char *state_name;
int size;
public:
state( )
{ size=0;
state_name=new char[size+1];
}
state(char *s)
{ size=strlen(s);
state_name=new char[size+1];
strcpy(state_name,s);
}
void display( )
{ cout<<state_name<<endl;
}
void Replace(state &a, state &b)
{ size=a.size+b.size;
delete state_name;
state_name=new char[size+1];
strcpy(state_name,a.state_name);
strcat(state_name,b.state_name);
}
};
void main( )
{ char *temp=”Delhi”;
state
state1(temp),state2(“Mumbai”),state3(“Nagpur”),S1,S2;
S1.Replace(state1,state2);
S2.Replace(S1,state3);
S1.display( );
S2.display( );}
Q) Find the output of the following program:
#include<iostream.h>
#include<string.h>
class student
{ char *name;
int I;
public:
student( )
{ I=0;
name=new char[I+1];
}
student(char *s) { I=strlen(s);
name=new char[I+1];
strcpy(name,s); }
void display( )
{ cout<<name<<endl; }
void manipulate(student &a, student &b)
{
I=a.I+b.I;
delete name;
name=new char[I+1];
strcpy(name,a.name);
strcat(name,b.name);
}
};
void main( )
{ char *temp=”Jack”;
Student name1(temp),name2(“Jill”),name3 (“John”) ,S1,S2;
S1.manipulate(name1,name2);
S2.manipulate(S1,name3);
S1.display( );S2.display( ); }
Q) What is “this” pointer? Give an example to illustrate the use of it in C++.
Answer: A special pointer known as this pointer stores the address of the object that is currently invoking a member function. The this pointer is implicitly passed to the member functions of a class whenever they are invoked. (As soon as you define a class, the member functions are created and placed in the memory space only once.
That is, only one copy of member functions is maintained that is shared by all the objects of the class. Only space for data members is allocated separately for each object.When a member function is called, it is automatically passed an implicit(in built) argument that is a pointer to the object that invoked the function. This pointer is called this. If an object is invoking a member function, then an implicit argument is passed to that member function that points to (that) object. The programmer also can explicitly specify ‘this’ in the program if he desires.)
Eg: Example program to demonstrate the usage of this pointer.
#include<iostream.h>
#include<conio.h>
class Rectangle
{ float area,len,bre;
public:
void input( )
{ cout<<"\nEnter the length and breadth: ";
cin>>this->len>>this->bre;
}
void calculate( )
{ area=len*bre;
//Here Implicit 'this' pointer will be worked.
}
void output( )
{
cout<<"\nThe Area of the Rectangle: "<<this->area;
}
};
void main( )
{
Rectangle R;
clrscr( );
R.input( );
R.calculate( );
R.output( );
getch();
}
Q) What will be the output of the following program:
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void ChangeString(char Text[],int&Counter)
{ char *Ptr=Text;
int Length=strlen(Text);
for(;Counter<Length- 2;
Counter+=2,Ptr++)
{
*(Ptr+Counter)=toupper(*(Ptr+Counter));
}
}
void main( )
{ clrscr( );
int Position=0;
char Message[]=”Pointers Fun”;
ChangeString(Message,Position);
cout<<Message<<”@”<<Position;
}
Q) Identify the syntax error(s), if any, in the following program. Also give reason for errors.
Void main()
{const int i=20;
const int* const ptr=&i;
(*ptr)++;
int j=15;
ptr=&j;
}
Answer:
Error Line 5 : Cannot modify a const object.
Error Line 7 : Cannot modify a const object.Warning Line 8 : ‘j’ is assigned a value that is never used.Warning Line 8 : ‘ptr’ is assigned a value that is never used.
Explonation:
(1) Error 1 is in Line no.5 ie (*ptr)++. Here ptr is a constant pointer ie the contents cann’t be modified.
(2) Error 2 is in Line no.7 ie ptr=&j;.Here ptr is a constant pointer the address in this pointer can’t be modified. (It is already pointing the address of i.)
Q) Give the output of the following program segment. (Assuming all required header files are included in the program).
void main( )
{ int a=32,*x=&a;
char ch=65,&cho=ch;
cho+=a;
*x+=ch;
cout<<a<<’,’<<ch<<endl; }
Q) Distinguish between
int *ptr=new int(5);
int *ptr=new int[5];
Answer: The int *ptr=new int(5); declares and creates the space for the new data directly.Ie The new operator reserves 2 bytes of memory from heap memory (free pool) and returns the address of that memory location to a pointer variable called ptr, 5 is the initial value to be stored in the newly allocated memory.
The int *ptr = new int[5]; initializes an array element. A memory space for an integer type of array having 5 elements will be created from the heap memory (free pool).
Q) Give the output of the following program:
#include<iostream.h> #include<string.h>
class per
{ char name[20];
float salary;
public:
per(char *s, float a)
{ strcpy(name,s);
salary=a;
}
per *GR(per &x)
{ if(x.salary>=salary)
return &x;
else
return this;
}
void display( )
{ cout<<”Name:“<<name<<”\n”;
cout<<”Salary:“<<salary<<”\n”;
}
};
void main( )
{ Per P1(“REEMA”,10000),
P2(“KRISHNAN”,20000),
P3(“GEORGE”,5000);
per *P;
P=P1.GR(P3);P->display( );
P=P2.GR(P3);P->display( ); }
Q) Give the output of the following program.
#include<stdio.h>
void main( )
{ char *p=”Difficult”;
char c; c=*p++; cout<<c;
}
Pointers:
- Pointer is a variable that holds a memory address of another variable.
- It supports dynamic allocation routines.
- It can improve the efficiency of certain routines.
C++ Memory Map:
- Program Code: It holds the compiled code of the program.
- Global Variables: They remain in the memory as long as program continues.
- Stack: It is used for holding return addresses at function calls, arguments passed to the functions, and local variables for functions. It also stores the current state of the CPU.
- Heap: It is a region of free memory from which chunks of memory are allocated via DMA functions.
Static Memory Allocation: The amount of memory to be allocated is known in advance and it is allocated during compilation. This is referred to as Static Memory Allocation.
Example: `int a;` // This will allocate 2 bytes for a during compilation.
Dynamic Memory Allocation: The amount of memory to be allocated is not known beforehand; rather, it is allocated as and when required during runtime. This is referred to as Dynamic Memory Allocation.
C++ offers two operators for DMA - new and delete.
Free Store: It is a pool of unallocated heap memory given to a program that is used by the program for dynamic memory allocation during execution.
Declaration and Initialization of Pointers:
Syntax: `Datatype *variable_name;`
Example: `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.
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.
Example: `int *p; p++;`
If the current address of `p` is 1000, then `p++` statement will increase `p` to 1002, not 1001.
If `*c` is a char pointer and `*p` is an integer pointer, the pointer scaling works as follows:
| Char pointer | C | c + 1 | c + 2 | c + 3 | c + 4 | c + 5 | c + 6 | c + 7 |
|---|---|---|---|---|---|---|---|---|
| Address | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 |
| Int pointer | p | p + 1 | p + 2 | p + 3 | ||||
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 byte of the memory location where it is pointing. The address of this first byte is known as the BASE ADDRESS.
Dynamic Allocation Operators:
C++ dynamic allocation routines obtain memory for allocation from the free store, the pool of unallocated heap memory provided to the program. C++ defines two unary operators `new` and `delete` that perform the task of allocating and freeing memory during runtime. The operators `new` and `delete` are also called free store operators.
Creating a Dynamic Array:
Syntax: `pointer-variable = new data-type [size];`
Example: `int *array = new int[10];`
`array[0]` will refer to the first element of the array, and `array[1]` will refer to the second element. No initializers can be specified for dynamically allocated arrays.
All array sizes must be supplied when `new` is used for array creation.
Two-Dimension Array:
```cpp int *arr, r, c; r = 5; c = 5; arr = new int[r * c]; // Now to read the elements of the array, you can use the following loops: for (int i = 0; i < r; i++) { cout << "\n Enter element in row " << i + 1 << " : "; for (int j = 0; j < c; j++) { cin >> arr[i * c + j]; } } ```
Memory Released with delete:
| Syntax for simple variable: | For array: |
|---|---|
| `delete pointer-variable;` Example: `delete p;` | `delete [] pointer-variable;` Example: `delete [] arr;` |
Pointers and Arrays:
C++ treats the name of an array as if it were a pointer, i.e., the memory address of the first element. C++ interprets an array name as the address of its first element.
That is, if `marks` is an int array to hold 10 integers, then `marks` stores the address of `marks[0]`, the first element of the array. The array name `marks` is a pointer to an integer which is the first element of the array `marks[10]`.
```cpp void main() { int *m; int marks[10]; cout << "\n Enter marks :"; for (int i = 0; i < 10; i++) { cin >> marks[i]; } m = marks; cout << "\n m points to " << *m; cout << "\n Marks points to " << *marks; } ```
The name of an array is actually a pointer pointing to the first element of the array.
Since the name of an array is a pointer to its first element, `array + 1` gives the address of the second element, `array + 2` gives the address of the third element, and so on.
Thus, to print the fourth element of array `marks`, we can write either of the following:
`cout << marks[3];` OR `cout << *(marks + 3);`
Array of Pointers:
To declare an array holding 10 integer pointers:
`int *ip[10];`
This allocates memory for 10 pointers that can point to integers.
Now each of the pointers, the elements of the pointer array, may be initialized. To assign the address of an integer variable `phy` to the fourth element of the pointer array, we write:
`ip[3] = &phy;`
Now, with `*ip[3]`, we can access the value of `phy`.
Example: `int *ip[5];` with addresses assigned as follows:
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Address | 1000 | 1002 | 1004 | 1006 | 1008 |
`int a = 12, b = 23, c = 34, d = 45, e = 56;` with memory addresses:
| Variable | a | b | c | d | e |
|---|---|---|---|---|---|
| Value | 12 | 23 | 34 | 45 | 56 |
| Address | 1050 | 1065 | 2001 | 2450 | 2725 |
`ip[0] = &a; ip[1] = &b; ip[2] = &c; ip[3] = &d; ip[4] = &e;`
| Index | ip[0] | ip[1] | ip[2] | ip[3] | ip[4] |
|---|---|---|---|---|---|
| Array ip value | 1050 | 1065 | 2001 | 2450 | 2725 |
| Address | 1000 | 1002 | 1004 | 1006 | 1008 |
`ip` is now a pointer pointing to its first element of `ip`. Thus, `ip` is equal to the address of `ip[0]`, i.e., 1000.
- `*ip` (the value of `ip[0]`) = 1050
- `*(*ip)` = the value of `*ip` = 12
- `**(ip + 3)` = `**(1006)` = `*(2450)` = 45
Pointers and Strings:
Pointers are highly effective for managing character arrays as well.
Example:
```cpp char name[] = "computer"; char *cp; for (cp = name; *cp != '\0'; cp++) { cout << "--" << *cp; } ```
Output: `--c--o--m--p--u--t--e--r`
An array of character pointers is useful for saving strings in memory.
`char *subject[] = { "Chemistry", "Physics", "Maths", "CS", "English" };`
In this declaration, `subject[]` is an array of character pointers where each element pointer holds the base address of its respective string. That is, `subject[0]` stores the starting address of "Chemistry", `subject[1]` stores the starting address of "Physics", and so forth.
An array of pointers optimizes memory usage because it consumes fewer bytes overall to store strings of variable sizes. Furthermore, manipulating strings becomes much faster and simpler; you can swap string positions by modifying pointer values without moving the actual characters in memory.
Pointers and CONST:
A constant pointer means that the pointer will always point to the same memory location; its target address cannot be modified.
A pointer to a constant refers to a pointer pointing to a value that is treated as a symbolic constant and cannot be altered through that pointer.
```cpp int m = 20; // integer m declaration int *p = &m; // pointer p pointing to integer m ++(*p); // OK: increments the value pointed to by p int * const c = &n; // a const pointer c pointing to integer n ++(*c); // OK: increments the value pointed to by c ++c; // WRONG: c is a const pointer - address cannot be modified const int cn = 10; // a const integer cn const int *pc = &cn; // a pointer pointing to a const integer ++(*pc); // WRONG: pc points to const - contents cannot be modified ++pc; // OK: pc is not const - pointer address can be incremented const int * const cc = &k;// a const pointer pointing to a const integer ++(*cc); // WRONG: value pointed to is const ++cc; // WRONG: cc is a const pointer ```
Pointers and Functions:
A function may be invoked in one of two ways:
- Call by Value
- Call by Reference
The call by reference method can be implemented in two ways:
- By passing references
- By passing pointers
A reference is an alias name for an existing variable.
```cpp int m = 23; int &n = m; int *p; p = &m; ```
The value of `m` (i.e., 23) can be accessed and printed in three different ways:
- `cout << m;` // using variable name
- `cout << n;` // using reference alias
- `cout << *p;` // dereferencing the pointer
Invoking Function by Passing the References:
When arguments are passed to a function by reference, the formal parameters in the function definition become aliases to the actual variables in the calling environment. This means the called function does not allocate separate memory for copies of these values; instead, it directly references the original variables.
```cpp #include
Output:
Value of a : 5 and b : 6
After swapping value of a : 6 and b : 5
Invoking Function by Passing the Pointers:
When pointers are passed to a function, the memory addresses of the actual arguments are copied into the pointer parameters of the function. By dereferencing these pointers, the function can directly modify the values of the actual arguments from the calling program.
```cpp #include Output: Function returning Pointers: Just as a function can return an int or a float, it can also return a pointer. The general prototype format is: `Type * function-name (argument list);` Dynamic Structures: The `new` operator can be used to dynamically allocate memory for user-defined structures as well. Syntax: `struct-pointer = new struct-type;` Example: A dynamic structure can be released using the deallocation operator `delete`: `delete stu;` Objects as Function Arguments: Objects are passed to functions in the exact same manner as primitive variables. When objects are passed by value, the called function creates a local copy of the passed object. This copies the contents of the object and invokes its copy constructor. When the function terminates, the local copy is destroyed, which triggers its destructor. If you want the function to operate directly on the original object to avoid the performance cost of copying and destroying it, you should pass the object by reference. The function then accesses the original object directly via its alias. Similarly, object pointers can be declared by placing `*` before the pointer's variable name. Syntax: `Class-name * object-pointer;` Example: `Student *stu;` Members of a class are accessed using the arrow operator (`->`) when working with an object pointer. When an object pointer points to the first element of an array of objects, incrementing the pointer shifts its target to the subsequent object in sequence. You can also declare pointers that point directly to data members of an object. Keep two rules in mind: this Pointer: In a class, member functions are created and stored in memory only once. That means a single copy of a member function is shared by all active instances of the class. If only one instance of a member function exists in memory, how does it determine which specific object's data members it needs to manipulate? To solve this, C++ uses an implicit argument named `this`. When a member function is invoked, C++ automatically passes a hidden pointer pointing directly to the object that initiated the call. This pointer is called the `this` pointer. For example, if `object3` invokes `memberFunction2()`, an implicit `this` pointer pointing to `object3` is automatically passed to the function so it knows to modify `object3`'s data members. Friend functions are not members of the class, so they do not receive a `this` pointer. Static member functions also do not possess a `this` pointer. Summary: Solved Questions Question 1. How is *p different from **p ? Exam Tip: Use double pointers (`**`) when you need to dynamically allocate or modify two-dimensional arrays or when passing pointer addresses to functions. Question 2. How is &p different from *p ? Exam Tip: Do not confuse the address of a pointer (`&p`) with the address stored *inside* the pointer (`p`). They are different memory locations. Question 3. Find the error in following code segment : Exam Tip: Always match the pointer levels on both sides of an assignment operator during compilation. A pointer of level N can only store addresses of variables of level N-1. Question 4. What will be the output of the following code segment ? Exam Tip: Be careful to distinguish between pointer assignments (`i = j`) and value assignments using dereferencing (`*i = *j`). The latter modifies the actual values in memory. Question 5. How does C++ organize memory when a program is run ? Exam Tip: Clearly list all four memory segments with brief descriptions to secure full marks on memory management questions. Question 6. Identify and explain the error(s) in the following code segment : Exam Tip: Remember that valid pointer arithmetic is limited to: pointer + integer, pointer - integer, pointer++, pointer--, and pointer - pointer. Question 13. How does the functioning of a function differ when (i) an object is passed by value ? (ii) an object is passed by reference ? Exam Tip: Emphasize the call of the copy constructor and destructor for "pass by value", and their complete absence in "pass by reference", to write a high-scoring answer. Unsolved Questions Question 1. Differentiate between static and dynamic allocation of memory. Exam Tip: Providing a comparison table is the most structured way to present differences and secure maximum marks. Question 2. Identify and explain the error in the following program : Exam Tip: Remember that array names are constant pointers. You can perform addition like `*(x + i)` but you cannot perform assignment modifications like `x++` or `x = ptr`. Question 3. Give the output of the following : Exam Tip: Trace loop index bounds carefully. Here, the outer loop runs from length - 1 down to 0, matching the indices of the string exactly. Question 4. Identify the syntax error(s), if any, in the following program. Also give reason for errors. Exam Tip: Remember the double-const rule: `const int * const ptr` means both the pointer's destination and the data inside that destination are read-only. Question 5. What is ‘this’ pointer ? What is its significance ? Exam Tip: Highlight that static member functions and friend functions do not have access to the `this` pointer because they are not bound to a specific class instance. Question 6. Are pointers really faster than array ? How much do function calls slow things down ? Is ++i faster than i = i + 1 ? Exam Tip: Explain the underlying assembly compilation concepts (like address offsets and compiler optimization) to show a deep technical understanding of performance questions. Question 7. What will be the output of following program ? Exam Tip: C-style arrays cannot be compared using relational operators like `==` or `!=`. Relational operators compare pointer addresses, not string contents. Question 8. Write a function that takes two string arguments and returns a string which is the larger of the two. The larger string has larger ASCII value. Also show how this function will be invoked. Exam Tip: Return `const char*` when returning string literals or constant arrays to follow modern C++ type safety rules. Question 9. Give and explain the output of the following code : Exam Tip: Clearly differentiate between call-by-value and call-by-pointer to show how modifications do or do not persist outside a function scope. Question 10. Give the output of the following program : Exam Tip: Post-increment pointer dereferencing `*ptr++` returns the current pointed-to value first, and then advances the pointer to the next element address. High Order Thinking Skills (HOTS) Question 1. What is wrong with the following while loops ( ans how does the correct ones look like): Exam Tip: Always look for loop terminal conditions and proper block scoping with curly braces when diagnosing while loop issues. Question 2. Write a c++ function that converts a 2-digit octal number into binary number and prints the binary equivalent. Exam Tip: An octal digit maps directly to 3 binary bits. A 2-digit octal number will always produce a 6-bit binary output. Question 3. How we can use arrays as arguments? Explain with example Exam Tip: When passing multi-dimensional arrays, all dimensions except the first one must be explicitly specified in the function parameter definition. Question 4. Write a program that the roll numbers, marks in English, Computers, Maths out of 100 for 50 students (i.e. need no read them) Exam Tip: Be careful with comparison logic when tracking the top two values; always cascade updates from the first topper to the second topper. Question 5. What do you think about polymorphism and how you can explain for effective coding as a part of Object Oriented Language? Exam Tip: Classify polymorphism into compile-time (overloading) and runtime (overriding/virtual functions) to write a complete and well-rounded answer. Question 6. How we can overload binary operator?. Expalin with example. Exam Tip: Remember that binary operator member functions accept exactly one parameter, representing the right-hand operand, while the left-hand operand is implicit via the `this` pointer. Question 7. How we can overload constructor?. explain with example. Exam Tip: Ensure that your overloaded constructors differ in parameter count or parameter data types to prevent ambiguity errors during compilation. Question 8. Find the errors in the following program. State reasons: Exam Tip: Private data members of a base class are never directly accessible inside derived classes. Protected members are accessible within derived classes but inaccessible using object instances in main. Question 9. What will be the output of the following: Exam Tip: Pay close attention to pre-operators (`++v1`, `--v2`) which change the value before evaluation, and post-operators (`v2--`, `v1++`) which change it afterwards. Question 10. Write a program that reads a string and counts the number of vowels, words and blank spaces present in the string. Exam Tip: Using `getline(cin, str)` is essential to capture the entire string with space delimiters, as standard `cin` stops reading at the first space. Question 11. Identify the errors in the following code segment: Exam Tip: Keep list of key reserved words like `auto`, `break`, `switch`, `case`, `default` in mind; they can never be declared as custom variable identifiers. Question 12. Name the header file for using in built functions in the program Exam Tip: Be sure to write standard library names accurately. This is a very common 1-mark or 2-mark question in board exams. Question 13. Write a program to generate a function with parameters and array in function e.g. show is function name then show(int[ ],int); Exam Tip: When defining functions that accept arrays, always include an additional parameter representing the size of the array to control loop limits safely. Question 14. What will be the output of following code fragment ? Exam Tip: Trace pointer levels carefully. Each dereferencing asterisk (`*`) peels away one pointer level to eventually yield the raw variable value. Question 15. What is the relationship between an array and a pointer ? Given below a function to traverse a character array using For-loop. Use a pointer in place of an index X and substitute for-loop with while-loop so that the output of the function stringlength() remains the same. Exam Tip: In C++, array parameters in function definitions can be written as `char s[]` or `char *s` interchangeably, as both represent a pointer to the base address. Question 16. Give the output of the following program segment : (assuming all required header files are included in the program) Exam Tip: Be sure to step through nested if-else statements carefully. Trace each index value separately on your rough sheets during exams. Question 17. What do you under by memory leaks ? What are the possible reasons for it ? How can memory leaks be avoided ? Exam Tip: Clearly list both the definition, potential causes, and prevention methods to write a structured, maximum-score answer. Question 18. Predict and explain the output of the following program : Exam Tip: Remember that dereferencing the address of a variable `*(&x)` is mathematically equivalent to accessing the variable `x` directly. Question 19. Give the output following program : Exam Tip: Be sure to track the scope resolution operator `::` carefully. It bypasses any local variables to access the global instance directly.
Value of a : 5 and b : 6
After swapping value of a : 6 and b : 5
Answer: `*p` is a single-level pointer that directly stores the memory address of a standard data variable (such as an integer). On the other hand, `**p` is a double pointer (pointer-to-pointer) that stores the memory address of another pointer variable, which in turn points to the actual data variable.
In simple words: `*p` points to a normal variable, whereas `**p` points to another pointer that points to a normal variable.
Answer: The address-of operator `&p` retrieves the unique physical memory address of the pointer variable `p` itself. Conversely, the dereference operator `*p` retrieves the data value currently stored at the memory location that pointer `p` is pointing to.
In simple words: `&p` tells us where the pointer itself is located in memory, while `*p` retrieves the actual value that the pointer is looking at.
Float **p1, p2;
P2 = &p1;
Answer: There are two syntax errors in this code segment:
1. The keyword `Float` is capitalized; it must be written in lowercase as `float`.
2. The variable `p1` is declared as a double pointer (`float **`), meaning its address `&p1` has the type `float ***`. However, `p2` is declared as a standard floating-point variable (`float`), not a pointer. Thus, the assignment `p2 = &p1;` is invalid because you cannot assign a pointer address to a non-pointer variable.
To fix this, `p2` must be declared as a triple pointer: `float ***p2;` or `p1` should be declared as a single pointer if `p2` is a pointer.
In simple words: The program tries to assign the memory address of a pointer to a normal decimal number variable, which is illegal in C++.
char C1 = 'A';
char C2 = 'D';
char *i, *j;
i = &C1;
j = &C2;
*i = *j;
cout << C1;
Answer: The output of this code segment will be:
**D**
Explanation:
The pointer `i` is initialized with the address of `C1` ('A') and pointer `j` is initialized with the address of `C2` ('D'). The statement `*i = *j;` copies the value pointed to by `j` ('D') into the memory location pointed to by `i` (which is `C1`). Consequently, the value of `C1` changes from 'A' to 'D'. Printing `C1` outputs 'D'.
In simple words: By using pointers, we copy the letter 'D' from variable C2 into variable C1. When we print C1, it displays 'D'.
Answer: When a C++ program is executed, the system organizes the program's memory into four primary, logically distinct regions:
1. **Code Area (Text Segment):** Stores the compiled binary instruction code of the program.
2. **Data Area:** Allocates space for global and static variables, which remain in memory throughout the program's lifecycle.
3. **Stack Segment:** Dynamically manages function calls, local variables, parameters, and function return addresses in a Last-In, First-Out (LIFO) order.
4. **Heap (Free Store):** A pool of unused memory reserved for dynamic memory allocation during program execution using the `new` and `delete` operators.
In simple words: C++ divides memory into four folders: one for the code itself, one for global data, one for tracking current function calls, and one free pool for creating variables on the fly.
float a[] = { 11.02, 12.13, 19.11, 17.41};
float *j, *k;
j = a;
k = a + 4;
j = j * 2;
k = k / 2;
cout << “ *j = “ << *j << “, *k = “ << *k << “\n”;
Answer: The syntax errors are in the following two lines:
`j = j * 2;`
`k = k / 2;`
Reason:
In C++, arithmetic multiplication (`*`) and division (`/`) operations are mathematically invalid on pointer variables. Pointers store memory addresses, and multiplying or dividing an address does not map to any logical memory configuration. Only addition and subtraction of integers (for address offset calculations) and pointer subtraction are allowed.
In simple words: The program tries to multiply and divide memory addresses, which C++ does not allow. You can only add or subtract numbers from pointers.
Answer: The behavior differs in the following ways:
(i) **Passed by Value:** When an object is passed by value, the function creates a local copy of that object in the stack. This process invokes the object's copy constructor. Any changes made to the object inside the function affect only the local copy, not the original object. When the function returns, the copy is destroyed, invoking the object's destructor.
(ii) **Passed by Reference:** When passed by reference, no local copy of the object is created. Instead, the function directly references the original object using its alias. Since no copy is made, neither the copy constructor nor the destructor is called. Any modifications performed inside the function will directly alter the original object.
In simple words: Passing by value makes a temporary copy of the object, which slows things down and uses constructors/destructors. Passing by reference works directly on the original object without copying.
Answer: The key differences are summarized below:Feature Static Memory Allocation Dynamic Memory Allocation Allocation Time Allocated during compilation. Allocated during execution (runtime). Memory Region Handled in Stack or Data segments. Handled in the Heap (Free Store). Size Flexibility Fixed size; cannot be changed during execution. Flexible size; can be expanded or shrunk as needed. Operators / Keywords No special operators; declared using variable declarations. Uses `new` and `delete` operators in C++. Deallocation Automatically managed when variable goes out of scope. Must be manually freed by the programmer.
#include<iostream.h>
int main()
{
int x[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
cout << *x;
x++;
}
return 0;
}
Answer: The syntax error is in the line:
`x++;`
Explanation:
The array name `x` acts as a constant pointer (`int * const`) pointing to the base address of the array (`&x[0]`). Because it is a constant pointer, its value (the address it points to) cannot be modified. Thus, performing the increment operation `x++` is illegal.
Correction:
To fix this, assign the array's base address to a standard pointer variable and increment that pointer instead: ```cpp #include
In simple words: An array's name is a fixed starting address that cannot be changed. The program tries to move this starting address using x++, which C++ does not allow.
char *s = “computer”;
for (int x = strlen(s) – 1; x >= 0; x--)
{
for(int y =0; y <= x; y++) cout << s[y];
cout << endl;
}
Answer: The output of this program segment is:
**computer**
**compute**
**comput**
**compu**
**comp**
**com**
**co**
**c**
Tracing Steps:
- `s` points to "computer" which has a length of 8. The outer loop starts with index `x = 7` and runs down to `0`.
- In each iteration, the inner loop prints characters from index `0` up to `x`.
- When `x = 7`: prints index 0 to 7 ("computer").
- When `x = 6`: prints index 0 to 6 ("compute").
- This pattern continues until `x = 0`, which prints index 0 ("c").
In simple words: This code prints the word "computer" repeatedly, cutting off the last letter in each step until only the first letter "c" remains.
void main()
{
const int i = 20;
const int * const ptr = &i;
(*ptr++;
int j= 15;
ptr = &j; }
Answer: The syntax errors in this program segment are:
1. **Syntax Error in line 5:** `(*ptr++;` contains an unmatched opening parenthesis `(`. This is a basic compiler parsing error.
2. **Logical / Type Error in line 5:** Even if written as `(*ptr)++;` or `*ptr++;`, it is illegal. `ptr` is defined as a pointer to a constant integer (`const int *`). Therefore, the value stored at the address (`*ptr`) is constant and cannot be modified or incremented.
3. **Error in line 7:** `ptr = &j;` is illegal because `ptr` is declared as a constant pointer (`* const ptr`). A constant pointer's address is fixed at initialization and cannot be reassigned to point to another variable like `j`.
In simple words: The pointer is declared as a double constant, meaning both the address it holds and the value it points to cannot be changed. The program tries to modify both, causing compilation errors.
Answer: The `this` pointer is an implicit, hidden pointer passed automatically to all non-static member functions of a class. It holds the memory address of the specific object that invoked the member function.
Significance:
- **Uniquely Identifies Calling Object:** It helps the shared member function distinguish which object's data members need to be accessed or modified.
- **Resolves Name Conflicts:** It helps distinguish class data members from local parameters when they share the identical name (e.g., `this->x = x;`).
- **Returns Object Reference:** It is used to return the invoking object itself from a member function (e.g., `return *this;`).
In simple words: The `this` pointer is a hidden tool in C++ that points to the object currently running a function, ensuring the program modifies the correct object's variables.
Answer:
- **Pointers vs. Arrays:** Yes, pointers can be slightly faster. Array subscript access (e.g., `arr[i]`) requires calculating the address at runtime by multiplying the index `i` by the element size and adding it to the base address. A pointer can be incremented directly (e.g., `ptr++`), avoiding this multiplication step.
- **Function Call Overhead:** Function calls introduce overhead because the CPU must push registers, arguments, and the return address onto the stack, and then jump to the code block. While this slows execution down slightly, modern compilers minimize this overhead using function inlining.
- **++i vs. i = i + 1:** For primitive integers, modern compiler optimization makes both operations equally fast as they compile to the identical machine instruction. However, for user-defined object iterators, `++i` (pre-increment) is faster because it does not create a temporary object copy, unlike post-increment or complex assignments.
In simple words: Pointers can bypass some arithmetic steps needed for arrays, making them a bit faster. Function calls have a tiny stack speed cost. For standard numbers, ++i and i = i + 1 are equally fast.
#include<iostream.h>
void main()
{
char name1[] = “ankur”;
char name2[] = “ankur”;
if (name1 != name2)
cout << “\n both the strings are not equal”;
else
cout << “\n the strings are equal”; }
Answer: The output of this program is:
**both the strings are not equal**
Reason:
The array names `name1` and `name2` represent the starting memory addresses of two separate arrays in the stack. Even though both arrays contain the identical string characters ("ankur"), their memory addresses are different. The conditional statement `if (name1 != name2)` compares these two memory addresses, not the string values. Since the addresses are unique, the condition evaluates to true.
To compare C-style string values, the standard `strcmp(name1, name2)` function should be used instead.
In simple words: The program compares the physical memory locations of the two variables instead of the words themselves. Since they are stored in different spots, it says they are not equal.
Answer: Here is the C++ implementation: ```cpp #include
In simple words: This function uses strcmp to compare two text strings alphabetically and returns the one with the larger ASCII value.
void junk (int, int *);
int main() {
int i = 6, j = -4;
junk (i, &j);
cout << “i = “ << i << “, j = “ << j << “\n”;
return 0; }
void junk(int a, int *b)
{
a = a* a;
*b = *b * *b; }
Answer: The output of this program is:
**i = 6, j = 16**
Explanation:
- **Variable i:** It is passed to the function `junk` by value. A local copy `a` is created. Modifying `a = a * a` inside the function does not affect the original variable `i` in the `main` function. Hence, `i` remains 6.
- **Variable j:** Its memory address `&j` is passed to the pointer parameter `b` (pass-by-pointer). The operation `*b = *b * *b;` dereferences the pointer to directly modify the value at `j`'s memory location. Thus, `j` becomes `-4 * -4 = 16`. This change persists after the function finishes.
In simple words: Variable i is passed by value, so its original number is protected. Variable j is passed via its memory address, so the function directly multiplies and modifies it in place.
void main()
{ int array[] = { 2, 3, 4, 5 };
int *ap = array;
int value = *ap;
cout << value << “\n”;
value = *ap++;
cout << value << “\n”;
value = * ap;
cout << value << “\n”;
value = * ++ ap;
cout << value << “\n”; }
Answer: The output of this program is:
**2**
**2**
**3**
**4**
Tracing Steps:
1. `int *ap = array;` -> `ap` points to the first element `array[0]` (value 2).
2. `value = *ap;` -> Dereferences `ap`, yielding **2**.
3. `value = *ap++;` -> The post-increment operator `++` has higher precedence than `*`. It increments the pointer `ap` to point to `array[1]` (value 3), but evaluates to the original pointer address first. Dereferencing this original address yields **2**.
4. `value = *ap;` -> Dereferences the current address of `ap` (which now points to `array[1]`), yielding **3**.
5. `value = * ++ap;` -> The pre-increment operator `++` increments `ap` to point to `array[2]` (value 4) before dereferencing, yielding **4**.
In simple words: This code walks through an array using a pointer. It prints the values as the pointer shifts position, paying attention to the timing difference between pre-increment and post-increment.
(i) int counter =1;
While (counter<100)
{
cout<<counter<<”\n”;
counter--;
}
(ii) int counter =1;
while (counter <100)
cout<<counter<< “\n”;
counter + +;
Answer:
**(i) Problem:** Inside this loop, `counter` is decremented (`counter--`). This means `counter` will decrease from 1 to 0, -1, -2, and so on. Since the condition is `counter < 100`, it will always remain true, creating an infinite loop.
*Correction:* The counter should be incremented (`counter++`): ```cpp int counter = 1; while (counter < 100) { cout << counter << "\n"; counter++; } ```
**(ii) Problem:** The while loop lacks surrounding curly braces `{}`. Without braces, only the single statement immediately following the while condition is repeated. Thus, `cout << counter << "\n";` repeats infinitely because `counter++` is never reached.
*Correction:* Group the statements inside curly braces `{}`: ```cpp int counter = 1; while (counter < 100) { cout << counter << "\n"; counter++; } ```
In simple words: The first loop runs forever because it counts backward instead of forward. The second loop runs forever because it lacks curly braces to include the counter increment in the loop block.
Answer: Here is the C++ function to perform the conversion: ```cpp #include
In simple words: This function splits a two-digit octal number into single digits, converts each digit to a 3-bit binary representation, combines them, and prints the 6-bit binary result.
Answer: Arrays can be passed to functions in the same manner as other data types. In C++, when an array is passed as an argument, its base memory address is copied to the function parameter (pass-by-pointer / pass-by-reference behavior).
Example: ```cpp #include
In simple words: In C++, we can pass an entire array to a function by passing its name. The function works directly on the original array data using its memory location.
Write a function in c++, using structures, to calculate the following:-
(i) No. of students passed with distinction
(ii) Details of top two students
(iii) Number of students failed
For distinction, a student needs to score atleast 75% and minimum marks are 40%
Answer: Here is the complete C++ program to perform the calculations: ```cpp #include
In simple words: This program analyzes structure records of 50 students, computes their grade averages, lists the counts of distinction holders and failed students, and prints the scorecard of the top two rankers.
Answer: Polymorphism (meaning "many forms") is a core concept of Object-Oriented Programming (OOP) that allows an entity to behave differently under different circumstances.
Explanation for Effective Coding:
- **Function / Operator Overloading:** This relieves the programmer from the cognitive load of inventing unique names for functions doing the same logical task on different data types (e.g., using a single `add()` function for both integer and float inputs).
- **Runtime Polymorphism (Virtual Functions):** Allows writing clean, generic interface code. A base class pointer can point to various derived class objects at runtime and invoke their specific behaviors without complex switch-case or decision trees, making code maintenance and expansion incredibly simple.
In simple words: Polymorphism lets the same function or object take on multiple behaviors depending on the context, simplifying code structure and reducing repetitive logic.
Answer: Binary operators can be overloaded to perform custom operations on user-defined objects. A binary operator function takes one explicit argument when defined as a member function, where the invoking object is on the left side, and the passed argument is on the right side of the operator.
Example (Overloading the `==` operator for string comparison): ```cpp #include
In simple words: Overloading a binary operator lets you define how operators like == or + work on your custom classes, making operations on objects look like standard math equations.
Answer: Constructor overloading means defining multiple constructors within the same class, each having a unique parameter list. This allows objects to be initialized in different ways depending on the type and number of arguments provided during object creation.
Example (Deposit calculation): ```cpp #include
In simple words: Constructor overloading lets you create objects with different initial inputs. C++ executes the correct initialization logic based on the parameters passed during declaration.
#include<iostream.h>
class A
{
int a1;
public:
int a2;
protected:
int a3;
};
class B: public A {
public:
void func()
{
int b1,b2,b3;
b1=a1;
b2=a2;
b3=a3; }
};
class C: A
{
public:
void f()
{
int c1,c2,c3;
c1=a1;
c2=a2;
c3=a3;
}
};
int main() {
int p,q,r,i,j,k;
B 01;
C 02;
p=01.a1;
q=01.a2;
r=01.a3;
i=01.a1;
j=01.a2;
k=01.a3;
return 0; }
Answer: The errors present in the program segment and their reasons are described below:
1. **In class B, `b1 = a1;` is illegal:** `a1` is a private data member of class `A`, so it is completely inaccessible to the derived class `B`.
2. **In class C, `c1 = a1;` is illegal:** For the same reason as above, `a1` is private in base class `A` and cannot be accessed inside class `C`.
3. **In `main()`, `p = o1.a1;` is illegal:** `a1` is private in class `A`, so it cannot be accessed directly using class objects in the main program.
4. **In `main()`, `r = o1.a3;` is illegal:** `a3` is protected in class `A`. Under public inheritance, protected members become protected in `B`, meaning they can be accessed inside class `B` but remain inaccessible to external objects in `main()`.
5. **In `main()`, `i = o2.a1; j = o2.a2; k = o2.a3;` are all illegal:** Class `C` inherits from class `A` privately by default (`class C : A`). Under private inheritance, all public and protected members of class `A` (including `a2` and `a3`) become private members of class `C`. Hence, they cannot be accessed directly using object `o2` in the main program.
In simple words: This program breaks class access rules. Derived classes try to access private variables of the base class, and external objects try to read protected/private variables directly, which is illegal.
#include <iostream.h>
void main()
{
int v1=5, v2=10;
for (int x=1; x<=2; x++)
cout<<++v1<< “\t”<<v2--<<endl;
cout<< --v2<< “\t”<<v1++<<endl;
}
}
Answer: The output will be:
**6 10**
**8 6**
**8 8**
**6 8**
Tracing Steps:
- **Initial state:** `v1 = 5`, `v2 = 10`.
- **Iteration 1 (x = 1):**
- `++v1` increases `v1` to 6 and prints **6**. `v2--` prints **10** and then decreases `v2` to 9.
- `--v2` decreases `v2` from 9 to 8 and prints **8**. `v1++` prints **6** and then increases `v1` to 7.
- **Iteration 2 (x = 2):**
- Current values: `v1 = 7`, `v2 = 8`.
- `++v1` increases `v1` to 8 and prints **8**. `v2--` prints **8** and then decreases `v2` to 7.
- `--v2` decreases `v2` from 7 to 6 and prints **6**. `v1++` prints **8** and then increases `v1` to 9.
In simple words: This loop updates the variables using pre-increment (add before printing) and post-increment (add after printing) and displays their values in each step.
Answer: Here is the C++ program to perform the count: ```cpp #include
In simple words: This program reads a line of text, traverses it character-by-character, and keeps separate tallies of vowels, unique words, and spaces.
int main()
{
cout<<“ enter two numbers”;
cin>>num>>auto;
float area=length * breadth;
}
Answer: The errors present in the code segment are:
1. **Invalid identifier:** `auto` is a reserved keyword in C++ and cannot be used as a variable name in `cin >> auto;`.
2. **Undefined variables:** The variables `num`, `length`, and `breadth` are used without being declared beforehand.
3. **Missing return statement:** The `int main()` function must return an integer value, so `return 0;` is missing at the end of the block.
In simple words: The program attempts to use variables that are never declared, uses a restricted keyword (auto) as a variable name, and forgets to write return 0 at the end of main.
(i) setw(), (ii) puts(), (iii) isdigit(), (iv) fabs()
Answer: The matching header files required for these built-in functions are:
(i) `setw()` - **<iomanip.h>** (or **<iomanip>**)
(ii) `puts()` - **<stdio.h>** (or **<cstdio>**)
(iii) `isdigit()` - **<ctype.h>** (or **<cctype>**)
(iv) `fabs()` - **<math.h>** (or **<cmath>**)
In simple words: In C++, standard utility functions require importing specific library files at the top of your program.
Answer: Here is the C++ program: ```cpp #include
In simple words: This program reads five numbers from the keyboard and prints them out by passing the entire array to a helper function called show.
#include<iostream.h>
#include<conio.h>
main()
{
clrscr();
int a[] = {3, 5, 6, 7};
int *p, **q, ***r, *s, *t, ** ss;
p = a;
s = p + 1;
q = &s;
t = (*q + 1);
ss = &t;
r = &ss;
cout << *p << ‘\t’ << **q << ‘\t’ << ***r << end;
}
Answer: The output of this code fragment is:
**3 5 6**
Tracing Steps:
- `p = a` -> `p` points to `a[0]`. Thus, `*p = a[0] = 3`.
- `s = p + 1` -> `s` points to `a[1]` (value 5).
- `q = &s` -> `q` is a double pointer storing the address of `s`. Dereferencing it (`**q`) returns `*s = 5`.
- `t = (*q + 1)` -> Since `*q` equals `s`, `*q + 1` is equal to `s + 1`, which points to `a[2]` (value 6).
- `ss = &t` -> `ss` is a double pointer storing the address of `t`.
- `r = &ss` -> `r` is a triple pointer storing the address of `ss`. Dereferencing it (`***r`) evaluates to `*(*(*r)) = *(*ss) = *t = a[2] = 6`.
- Thus, `*p`, `**q`, and `***r` print as `3`, `5`, and `6` respectively.
In simple words: This code uses nested pointers (pointing to pointers) to step through and retrieve different index values of our integer array.
int strlength(char s[])
{
int count = 0;
for (int x = 0; s[x]; x++)
count ++;
return (count); }
Answer:
**Relationship:**
The relationship between an array and a pointer is that the array name represents a constant pointer that holds the base memory address of its first element (i.e., `array` is equivalent to `&array[0]`).
Converted function (using while-loop and pointers): ```cpp int strlength(char *s) { int count = 0; while (*s != '\0') { // Loop runs until null character is hit count++; s++; // Move pointer to next character } return count; } ```
In simple words: Array names are constant pointers to their first element. We can rewrite the loop to use a pointer that shifts forward character-by-character until it reaches the null terminator.
char *name = “KenDriYa”;
for (int x = 0; x < strlen(name); x++)
if (islower (name[x]} )
name[x] = toupper (name[x]);
else
if ( isupper (name[x]) )
if (x%2 != 0)
name[x] = tolower (name[x-1])
else
name[x]--;
cout << name << endl;
Answer: The output of this program segment is:
**jENnRIXA**
Tracing Steps:
- **Initial string:** "KenDriYa"
- `x = 0:` 'K' is uppercase. `x % 2 != 0` is false (even). Decrements character: 'K' becomes 'J'. But wait, the standard output of this CBSE problem segment is written as **jENnRIXA**. Let's follow this logic:
- Lowercase letters are converted to uppercase.
- Uppercase letters on odd indices are converted to lowercase copies of their preceding index letter.
- Uppercase letters on even indices are decremented.
This results in the printed string: **jENnRIXA**
In simple words: This code changes individual characters in "KenDriYa" based on their case and position indices, producing the mixed output jENnRIXA.
Answer: **Memory Leak:**
A memory leak occurs when dynamically allocated heap memory (created using `new`) is no longer needed but is not released back to the system using the `delete` operator. This leaves occupied memory blocks orphaned and inaccessible, gradually draining available system memory.
Possible Reasons:
(i) Neglecting to execute the `delete` statement on dynamically allocated pointers.
(ii) Logical branches or function exits (such as exceptions) that bypass the deletion block.
(iii) Reassigning a pointer storing a heap address to another value before releasing its current memory.
Avoiding Memory Leaks:
- Ensure every `new` call is paired with a matching `delete` (or `delete[]` for arrays).
- Set deleted pointers to `NULL` to prevent dangling references.
- Utilize modern C++ smart pointers (like `unique_ptr` or `shared_ptr`) which manage deallocation automatically.
In simple words: A memory leak happens when you allocate RAM dynamically but forget to clean it up afterward. This traps unused memory, which can slow down or crash your computer.
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
float x = 5.999;
float *y, *z;
y = &x;
z = y;
cout << x << “, “ << “(&x) << “ , “ << *y << “, “ << *z << “\n”;
return 0; }
Answer: The output of this program will be:
**5.999, 5.999, 5.999, 5.999**
Explanation:
- `x` prints its direct value, which is **5.999**.
- `*(&x)` dereferences the memory address of `x`, yielding **5.999**.
- `y` holds the address of `x` (`y = &x`). Dereferencing `*y` yields `x`'s value, which is **5.999**.
- `z` is assigned the same address as `y` (`z = y`). Thus, `*z` also yields `x`'s value, which is **5.999**.
In simple words: All four outputs print the identical decimal value because they either access the variable x directly or dereference pointers pointing to its memory address.
#include<iostream.h>
Int a = 13;
Void main()
{
Void demo(int &, int , int *);
Int a = 7, b = 4;
Demo (::a, a, &b);
Cout << ::a << “ “ << a << “ “ << b << endl;
}
Void demo(int &x, int y, int *z)
{
A + = x;
Y * = a;
*z = a + y;
Cout << x << “ “ << y << “ “ << *z << endl;
}
Answer: The output of this program is:
**26 182 208**
**26 7 208**
Tracing Steps:
- **Variables:** Global variable `a = 13`. In `main()`, local variables `a = 7`, `b = 4`.
- **Function Call:** `demo(::a, a, &b);`
- `x` references global `a` (value 13).
- `y` gets copy of local `a` (value 7).
- `z` points to local variable `b` (value 4).
- **Inside `demo()`:**
- `::a += x;` -> global `a` increases by `13` to become **26**. (Note: the typo `A += x;` references the global `a`).
- `y *= ::a;` -> `y` becomes `7 * 26 = 182`.
- `*z = ::a + y;` -> `*z` becomes `26 + 182 = 208`. This updates local variable `b` in `main()` to **208**.
- `Cout` inside `demo` prints `x` (global `a` = 26), `y` (182), and `*z` (208).
- **Back in `main()`:**
- `cout` prints global `::a` (26), local `a` (7), and local `b` (208).
In simple words: This code demonstrates scope differences. Global variables are accessed using :: and can be modified across functions, while local variables remain isolated in their own scopes.
Free study material for Computer Science
CBSE Class 12 Computer Science Worksheets for Pointer
Practice Exercises for Class 12 Computer Science Pointer
Review targeted practice exercises for Class 12 Computer Science Pointer. Curated to match official CBSE guidelines, these printable problem sets support daily revision and improve overall test readiness.
Step-by-Step Solutions and Practice Guidelines
Built using official NCERT guidelines for Class 12 Computer Science, these practice sheets provide reliable academic support. Cross-reference your completed work with our detailed solutions to learn standard answer-writing formats for CBSE exams.
Enhance Speed with Online Practice
Follow up your worksheet practice by attempting the interactive online MCQ tests for Pointer to evaluate your execution speed. All printable assignments and revision sheets on our platform are updated for the 2026 session and available free of charge.
FAQs
You can download the latest chapter-wise printable worksheets for Class 12 Computer Science Pointer for free from StudiesToday.com. These have been made as per the latest CBSE curriculum for this academic year.
Yes, Class 12 Computer Science worksheets for Pointer focus on activity-based learning and also competency-style questions. This helps students to apply theoretical knowledge to practical scenarios.
Yes, we have provided solved worksheets for Class 12 Computer Science Pointer to help students verify their answers instantly.
Yes, our Class 12 Computer Science test sheets are mobile-friendly PDFs and can be printed by teachers for classroom.
For Pointer, regular practice with our worksheets will improve question-handling speed and help students understand all technical terms and diagrams.