0% found this document useful (0 votes)
25 views

My Notes!!

The document discusses recursion, templates, pointers, and provides examples of each in C++. Recursion is defined as a function calling itself to solve a problem, with a base case to terminate the recursion. Templates allow writing generic code to work with different data types. Pointers store memory addresses and are used for dynamic memory allocation, passing arguments by reference, and accessing memory locations directly.

Uploaded by

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

My Notes!!

The document discusses recursion, templates, pointers, and provides examples of each in C++. Recursion is defined as a function calling itself to solve a problem, with a base case to terminate the recursion. Templates allow writing generic code to work with different data types. Pointers store memory addresses and are used for dynamic memory allocation, passing arguments by reference, and accessing memory locations directly.

Uploaded by

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

NOTES ON COS1512

RECURSIONS:
Recursion in C++ refers to the technique where a function calls itself in order to solve a
problem or perform a task. In a recursive function, the function continues to call itself with
modified arguments until a base case is reached, at which point the recursion stops and the
function returns values that can be used to compute the final result.

Key elements of a recursive function in C++ include:

1. Base Case: This is the condition that terminates the recursion. Without a base case,
the recursion would continue indefinitely. The base case allows the function to return
a result without making further recursive calls.
2. Recursive Case: This is the part of the function where it calls itself with modified
arguments. The recursive case typically reduces the problem size or moves closer to
the base case.

Here's a simple example of a recursive function in C++ that calculates the factorial of a
number:

#include <iostream>
int factorial(int n) {
// Base case
if (n == 0 ) { return 1 ; } // Recursive case else { return n * factorial (n - 1 ); } } int main() { int num =
5 ; int result = factorial (num); std::cout << "Factorial of " << num << " is " << result << std::endl; return
0; }

In this example, the factorial function calculates the factorial of a number by calling itself
with a smaller number in each recursive step until it reaches the base case (when n is 0).
When the base case is reached, the recursion stops, and the results are combined as the
recursive calls are unwound.

Recursion is a powerful tool in C++ and can be used to solve problems that have a recursive
structure, such as tree traversal, mathematical calculations, and more. However, it's important
to ensure that there's a proper base case and that the problem size decreases with each
recursive call to avoid infinite recursion.

What are templates in C++


Templates in C++ are a powerful feature that allows you to write generic code to work with
different data types without having to rewrite the code for each specific data type. C++
templates are used to create generic classes and functions, and they are especially useful for
creating data structures and algorithms that can work with various data types.

There are two main types of templates in C++:

1. Function Templates:
• Function templates allow you to define a template function that can work with
multiple data types. You specify the data type as a parameter when calling the
function.
• Function templates are defined using the template keyword followed by a
list of template parameters enclosed in angle brackets (<>).
• For example:
code
template < typename T> T add(T a, T b) { return a + b; }
You can use this function template with various data types like int , double , or even
custom types.
2. Class Templates:
• Class templates are similar to function templates, but they allow you to create
generic classes.
• Class templates are defined using the template keyword followed by a list of
template parameters enclosed in angle brackets (<>), just like function
templates.
• For example:
code
template < typename T> class Stack { public : // Implement a stack data structure that works
with type T void push(T value) ; T pop() ; };
You can then create instances of the Stack class for different data types, such as int ,
double , or custom types.

When you use a template, the C++ compiler generates code for specific data types at compile
time. This is known as template specialization. Template specialization allows you to write
code that is both generic and efficient because it's customized for the specific data types you
use.

Here's an example of how you might use a function template:

cppCopy code
int main() { int x = 5 , y = 10 ; double a = 3.5 , b = 2.7 ; int sum_int = add (x, y); // Calls add<int>(x, y)
double sum_double = add (a, b); // Calls add<double>(a, b) return 0 ; }

Templates are an essential feature in C++ for creating flexible and reusable code, and they
are widely used in the standard library to provide generic containers (like std::vector and
std::map ) and algorithms (like std::sort ).

What are pointers in C++


Pointers in C++ are variables that store memory addresses, allowing you to work with the
memory directly. They are a fundamental feature of the C++ language and are used for
various purposes, such as dynamic memory allocation, data manipulation, and efficient
access to memory locations. Here are some key aspects of pointers in C++:

1. Declaration and Initialization:


• To declare a pointer, you use an asterisk (*) in the type declaration. For
example: int* ptr; declares a pointer to an integer.
• You can initialize a pointer with the address of a variable: int x = 42;
int* ptr = &x; initializes the pointer ptr with the address of the integer
variable x .
2. Accessing the Value:
• You can access the value stored at the memory location pointed to by a pointer
using the dereference operator * . For example, int value = *ptr; assigns
the value of x to the value variable.
3. Pointer Arithmetic:
• Pointers can be used for pointer arithmetic. Incrementing or decrementing a
pointer moves it to the next or previous memory location of its pointed type.
For example, if ptr points to an integer, ptr++ will point to the next integer
in memory.
4. NULL Pointers:
• Pointers can be set to a special value called a NULL pointer, which indicates
that the pointer does not point to a valid memory location. This is often used
as a sentinel value to check for the absence of a valid memory address.
code
int * ptr = nullptr ; // C++11 and later // OR int * ptr = NULL ; // Pre-C++11
5. Dynamic Memory Allocation:
• Pointers are commonly used for dynamic memory allocation using new and
delete (or malloc and free in C). Dynamic memory allocation allows you
to allocate memory on the heap during program execution, which is especially
useful for creating data structures like arrays and linked lists.
code
int * dynamicArray = new int [ 10 ]; // Allocate an array of 10 integers on the heap // ...
delete [] dynamicArray; // Deallocate the array
6. Passing by Reference:
• Pointers are used to pass arguments to functions by reference, which allows
functions to modify the original values. This is often used when you want to
return multiple values from a function or modify the input data in-place.
code
void modifyValue(int* ptr) { *ptr = 100 ; // Modifies the value pointed to by ptr }

Pointers require careful management to avoid issues like memory leaks, dangling pointers,
and accessing invalid memory locations. Smart pointers, introduced in C++11, help with
memory management by automatically deallocating memory when it's no longer needed,
reducing the risk of common pointer-related problems.

Please provide an example of pointers in C++


Here's an example of pointers in C++ that demonstrates the basics of pointer declaration,
initialization, dereferencing, and pointer arithmetic:

cppCopy code
#include <iostream> int main() { int x = 42 ; // Declare an integer variable int * ptr = &x; // Declare a
pointer and initialize it with the address of 'x' // Access the value using the pointer and dereference
operator std::cout << "Value of x: " << x << std::endl; std::cout << "Value pointed to by ptr: " << *ptr <<
std::endl; // Pointer arithmetic int y = 10 ; int * ptr2 = &y; std::cout << "Value of y: " << y << std::endl;
// Increment the pointer, moving it to the next int in memory ptr2++; std::cout << "Value pointed to by
ptr2 after increment: " << *ptr2 << std::endl; // Decrement the pointer ptr2--; std::cout << "Value
pointed to by ptr2 after decrement: " << *ptr2 << std::endl; // Demonstrating NULL pointers int *
nullPtr = nullptr ; // Declare a NULL pointer if (nullPtr == nullptr ) { std::cout << "nullPtr is a NULL
pointer." << std::endl; } // Changing the value using the pointer *ptr = 100 ; // Modify the value of 'x'
using the pointer std::cout << "Updated value of x: " << x << std::endl; return 0 ; }

In this example:

1. We declare an integer variable x and a pointer ptr that is initialized with the address
of x .
2. We access the value of x using both x and *ptr .
3. We declare another integer variable y and a pointer ptr2 . We demonstrate pointer
arithmetic by incrementing and decrementing ptr2 .
4. We declare a NULL pointer nullPtr and check if it's a NULL pointer using the
nullptr keyword.
5. We use the pointer to modify the value of x .

Keep in mind that pointers require careful handling, and improper use can lead to issues like
memory corruption and segmentation faults. Always make sure you are working with valid
memory locations and consider using smart pointers and standard containers whenever
possible to manage memory more safely.

How to convert templates to classes and vise versa

In C++, templates and classes serve different purposes, but you can achieve some level of
interchangeability or conversion between them in certain situations. Here's how you can
convert templates to classes and vice versa:

1. Converting a Template Class to a Concrete Class:


If you have a template class and you want to create a concrete class (a non-generic
class), you need to specify a particular data type for the template parameters. This
effectively "fixes" the generic class for that specific data type.
For example, let's say you have a generic Stack template class, and you want to
create a concrete integer stack class:
cppCopy code
// Template class template < typename T> class Stack { // Implementation for a generic stack
}; // Convert to a concrete integer stack class IntStack { // Implement the integer-specific
stack };
In the IntStack class, you'll provide the implementation specific to integers. This
allows you to use it as a regular class without any template parameters.
2. Converting a Concrete Class to a Template Class:
If you have a concrete class and you want to make it generic (a template class), you
can convert it by adding template parameters to the class and modifying the class's
methods and attributes to work with those parameters.
For example, if you have a concrete Rectangle class and you want to make it a
template class for various data types:
cppCopy code
// Concrete class class Rectangle { public : Rectangle ( int width, int height) : width (width),
height (height) { } int getArea() { return width * height; } private : int width; int height; }; //
Convert to a template class template < typename T> class GenericRectangle { public :
GenericRectangle (T width, T height) : width (width), height (height) { } T getArea() { return
width * height; } private : T width; T height; };
In the GenericRectangle class, we've added a template parameter T and modified
the attributes and methods to work with that type. Now, you can create instances of
GenericRectangle for various data types.

Remember that the choice between a template and a concrete class depends on your specific
requirements. Templates are best suited when you want to create generic classes or functions
that work with multiple data types, whereas concrete classes are used for specific data types
or when you don't need the flexibility of generics.

IMPLEMENTATION OF ADT’S

// Example ADT header file (e.g., myadt.h)


#ifndef MYADT_H
#define MYADT_H

// Define the data structure


typedef struct MyADT MyADT;

// Function prototypes
MyADT* createMyADT();
void destroyMyADT(MyADT* adt);
void insertData(MyADT* adt, int data);
int retrieveData(MyADT* adt);

#endif
ACCESSING ADT

// Example ADT source file (e.g., myadt.c)


#include "myadt.h"

struct MyADT {
// Define the internal representation of the data structure
};

MyADT* createMyADT() {
// Implementation of create function
}

void destroyMyADT(MyADT* adt) {


// Implementation of destroy function

You might also like