In this article, we will learn about How to find Largest among three numbers using pointer with examples.
1. C Program to find Largest among three numbers using pointer
In this example, we are taking 3 numbers as input from the user and then using the pointers, we are doing the comparison using the if-else statements to find the largest number among the 3 numbers input by the user.
#include<stdio.h>
int main()
{
float Num1, Num2, Num3;
float *ptrNum1, *ptrNum2, *ptrNum3;
ptrNum1=&Num1;
ptrNum2=&Num2;
ptrNum3=&Num3;
printf("Please enter three number:");
scanf("%f %f %f", ptrNum1, ptrNum2, ptrNum3);
if(*ptrNum1 > *ptrNum2)
{
if(*ptrNum1 > *ptrNum3)
printf("The Largest Number is = %.2f", *ptrNum1);
else
printf("The Largest Number is = %.2f", *ptrNum3);
}
else
{
if(*ptrNum2 > *ptrNum3)
printf("The Largest Number is = %.2f", *ptrNum2);
else
printf("The Largest Number is = %.2f", *ptrNum3);
}
return 0;
}
Output
Please enter three number:90
23
56
The Largest Number is = 90.00
2. C Program to find Largest among three number using pointer & function
In this example, we are modifying the logic which we used in the above code. Here we have moved the comparison code to a separate function. This function will take 3 numbers as input and will tell us which one is the biggest number.
#include<stdio.h>
void findLargestNumber(int *No1, int *No2, int *No3);
int main()
{
int Num1, Num2, Num3;
int *ptrNum1, *ptrNum2, *ptrNum3;
ptrNum1 = &Num1;
ptrNum2 = &Num2;
ptrNum3 = &Num3;
printf("Please enter three number: ");
scanf("%d %d %d", ptrNum1, ptrNum2, ptrNum3);
findLargestNumber(ptrNum1, ptrNum2, ptrNum3);
return 0;
}
void findLargestNumber(int *No1, int *No2, int *No3)
{
if( (*No1 > *No2) && (*No1 > *No3) )
{
printf("The Largest Number is = %d", *No1);
}
else if((*No2 > *No1) && (*No2 > *No3))
{
printf("The Largest Number is = %d", *No2);
}
else
{
printf("The Largest Number is = %d", *No3);
}
}
Output
Please enter three number: 78
45
89
The Largest Number is = 89