Saturday 4 April 2020

if statement in C++


It is used to execute an instruction or block of instructions only if a condition is fulfilled. Its form is:
if (condition
statement;

where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues on the next instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:
if (x == 100)
  cout << "x is 100";

If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:

if (x == 100)
 {
  cout << "x is ";
  cout << x;
 }

No comments:

Post a Comment