How to find the greatest integer of three integers using Pointers in C++

In this tutorial, we will learn how to write the code to find the greatest 3 integers using the pointers in C++. Pointers are used to store the address of the variables. It is initialized by using the ‘*’ symbol before the variable name.

First of all, we initialize 3 integer variables and the variables will be given as an input, then we use the pointers to store the address of the integers. Using the conditional statements and pointers we will find the greatest integer of the 3 integers.

Program to Find the greatest of 3 integers in C++

If we initialize three integer variables p,q, and r with the values 10,2,36 (taken as an example), and then declare three-pointers named *a1,*a2,*a3. The Pointers store the address of the integer values.Using the if Conditional statement we can compare the three values and find out the greatest integer of the three integers.

#include<iostream>
using namespace  std;
int main(){
int p=10,q=2,r=36;
int *a1,*a2,*a3;
cout<<"Enter three different Numbers"<<endl;
cin>>p;
cin>>q;
cin>>r;
a1=&p;
a2=&q;
a3=&r;
if (*a1 > *a2 && *a1 >*a3)
cout<<*a1<<" is the Greatest number"<<endl;
if (*a2> *a1 && *a2 >*a3)
cout<<*a2<<" is the Greatest number"<<endl;
if(*a3> *a1 && *a3 >*a2)
cout<<*a3<<" is the Greatest number"<<endl;    
return 0;
}

The output of the code is:

36 is the Greatest number

Also read: What is a smart pointer and when should I use one in C++

Leave a Reply

Your email address will not be published.