C++: if construct

Author: Ronald S. Holland
at
Total Application Works

ronholland@sumtotalz.com





To contact us



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/CPP/CPP_IF_Construct.html">
    IF_Construct/Statement </a>
    </table>
    </body>
    </html>


Introduction

This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on c++ or programming. As we ease into c++, we will briefly discuss the if control structure. c++ as a programming language is widespread and can be found on nearly all computers. In the next section, we will briefly describe control structures.

Control Structures

Bohm and Jacopini demonstrated, in their Structured program theorem, that all programs could be written using just three control structures.

  • sequence structure
      Consider the following example:

      
      int a = 8 , b ;
      b = (5 + 2) * a  ;
      cout << b << endl ;
      
      Figure 1: Squence of statements structure
      If a code snippet consists of the above three statements, then the statements will execute in the order/sequence that they are listed. This is also known as an ordered execution of statements.
  • selection structure
      In a selection statement, one of a number of statements is executed depending on the state of the program. Consider the following example:

      
      int a, b = 0;
      
      cout << "Enter a number less than 10 and greater than 0." << endl ;
      cin >> a ;
      
      if( a > 5 )
         b = (5 + 2) * a  ;
      
      cout << "The value of b is " <<  b << endl ;
      
      Figure 2: selection structure
  • repetition structure
      A repetition structure is used when a set of instructions need to be executed more than once.

      
      int b = 0;
      
      for( int ii = 0 ; ii < 10 ; ii++ ) {
         b = (5 + 2) * ii  ;
         cout << "The value of b is " <<  b << endl ;
      }
      
      Figure 3: repetition structure
Control Structures or constructs are described further in the next section.

Control Structures or constructs

What are Control Structures or constructs? The Control Structures constructs used in programming are:
  1. if - single selection structure
      This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken.
      
      if( condition is true ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      
      Figure 4: if - single selection structure


  2. if/else - double selection structure
      This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken; otherwise, a different action is taken.
      
      if( condition is true ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      else {
         statements
      }
      
      Figure 5: if/else - double selection structure


  3. switch - multiple selection structure
      This structure allows selection among multiple sections of code, depending on the value of an integral expression. It operates much like a nested if construct.
      
      switch( expression ) {
         case 1;
            do something ;
         case 2;
            do something ;
         case 3;
            do something ;
         ...
      
         default;
            do something ;
      }
      
      Figure 6: switch - multiple selection structure


  4. while
      In this construct, the condition is a boolean statement that is checked after the final } braces of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the statements inside the while construct do not execute again, due to the code branching out of the construct.
      while( condition  is true ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      
      Figure 7: while loop structure


  5. do/while
      The do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop. This construct guarantees that the body of the loop always executes at least one time. The format of the do-while loop is shown below.
      do {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      while( condition is true )
      
      Figure 8: do-while loop structure


  6. for
      Executes the statements and loop-expression repeatedly until test becomes false. After the first pass, the loop counter is updated and then the test-condition is checked to determine whether it is true or false.
      for( initialization ; test ; update ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      
      Figure 9: for loop structure


For the remainder of this tutorial, we will describe the if contruct.

The if selection construct

How do we use the if selection construct? In the real world, we often use the if selection construct, during the day. A teacher must decide at the end of the semester who gets a passing grade. What criteria is used? The criteria used is: if a student's grade is greater than or equal to 60 they enter a passing grade.

Flowchart

               _
              ( )               
               |
               -          +--------------+
              /g\  true   |   Email      |
             />= \________|              |
             \60 /        |   'passed'   |
              \ /         +--------------+
               -                |
    false -->  |                |
               |<---------------+
               V
               -
              ( ) 



 

       Decision symbol    Processing symbol
               +                  +
               |                  |
               V                  V
               -           +--------------+
              / \          |              |
             /   \         |              |
             \   /         |              |
              \ /          +--------------+
               -                 


 The Decision symbol is used when a decision 
     needs to be made or evaluated

 The Processing symbol is used when processing 
     a sequence of needs to be made
  
Pseudocode
          if grade is greater than or equal to 60 
             email "passed" to the student
Figure 11: if construct

Without a conditional statement such as if, programs would run practically same way every time. The if statements allow the flow of a program to be altered.

The if/else selection structure

In this section, we descibe the The if/else selection structure, in terms of the following:

  1. Pseudocode
  2. The conditional operator ? :, and
  3. nested ifs


Pseudocode
 

   if a student's grade is greater than or equal to 60
       print "passed"
   else
       print "failed" 



  
   
                    _
                   ( )               
                    |
+---------+         ^          +--------------+
| print   | false  /g\ true    |   print      |
|         |<----- />= \________|              |
| "failed"|       \60 /        |   'passed'   |
+---------+        \ /         +--------------+
     |              v                |
     |              |                |
     +------------->|<---------------+
                    V
                    _
                   ( ) 
                    -


  
   
          if (grade >= 60) 
             cout << "Passed" << endl;
          else 
             cout << "Failed" << endl;
  
conditional operator ? :
   
cout <<  (grade >= 60 ? "Passed" : "Failed" ) << endl;

   --- or  ----

cout <<  grade >= 60 ? cout << "Passed\n" : cout << "Failed\n"  ;
  
nested ifs
   
          if (grade >= 90) 
             cout << "A" << endl;
          else if (grade >= 80) 
             cout << "B" << endl;
          else if (grade >= 70) 
             cout << "C" << endl;
          else if (grade >= 60) 
             cout << "D" << endl;
          else  
             cout << "F" << endl;

 
Figure 12: nested if/else selection structure


An example of a The if selection construct program will be depicted in the next section.

The if selection construct program

In the following table, we show the code for an if selection construct program.

 
/** **************************************************************************
 * This program averages 4 test scores. The If_Construct.cpp:
 *  1- Obtains four numbers from the user;
 *  2- Calculates the average of those four numbers;
 *  3- Prints the average to the screen.
 ***************************************************************************/

#include "stdafx.h"
#include <iostream>

using namespace std;

/** ***************************************************
 * _tmain() method defines the C++ entry point for the 
 *  console application that is used when the program is 
 *  loaded into memory. 
 *
 ******************************************************/
int _tmain(int argc, _TCHAR* argv[])
{
	int Score1, Score2, Score3, Score4 ;
	double average;

	cout << "Enter 4 test scores and they will be averaged: ";
	cin >> Score1 >> Score2 >> Score3 >> Score4 ;

	average = (Score1 + Score2 + Score3 + Score4) / 4.0;

	cout.precision(1);
	cout.setf(ios::showpoint | ios::fixed);
	cout << "Your average is " << average << "\n" << endl;

	if (average == 100)
		cout << "Congratulations! You've achieved a perfect score!\n";

	return 0;
}

 
Figure 13: Single selection structure

The if/else nested selection construct program

In this section, we will show the nested if in the table below.

 
/** **************************************************************************
 * This program averages 4 test scores using a nested if construct. This 
 * program does the following:
 *  1- Obtains four numbers from the user;
 *  2- Calculates the average of those four numbers;
 *  3- Prints the average to the screen.
 *  4- Prints the grade to the screen.
 ***************************************************************************/

#include "stdafx.h"
#include <iostream>

using namespace std;

/** ***************************************************
 * _tmain() method defines the C++ entry point for the 
 *  console application that is used when the program is 
 *  loaded into memory. 
 *
 ******************************************************/
int _tmain(int argc, _TCHAR* argv[])
{
	int Score1, Score2, Score3, Score4 ;
	float average;

	cout << "Enter 4 test scores and they will be averaged: ";
	cin >> Score1 >> Score2 >> Score3 >> Score4 ;

	average = (Score1 + Score2 + Score3 + Score4) / 4.0;

	cout.precision(1);
	cout.setf(ios::showpoint | ios::fixed);

	if (average == 100)
           cout << "Congratulations! You've achieved a perfect score!\n";
	else if (average >= 90) {
           cout << "Your average is " << average << "\n" << endl;
           cout << "Your grade is "A" \n" << endl;
	}
	else if (average >= 80) {
           cout << "Your average is " << average << "\n" << endl;
           cout << "Your grade is "B" \n" << endl;
	}
	else if (average >= 70) {
           cout << "Your average is " << average << "\n" << endl;
           cout << "Your grade is "C" \n" << endl;
	}
	else if (average >= 60) {
           cout << "Your average is " << average << "\n" << endl;
           cout << "Your grade is "D" \n" << endl;
	}
	else if (average < 60) {
           cout << "Your average is " << average << endl;
           cout << "Your grade is \"F\" \n" << endl;
	}

	system("Pause") ;

	return 0;
}

 
Figure 14: nested if/else selection structure

Definitions

Böhm-Jacopini

    Computer scientists usually credit the Structured program theorem to a 1966 paper by Corrado Böhm and Giuseppe Jacopini.

conditional operator ? :

    The conditional operator ? : is a ternary operator (it takes three operands). It is of the form:
     
    (condition ? expression 1 : expression 2 ) 
     

  • If the condition evaluates to true then expression 1 is executed; otherwise, expression 2 is executed.

control structure

    allows for a change of linear sequence/flow of program execution, based on some condition evaluating to true.

Flowchart

    A flowchart is a method of diagraming the layout and/or flow of a program or algorith. This flow is shown using figures of various kinds, and their order by connecting them with arrows.

Pseudocode

    is a compact and informal high-level design description (usually written in a spoken language) of a computer programming algorithm that adheres to the structural conventions of a programming language. Pseudocode is intended to be read by humans rather than by machine.






HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works