Program to find the smallest integer of three integers in C++

In this tutorial, we will learn how to write the code to find the smallest integer of three integers using 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 smallest integer of the three integers.

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

If we initialize three integer variables p,q, and r with the values 20,12,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 smallest integer of the three integers.

#include<iostream>
using namespace  std;
int main(){
int p=20,q=12,r=36;
int *a1,*a2,*a3;
a1=&p;
a2=&q;
a3=&r;
if (*a1 < *a2 && *a1 <*a3)
cout<<*a1<<" is the smallest number"<<endl;
if (*a2< *a1 && *a2 <*a3)
cout<<*a2<<" is the smallest number"<<endl;
if(*a3< *a1 && *a3 <*a2)
cout<<*a3<<" is the smallest number"<<endl;    
return 0;
}

The output of the code is:

12 is the smallest number

 

Hope you liked the tutorial.

Leave a Reply

Your email address will not be published.