If and If-Else Program
If statement :-
The if statement evaluates the test expression inside parentheses.
If test expression is evaluated to true ( nonzero ), statements inside the body of if is executed.
If test expression is evaluated to false ( 0 ), statement inside the body of if is skipped.
Flow Chart of if statement :-
if ( statement is TRUE ) {
/* between the braces is the body of the if statement */
Execute all statements inside the body
}
Example :-
Ques - Program to Print number is even.
#include <iostream> //Header file
using namespace std;
int main() //Main function
{
int number;
cout<<"Enter a number :"; // Print on the screen
cin>>number; // Take input from the console / user.
// Test expression is true if number is perfectly divide by 2
if ( number % 2 == 0) // % means find remainder , == means perfectly equal
{
cout<<"Even number";
}
return 0;
}
Output :
Enter an number:2 Even number
If else statement :-
If test expression is true, code inside the body of if statement is executed; and code inside the body of else statement is skipped.
If test expression is false, code inside the body of else statement is executed; and code inside the body of if statement is skipped.
Flow Chart of if..else statement :-
Basic if syntax :-
if ( TRUE ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}
Example :-
Ques - Program to check whether an integer entered by the user is odd or even.
#include <iostream>
using namespace std;
int main()
{
int number;
cout<<"Enter an integer: ";
cin>>number;
// True if remainder is 0
if( number%2 == 0 )
cout<<number<<" is an even integer.";
else
cout<<number<<" is an odd integer.";
return 0;
}
Output 1:Enter an integer: 7 7 is an odd integer.
Output 2:
Enter an integer: 8 8 is an even integer.
Comments
Post a Comment