You are on page 1of 4

Fundamentals of Programming

Lab Journal - Lab # 9


Name: Affan Ali Dogar

Enrollment #: 01-134212-015

Class: 1-A

Objective: This lab will cover pointers in C++.

Exercise No 1:

Write the output of the following code fragments.


1. #include <iostream>
#include <conio.h>

using namespace std;

void main()
{
int num[5] = { 3,4,6,2,1 };
int* p = num;
int* q = num + 2;
int* r = &num[1];
cout << num[2] << " " << *(num + 2) << endl;
cout << *p << " " << *(p + 1) << "\n";
cout << *q << " " << *(q + 1) << endl;
cout << *r << " " << *(r + 1) << endl;
_getch();
}

Output:

2. #include <iostream>
#include <conio.h>

using namespace std;

void main()
{
int a = 2, b = 3, c = 4;
int* x = &a;
int* y;
*x = 11;
y = &c;
c++;
x = &b;
b--;
cout << a << " " << b << endl;
cout << *x << " " << *y << endl;
_getch();
}

Output:

3. #include <iostream>
#include <conio.h>

using namespace std;

void main()
{
int a[] = { 1,2,3,4,5,6,7,8,9 };
int* b;
int* c = &(a[1]);
b = a;
b[2] = 0;
cout << b[1] << c[0] << c[1] << a[2] << endl;
_getch();
}

OUTPUT:
Exercise 2:

Write a program that declares five integer variables a, b, c, d and e. It also declares an array of pointer
with five elements. The first element refers to a, the second element refers to b and so on. The program
should use the array to input values in the variables and then display the maximum value.

Solution:

#include <iostream>
#include <conio.h>
using namespace std;

void main()
{
int num1 = 0 , num2 = 0 , num3 = 0 , num4 = 0 , num5 = 0;
int *array[5] = {&num1 , &num2 , &num3 , &num4 , &num5 };

cout << "Enter values in the array :\n";


for (int i = 0; i < 5; i++)
{
cout << "Enter the element number " << i + 1 << " : ";
cin >> *array[i];
}

cout << endl;


cout << "\nMy array is :\n";
int max = *array[0];
for (int i = 0; i < 5; i++)
{
cout << *array[i] << "\t";
if (max < *array[i])
{
max = *array[i];
}
}
cout << endl;
cout << "Maximum value of the array : " << max << endl;
_getch();
}

Exercise 3 :
Write the two ways of displaying the 4th element
of an array num of type float and size 10.
float num[10] = {};
using array subscript notation:
cout << num[4] << endl;

using array offset notation:


cout << *(num + 4) << endl;

You might also like