C program to find the largest of three numbers using Pointers

In this C Programming example, we will implement the program to find the largest of three numbers using Pointers and print the output on the console.

1. How to find the Largest of three numbers?

In the following program, we have three numbers as number1, number2, and number3. We will assign the address of these numbers to the three-pointers namely – p1, p2, and p3. Later, we compare values stored at the address pointed by the pointers.

Example

Input: 
number1 = 12
number2 = 30
number3 = 20

Output:
The largest number is: 30

Helpful topics to understand this program better are-


2. C Program to find the largest of three numbers using Pointers

Let’s discuss the execution for the program to find the greatest of three numbers using Pointers in C.

  1. Initially, the program will prompt the user to enter three numbers and we will assign a pointer to each number.
  2. Then we call largestNumber() function where we pass the numbers.
  3. We have if-else block within this function that executes and compares the numbers and the largest number among the three is printed on the console.

Let us now implement the above execution of the program to find the largest of three numbers using Pointers in C.

#include <stdio.h>

int *p1, *p2, *p3;

void largestNumber() {
  if (*p1 > *p2) {
    if (*p1 > *p3) {
      printf("%d is the largest number", *p1);
    } else {
      printf("%d is the largest number", *p3);
    }
  } else {
    if (*p2 > *p3) {
      printf("%d is the largest number", *p2);
    } else {
      printf("%d is the largest number", *p3);
    }
  }
}
int main() {

  int number1, number2, number3;
  printf("Enter the First Number: ");
  scanf("%d", &number1);
  printf("Enter the Second Number: ");
  scanf("%d", &number2);
  printf("Enter the Third Number: ");
  scanf("%d", &number3);

  p1 = &number1;
  p2 = &number2;
  p3 = &number3;
  largestNumber();
  return 0;
}
Output
Enter the First Number: 21
Enter the Second Number: 22
Enter the Third Number: 54
54 is the largest number

Note: We can achieve the same results by using the ternary operator. Try it and share the solutions with us.


3. Conclusion

In this C Programming example, we have discussed how to find the largest of three numbers using Pointers in C.


Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples.

All examples are hosted on Github.


Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index