0% found this document useful (0 votes)
11 views53 pages

C++ Session 3

Uploaded by

Kelvin Igbodika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views53 pages

C++ Session 3

Uploaded by

Kelvin Igbodika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Session 3

Flow Control
Operators and Meaning
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
== Equality
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
% Modulo Operator (remainder)
If( (6!=6 & 7<=8) ||4>=4)
cout<<“Onaapo”;
else
cout<< “Obanapo”;
Flow control can be broken down into two
• Conditional Statements
• Loops

A conditional statement can be executed upon


the truth of a Boolean expression or variable

We will input data using cin>>

//prevents scientific notation output << std::fixed <<k;


cin
• cin implies character input
• It is part of the standard input stream stdin
• It takes inputs from standard input device
such as keyboard
• The extraction operator >> is used along with
the object cin to read the input
• The extraction operator extracts the data from
the objet cin entered from the keyboard
cin for numbers. continuation
// cin object n // cin object n
#include <iostream> #include <iostream>
using namespace std; using namespace std;
// Driver Code // Driver Code
int main() int main() enter a number
enter s
24
{ 14 { You entered 24
You entered 14
int s; double sam;
cout<<“enter s”; cout<<“enter a number”;
cin >> s; cin >> sam;
// Print output // Print output
cout <<“you entered”<< s; cout <<“you entered”<< s;
return 0; return 0;
} }
Multiple inputs
• #include <iostream> Enter name and age
James
• using namespace std;
14
• int main()
Name: James
• { string name; Age: 14
• int age;
• cout<<“enter name and age”;
• // Take multiple input using cin
• cin >> name >> age;
• cout << "Name : " << name << endl;
• cout << "Age : " << age << endl;
• return 0;
• }
cin for string
• Cin does not work well with strings
• It ignores the words after a white space
• If you enter Joshua Kimbele Adamson
• It takes only Joshua and ignores the rest
Cin for String
// cin object n
#include <iostream>
using namespace std;
int main() enter name
{ Salomay Richardson Arnold
string name; You entered Salomay
cout<<“enter name”;
cin >> name;
// Print output
cout <<“you entered”<< s;
return 0;
}
Correction – Two approaches
1. Define the variable as char array and use
cin.get() function for C

#include <iostream>
using namespace std;
int main()
{ char man[34];
cout << "enter man" << endl;
cin.get(man,34);
cout<<"you entered "<<man;
return 0; }
Correction – Two approaches
1. Define the variable as char array and use
puts() – for message and gets() for variable
• #include <iostream> enter name:
• using namespace std; Jame Aglawal Solomons
• int main() you entered
Jame Aglawal Solomons
• { char name[12];
• puts( "enter name: " ); //display
• gets(name); //collect
• puts("you entered ");//display
• puts(name); //display
• return 0; }
Correction – Two approaches
1. Define the variable as string and use
getline(cin, name) function for c++

#include <iostream> enter name:


using namespace std; james Agalga Shoto
int main() you entered james Agalga Shoto
{ string name;
cout << "enter name" << endl;
getline(cin,name);
cout<<"you entered "<<name;
return 0; }
C++ if Statement
• The if statement checks whether a test
condition is true or not (Boolean).
• If the test condition is true, it executes the
code/s inside the body of if statement.
• But if the test condition is false, it skips the
code/s inside the body of if statement
• This means that it could be used for all the
data types so far as the Boolean statement is
true
C++ if Statement
• A single if statement Note: There can be no
is written as: else without an if
If (Boolean_expression) statement
Yes_statement;
else
No_Statement;
Code execution
•#include <iostream>
•using namespace std;
•int main()
•{ //if code is correct everything within {}
must execute
• return 0; }
Example
#include <iostream> cout << "You entered a
using namespace std; positive integer: “
<<fan<<endl;
int main()
{ else
int fan; cout <<"You entered a
cout<< "Enter a no: "; negative number“
cin>> fan; <<fan;

if ( fan > 0) return 0;


}
Example 2
#include <iostream>
using namespace std;

int main()
{
int num;
cout<<"Enter a whole number: ";
cin>> num;
if (num % 2 == 0)
cout<<"The number you entered is even,";
else
cout<<"The number you entered is odd";

return 0;

}
Example 3
#include <iostream> if ((age>5) && (age <=10))
using namespace std; cout<<"You are not yet a teen";
int main()
if ((age >10)&& (age <= 15))
{
cout <<"You are not matured";
int age;
cout<<"Enter a whole number: "; //else affect only the if above
cin>> age ; else
if (age <= 0) cout<<endl<<endl;
cout<<"You need to
cout<<"You are not yet born";
support Chelsea no matter
if((age>0 )&&(age<=5 )) what is happening";
cout << "you are a todler"; return 0;
}
To modify the code such that the else affect all the if above add else to all the if’s except the first
# include<iostream> else if ((age>5)&(age<=10))
using namespace std; cout<<"you are not yet a teen ";

else if ((age >10)& (age<=15))


int main()
{ cout<<"you are now growing to
int age; maturity";
cout<<"enter a whole number: " ;
else
cin>>age;
cout<<"you need to support
if(age<=0) chelsea";
cout<<"you are not yet born "; return
0;
else if((age >0)& (age<=5)) }
cout<<"you are a todler ";
• Int main()
• { float salary;
• cout<<“enter your salary”;
• cin>>salary;
• If(salary<2500) {
• cout<<“you are a junior staff”<<endl;
• cout<<“you have to upgrade yourself”;
• }
• else
• cout<<“”you are a senior staff”;
• }
If else statement using a block
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
Example {}
#include <iostream> else
using namespace std; {
// if condition is false then
//print the following
int main () cout << "a is not less than 20;"
{ // local variable declaration: << endl;
int a = 100; }
// check the boolean condition //not part of the if else statement
if( a < 20 ) //will run no matter what
cout << "value of a is : " << a <<
{ endl;
// if condition is true then print
//the following return 0;
cout << "a is less than 20;" << }
endl;
}
#include <iostream>
using namespace std;
int main()
{
int x =4, y=9;
if(x==4){
if (y>9)
cout<<"onaapo";
else cout<<"James Bond\n";
cout<<"Chelsea\n";
cout<<"Orange";
}
else
cout<<"fanta\n";
cout<<"AiT\n";
cout<<"Fadama";
return 0;
}
#include <iostream> else if( a == 30 )
using namespace std; {
cout << "Value of a is 30" << endl;
int main ()
}
{
int a = 100; else
{
if( a == 10 ) cout << "Value of a is not matching"
{ << endl;
cout << "Value of a is 10" << endl; }
} cout << "Exact value of a is : " << a
else if( a == 20 ) << endl;
{
cout << "Value of a is 20" << endl; return 0;
} }
Nested if else statements
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is
true
}
}
example
#include <iostream> if(leaveDays>=12)
{
using namespace std; if(department ==13)
{
cout<<"you are from zoology and a
int main()
senior staff";
{ }
else
cout<<"you are a senior staff but
int leaveDays, department; not from zoology";
cout<<"enter your leave days: "; }
else
cin>>leaveDays; cout<<"you are a junior staff";
cout<<"please enter your
department: "; return 0;
}
cin>>department;
You can amend the code to use && instead
Nested if
#include <iostream>
using namespace std;
int main()
{ int leaveDays, department;
cout<<"enter your leave days: ";
cin>>leaveDays;
cout<<"please enter your department: ";
cin>>department;
if((leaveDays>=12)&&(department == 13))
{
cout<<"you are from zoology and a senior staff";
}
else
cout<<"you are a junior staff";
return 0;
#include <iostream>
using namespace std; else {
if( marks >= 60) {
cout << "U are within 2nd class !!";
int main () }
{ else {
int marks; if( marks >= 40) {
cout<<"Enter your marks: "; cout << "U are within 3rd class !!";
cin>>marks; }
else {
if( marks >= 80) cout << "U have failled !!";
{ }
cout << "U are within 1st class !!"; }
} }
return 0;
}
Var1 ? Var2 : var3
int a;
if (x > y)
a = x;
else
a = y;
//this is equivalent to:
int a = ( x > y ) ? x : y;
Example
#include <iostream>
using namespace std;
What is displayed

int main ()
{
// Local variable declaration:
int x, y = 10;
x = (y <= 10) ? 30 : 40;

cout << "value of x: " << x << endl;

return 0;
}
#include <iostream>
using namespace std; T = (A<=R) ? 12 : 11;
int main ()
{ cout << "value of T is "
// Local variable declaration: << T << endl;
int A,R,T;
cout<<"enter the value of A: return 0;
";
}
cin>> A;
cout<<"enter the value of R:
";
cin>>R;
#include <iostream>
using namespace std;
int main ()
{ // Local variable declaration:
int a,b = 6,x = 9;
a = (b>x)? 20: 40;
cout << "value of a: " << a << endl;
return 0;
}
?
What will be displayed and why
#include <iostream>
using namespace std;
int main ()
{ int x, y = 4, z = 2;
x = (y>z) ? y:z;
cout<< "The value of x is "<<x;
return 0;
}
?
What will be displayed and why
Many cin can be put together
#include <iostream>
int main()
{
using namespace std;
cout<<"enter two numbers: ";
int a,b;
cin>>a>>b;
cout<<"The larger of the two is "<<((a>b)?a:b)<<endl;
}
The switch statement
The switch statement
• The switch statement is similar to the if/ else,
statement.
• It evaluates the value of an integer and
compares with two or more values and
determine which code to execute.
• The following program determines your
average based on your grade.
The switch statement
• The switch statement is similar to the if/ else,
statement.
• It evaluates the value of an integer and
compares with two or more values and
determine which code to execute.
• The following program determines your
average based on your grade.
#include <iostream> case 'B':
cout<<"Your grade is between 70 - 79";
using namespace std; case 'C':
cout<<"Your grade is between 60 -
69"<<endl;
int main()
{ break;
char grade; case 'D':
cout<<"Enter your grade: "; cout<<"Your grade is between 50 - 59";
cin>>grade; break;
default:
cout<<"Your grade is below 50";
switch (grade) cout<<endl<<endl;
{ }
case 'A': return 0;
cout<<"Your grade is between }
80 - 100";
break;
Interpretation
• The switch key word evaluates an integer
expression grade while grade is a character
variable.
• Every character has a corresponding integer
value in the American Standard Code for
Information Interchange (ASCII) between 1 to
127.
• Note that ASCII value for upper cases are
different from those of lower cases
Interpretation Cont.
• The default key word serves the same
purpose as an final else in an if / else
statement.
• The integer following the switch key word is
evaluated and compared with the integer
constant following each case key word.
• If there is a match ie the two integers are
equal.
• The statement belonging to that case is
executed . Otherwise they are not
• Thus the statement belonging to a case are
conditional just as those of if / else
Differences between if /else and switch
• With an if / else statement, comparison
following the if part may be different from
comparison following the else part. Example
• If (apple == orange)
• Do this;
• else if (sales >= 500)
• Do that;
• In a switch statement, the constant integer
following a case must be compared with value
following the switch key word and nothing
else.
Differences between if /else and switch
• With an if / else statement, comparison
following the if part may be different from
comparison following the else part. Example
• If (apple == orange)
• Do this;
• else if (sales >= 500)
• Do that;
• In a switch statement, the constant integer
following a case must be compared with value
following the switch key word and nothing
else.
Possible
#include <iostream> case 'B':
case 'b':
using namespace std; cout<<"Your grade is between 70 - 79\n";
break;
int main()
{ case 'C':
char grade; case 'c':
cout<<"Enter your grade: "; cout<<"Your grade is between 60 - 69\n";
cin>>grade; break;

case 'D':
switch (grade) case 'd':
{ cout<<"Your grade is between 50 - 59\n";
case 'a': break;
case 'A': default:
cout<<"Your grade is between 80 - 100\n"; cout<<"Your grade is below 50\n";
break;
}
return 0;
}
Range of numbers
If (testScore >= 90)
Cout<< “Your grade is A”;
else if (testScore >=88)
cout<<“Your grade is B”;
else
cout<<"Your grade is blow
B\n";
#include <iostream> case 94:
using namespace std; case 93:
case 92:
int main() case 91:
{ case 90:
int testScore;
cout<<"Enter your test score: "; cout<<"Your grade is A\n";
cin>>testScore; break;
case 89:
switch (testScore) case 88:
{ cout<<"Your grade is B\n";
case 100: break;
case 99:
case 98: default:
case 97: cout<<"Your grade is blow B\n";
case 96:
case 95: }
return 0;
}
#include <iostream> Double Arguments
using namespace std; produce Semantic
int main()
errors
{ char echo;
char bank;
cout<<"enter two variables: "; Irrelevant output
cin>>bank>>echo; would be generated
switch (echo || bank) { for both or (||) and
case '8' ||'g': (&&)
cout<<"The wish is
through"<<endl; Try it out
// case 'n'&& 'p':
default:
cout<<"Catch up"; }
return 0;
Lab Exercise 2
a) Suppose savings and expenditure are
variables of type double. Write an if – else
statement that request two inputs from the user
and outputs the word “Solvent”, decreases the
value of savings by the value of expenditure, and
sets the value of expenditure to zero, provided
savings is at least greater than the expenditure.
If, however, savings is less than expenditure, the
program should output the word “Bankrupt”.
Lab Exercise 2 Cont.
Students of Amasaman Polytechnic will have to
travel to the school campus to check their
results. The authorities decided to make it
possible for them to check their results online.
On a trial basis, they asked that two persons
with the following credentials be used to test
the system.
Student’s name : Paulina Sosu
Index number PS1024
Lab Exercise 2 Cont.
Student’s name: Emmanuel Tetteh
Index number: ET1025
Write a c++ console application that would be embedded in a web application such
that if a username, PSosu and password PS1024 is inputted, the following should be
displayed

Welcome Paulina Sosu


Physics B
Chemistry B+
Mathematics B
However if a username ETetteh and password EY1025 is inputted
Welcome Emmanuel Tetteh
CS103: A
CS225: B
IT: 204: B+
Any other input should produce. Sorry you are not registered to use the application.
See the registrar.
NB: your job is just to provide the c++ code not how to embed it in the web app.
Exercises
1. Write an if – else statement that outputs the
word High if the value of the variable score is
greater than 100 and Low if the value score is at
most 100. the variable score is of type int
Exercises Cont.
2. Write an if – else statement that output the
word Passed provided the value of the variable
exam is greater than 60 and also the value of
variable program_done is greater than or equal
to 10.
Otherwise the if – else statement outputs the
word Fail.
The variables exam and program_done are both
of type int.
Lab Exercise
Write an if – else statement to display the
sentence
Welcome to Chigolo Bank
Your balance is GHC 500
Provided the username = Frank and password
Frank1235 are entered correctly.
The variable username and password are of type
String.
Submission date is
midnight 18/02/2018
Good Luck

You might also like