Largest of two numbers using pointers
C program to find largest of two numbers using pointers.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2;
int *ptr1, *ptr2;
printf("Enter the first number\t:");
scanf("%d",&num1);
printf("Enter the second number\t:");
scanf("%d",&num2);
ptr1 = &num1;
ptr2 = &num2;
if(*ptr1 > *ptr2)
printf("\n%d is greater",*ptr1);
else if(*ptr1 < *ptr2)
printf("\n%d is greater",*ptr2);
else
printf("\nBoth the numbers are equal");
getch();
}
Output
********** Run1 **********
Enter the first number :5
Enter the second number :9
9 is greater
********** Run2 **********
Enter the first number :7
Enter the second number :3
7 is greater
********** Run3 **********
Enter the first number :4
Enter the second number :4
Both the numbers are equal
Explanation
In the above program, two variables 'num1' and 'num2' are taken, and two pointer variables '*ptr1' and '*ptr2' are also taken, ptr1 points to num1 and ptr2 points to num2 using the statements
ptr1 contains the address of variable num1 and ptr2 contains address of variable num2.
Let, first number entered by yser be 9 and second number ne 5.
*ptr1 means "value at the address contained in ptr1". ptr1 contains the address of num1. so, *ptr1 means "value at num1" which is the first number entered by the user i.e. 9
Similarly, *ptr2 = 5
if - else construct is used to find the greater of two numbers.*ptr1 > *ptr2 If this condition evaluates to true, then first number is greater
*ptr1 < *ptr2 If this condition evaluates to true, then second number is greater
If both the above conditions result in false, then both the numbers are equal.
ptr1 = &num1;
ptr2 = &num2;
ptr1 contains the address of variable num1 and ptr2 contains address of variable num2.
Let, first number entered by yser be 9 and second number ne 5.
*ptr1 means "value at the address contained in ptr1". ptr1 contains the address of num1. so, *ptr1 means "value at num1" which is the first number entered by the user i.e. 9
Similarly, *ptr2 = 5
if - else construct is used to find the greater of two numbers.