0% found this document useful (0 votes)
5 views

Basic computer programming II

class note

Uploaded by

akliluasebot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Basic computer programming II

class note

Uploaded by

akliluasebot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Basic computer programming II

Compiled by: Desiyalew Haregu


@CCI, WKU, 2014 EC.

Compiled by: Desiyalew H 1


Chapter one
Overview of programming
❖What is program?
✓Program is a specific set of ordered operations for a computer to perform.
✓Sets of instructions that tells the computer or any electronic device what to do.
✓Programs are created using specific programming languages such as C++,
Phyton, and the like.
✓Those are high level programming language that are human readable and
writable.
✓High level languages translated into low level machine languages by
compilers ,interpreters and assembler to be understandable by computer.

Compiled by: Desiyalew H 2


Cont.
❖What is programming?
✓Programming is a skill that can be acquired by a computer professional
that gives him/her the knowledge of making the computer perform the
required operation or task.
❖What is Computer programming?
✓It is the act of writing computer programs, which are a sequence of
instructions written using a Computer Programming Language to perform
a specified task by the compute.
❖What is Programming Language?
✓It is a set different category of written symbols that instruct computer
hardware to perform specified operations required by the designer.
❖What is computer program?
✓It is a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.

Compiled by: Desiyalew H 3


Cont.
❖What is programming?
✓Programming is a skill that can be acquired by a computer professional that gives.
✓When some one writes computer program.
❖Programmer
✓A person who is to produce computer program.
❖Algorithm
✓ A digital computer is a useful tool for solving a great variety of problems.
✓A solution to a problem is called an algorithm.
✓A step-by-step problem-solving process in which a solution is arrived at in a finite
amount of time.
✓It describes the sequence of steps to be performed for the problem to be solved.
✓A sets of instructions for solving a problem or accomplishing a task.
✓ Sequence of simple and human understandable set of instructions showing the step
of solving the problem.

Compiled by: Desiyalew H 4


Cont.
❖The algorithm should be:
✓Precise and unambiguous
✓Simple
✓Correct
✓Efficient
❖ Syntax?
✓In every programming Language there are sets of rules that govern
the symbols used in a programming language.
✓These set of rules determine how the programmer can make the
computer hardware to perform a specific operation.
✓These sets of rules are called syntax.

Compiled by: Desiyalew H 5


What skills do we need to be a programmer?
❖ In addition to basic computer skills in computer, needs to
have the following major skills .
✓Programming Language Skill
✓Problem Solving Skill
✓Algorithm Development

Compiled by: Desiyalew H 6


Basic Program development tips.
❖ The program we design in any programming language need to be:
✓Reliable: the program should always do what it is expected to do
and handle all types of exception.
✓Maintainable: the program should be in a way that it could be
modified and upgraded when the need arises.
✓Portable: It needs to be possible to adapt the software written for
one type of computer to another with minimum modification.
✓Efficient: the program should be designed to make optimal use of
time, space and other resources of the computer.

Compiled by: Desiyalew H 7


What is C++ ?
❖ C++: A programming language developed in 1983 by Bjarne
Stroustrup.
✓One of the world's most widely used languages today
✓Built for systems programming with high speed/efficiency
✓Built on older C language by adding object-oriented programming
✓Continues to be improved over time (latest version: C++17)
❖C++ syntax has many similarities with Java and C
✓Similar data types (int, double, char, void)
✓Similar operators (+, -, *, /, %) and keywords
✓Use of { }braces for scope
✓Comes equipped with a large standard library for you to use

Compiled by: Desiyalew H 8


Developing a C++ Program
Translating a C++ Program
❖The following three steps are required to create and translate a C++
program:
1) First, a text editor is used to save the C++ program in a text file. In other
words, the source code is saved to a source file(.cpp).
2) The source file is put through a compiler for translation. If everything
works as planned, an object file made up of machine code is created. The
object file is also referred to as a module.
3) Finally, the linker combines the object file with other modules to form an
executable file. These further modules contain functions from standard
libraries or parts of the program that have been compiled previously.
Linker: A program that combines the object program with other programs
in the library and is used in the program to create the executable code.
Loader: A program that loads an executable program into main memory.

Compiled by: Desiyalew H 9


Developing a C++ Program
Translating a C++ Program

Compiled by: Desiyalew H 10


Developing a C++ Program
Translating a C++ Program

Compiled by: Desiyalew H 11


Programming with the Problem Analysis–Coding–
Execution Cycle

Compiled by: Desiyalew H 12


Programming with the Problem Analysis–Coding–
Execution Cycle

Compiled by: Desiyalew H 13


The building blocks of programs
❖ Sequence of statements, typically grouped into functions.
❖For a C++ executable, exactly one function called main().
❖Can consist of multiple files and typically use libraries.
❖Statement -- smallest complete executable unit of a program
✓ Declaration statement
✓ Execution statement
✓ Compound statement -- any set of statements enclosed in set braces { } (often
called a block )

Compiled by: Desiyalew H 14


C++ Program Structure
❖ A C++ program is a collection of commands or statements. •
Example:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!";
return 0;
}
Let's break down the parts of the code:

Compiled by: Desiyalew H 15


C++ Program Structure (cont.)
❖ #include <iostream>
✓C++ offers various headers, each of which contains information needed for
programs to work properly.
✓This program calls for the header <iostream>.
✓The number sign (#) at the beginning of a line targets the compiler's
preprocessor.
✓In this case, #include tells the pre-processor to include the <iostream> header.
✓The <iostream> header defines the standard stream objects that input and
output data.
✓The C++ compiler ignores blank lines.
✓In general, blank lines serve to improve the code's readability and structure.
✓Whitespace, such as spaces, tabs, and newlines, is also ignored, although it is
used to enhance the program's visual attractiveness.

Compiled by: Desiyalew H 16


C++ Program Structure (cont.)
❖ using namespace std;
✓In our code, the line using namespace std; tells the compiler to use the std
(standard) namespace.
✓The std namespace includes features of the C++ Standard Library.
❖Main
✓Program execution begins with the main function, int main().
✓Curly brackets { } indicate the beginning and end of a function, which can also
be called the function's body (block).
✓The information inside the brackets indicates what the function does when
executed.
✓The entry point of every C++ program is main(), irrespective of what the
program does

Compiled by: Desiyalew H 17


C++ Program Structure (cont.)
❖ cout
✓The next line, cout << "Hello world!"; results in the display of "Hello world!"
to the screen.
✓In C++, streams are used to perform input and output operations.
✓ cout is the used for the output operations.
✓ cout is used in combination with the insertion operator.
✓ Write the insertion operator as << to insert the data that comes after it into the
stream that comes before.
✓ In C++, the semicolon is used to terminate a statement. Each statement must
end with a semicolon. It indicates the end of one logical expression.

Compiled by: Desiyalew H 18


C++ Program Structure (cont.)
❖ Statements
✓A block is a set of logically connected statements, surrounded
by opening and closing curly braces.
✓For example:
{
cout << "Hello world!";
return 0;
}
✓You can have multiple statements on a single line, if you
remember to end each statement with a semicolon.
✓Failing to do so will result in an error.

Compiled by: Desiyalew H 19


C++ Program Structure (cont.)
❖ Return
✓The last instruction in the program is the return statement.
✓The line return 0; terminates the main() function and causes it to return the value 0 to the
calling process.
✓A non-zero value (usually of 1) signals abnormal termination.
#include <iostream>
using namespace std;
int main()
{
cout<<“hello world”;
return 0;
}
✓If the return statement is left off, the C++ compiler implicitly inserts "return 0;" to the end
of the main() function.
✓Note: we can remove the (return 0) line from the code and still we get the same result.

Compiled by: Desiyalew H 20


C++ Program Structure (cont.)
❖ New Line
✓The cout operator does not insert a line break at the end of the output.
✓One way to print two lines is to use the endl manipulator, which will put in a line break..
✓ The new line character \n can be used as an alternative to endl.
✓ The backslash (\) is called an escape character, and indicates a "special" character
#include <iostream>
using namespace std;
int main()
{
cout<<“hello world”<<endl; // we can also use \n instead of endl.
cout<<“hello world \n”<<endl;
cout << "I love programming!";
return 0;
}
✓The endl manipulator moves down to a new line to print the second text.

Compiled by: Desiyalew H 21


Basic Elements of Programming
❖ Identifiers
✓A valid identifier is a sequence of one or more letters, digits or
underlined symbols. The length of an identifier is not limited.
✓Neither space nor marked letters can be part of an identifier.
✓Only letters, digits and underlined characters are valid.
✓Variable identifiers should always begin with a letter or an
underscore. By any means they should begin with a digit.
✓Key words should not be used as names for identifiers.
✓C++ is not case sensitive. Small letter and capital letters are
different for C++. Eg: variable Age is not identical with
variable age .

Compiled by: Desiyalew H 22


Basic Elements of Programming (Cont.)
❖ Variables
✓Creating a variable reserves a space in memory for storing
values.
✓A variable will have three component
✓ Variables are used for holding data values so that they can
be used in various computations in a program.
✓ All variables have three important properties:
1. Data Type: a type which is established when the variable is
defined. (e.g. integer, real, character etc.).
⁘Data type describes the property of the data and the size of the
reserved memory

Compiled by: Desiyalew H 23


Basic Elements of Programming (Cont.)
❖ Variables
2. Name: a name which will be used to refer to the value in the
variable.
✓ A unique identifier for the reserved memory location
3. Value: a value which can be changed by assigning a new
value to the variable.

Compiled by: Desiyalew H 24


Basic Elements of Programming (Cont.)
❖ C++ Keywords
✓ Words with special meaning to the compiler
✓ Examples : int , main ,float, cin, cout, char, else, for, if …
❖ Data type
✓ data types are the built-in types defined by the C++ language.
✓bool: has two possible values, true or false
✓ char - 1 byte on most systems.
➢ Typically used for representing characters
➢ Stored with an integer code underneath (ASCII on most computers today)
✓ short - (usually at least 2 bytes)
✓ int - represent whole number value(4 bytes on most systems)
✓ long - (usually 4 or more bytes)
✓ floating point types - for storage of decimal numbers (i.e. a fractional part after the decimal)
➢ float
➢ double
➢ long double
Compiled by: Desiyalew H 25
Basic Elements of Programming (Cont.)
❖Data type

Compiled by: Desiyalew H 26


Basic Elements of Programming (Cont.)
❖ Comments
✓ Comments are explanatory statements that you can include in the C++ code to explain what
the code is doing.
✓ The compiler ignores everything that appears in the comment, so none of that information
shows in the result.
✓ A comment beginning with two slashes (//) is called a single-line comment.
✓ The slashes tell the compiler to ignore everything that follows, until the end of the line.
✓ For example:
#include <iostream>
using namespace std;
int main()
{ // prints "Hello world"
cout << "Hello world!";
return 0;
}
✓ When the above code is compiled, it will ignore the // prints "Hello world" statement and will
produce the following result:

Compiled by: Desiyalew H 27


Basic Elements of Programming (Cont.)
❖ Multi-Line Comments
✓Comments that require multiple lines begin with /* and
end with */
✓You can place them on the same line or insert one or more
lines between them.
Example : /* This is a comment */
/* C++ comments are used to
insert notes or descriptions */

Compiled by: Desiyalew H 28


Basic Elements of Programming (Cont.)
❖ Constants
✓ A variable can be declared to be constant. This means it cannot change once it’s declared and
initialized
✓ Use the keyword const
✓ MUST declare and initialize on the same line
✓ Syntax: const datatype constant_name= value;
Example:
const int SIZE = 10;
const double PI = 3.1415;
// this one is illegal, because it’s not // initialized on the same line const int LIMIT; // BAD!!!
LIMIT = 20;
✓A symbolic constant is created with a preprocessor directive, #define. (This
directive is also used to create macros).
Examples:
#define PI 3.14159
#define DOLLAR ‘$’
#define MAXSTUDENTS 100
✓The preprocessor replaces all occurrences of the symbol in code with the value
following it. (like find/replace in MS Word).
✓This happens before the actual compilation stage begins
Compiled by: Desiyalew H 29
Basic Elements of Programming (Cont.)
❖ Literals
✓Literals are also constants. They are literal values written
in code.
✓integer literal -- an actual integer number written in code
(4, -10, 18)
✓float literal -- an actual decimal number written in code
(4.5, -12.9, 5.0) -- Note: these are interpreted as type
double by most C++ compilers
✓character literal -- a character in single quotes: ('F', 'a', '\n’)
✓string literal -- a string in double quotes: ("Hello", "Bye",
"Wow!\n")
Compiled by: Desiyalew H 30
Basic Elements of Programming (Cont.)
❖ Escape Sequences
✓String and character literals can contain special escape sequences.
✓They represent single characters that cannot be represented with a
single character from the keyboard in your code.
✓The backslash \is the indicator of an escape sequence. The
backslash and the next character are together considered ONE item
(one char) .

Compiled by: Desiyalew H 31


Basic Elements of Programming (Cont.)
❖Declaring Variables
✓ Variables can be created in a process known as declaration.
✓ Declaration will instruct the computer to reserve a memory location with the name and size
specified during the declaration.
✓ The name of a variable sometimes is called an identifier which should be unique in a program.
✓ Syntax: Datatype Variable_name;
✓ Example : int age; string name; float gpa;
❖Initializing Variables
✓ When a variable is assigned a value at the time of declaration, it is called variable
initialization.
✓ Assigning a value to the variable immediately after declaration
✓ Syntax : Datatype Variable_name = initial value;
✓ Example : int age=20;
or
int age;
age=20;

Compiled by: Desiyalew H 32


Basic Elements of Programming (Cont.)
❖Scope of Variables.
✓Scope of a variable is the boundary or block in a program where a
variable can be accessed.
✓Global variables: are variables that can be referred/accessed any
where in the code, within any function, as long as it is declared first. A
variable declared before any function immediately after the include
statements are global variables.
✓Local Variables: the scope of the local variable is limited to the code
level or block within which they are declared.

Compiled by: Desiyalew H 33


Basic Elements of Programming (Cont.)
Example: c = a + b;
#include <iostream> cout << c << endl ;
using namespace std; GPA = 70.0/3.0;
// Variable declaration: add();
float GPA; //global var cout << GPA << endl ;
void add(); }
int main () void add()
{ { int num1;
// Variable definition: num1 =50;
int a, b; //local var float sum;
int c; sum=num1+GPA;
// actual initialization cout<<sum<<endl;
a = 10; }
b = 20;
Compiled by: Desiyalew H 34
Basic Elements of Programming (Cont.)
❖User Input
✓To enable the user to input a value, use cin in combination with the extraction
operator (>>).
✓The variable containing the extracted data follows the operator.
✓The following example shows how to accept user input and store it in the num
variable: int num; cin >> num;
✓As with cout, extractions on cin can be chained to request more than one input
in a single statement: cin >> a >> b;
Example 1:
#include <iostream>
using namespace std;
int main()
{ int a, b, sum;
cout << "Enter a number \n";
cin >> a;
cout << "Enter another number \n";
cin >> b;
Sum= a +b;
Cout<<“the sum of the number is”<< sum;
return 0;
}
Compiled by: Desiyalew H 35
Basic Elements of Programming (Cont.)
❖Operators
✓Operators are functions! They just have a more familiar notation
(often known as infix notation. Get used to thinking of operators as
functions -- we will eventually be defining our own operators.
✓ int x, y, z; ...
✓ z = x + y; // infix notation for + operator
✓ z = +(x,y); // alternate (valid) notation -- called like a function
✓Arity : how many operands
➢unary operator -- has one operand
➢binary operator -- has two operands
➢ternary operator -- has three operands
✓Only ternary operator is the "conditional expression" operator
(expr ? expr : expr).
✓The rest are unary or binary
Compiled by: Desiyalew H 36
Arithmetic Operators and Operator Precedence
❖C++ arithmetic operators:
✓+ addition
✓- subtraction
✓* multiplication
✓/ division
✓% modulus operator
✓+, -, *, and / can be used with integral and floating-point data types
✓Operators can be unary or binary
❖Order of Precedence
✓ All operations inside of () are evaluated first
✓*, /, and % are at the same level of precedence and are evaluated next
✓+ and – have the same level of precedence and are evaluated last
✓When operators are on the same level − Performed from left to right
(associativity)
✓3 * 7 - 6 + 2 * 5 / 4 + 6 means (((3 * 7) – 6) + ((2 * 5) / 4 )) + 6

Compiled by: Desiyalew H 37


Arithmetic Operators and Operator Precedence
❖Expressions
✓ If all operands are integers
➢ Expression is called an integral expression
➢ Yields an integral result
➢ Example: 2 + 3 =5
✓ If all operands are floating-point
➢ Expression is called a floating-point expression
➢ Yields a floating-point result
➢ Example: 12.8 +17.5 = 30.3
✓ Mixed expression
➢ Has operands of different data type
➢ Contains integers and floating point
➢ Example: 2+2.3 , 6/4+3.9
✓ Evaluation rules:
➢ If operator has same types of operands : Evaluated according to the type of the operands
➢ If operator has both types of operands
❑ Integer is changed to floating-point
❑ Operator is evaluated
❑ Result is floating-point
➢ Entire expression is evaluated according to precedence rules
Compiled by: Desiyalew H 38
Arithmetic Operators and Operator Precedence
❖Expressions
✓The examples below show legal and illegal C++ expressions.
✓55+15 // legal C++ expression (Both operands of the + operator are
integers)
✓55 + "John" // illegal (The + operator is not defined for integer and
string)
✓ "Hello," + "John" // legal (The + operator is used for string
concatenation)

Compiled by: Desiyalew H 39


Increment and Decrement
❖ Pre-increment: incrementing is done before the
value of x is used in the rest of the expression.
❖ Post-increment: incrementing is done after the #include<iostream>
value of x is used in the rest of the expression.
using namespace std;
❖ Note - this only matters if the variable is actually int main()
used in another expression. These two statements { int x = 5, count = 7;
by themselves have the same effect. int result = x * ++count;
Prefix example: cout<<result<<endl;// result = 40, count = 8
x = 5; y = ++x; // x is 6, y is 6 x = 5, count = 7;
• Postfix example: result = x * count++;
x = 5; y = x++; // x is 6, y is 5 cout<<result<<endl;
int k = 5; int m=10;
(auto increment prefix) y= ++k + 10; //gives 16 for y int sum;
(auto increment postfix) y= k++ + 10; //gives 15 for y sum=m+count;
(auto decrement prefix) y= --k + 10; //gives 14 for y
(auto decrement postfix) y= k-- + 10; //gives 15 for y cout<<sum;
}

✓Output: 40,35,18

Compiled by: Desiyalew H 40


Increment and Decrement
❖Strings ❖Characters
✓Characters are single letters or
❖A string is composed of numbers, symbols, and must be enclosed
characters, or symbols. between single quotes, like 'a', 'b', etc.
❖String literals are placed in double ✓In C++, single quotation marks
quotation marks. indicate a character;
✓double quotes create a string literal.
❖Examples: "Hello", "My name is ✓While 'a' is a single a character literal,
David". "a" is a string literal.
❖ You need to include the <string> ✓A char variable holds a 1-byte integer.
library to use the string data type. ✓ However, instead of interpreting the
value of the char as an integer, the
❖You don't need to include <string> value of a char variable is typically
separately, if you already use interpreted as an ASCII character.
<iostream>. ✓Example: char test = 'S';
#include <string>
using namespace std;
int main()
{
string a = "I am learning C++";
return 0;
}
Compiled by: Desiyalew H 41
MODIFIER TYPES
❖A modifier is used to alter the meaning of the base type so that it
more precisely fits the needs of various situations. The data type
modifiers are listed here:
➢ signed
➢ unsigned
➢ long
➢ short
❖The modifiers signed, unsigned, long, and short can be applied to
integer base types.
❖In addition, signed and unsigned can be applied to char, and long
can be applied to double.
❖The modifiers signed and unsigned can also be used as prefix to
long or short modifiers. For example, unsigned long int.
Example: unsigned x;
Unsigned int x;

Compiled by: Desiyalew H 42


Relational operator (==, !=, > , <, >=, <=)
❖In order to evaluate a comparison between two expressions,
we can use the relational operator.
❖The result of a relational operator is a bool value that can
only be true or false according to the result of the
comparison.
❖E.g.: (7 = = 5) would return false or returns 0
(5 > 4) would return true or returns 1
❖The operands of a relational operator must evaluate to a
number. Characters are valid operands since they are
represented by numeric values.
❖For E.g.: ‘A’ < ‘F’ would return true or 1. it is like (65 < 70)
Compiled by: Desiyalew H 43
Logical Operators (!, &&, ||):
✓Logical negation (!) is a unary operator, which negates the logical
value of its operand. If its operand is non zero, it produce 0, and
if it is 0 it produce 1.
✓Logical AND (&&) produces 0 if one or both of its operands
evaluate to 0 otherwise it produces 1.
✓Logical OR (||) produces 0 if both of its operands evaluate to 0
otherwise, it produces 1.
E.g.:
!20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
✓N.B. In general, any non-zero value can be used to represent the
logical true, whereas only zero represents the logical false.
Compiled by: Desiyalew H 44
Conditional Operator (?:)
✓The conditional operator takes three operands.
✓It has the general form:
Syntax: operand1 ? operand2 : operand3
✓First operand1 is a relational expression and will be evaluated. If
the result of the evaluation is non zero (which means TRUE),
then operand2 will be the final result. Otherwise, operand3 is the
final result.
E.g.: General Example Z=(X<Y? X : Y)
✓This expression means that if X is less than Y the value of X will
be assigned to Z otherwise (if X>=Y) the value of Y will be
assigned to Z.
E.g.: int m=1,n=2,min;
min = (m < n ? m : n); The value stored in min is 1.
E.g.: (7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
Compiled by: Desiyalew H 45
The sizeof() Operator
✓This operator is used for calculating the size of any data item
or type.
✓It takes a single operand (e.g. 100) and returns the size of the
specified entity in bytes. The outcome is totally machine
dependent.
E.g.: a = sizeof(char)
b = sizeof(int)
c = sizeof(1.55) etc.
Explicit type casting operators.
✓Type casting operators allows you to convert a datum of a given type to another
data type.
E.g. int i;
float f = 3.14;
i = (int)f; ➔ equivalent to i = int(f);
Then variable i will have a value of 3 ignoring the decimal point
Compiled by: Desiyalew H 46
Control statements
✓A control statement is a statement that determines whether other
statement will be executed.
✓Control flow is the order in which the statement executed.
✓There are 3 types of control statement :
➢Loops / iteration : while, do-while, and for
➢Conditional/selections statements: if-else,switch,and the
conditional operator
➢ jumps : goto, continue, and break

Compiled by: Desiyalew H 47


Conditional/selections statements
❖The if Statement
✓The if statement is used to execute some code if a condition is true.
Syntax: if (condition)
{ //statements }
✓The condition specifies which expression is to be evaluated.
✓If the condition is true, the statements in the curly brackets are
executed.
✓If the condition is false, the statements in the curly brackets are
ignored, and the program continues to run after the if statements body.
✓Use relational operators to evaluate conditions.
Example: if (7 > 4)
{ cout << "Yes"; } // Outputs "Yes"
✓ Note: A condition specified in an if statement does not require a
semicolon.
Compiled by: Desiyalew H 48
Conditional/selections statements
❖The if..else Statement
✓An if statement can be followed by an optional else statement, which
executes when the condition is false.
Syntax: if (condition)
{ //statements }
else
{ //statements }
✓The compiler will test the condition:
➢If it evaluates to true, then the code inside the if statement will be executed.
➢If it evaluates to false, then the code inside the else statement will be executed.
✓When only one statement is used inside the if/else, then the curly
braces can be omitted.
Example: int mark = 90;
if (mark < 50)
{ cout << "You failed." << endl; }
else
{ cout << "You passed." << endl; }
// Outputs "You passed."
Compiled by: Desiyalew H 49
Conditional/selections statements
❖Nested if Statement
✓You can also include, or nest, if statements within another if
statement.
int mark = 100;
if (mark >= 50)
{
cout << "You passed." << endl;
if (mark == 100)
{
cout <<"Perfect!" << endl;
}
}
else
{
cout << "You failed." << endl;
}
/*Outputs You passed. Perfect! */
Compiled by: Desiyalew H 50
Conditional/selections statements
❖ Nested if .. Else Statement
✓ C++ provides the option of nesting an unlimited number of if/else statements.
int age = 18;
if (age > 14)
{
if(age >= 18)
{
cout << "Adult";
}
else
{
cout << "Teenager";
}
}
Else
{
if (age > 0)
{
cout << "Child";
}
else
{
cout << "Something's wrong";
}
}

✓ Remember that all else statements must have corresponding if statements.


✓ In if/else statements, a single statement can be included without enclosing it into curly braces.
Compiled by: Desiyalew H 51
Loops / iteration
❖The while Loop
✓A loop repeatedly executes a set of statements until a particular
condition is satisfied.
✓A while loop statement repeatedly executes a target statement as
long as a given condition remains true.
Syntax: while (condition)
{ statement(s); }
✓ The loop iterates while the condition is true.
✓At the point when the condition becomes false, program control
is shifted to the line that immediately follows the loop.
✓The loop's body is the block of statements within curly braces.
Compiled by: Desiyalew H 52
Conditional/selections statements
❖The while Loop (cont.) Example 2:
Example1: #include<iostream>
int num = 1; Using namespace std;
while (num < 6) int num = 1;
{ int number;
cout << "Number: " << num << endl; int total = 0;
num = num + 1;
while (num <= 5)
}
/* Outputs
{
Number: 1 cin >> number;
Number: 2 total += number;
Number: 3 num++;
Number: 4
}
Number: 5 */.
cout << total << endl
Compiled by: Desiyalew H 53
Conditional/selections statements
❖The for loop
✓A for loop is a repetition control structure that allows you to efficiently
write a loop that executes a specific number of times.
Syntax: for ( init; condition; increment )
{ statement(s); }
✓The init step is executed first and does not repeat.
✓Next, the condition is evaluated, and the body of the loop is executed
if the condition is true.
✓In the next step, the increment statement updates the loop control
variable.
✓Then, the loop's body repeats itself, only stopping when the condition
becomes false.
Example: for (int x = 1; x < 10; x++)
{ // some code }
Compiled by: Desiyalew H 54
Conditional/selections statements
❖The for loop (cont.)
✓ The init and increment statements may be left out, if not needed, but remember that the
semicolons are mandatory.
✓ The example below uses a for loop to print numbers from 0 to 9.
f or (int a = 0; a < 10; a++)
{ cout << a << endl; } /* Outputs 0 1 2 3 4 5 6 7 8 9 */
✓ In the init step, we declared a variable a and set it to equal 0. a < 10 is the condition.
✓ After each iteration, the a++ increment statement is executed.
✓ When a increments to 10, the condition evaluates to false, and the loop stops.
✓ It's possible to change the increment statement.
for (int a = 0; a < 50; a+=10)
{ cout << a << endl; } /* Outputs 0 10 20 30 40 */
✓ You can also use decrement in the statement.
for (int a = 10; a >= 0; a -= 3)
{ cout << a << endl; } /* Outputs 10 7 4 1 */
✓ When using the for loop, don't forget the semicolon after the init and condition statements.
Compiled by: Desiyalew H 55
Conditional/selections statements
❖The do...while Loop
✓Unlike for and while loops, which test the loop condition at the top of
the loop, the do...while loop checks its condition at the bottom of the
loop.
✓A do...while loop is like a while loop. The one difference is that the
do...while loop is guaranteed to execute at least one time.
Syntax: do { statement(s); }
while (condition);
Example:
int a = 0;
do {
cout << a << endl;
a++;
}
while(a < 5); /* Outputs 0 1 2 3 4 */
✓Don't forget the semicolon after the while statement.
Compiled by: Desiyalew H 56
Conditional/selections statements
❖while vs. do...while
✓ If the condition evaluated to false, the statements in the do would still run once:
int a = 42;
do {
cout << a << endl;
a++;
}
while(a < 5); // Outputs 42
✓ The do...while loop executes the statements at least once, and then tests the condition.
✓ The while loop executes the statement after testing condition.
❖The do...while Loop
✓ As with other loops, if the condition in the loop never evaluates to false, the loop will run
forever.
Example: int a = 42;
do { cout << a << endl; }
while (a > 0);
✓ This will print 42 to the screen forever.
✓ Always test your loops, so you know that they operate in the manner you expect.
Compiled by: Desiyalew H 57
Conditional/selections statements
❖Multiple Conditions
✓Sometimes there is a need to test a variable for equality
against multiple values.
✓That can be achieved using multiple if statements.
Example:
int age = 42;
if (age == 16)
{ cout <<"Too young"; }
if (age == 42)
{ cout << "Adult"; }
if (age == 70)
{ cout << "Senior"; }
✓The switch statement is a more elegant solution in this
scenario.
Compiled by: Desiyalew H 58
Conditional/selections statements
❖The switch Statement
✓The switch statement tests a variable against a list of values, which are
called cases, to determine whether it is equal to any of them.
Syntax: switch (expression)
{
case value1:
statement(s);
break;
case value2:
statement(s);
break;
...
case valueN:
statement(s);
break;
}
Compiled by: Desiyalew H 59
Conditional/selections statements
❖The switch Statement(cont.)
✓ Switch evaluates the expression to determine whether it's equal to the value in the case statement.
✓ If a match is found, it executes the statements in that case.
✓ A switch can contain any number of case statements, which are followed by the value in question and a
colon.
✓ Here is the previous example written using a single switch statement:
int age = 42;
switch (age)
{ case 16:
cout << "Too young";
break;
case 42:
cout << "Adult";
break;
case 70:
cout << "Senior";
break;
}
✓ The code above is equivalent to three if statements.
✓ Notice the keyword break; that follows each case. That will be covered shortly.
Compiled by: Desiyalew H 60
Conditional/selections statements
❖The switch Statement(cont.)
✓The default Case
✓In a switch statement, the optional default case can be used to perform a task
when none of the cases is determined to be true.
Example: int age = 25;
switch (age)
{ case 16: cout << "Too young"; break;
case 42: cout << "Adult"; break;
case 70: cout << "Senior"; break;
default: cout << "This is the default case"; } // Outputs "This is the default case"
✓The default statement's code executes when none of the cases matches the
switch expression.
✓The default case must appear at the end of the switch.

Compiled by: Desiyalew H 61


jumps
❖The break Statement
✓ The break statement's role is to terminate the switch statement.
✓ In instances in which the variable is equal to a case, the statements that come after the case continue to
execute until they encounter a break statement.
✓ In other words, leaving out a break statement results in the execution of all of the statements in the
following cases, even those that don't match the expression.
Example: int age = 42; switch (age)
{ case 16: cout << "Too young" << endl;
case 42: cout << "Adult" << endl;
case 70: cout << "Senior" << endl;
default: cout <<"This is the default case" << endl;
} /* Outputs Adult Senior This is the default case */
✓ As you can see, the program executed the matching case statement, printing "Adult" to the screen.
✓ With no specified break statement, the statements continued to run after the matching case.
✓ Thus, all the other case statements printed.
✓ This type of behavior is called fall-through.
✓ As the switch statement's final case, the default case requires no break statement.
✓ The break statement can also be used to break out of a loop.
Compiled by: Desiyalew H 62
Conditional/selections statements
❖The continue statement
✓The continue statement terminates the current iteration of a loop and instead jumps to the next
iteration.
✓It is an error to use the continue statement outside a loop.
✓In while and do while loops, the next iteration commences from the loop condition.
✓In a “for” loop, the next iteration commences from the loop’s third expression.
E.g.: for(int n=10;n>0;n--)
{ if(n==5) continue; //causes a jump to n—
cout<<n<< “,”; }

✓When the continue statement appears inside nested loops, it applies to the loop immediately
enclosing it, and not to the outer loops. For example, in the following set of nested loops, the
continue statement applies to the “for” loop, and not to the “while” loop.
E.g.: while(more)
{
for(i=0;i<n;i++)
{
cin>>num; if(num<0)
continue; //causes a jump to : i++
}
}

Compiled by: Desiyalew H 63


Conditional/selections statements
❖The break statement
✓A break statement may appear inside a loop (while, do, or for) or a switch
statement. It causes a jump out of these constructs, and hence terminates
them.
✓Like the continue statement, a break statement only applies to the “loop”
or “switch” immediately enclosing it. It is an error to use the break
statement outside a loop or a switch statement.
E.g.: for(n=10;n>0;n--)
{ cout<<n<< “,”;
if(n = = 3)
{ cout<< “count down aborted!!”;
break;
}
} Compiled by: Desiyalew H 64
Conditional/selections statements
❖goto Statement LOOP:do
{
❖A goto statement provides an if( a == 15)
unconditional jump from the goto to a
labeled statement in the same {
function. // skip the iteration.
Syntax: goto label; a = a + 1;
.. goto LOOP;
. }
label: statement; cout << "value of a: " << a
E.g.: int main () << endl;
{ a = a + 1;
// Local variable declaration: }while( a < 20 );
int a = 10;
return 0;
// do loop execution }
Compiled by: Desiyalew H 65

You might also like