Monday, 16 June 2014

C++ program to find the largest of two numbers


Here are the C++ program to find largest of two numbers through if statement, without using if statement, through conditional operator, through functions and through pointers .

Method 1 : C++ program to find largest among two numbers using if else condition
#include<iostream>
using namespace std;
int main()
{
    int a,b,c;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    if(a>b)
        cout<<"Greater number is "<<a<<endl;
    else
        cout<<"Greater number is "<<b<<endl;
    return 0;
}



Method 2 : C++ program to find largest among two numbers using only if condition
#include<iostream>
using namespace std;
int main()
{
    int a,b;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    if(a>b)
        b=a;
        cout<<"Greater number is "<<b<<endl;
    return 0;
}


Method 3 : C++ program to find largest among two numbers using function
#include<iostream>
using namespace std;
int grt(int a ,int b)
{
    return a>b?a:b;
}
int main()
{
    int a,b,c;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    c=grt(a,b);
    cout<<"Greater number is "<<c<<endl;
    return 0;
}



Method 4 : C++ program to find largest among two numbers using conditional operator
#include<iostream>
using namespace std;

int main()
{
    int a,b,c;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    c=a>b?a:b;
    cout<<"Greater number is "<<c<<endl;
    return 0;
}



Method 5 : C++ program to find largest among two numbers using pointer
#include<iostream>
using namespace std;
int main()
{
    int a,b,c;
    int *p,*q;
    p=&a;
    q=&b;
    cout<<"Enter two numbers : ";
    cin>>a>>b;
    if(*p>*q)
       cout<<"Greater number is "<<*p<<endl;
    else
       cout<<"Greater number is "<<*q<<endl;

    return 0;
}



Method 6 : C++ program to find largest among two numbers without using any if else or conditional operator
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    int num1,num2,maxi;
    cout<<"Enter the two numbers ";
    cin>>num1>>num2;
    maxi=((num1+num2)+abs(num1-num2))/2;
    cout<<"Greater of two number is "<<maxi;
    return 0;
}

No comments:

Post a Comment