We now introduce a simple version of C++’s if statement that allows a program to take alternative action based on whether a condition is true or false. If the condition is true, the statement in the body of the if statement is executed. If the condition is false, the body statement is not executed. We’ll see an example shortly. Conditions in if statements can be formed by using the equality operators and relational operators summarized in Fig. 2.12. The relational operators all have the same level of precedence and associate left to right. The equality operators both have the same level of precedence, which is lower than that of the relational operators, and associate left to right. The following example (Fig. 2.13) uses six if statements to compare two numbers input by the user. If the condition in any of these if statements is satisfied, the output statement associated with that if statement is executed.
#include <iostream>
using namespace std;
int main()
{
int num1,num2;
cout<<"Enter Two integers:";
cin>>num1>>num2;
if(num1==num2)
cout<<num1<<"=="<<num2<<endl;
if(num1!=num2)
cout<<num1<<"!="<<num2<<endl;
if(num1<num2)
cout<<num1<<"<"<<num2<<endl;
if(num1>num2)
cout<<num1<<">"<<num2<<endl;
if(num1>=num2)
cout<<num1<<">="<<num2<<endl;
if(num1<=num2)
cout<<num1<<"<="<<num2<<endl;
system("pause");
return 0;
}
Output:-
No comments:
Post a Comment