0% found this document useful (0 votes)
47 views42 pages

Oop Abeer

Uploaded by

kalasingayvonne
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)
47 views42 pages

Oop Abeer

Uploaded by

kalasingayvonne
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/ 42

Object Oriented Programming

(OOP)

)Theoretical & Practical(

MSc. Ahmed Hussein


&
MSc. Abeer Mohammed

2022/2021
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Review of C++
PROGRAMMING

• A digital computer is a useful tool for solving a great variety of problems.

• A solution to a problem is called an algorithm; it describes the sequence of


steps to be performed for the problem to be solved.

• To make an algorithm intelligible to a computer, it needs to be expressed in a


language understood by a computer (machine language).

• Programs expressed in the machine language are said to be executable.

• A further abstraction of machine language is the assembly language.

• High-level languages such as C++ provide a much more convenient notation


for implementing algorithms.

COMPILER

• A program written in a high-level language is translated to assembly


language by a translator called a compiler.

• Compilers are utility programs that take your code and transform it into
executable machine code files.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Fig(1): C++ COMPITAION

In figure (1) show definition of compilation process (definition) :

• The C++ source code is your program.


• The compiler is a program that translate your C++ code into object code.
• Object code consists of machine instructions and information on how to
load the program into memory.
• A linker program takes the object code from your program and the code
from the various libraries and builds them into an executable file.
• Libraries contain the (already translated) code used by your program
(such as iostream).

STRCTURE OF A C++ PROGRAM

A C++ program is structured in a specific and particular manner. In C++, a


program is divided into the following three sections:

1. Standard Libraries Section


2. Main Function Section
3. Function Body Section

For example, let’s look at the implementation of the Hello World program:
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Standard libraries section

• #include is a specific preprocessor command that effectively copies and


pastes the entire text of the file, specified between the angle brackets,
into the source code.

• The file <iostream>, which is a standard file that should come with the
C++ compiler, is short for input-output streams. This command
contains code for displaying and getting an input from the user.

• namespace is a prefix that is applied to all the names in a certain


set. iostream file defines two names used in this program -
cout and endl.

• This code is saying: Use the cout and endl tools from the std toolbox.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Main function section

• The starting point of all C++ programs is the main function.

• This function is called by the operating system when your program is


executed by the computer.

• { signifies the start of a block of code, and } signifies the end.

Function body section

• The name cout is short for character output and displays whatever is
between the << brackets.

• Symbols such as << can also behave like functions and are used with the
keyword cout.

• The return keyword tells the program to return a value to the


function int main

• After the return statement, execution control returns to the operating


system component that launched this program.

• Execution of the code terminates here.


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

NAMESPACE

Consider a situation, when we have two persons with the same name,
(Ahmed), in the same class. Whenever we need to differentiate them
definitely we would have to use some additional information along with
their name, like either the area, if they live in different area or their
mother’s or father’s name, etc.

Same situation can arise in your C++ applications. For example, you might
be writing some code that has a function called xyz() and there is another
library available which is also having same function xyz(). Now the
compiler has no way of knowing which version of xyz() function you are
referring to within your code.

A namespace is designed to overcome this difficulty and is used as


additional information to differentiate similar functions, classes, variables
etc. with the same name available in different libraries. Using namespace,
you can define the context in which names are defined. In essence, a
namespace defines a scope.

IDENTIFIERS

An identifier is a name used to identify a class, variable, function, or any other


user-defined item. The basic rules for naming classes in C# are as follows −

• A name must begin with a letter that could be followed by a sequence of


letters, digits (0 - 9) or underscore. The first character in an identifier
cannot be a digit.

• It must not contain any embedded space or symbol such as? - + ! @ # %


^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

• It should not be a C# keyword.

The following are some examples of identifiers

Class Names
class Calculation
class Demo Variable Names
int a;
Valid Functions Names int marks;
void display() int rank;
void getMarks() double res_marks;

VARIABLES

A variable provides us with named storage that our programs can manipulate.
Each variable in C++ has a specific type, which determines the size and layout
of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable. The
name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C++ is case-sensitive: There are
following basic types of variable in C++

Type Description
bool Stores either value true or false.
char Typically a single octet one byte. This is an
integer type.
int The most natural size of integer for the
machine.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

float A single-precision floating point value.


double A double-precision floating point value
void Represents the absence of type.
wchar_t A wide character type.

Variable Definition in C++

A variable definition tells the compiler where and how much storage to create
for the variable. A variable definition specifies a data type, and contains a list
of one or more variables of that type as follows −

Here, type must be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., and variable_list may consist of
one or more identifier names separated by commas. Some valid declarations
are shown here

The line int i, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Variables can be initialized assigned an initial value in their declaration. The


initializer consists of an equal sign followed by a constant expression as
follows

Some examples are:

For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL allbyteshavethevalue0; the initial value of all
other variables is undefined.

Variable Declaration in C++

A variable declaration provides assurance to the compiler that there is one


variable existing with the given type and name so that compiler proceed for
further compilation without needing complete detail about the variable. A
variable declaration has its meaning at the time of compilation only, compiler
needs actual variable declaration at the time of linking of the program. A
variable declaration is useful when you are using multiple files and you define
your variable in one of the files which will be available at the time of linking of
the program. You will use extern keyword to declare a variable at any place.
Though you can declare a variable multiple times in your C++ program, but it
can be defined only once in a file, a function or a block of code.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Example

Try the following example where a variable has been declared at the top, but it
has been defined inside the main function:

CONSTANTS
Constants refer to fixed values that the program may not alter and they are
called literals.

Constants can be of any of the basic data types and can be divided into
Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean
Values.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Again, constants are treated just like regular variables except that their values
cannot be modified after their definition.

Defining Constants

There are two simple ways in C++ to define constants −

1. Using #define preprocessor.

2. Using const keyword.

1. The #define Preprocessor

Following is the form to use #define preprocessor to define a constant −

#define identifier value. Following example explains it in detail

When the above code is compiled and executed, it produces the following
result −

50
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

2. The const Keyword

You can use const prefix to declare constants with a specific type as follows −

const type variable = value;


Following example explains it in detail –

When the above code is compiled and executed, it produces the following
result −

50

Enumeration (ENUM)
Enumeration is a user defined data type in C/C++ language. It is used to
assign names to the integral constants which makes a program easy to read
and maintain. The keyword “enum” is used to declare an enumeration.

The following is the syntax of enums.

enum enum_name{const1, const2, ....... };


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Here,

enum_name − Any name given by user.

const1, const2 − These are values of type flag.

The enum keyword is also used to define the variables of enum type. There are
two ways to define the variables of enum type as follows −

enum colors{red, black};

enum suit{heart, diamond=8, spade=3, club};

Example
#include <iostream>
using namespace std;
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
int main() {
cout <<"The value of enum color : "<<red<<","<<black;
cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
return 0;
}
Output

The value of enum color : 5,6

The default value of enum suit : 0,8,3,4

In the above program, two enums are declared as color and suit outside the
main() function.

enum colors{red=5, black};

enum suit{heart, diamond=8, spade=3, club};

In the main() function, the values of enum elements are printed.


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

out <<"The value of enum color : "<<red<<","<<black;

cout <<"\nThe default value of enum suit :


"<<heart<<","<<diamond<<","<<spade<<","<<club;

OPERATORS

An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations. C++ is rich in built-in operators and
provide the following types of operators −

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators

Arithmetic Operators

There are following arithmetic operators supported by C++ language −

Assume variable A holds 10 and variable B holds 20, then

Operator Description Example

+ Adds two operands A + B will give 30


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

- Subtracts second operand from A - B will give -10


the first

* Multiplies both operands A * B will give 200

/ Divides numerator by de- B / A will give 2


numerator

% Modulus Operator and B % A will give 0


remainder of after an integer
division

++ Increment operator, increases A++ will give 11


integer value by one

-- Decrement operator, decreases A-- will give 9


integer value by one

Relational Operators

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then

Operator Description Example


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

== Checks if the values of two (A == B) is not true.


operands are equal or not, if yes
then condition becomes true.

!= Checks if the values of two (A != B) is true.


operands are equal or not, if
values are not equal then
condition becomes true.

> Checks if the value of left (A > B) is not true.


operand is greater than the value
of right operand, if yes then
condition becomes true.

< Checks if the value of left (A < B) is true.


operand is less than the value of
right operand, if yes then
condition becomes true.

>= Checks if the value of left (A >= B) is not true.


operand is greater than or equal
to the value of right operand, if
yes then condition becomes true.

<= Checks if the value of left (A <= B) is true.


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

operand is less than or equal to


the value of right operand, if yes
then condition becomes true.

For example :

#include <iostream>
using namespace std;

int main() {
int a = 21;
int b = 10;
int c ;

if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ;
} else {
cout << "Line 1 - a is not equal to b" << endl ;
}

if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}

if( a > b ) {
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

cout << "Line 3 - a is greater than b" << endl ;


} else {
cout << "Line 3 - a is not greater than b" << endl ;
}

/* Let's change the values of a and b */


a = 5;
b = 20;
if( a <= b ) {
cout << "Line 4 - a is either less than \ or equal to b" << endl ;
}

if( b >= a ) {
cout << "Line 5 - b is either greater than \ or equal to b" << endl ;
}

return 0;
}

When the above code is compiled and executed, it produces the following
result −

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or euqal to b
Line 5 - b is either greater than or equal to b

Logical Operators
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

There are following logical operators supported by C++ language.

Assume variable A holds 1 and variable B holds 0, then −

Operator Description Example

&& Called Logical AND operator. If (A && B) is false.


both the operands are non-zero,
then condition becomes true.

|| Called Logical OR Operator. If (A || B) is true.


any of the two operands is non-
zero, then condition becomes
true.

! Called Logical NOT Operator. !(A && B) is true.


Use to reverses the logical state
of its operand. If a condition is
true, then Logical NOT operator
will make false.

For example

#include <iostream>

using namespace std;

int main() {

bool is male= true;


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

bool is tall=true;

if (is male && is tall){

cout<<"You are a tall male";

else {

cout<< "You are not male";

return 0;

Example2:

#include <iostream>
using namespace std;

int main() {
int a = 5;
int b = 20;
int c ;

if(a && b) {
cout << "Line 1 - Condition is true"<< endl ;
}

if(a || b) {
cout << "Line 2 - Condition is true"<< endl ;
}
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

/* Let's change the values of a and b */


a = 0;
b = 10;

if(a && b) {
cout << "Line 3 - Condition is true"<< endl ;
} else {
cout << "Line 4 - Condition is not true"<< endl ;
}

if(!(a && b)) {


cout << "Line 5 - Condition is true"<< endl ;
}

return 0;
}

When the above code is compiled and executed, it produces the following
result −

Line 1 - Condition is true


Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

The truth tables for &, |, and ^ are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

TYPE CASTING
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

As the name itself suggest, typecasting means the conversion of a variable


type to another. In other words, making an integer type variable to act like
another such as character for a single set of operation when required. So
basically there are two types of conversion in C++. One is known as Implicit
Type conversion whereas the other one is Explicit Type conversion. Implicit
conversion is also known as automatic type conversion because it is done by
the compiler on its own without any user intervention. If more than one data
type is present implicit will work.

Syntax:

int num1;

float num2;

num2 = (float) num1;

In the above syntax, the value of num1 has promoted from int to float directly
which is also known as standard conversion.

There are basically 4 sub-types of casting in cast operator.

• Static Cast: It is used to cast a pointer of base class into derived class.
• Dynamic Cast: It is used in runtime casting.
• Constant Cast: It is used in explicitly overriding constant in a cast.
• Reinterpret Cast: It is used to change a pointer to any other type of
pointer.

Example

here is c++ program to demonstrate the working of implicit & explicit type
conversion:
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

#include <iostream>

using namespace std ;

int main()

int a = 15 ;

char b = 'c' ;

a = a + b ; // implicitly conversion of a.

float z = a + 3.0 ; // implicitly conversion of z

cout << " The Value of a is = " << a << endl

<< " The Value of b is = " << b << endl

<< " The Value of z is = " << z << endl ;

return 0 ;

Output:

The value of a is 114

The value of b is c

The value of c is 117

Example 2

#include <iostream>
using namespace std;
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}
Output

x = 107
y=a
z = 108

CONTROL STRCTURE

C++ has only three kinds of control structures, which from this point forward
we refer to as control statements: the sequence statement, selection
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

statements (three types—if, if...else and switch) and repetition statements


(three types—while, for and do...while).

C++ if, if...else and Nested if...else

In computer programming, we use the if statement to run a block code only


when a certain condition is met.

For example, assigning grades (A, B, C) based on marks obtained by a student.

• if the percentage is above 90, assign grade A


• if the percentage is above 75, assign grade B
• if the percentage is above 65, assign grade C
There are three forms of if...else statements in C++.
1. if statement
2. if...else statement
3. if...else if...else statement

C++ if Statement

The syntax of the if statement is:

if (condition) {
// body of if statement
}

The if statement evaluates the condition inside the parentheses ( ).


• If the condition evaluates to true, the code inside the body of if is executed.
• If the condition evaluates to false, the code inside the body of if is skipped.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

Note: The code inside { } is the body of the if statement.

Example

// Program to print positive number entered by the user

// If the user enters a negative number, it is skipped

#include <iostream>

using namespace std;

int main() {

int number;

cout << "Enter an integer: ";

cin >> number;

// checks if the number is positive

if (number > 0) {
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

cout << "You entered a positive integer: " << number << endl;

cout << "This statement is always executed.";

return 0;

C++ if...else

The if statement can have an optional else clause. Its syntax is:

if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}

The if..else statement evaluates the condition inside the parenthesis.


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

If the condition evaluates true,


• the code inside the body of if is executed
• the code inside the body of else is skipped from execution
If the condition evaluates false,
• the code inside the body of else is executed
• the code inside the body of if is skipped from execution
Example 2

// Program to check whether an integer is positive or negative

// This program considers 0 as a positive number

#include <iostream>

using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

cin >> number;

if (number >= 0) {

cout << "You entered a positive integer: " << number << endl;

else {

cout << "You entered a negative integer: " << number << endl;

cout << "This line is always printed.";

return 0;

C++ if...else...else if statement

The if...else statement is used to execute a block of code among two


alternatives. However, if we need to make a choice between more than two
alternatives, we use the if...else if...else statement.
The syntax of the if...else if...else statement is:

if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

// code block 3
}

Here,

• If condition1 evaluates to true, the code block 1 is executed.


• If condition1 evaluates to false, then condition2 is evaluated.
• If condition2 is true, the code block 2 is executed.
• If condition2 is false, the code block 3 is executed.

Note: There can be more than one else if statement but only
one if and else statements.

Example 3

// Program to check whether an integer is positive, negative or zero

#include <iostream>

using namespace std;

int main() {
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

int number;

cout << "Enter an integer: ";

cin >> number;

if (number > 0) {

cout << "You entered a positive integer: " << number << endl;

else if (number < 0) {

cout << "You entered a negative integer: " << number << endl;

else {

cout << "You entered 0." << endl;

cout << "This line is always printed.";

return 0;

C++ Nested if...else

Sometimes, we need to use an if statement inside another if statement. This is


known as nested if statement.
Think of it as multiple layers of if statements. There is a first,
outer if statement, and inside it is another, inner if statement. Its syntax is:
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

// outer if statement
if (condition1) {
// statements

// inner if statement
if (condition2) {
// statements
}
}

Notes:
• We can add else and else if statements to the inner if statement as required.
• The inner if statement can also be inserted inside the outer else or else
if statements (if they exist).
• We can nest multiple layers of if statements.

Example

// C++ program to find if an integer is even or odd or neither (0)

// using nested if statements

#include <iostream>

using namespace std;

int main() {

int num;

cout << "Enter an integer: ";


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

cin >> num;

// outer if condition

if (num != 0) {

// inner if condition

if ((num % 2) == 0) {

cout << "The number is even." << endl;

// inner else condition

else {

cout << "The number is odd." << endl;

// outer else condition

else {

cout << "The number is 0 and it is neither even nor odd." << endl;

cout << "This line is always printed." << endl;

In the above example,


Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

• We take an integer as an input from the user and store it in the variable num.
• We then use an if...else statement to check whether num is not equal to 0.
o If true, then the inner if...else statement is executed.
o If false, the code inside the outer else condition is executed, which prints
"The number is 0 and neither even nor odd."
• The inner if...else statement checks whether the input number is divisible
by 2.
o If true, then we print a statement saying that the number is even.
o If false, we print that the number is odd.
Notice that 0 is also divisible by 2, but it is actually not an even number. This
is why we first make sure that the input number is not 0 in the
outer if condition.

Note: As you can see, nested if...else makes your logic complicated. If
possible, you should always try to avoid nested if...else.

Example

Read three number and check which one is larger using if-else?

#include <iostream>

using namespace std;

int main() {

int a,b,c;

cout <<"Enter first number";

cin>>a;
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

cout <<"Enter second number";

cin>>b;

cout <<"Enter third number";

cin>>c;

if(a>b && a>c)

cout <<a<<"is the large number";

else if(b>a && b>c)

cout <<b<<"is the large number";

else if(c>a && c>b){

cout <<c<<"is the large number";

else

cout <<"ALL the number is same";

}
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

return 0;

SWITCH STATEMENT

A switch statement allows a variable to be tested for equality against a list of


values. Each value is called a case, and the variable being switched on is
checked for each case

Syntax:

The syntax for a switch statement in C++ is as follows −

switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional

// you can have any number of case statements.


default : //Optional
statement(s);
}

The following rules apply to a switch statement −

• The expression used in a switch statement must have an integral or


enumerated type, or be of a class type in which the class has a single
conversion function to an integral or enumerated type.
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

• You can have any number of case statements within a switch. Each case
is followed by the value to be compared to and a colon.

• The constant-expression for a case must be the same data type as


the variable in the switch, and it must be a constant or a literal.

• When the variable being switched on is equal to a case, the statements


following that case will execute until a break statement is reached.

• When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.

• Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.

• A switch statement can have an optional default case, which must


appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed in
the default case.

Example

#include <iostream>
using namespace std;

int main () {
// local variable declaration:
char grade = 'A';

switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;

return 0;
}

Another solution

#include <iostream>

using namespace std;

int main () {

int grade;

cout<<"Enter your grade";

cin>>grade;

switch(grade) {

case 100 :

cout << "Excellent!" << endl;

break;

case 80 :

cout << "Very good" << endl;

break;
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

case 60 :

cout << "Passing" << endl;

break;

case 49 :

case 30 :

cout << "Too bad, go study" << endl;

break;

default :

cout << "This is not a possible grade" << endl;

return 0;

Example: Write a program in the C++ language to design a simple calculator.


We give it two integer numbers and one signs of addition, subtraction,
multiplication or division, and it returns the result to us. In the case of
entering any symbol for another operation, it tells us that it is not known?

# include <iostream>

using namespace std;

int main() {

char op;
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

int num1, num2;

cout << "Enter two operands: ";

cin >> num1 >> num2;

cout << "Enter operator: +, -, *, /: ";

cin >> op;

switch(op) {

case '+':

cout << num1 << " + " << num2 << " = " << num1 + num2;

break;

case '-':

cout << num1 << " - " << num2 << " = " << num1 - num2;

break;

case '*':

cout << num1 << " * " << num2 << " = " << num1 * num2;

break;

case '/':

cout << num1 << " / " << num2 << " = " << num1 / num2;
Object Oriented Programing MSc.Ahmed& Abeer
Computer Engineering Department -2nd Stage Al- Esraa University Collage

break;

default:

// If the operator is other than +, -, * or /, error message is shown

cout << "Error! operator is not correct";

break;

return 0;

You might also like