Oop Lab 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Superior University Lahore, Faisalabad Campus

"Programming is not about what you


know; it's about what you can figure
out." - Chris Pine
Superior University Lahore, Faisalabad Campus

Creating Pointers
You learned from the previous chapter, that we can get the memory
address of a variable by using the & operator:

Example
string food = "Pizza"; // A food variable of type string

cout << food;  // Outputs the value of food (Pizza)


cout << &food; // Outputs the memory address of food (0x6dfed4)

A pointer however, is a variable that stores the memory address as its


value.

A pointer variable points to a data type (like int or string) of the same type, and
is created with the * operator. The address of the variable you're working with is
assigned to the pointer:

Example
string food = "Pizza";  // A food variable of type string
string* ptr = &food;    // A pointer variable, with the name ptr, that
stores the address of food

// Output the value of food (Pizza)


cout << food << "\n";

// Output the memory address of food (0x6dfed4)


cout << &food << "\n";

// Output the memory address of food with the pointer (0x6dfed4)


cout << ptr << "\n";

Example explained
Create a pointer variable with the name ptr, that points to a string variable, by
using the asterisk sign * (string* ptr). Note that the type of the pointer has to
match the type of the variable you're working with.

Use the & operator to store the memory address of the variable called food, and
assign it to the pointer.
Superior University Lahore, Faisalabad Campus
Now, ptr holds the value of food's memory address.

Tip: There are three ways to declare pointer variables, but the first way is
preferred:

string* mystring; // Preferred


string *mystring;
string * mystring;

what is use of pointers:

Pointers are variables that store the address of another variable or a memory location.
They are used for various purposes, such as:

 To pass arguments by reference 1

 To access array elements 1

 To return multiple values


1

 To allocate memory dynamically 12

 To implement data structures 1

 To do system-level programming where memory addresses are useful 1

Here is a list of headings with coding examples for some of the uses of pointers:

 Passing arguments by reference:

// a function that swaps two integers using pointers


void swap(int *a, int *b)
{
// store the value pointed by a in a temporary variable
int temp = *a;

// assign the value pointed by b to the location pointed by a


*a = *b;

// assign the value stored in temp to the location pointed by b


*b = temp;
}

// main function
int main()
{
// declare two integers
int x = 10;
Superior University Lahore, Faisalabad Campus
int y = 20;

// print their values before swapping


cout << "x = " << x << ", y = " << y << endl;

// call the swap function with the addresses of x and y


swap(&x, &y);

// print their values after swapping


cout << "x = " << x << ", y = " << y << endl;

// output:
// x = 10, y = 20
// x = 20, y = 10

return 0;
}

 Accessing array elements:


// declare an array of 5 integers
int arr[5] = {10, 20, 30, 40, 50};

// declare a pointer to an integer


int *ptr;

// assign the address of the first element of the array to the pointer
ptr = arr;

// print the elements of the array using pointer arithmetic


for (int i = 0; i < 5; i++)
{
// print the value pointed by ptr
cout << *ptr << " ";

// increment the pointer to point to the next element


ptr++;
}

// output: 10 20 30 40 50

 Returning multiple values:


Superior University Lahore, Faisalabad Campus
// a function that returns the sum and product of two integers using
pointers
void sum_and_product(int a, int b, int *sum, int *product)
{
// assign the sum of a and b to the location pointed by sum
*sum = a + b;

// assign the product of a and b to the location pointed by product


*product = a * b;
}

// main function
int main()
{
// declare two integers
int x = 5;
int y = 10;

// declare two pointers to store the sum and product


int *s = nullptr;
int *p = nullptr;

// allocate memory for s and p using new operator


s = new int;
p = new int;

// call the sum_and_product function with x, y, s and p as arguments


sum_and_product(x, y, s, p);

// print the values pointed by s and p


cout << "Sum = " << *s << ", Product = " << *p << endl;

// output: Sum = 15, Product = 50

// deallocate memory for s and p using delete operator


delete s;
delete p;

return 0;
}
Superior University Lahore, Faisalabad Campus

here are 5 lab tasks on the topic of pointers in C++:

1. Task 1: Write a C++ program that uses pointers to swap the values of two variables. Prompt the
user to input two integers and then use pointers to swap the values.

2. Task 2: Write a C++ program that uses pointers to allocate dynamic memory for an array of
integers. Prompt the user to input the size of the array, and then use pointers to allocate
memory for the array. Once the memory is allocated, prompt the user to input values for the
array elements and then display the contents of the array.

3. Task 3: Write a C++ program that uses pointers to find the maximum value in an array of
integers. Prompt the user to input the size of the array, allocate dynamic memory for the array,
prompt the user to input values for the array elements, and then use pointers to find the
maximum value in the array.

4. Task 4: Write a C++ program that uses pointers to create a linked list. The program should
prompt the user to input values for each node in the list and then display the contents of the
list.

5. Task 5: Write a C++ program that uses pointers to implement a stack. The program should
prompt the user to input values to push onto the stack or pop from the stack, and then display
the contents of the stack after each operation.

Task 1: Write a C++ program that uses pointers to swap the values of two variables. Prompt the user to
input two integers and then use pointers to swap the values.

#include <iostream>

using namespace std;

void swap(int* a, int* b)

int temp = *a;

*a = *b;

*b = temp;

}
Superior University Lahore, Faisalabad Campus
int main()

int num1, num2;

cout << "Enter two integers: ";

cin >> num1 >> num2;

cout << "Before swapping:" << endl;

cout << "num1 = " << num1 << ", num2 = " << num2 << endl;

swap(&num1, &num2);

cout << "After swapping:" << endl;

cout << "num1 = " << num1 << ", num2 = " << num2 << endl;

return 0;

Task 2: Write a C++ program that uses pointers to allocate dynamic memory for an array of integers.
Prompt the user to input the size of the array, and then use pointers to allocate memory for the array.
Once the memory is allocated, prompt the user to input values for the array elements and then display
the contents of the array.

#include <iostream>

using namespace std;

int main()

int size;
Superior University Lahore, Faisalabad Campus
cout << "Enter the size of the array: ";

cin >> size;

int* arr = new int[size];

cout << "Enter " << size << " integers: ";

for (int i = 0; i < size; i++)

cin >> *(arr + i);

cout << "The array elements are: ";

for (int i = 0; i < size; i++)

cout << *(arr + i) << " ";

delete[] arr;

return 0;

Task 3: Write a C++ program that uses pointers to find the maximum value in an array of integers.
Prompt the user to input the size of the array, allocate dynamic memory for the array, prompt the user
to input values for the array elements, and then use pointers to find the maximum value in the array.

#include <iostream>
Superior University Lahore, Faisalabad Campus
using namespace std;

int findMax(int* arr, int size)

int max = *arr;

for (int i = 1; i < size; i++)

if (*(arr + i) > max)

max = *(arr + i);

return max;

int main()

int size;

cout << "Enter the size of the array: ";

cin >> size;

int* arr = new int[size];

cout << "Enter " << size << " integers: ";

for (int i = 0; i < size; i++)


Superior University Lahore, Faisalabad Campus
{

cin >> *(arr + i);

int max = findMax(arr, size);

cout << "The maximum value in the array is: " << max << endl;

delete[] arr;

return 0;

Task 4: Write a C++ program that uses pointers to create a linked list. The program should prompt the
user to input values for each node in the list and then display the contents of the list.

#include <iostream>

using namespace std;

struct Node

int data;

Node* next;

};

void addNode(Node** head, int data)

Node* newNode = new Node;

newNode->data = data;

newNode->next = *head;
Superior University Lahore, Faisalabad Campus
*head = newNode;

void displayList(Node* head)

cout << "The linked list is: ";

while (head != nullptr)

cout << head->data << " ";

head = head->next;

cout << endl;

int main()

Node* head = nullptr;

int numNodes, data;

cout << "Enter the number of nodes: ";

cin >> numNodes;

for (int i = 0; i < numNodes; i++)

cout << "Enter the data for node " << i + 1 << ": ";

cin >> data;


Superior University Lahore, Faisalabad Campus

addNode(&head, data);

displayList(head);

return 0;

Task 5: Write a C++ program that uses pointers to implement a stack. The program should prompt the
user to input values to push onto the stack or pop from the stack, and then display the contents of the
stack after each operation.

#include <iostream>

using namespace std;

const int MAXSIZE = 10;

class Stack

private:

int top;

int data[MAXSIZE];

public:

Stack()

top = -1;

}
Superior University Lahore, Faisalabad Campus
bool push(int item)

if (top >= MAXSIZE - 1)

cout << "Stack overflow." << endl;

return false;

else

top++;

data[top] = item;

return true;

bool pop(int& item)

if (top < 0)

cout << "Stack underflow." << endl;

return false;

else

item = data[top];

top--;

return true;

}
Superior University Lahore, Faisalabad Campus

void display()

if (top < 0)

cout << "Stack is empty." << endl;

else

cout << "Stack contents: ";

for (int i = top; i >= 0; i--)

cout << data[i] << " ";

cout << endl;

};

int main()

Stack myStack;

int choice, value;

cout << "1. Push an item onto the stack" << endl;

cout << "2. Pop an item from the stack" << endl;

cout << "3. Display the stack" << endl;


Superior University Lahore, Faisalabad Campus
cout << "4. Quit" << endl;

do

cout << "Enter your choice: ";

cin >> choice;

switch (choice)

case 1:

cout << "Enter a value to push onto the stack: ";

cin >> value;

if (myStack.push(value))

cout << "Item pushed onto stack." << endl;

break;

case 2:

if (myStack.pop(value))

cout << "Item popped from stack: " << value << endl;

break;

case 3:
Superior University Lahore, Faisalabad Campus
myStack.display();

break;

case 4:

cout << "Exiting program..." << endl;

break;

default:

cout << "Invalid choice. Try again." << endl;

break;

} while (choice != 4);

return 0;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy