Learn C++ - C++ if






The syntax for the if statement is similar to the that of the while syntax:

if (test-condition) 
  statement 

A true test-condition causes the program to execute statement, which can be a single statement or a block.

A false test-condition causes the program to skip statement.

An if test condition is type cast to a bool value, so zero becomes false and nonzero becomes true.

The entire if construction counts as a single statement.

Example


#include <iostream> 
int main() //from  ww w  . j  a v a 2s .  c om
{ 
     using std::cin;
     using std::cout; 
     char ch; 
     int spaces = 0; 
     int total = 0; 
     cin.get(ch); 
     while (ch != '.')   // quit at end of sentence 
     { 
          if (ch == ' ')  // check if ch is a space 
              ++spaces; 
         ++total;        // done every time 
         cin.get(ch); 
     } 
     cout << spaces << " spaces, " << total; 
     cout << " characters total in sentence\n"; 
     return 0; 
} 

The code above generates the following result.





The if else Statement

An if else statement lets a program decide which of two statements or blocks is executed.

The if else statement has this general form:

if (test-condition) 
  statement1 
else 
  statement2 

If test-condition is true, or nonzero, the program executes statement1 and skips over statement2.

Otherwise, when test-condition is false, or zero, the program skips statement1 and executes statement2 instead.


#include <iostream> 
int main() { //from  w  w w  .j  av a2  s . co  m
     char ch; 

     std::cout << "Type, and I shall repeat.\n"; 
     std::cin.get(ch); 
     while (ch != '.') 
     { 
         if (ch == '\n') 
              std::cout << ch;     // done if newline 
         else 
              std::cout << ++ch;   // done otherwise 
         std::cin.get(ch); 
     } 
     return 0; 
} 

The code above generates the following result.





using if else if else


#include <iostream> 
const int Fave = 27; 
int main() //from  w w  w . j  a v  a2  s.c o  m
{ 
     using namespace std; 
     int n; 

     cout << "Enter a number in the range 1-100 to find "; 
     cout << "my favorite number: "; 
     do 
     { 
         cin >> n; 
         if (n < Fave) 
              cout << "Too low -- guess again: "; 
         else if (n > Fave) 
              cout << "Too high -- guess again: "; 
         else 
              cout << Fave << " is right!\n"; 
     } while (n != Fave); 
     return 0; 
} 

The code above generates the following result.