Share
C++ Programming

Course Outline

Week 1
Week 2
Week 3

DECISION MAKING

  • If statement
  • If else statement
  • Switch statement
  • Nested if statement
  • The conditional Operator (?)
Week 4

SponsoredAdvertise

Explanations to week content

A computer can process a program in one of the following ways: in sequence; selectively,

by making a choice, which is also called a branch;repetitively, by executing a statement

over and over, using a structure called a loop; or by calling a function. The figure below illustrates the first three types of program flow.



 


If Statement

 

The if statement is in this format:

 

if(condition is true){

            Run this block of codes

}

 

If a block of code(s) needs to be run if the condition is false, the else is included as shown below:

 

if(condition is true){

            Run this block of codes

}else{

            Run this block of codes

}

 

Examples

 

1. if (score is greater than or equal to 90)

grade is A

2. if (hours worked are less than or equal to 40)

wages = rate *hours

otherwise

wages = (rate *40) + 1.5 *(rate *(hours – 40))

3. if (temperature is greater than 70 degrees and it is not

raining)

Go golfing!

 

Relational Operators

 

OperatorDescription
==Equal to (NB: is two equal to signs)
!=Not equal to
Greater than
>=Greater than or equal to
Less than
<=Less than or equal to

 

 

Code Examples

 

Write a program that grades students in a class as either “Pass” or “Fail”. The pass mark is 70%.

The program should ask the user to enter the percentage mark.

 

Sample Code

 

#include <iostream>
 
using namespace std;
 
int main()
{
    float score;
    cout<< "Please enter the percentage score"<<endl;
    cin>>score;
   if(score>=70){
        cout<<"Grade:Pass"<<endl;
    }else{
        cout<<"Grade:Fail"<<endl;
    }
    return 0;
}

 

Alternative

 

The condition statement could also be written as


if(score<70){
        cout<< "Grade:Fail"<<endl;
}else{
        cout<< "Grade:Pass"<<endl;
}

 

Write a program which determines whether an integer entered is an even number or not

 

Sample Code

 

Concept.

 

An even number is a number divisible by 2 without are remainder. The operator for calculating a remainder of a number divided by another number is modulus (%) as stated in week 2 lesson. If the remainder is 0, then it means the number is an even number. Hence the sample code below.

 

#include <iostream>
 
using namespace std;
 
int main()
{
    int number;
    cout<< "Please enter an integer number"<<endl;
    cin>>number;
    if(number%2== 0){
        cout<< number<<" is an even number"<<endl;
    }else{
        cout << number<<" is not an even number"<<endl;
    }
 
    return 0;
}

 

 

Conditions and Meaning

 

 

ConditionMeaning
Condition 1 && Condition 2        
 e.g int a = 2;       int b = 3;
 if((a%2==0)&&(b>=3)){      
…………..
 }  
 If((!(a%2==0))&&(!(b%2==0))){
      ……………
 }
&& means and If both condition 1 and condition 2 are true, the Boolean will be true, else if at least one of the conditions is false, the Boolean will be false.   This if statement will be true because a%2 =0 and b is equal to 3. Since both conditions are true, the Boolean of the if statement will be true.     NOTE: ! means not. Hence !(a%2==0) means modulus 2 not equal to 0. This conditional statement will be false since is 2 and 2%2 is 0.   !(b%2==0) means modulus 2 not equal to 0. This conditional statement will be true since is 3 and 3%2 is 1 which is not equal to 0.   But since one of the condition is false in the && operation, the entire if statement will be false.
Condition 1 || condition 2        
 e.g int a = 2;       int b = 3;
 if((a%2==0)||(b>=3)){      
…………..
 }  
 If((!(a%2==0))||(!(b%2==0))){     
……………
 }
|| means or This means if Condition 1 is true or Condition 2 is true. In this case if any of the conditions is true, the Boolean will be true.       The Boolean will be true because at least one of the conditions is true. Since a = 2 and b =3, 2%2 is 0 and 3 is equal to 3. Both statements are true.   The Boolean for (!(a%2==0)) will be false. The Boolean for (!(b%2==0)) will be true. Since one of the conditions is true, the Boolean for the if statement will also be true for the || operation.

 

 

Else if

 

The else if is used for multiple if statements. It is written in the following format.

 

if(statement 1 is true){

            run this block of code

}else if(statement 1 is false and statement 2 is true){

            run this block of code

}else if(statement 2 is false and statement 3 is true){

            run this block of code.

}

.

.

.

else if(statement n-1 is false and statement is true){

            run this block of code.

}else{

     if none of the above statements is true, run this block of code

}

 

Example

 

The following is the grading system in a school.

 

90 – 100A
80 – 89….B
50 – 79…C
0 – 49….FAIL

 

Write a program to take the percentage score and output the grade to a user.

 

Sample Code

 

#include <iostream>
using namespace std;
 
int main()
{
  float score;
 cout<<"Please enter the exam score"<<endl;
  cin >>score;
 if(score>=90){ // 90 and above is A
       cout<<"Grade A"<<endl;
  }elseif(score>=80){ // If less than 90 but greater than or equal to 80, grade is B
       cout<<"Grade B"<<endl;
  }elseif(score>=50){ // If less than 80 but greater than or equal to 50, grade is C
       cout<<"Grade C"<<endl;
  }else{//Anything else is Fail
       cout<<"Fail"<<endl;
  }
  return 0;
}

 


Switch

 

Recall

that there are two selection, or branch, structures in C++. The first selection structure,which is implemented with if and if. . .else statements, usually requires the evaluation of a (logical) expression. The second selection structure, which does not require the evaluation of a logical expression, is called the switch structure. C++’s switch structure gives the computer the power to choose from among many alternatives.


A general syntax of the switch statement is:

 

switch(expression)

{

case value1:

statements1

break;

case value2:

statements2

break;

.

.

.

case valuen:

statementsn

break;

default:

statements

}

In C++, switchcasebreak, and default are reserved words. The default statement is run when none of the case values is the expression.

 

The switch statement executes according to the following rules:

 

1.         


When the value of the expression is matched against a case value(also called a label), the statements execute until either       a break statement is found or the end of the switch structure is reached.

 

2.            


If the value of the expression does not match any of the case values, the statements following the default label execute. If the switch

structure has no default label and if the value of the expression does not match any of the case values, the entire switch statement is

skipped.

 

3.          


break statement causes an immediate exit from the switch structure.

 

This is illustrated in the figure below.

 

 

 

 

Example

 

The following are games played by students in a class base on their genders.

 

MaleFootball, Volleyball, Tennis Ball
FemaleAmpe, Ludo

 

Write a program that takes the gender of a student in that class (M for male and F for female) and outputs the possible game played by that student.

 

Sample Code

 

#include <iostream>
using namespace std;
 
int main()
{
  char gender;
 cout<<"Please enter your gender. M for male and F for female."<<endl;
  cin >>gender;
  switch(gender){
    case 'M':
    cout<< "You play any of these games: Football, Volleyball, Tennis Ball"<<endl;
    break;
    case 'F':
    cout<< "You play any of these games: Ampe, Ludo"<<endl;
    break;
    default:
    cout<< "Please entered letter for gender is incorrect."<<endl;
  }
  return 0;
}

 

The switch expression can be statement such as score/10,age >=18 etc

The result of the expression is what is used to analyze if the case is true or false.

 

Examples

 

Write a program which takes the integer age of a user and output if the user is an adult ornot. The adult age is 18 and above.

 

Sample Code

 

#include <iostream>
using namespace std;
 
int main()
{
  int age;
 cout<<"Please enter your integer age"<<endl;
  cin >>age;
 switch(age>=18){ // Any age which is equal to or greater than 18 will be true, else the expression will be false
    case true:
    cout<< "You are an adult"<<endl;
    break;
    case false:
    cout<< "You are not an adult"<<endl;
    break;
  }
  return 0;
}

 


Write a program that ask a user to enter an integer value. The program then check if the entered integer is an even number or not.

 

Sample Code


#include <iostream>
using namespace std;
 
int main()
{
  int number;
 cout<<"Please enter an integer"<<endl;
  cin >>number;
 switch(number%2){ // If number is an integer, number%2 will be 0
    case 0:
    cout<< "You entered an integer number"<<endl;
    break;
    default:
    cout<< "The entered number is not an integer"<<endl;
  }
  return 0;
}

 

Nested If

 

When one control statement is located within another, it is said to be nested.

 

Nested if is therefore an if  statement in another if statement.

 

Example

 

Write a program that determine if a number is an even or not and if even, determine whether is divisible by 10 or not.

 

Sample Code Using Nested If

 

#include <iostream>
using namespace std;
 
int main()
{
  int number;
 cout<<"Please enter an integer"<<endl;
  cin >>number;
 if(number%2==0){
   if(number%10==0){ // Nested if
        cout<<number<<" is an even and divisible by 10"<<endl;
    }else{
        cout<<number<<" is an even and but not divisible by 10"<<endl;
    }
  }else{
    cout<< number<<" is not an even number"<<endl;
  }
  return 0;
}

 

Conditional Operator (?:)

 

Certain if. . .else statements can be written in a more concise way by using C++’s conditional operator. The conditional operator, written as ?:, is a ternary operatorwhich means that it takes three arguments. The syntax for using the conditional operator is:

expression1 ? expression2 : expression3

 

This type of statement is called a conditional expression. The conditional expression is evaluated as follows: 

If expression1 evaluates to a nonzero integer (that is, to true), the result of the conditional expression is expression2. Otherwise, the result of the conditional expression is expression3.

 

Consider the following statements:

if (a >= b)

max= a;

else

max= b;

 

The above code could be simplified using a conditional operator as follows:

 

max = (a >= b) ? a : b;

 

Sample code

 

#include <iostream>
using namespace std;
 
int main()
{
  int max,a,b;
  a = 2;
  b = 3;
  max =(a>=b)?a:b;
 cout<<"The maximum value of a="<<a<<"and "<<b<<" is "<<max;
  return 0;
}

 

Explanation

 

if a>=b is true, the value of max will be a(the second expression, the expression before the ) but if a>=b is false,the value of max will be b(the third expression, the expression after the )

 

 

Practical Application

 

Write a simple login application which asks user to enter the username and password. If username is root and password is 123456,grant user access. In actual program, the password is fetched from a database using the username and is compared to the entered password by the user.

But this simple application has fixed username and password.

 

Sample Code

 

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
  //Declare thestring variables
  stringusername,password;
  //Get thevariables
 cout<<"Please enter your username"<<endl;
  cin>>username;
 cout<<"Please enter your password"<<endl;
 cin>>password;
  //if usernameis root and password is 123456, then grant the user access
 if((username=="root")&&(password=="123456")){
   cout<<"Accress granted"<<endl;
  }else{
    cout<<"Incorrectusername or password"<<endl;
  }
return 0;
}

 

NOTE: Before you can use the string variable type, you need to add the string library by including this line of code #include <string> as shown in the code above.

 

String will be considered in more detail in week 7.

 

Assignment

 

Write a program that calculates the area for multiple shapes. You first ask the user the shape he/she wants to calculate the area for. Once the shape is entered, take the necessary inputs from the user and display the area.

SponsoredAdvertise

Kuulchat Premium