0% found this document useful (0 votes)
6 views233 pages

Lecture Notes Introduction To Computing 2025-2026

Uploaded by

nesma1999200
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)
6 views233 pages

Lecture Notes Introduction To Computing 2025-2026

Uploaded by

nesma1999200
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

Introduction to Computing

 Module Title:
 Introduction to Computing
 Module Code :
 25CSCI01P
 Assessment :
 1. One in-Class test. This method carries 20% of the total mark and aims to develop and assess
learning outcomes 1 - 3. It covers lectures from lecture 1 to lecture 7. It will take place in Week 8
 2. One in-Lab test. This method carries 30% of the total mark and aims to develop and assess
learning outcomes 4 - 6. It covers lectures from lecture 1 to lecture 9. It will take place in Week 10
 3. One 2-hour unseen written final examination. This method carries 50% of the total mark and
assesses learning outcomes 1 - 6.
 Text Book :
 Tony Gaddis, "Starting Out with C++: From control structures through
objects", 7th Edition, Pearson, 2012.
 Nell Dale, Charles C. Weems, "Programming and Problem Solving with C++, 4th Edition", Jones and
Bartlett Publishers, Sudbury, MA, 2004, 1100 pp.

1
Introduction to
Computing

Lecture 1
What is Programming???

Dr. Mostafa Salama


Dr. Wessam Elbehaidy
What is a computer?

 A computer is a programmable electronic


device/machine.
 A program can control the operations done
by a computer
 The electronic device depends on electricity
Program
in its operations, which is either OFF(0) or
ON(1). Any data in a computer is represented Operating System
only by a binary number.
 For example, any decimal number can be
represented as binary number:
Input Output
 0 ➔ 00000000, 1 ➔ 00000001
Device Computer Device
 2 ➔ 00000010, 3 ➔ 00000011
 Also, any character can be represented by a
decimal number (called ASCII code) that is
converted to also to a binary number: 3
 ‘A’ ➔ 65 ➔ 01000001
What is a Program?

 A program
 is set of coded instructions that a computer
can operate.
 Its purpose is to solve a problem or produce
a desired result.
 An instruction is an order that is given to a
Program
computer to operate, like get, calculate,
print.
 A program example: If a program is required
Operating System
to calculate the sum of two numbers:
 Instruction 1: get from the user two
numbers, through the input device of the
computer, : Input Computer Output
 Instruction 2: calculate the sum of the two
Device Device
numbers by using the Arithmetic-Logic (AL) AL unit
unit in the computer.
 Instruction 3: print put the resulted sum to
the user, through the output device in the
4
computer.
What does the Programmer
do? Programmer

 A programmer writes a program, then writes


users starts to use this program.
 A programmer uses a formal language C++ Program
(called a Programming language) to write High-Level Language
programs, for example, C++ and java.
 A C++ programming language is a high translates
level programming language, where a
human can understand and use.
Machine Code
 A C++ program must follow a specific Low-Level Language
grammar (syntax), the program must learn
this syntax to write a correct program. Input Computer Output
 When the programmer writes a C++ Device Device
program (high-level), this program must be AL unit

converted (translated) to a language that a


5
computer can understand (low level) which
is called machine language.
How does the programmer prepares
an executable program?Programmer
 An executable program written by a writes
programmer is a program that is ready to
run (a user can start to use this program).
C++ Program
 A programmer writes a C++ program using High-Level Language
an integrated development environment
(IDE) like Microsoft visual studio. This IDE is
installed in the computer of the IDE (e.g. Visual Studio)
programmer that contains a space to write
his program. Compiler Libraries
 The IDE contains a software called a
compiler. The task of the compiler is to Machine Code
check the syntax of the programmers’ code, Low-Level Language
then the compiler translates the code from
the high level language (C++) to the low Input Computer Output
level language (machine code). Device 6 Device
AL unit
 So after writing the program, the
programmer compiles the codes, then run
the code for testing.
How does the programmer prepares
an executable program?Programmer
Another important component in the IDE is

called the libraries. writes
 A programmer can not write every part in his
program from scratch, in every time she/he
C++ Program
High-Level Language
creates a new program.
 For example, to print in the output screen, you
need an instruction that is already programmed to IDE (e.g. Visual Studio)
do the printing. Also to do a mathematical
operation like 2 to the power 3 (23), it would be Compiler Libraries
simple if there is an already made (programmed)
instruction that can do the power calculation.
Machine Code
 Each library in IDE of C++ contains a set of Low-Level Language
already programmed instructions that can
perform the usually used tasks. Input Device Computer Output
 One of most used library in the IDE is named as 7 Device
“iostream” which is responsible for printing to AL unit
user some output, and getting from user some
input.
How to start programming
with Visual Studio?
 As a new programmer, You can simple
go the following link and install visual
studio with C++, professional 2019.
 After Installation, a programmer can create
a new empty C++ project. Then from
Source files in the solution explorer, add a
new item, C++ file of extension cpp.
 An empty page will be created, where the
programmer can write his new c++ code.
 After writing your program, and to run the
code of the program, click ctrl+F5. This will
push the compiler to check the syntax of
your program, then convert the code to a
machine code. Finally, the Visual Studio
(VS) will run your program.
 The running environment of VS is called the
command prompt.
Introduction to
Computing

Lecture 2
Writing a Program in C++

Dr. Mostafa Salama


A sample program 1 to run in
the VS:
1. // This program prints out a welcome statement.
2. #include <iostream>;
3. using namespace std;
4. int main(){
5. cout << "Programming is great fun!";
 The output screen of visual
6. cout << "Enjoy your first program!"; studio.
7. return 0;  This program prints out two
successive statements on the
8. } output screen.
 This output screen is called the
“Console”
A sample program 1 to run in
the VS:
1.

2.

3.

4.
Going through every line in
this sample program.
5.

6.

7.

8.

11
A sample program 1 to run in
the VS:
1. // This program calculates the user's pay.

 The // marks the beginning of a comment.


 The compiler ignores everything from the double slash to
the end of the line. This means you can type anything you
want on that line and the compiler will never complain
about its wrong syntax, and also the compiler will not
include this line in the translated machine code.
 Note that only the translated code will run in your
machine.
 Although comments are not required, they are very
important to programmers. Comments help explain what is
purpose of the following piece of code.
A sample program 1 to run in
the VS:
2. #include <iostream>;

 The #include directive causes the preprocessor to include the


contents of another file in the program. The word inside the
brackets, “iostream”, is the name of the file that is to be included.
The iostream file contains a set of commands that allows a C++
program to display output on the screen and read input from the
keyboard.
 Because this program uses a command called “cout” to display
output on the screen, the iostream file must be included.
 The contents of the iostream file are included in the program at the
point where the #include statement appears. The iostream file is
called a header file, so it should be included at the head, or the
top, of the program.
 Every statement in C++ must end with a semicolon “;” which is the
same like using a fullstop in English language to end its statements.
A sample program 1 to run in
the VS:
3. using namespace std;

 A namespace is list of names or abbreviations that are used in this


program by C++. These names are reserved only to your C++
programs. The word std is an abbreviation for standard names. These
name in the std namespace are almost used by most of the
programming languages.
 The statement “using namespace std;” declares that the program
will be accessing entities whose names are part of the namespace
called std.
 In order for a C++ program to use the entities in iostream , it must
have access to the std namespace.

 Please remember that C++ is a case sensitive programming


language, which means you can use capital or small letters any time.
For example, Using is incorrect, while using is correct.
A sample program 1 to run in
the VS:
4. int main() {

 The word “int” is an abbreviation for an integer. An integer is a


decimal number that does not contain a floating point. For
example, 43 is an integer, but 43.0 is not an integer.
 main() can considered as a title of the list of instructions of your
program. All the lines of code between the two curly brackets {
and } is going to be executed. Every thing outside these brackets
are only helping to run the code inside these brackets.
 main() is a function!, a function is a list of statements that lay
between { and } brackets, and has a specific task to do.
 Although most C++ programs have more than one function, every
C++ program must have a function called main.
A sample program 1 to run in
the VS:
5. cout << "Programming is great fun!";

 To put it simply, this line displays a message on the screen.


 cout is command that prints To print a message on the console
screen. So this word “cout” is an abbreviation for “Output on
Console”. This abbreviation name exists in the namespace std.
 This command exists in the iostream library, as you send a
stream of characters to the console output.
 cout << "Programming is great fun!";
 Notice that the << operator is used to send the text
“Programming is great fun!” to the cout command. When the <<
symbol is used this way, it is called the stream insertion
operator. The item immediately to the right of the operator is
sent to cout and then displayed on the screen.
 To print a text, the text must be inside two double quotations
"".
A sample program 1 to run in
the VS:
7. return 0;

 This sends the integer value 0 back to the visual studio upon the
program(s) completion.
 The value 0 usually indicates that a program executed
successfully.
 This statement does not affect the execution of your program. It
informs the visual studio that your program is terminated and no
further instructions to execute.
A sample program 2 to run in
the VS:
1. // This program prints new lines.
2. #include <iostream>;
3. using namespace std;
4. int main(){
5. cout << "Programming is great fun! \n";
 The output screen of visual
6. cout << "Enjoy your \t first program!" << endl; studio.
7. cout << "a \t b\t c\t d\t" << endl;  This program shows you how to
enter to a new line, like pressing
8. return 0; enter after writing the statement
on the output.
9. }
 Writing “\n” inside the text
between “”, or writing endl in
separate printing place, after <<.
 \t is to do a tab space inside the
text you are writing.
A sample program 2 to run in
the VS:
1. // This program prints new lines.
2. #include <iostream>;
3. using namespace std;

 In summary, the first line is just a comment that will not affect
the operations inside your program.
 The second line is to inform the compiler that you are going to
use functionalities that are existing in a library called
“iostream”. The function that is going to be used in this library
is the “cout” function. This function is responsible for printing
on the output screen.
 The third line is to inform the compiler that you are going to
use the standard name space “using namespace std;”. The
names here are the abbreviations that are going to be used in
the program. The name of the printing function “cout” is an
abbreviation for console output.
A sample program 2 to run in
the VS:
4. int main(){ … }

 In summary, the fourth line is referring to the main


functionality of your program.
 A function contains a list of instructions, laying between two
curly brackets {, and }. Your code is going to be listed in-
between these brackets.
 The word “int” is an abbreviation to the word “integer”. This
abbreviation is saved inside std namespace.
 main is the name of the function that contains the programmer
code.
A sample program 2 to run in
the VS:
5. cout << "Programming is great fun! \n";
6. cout << "Enjoy your \t first program!" << endl;
7. cout << "a \t b\t c\t d\t" << endl;
 The “cout” command is responsible for printing a text on the
console window.
 The text may contain special characters that refers to special
keyboard keys
 “\n” is corresponding to “new line, the [enter] key”, it instruct
the text to got to new line for writing.
 “\t” is corresponding to “Tab” key, it instruct the text to
include a space for writing the next text.
 Another way to go to a new line, “endl”.
 These special characters are used for organizing the output
on the screen.
A sample program 3 to run in
the VS:
1. // This program shows the use of “<<“.
2. #include <iostream>;
3. using namespace std;
4. int main(){
5. cout << "==>==>==>\n";
6. cout << "==>" << "==>" << "==>" << endl;  The output screen of visual
studio.
7. cout << "==>\n===>\n====>\n" << endl;  This program uses the separator
8. return 0; “<<” to print another text
following the old text.
9. }  Notice that statements 5 and 6
are printing the same text.
 Statement line 7 prints a text
“==>”, followed by going to a
new line “==>”, followed by
going to a new line “==>”.
A sample program 4 to run in
the VS:
1. // This program prints out variable values.
2. #include <iostream>;
3. using namespace std;
4. int main(){
5. //defining a variable x, x is an integer.
6. int x;
7. //assigning a value to x, this is an initial value  The output screen of visual
8. x = 4; studio.
 The program defines a variable
9. //printing out the value number 4
and set a value to this variable.
10. cout << "==>" << 4 << endl;  This program prints 4 as a
11. //printing out the stored value in x. value, then prints the value
inside the variable x, then
12. cout << "==>" << x << endl;
prints the text of variable x
13. //printing out the text value of variable name x which is “x”.
14. cout << "==>" << "x" << endl;
15. return 0;
16. }
A sample program 4 to run in
the VS: RAM

5. //defining a variable x, x is an integer.


6. int x;

 The program “list of instructions” starts in line 5, where this


line is first line after the left curly bracket “{” of the main
x
function.
 Line number 5 is a comment, has no use in processing, that
describes the next line.
 Line number 6 is called a definition statement. The
programmer is defining a new variable. This statement actually
creates in the RAM a space of a specific size to store the value
of x. The location of this space is randomly defined, that is why
this type of memory is called “Random” Access memory.
 Initially, this variable has no value, so variable x is un-
initialized variable.
A sample program 4 to run in
the VS: RAM

7. //assigning a value to x, this is an initial value


8. x = 4;

 Line number 7 is called an assignment statement, where the


programmer is assigning a value “4” value x.
x
 This statement actually set a new value to created space inside 4
the RAM. This space that represents the variable x, has the
value of 4 stored inside.
 Since this is the first time in this program to set a value inside
this variable, this statement can be called “initialization
statement” as in addition, it is still an assignment statement.
 The size of this space in the memory is 4 bytes. A byte is
formed of 8 bits, each bit is either 0 or 1.
 So the data inside this variable is saved as follows: [00000000
00000000 00000000 00000100], where 4 as a decimal is 100 in
binary.
A sample program 4 to run in
the VS: RAM

9. //printing out the value number 4


10. cout << "==>" << 4 << endl;
11. //printing out the stored value in x.
12. cout << "==>" << x << endl;
x
 Line number 10 prints a text “==>”, followed by printing the 4
numerical value of 4, followed by going to a new line.
 Notice that the value of 4 is not between double quotations ""
like text “==>”. This is because numerical values are printed
directly.
 Line number 12 again prints “==>” in a new line because of the
previous line, followed by printing the numerical value inside
the variable x which is 4, followed by going to a new line.
 Notice that the variable x is not between double quotations "",
tis is because variables are also printed directly like the
numerical values.
A sample program 4 to run in
the VS:
13. //printing out the text value of variable name x

14. cout << "==>" << "x" << endl;

 Line number 14 prints out the text “==>” followed by the text
“x” followed by going to a new line
 Notice that C++ considers here x as a usual text between
quotations, and not as a variable.
A sample program 4 to run in
the VS: RAM

5. //defining a variable x, x is an integer.


6. int x;

Back to line 6, this statement is called a definition statement. The



variable x is defined as an integer. x
 Here, the name of the variable is “x”. The programmer is free to
choose the name of the variable
 However, the variable name is restricted to some rules, the first
rule is that the variable name can not start by a number. For
example a programmer can not define a variable of name 45x,
however, x45 is correct.
 Wrong: int 4x;
 Correct: int x4;
 Also, variable names can not include special characters.
 Wrong: int p@y;
 Correct: int pay;
A sample program 4 to run in
the VS: RAM

5. //defining a variable x, x is an integer.


6. int x;

 Also, variable names can not include – or ., but can include _.


x
 Wrong: int building.Number;
 Correct: int building_Number;

 Also, variable names can not include space.


 Wrong: int pay of item;
 Correct: int payOfitem;

 Also, variable names can not be reserved words of C++, like the
word “include”, “using”, “main”, “int”, “return”, “cout”, …..
Reserved words are group of words in C++ that are used in the
commands and instructions.
 Notice that variable of name “x” in small letters is different from
another variable “X” in capital letter. C++ is case sensitive.
A sample program 4 to run in
the VS: RAM

5. //defining a variable x, x is an integer.


6. int x;

 Notice that the variable “x” is named as an identifier. It


identifies a variable of type integer.
x
 Programmer cannot define two variables by the same name in
the same program, that is why it is called identifier.
 For example:
 Wrong:
 int x = 4;

 Int x = 5;

 Correct: because x and X are different identifiers.


 int x = 4;

 int X = 5;
A sample program 5 to run in
the VS:
1. // This program calculates the user's pay.
2. #include <iostream>;
3. using namespace std;
4. int main() {
5. int hours, rate, pay;
 The output screen of visual
6. cout << "How many hours did you work? "; studio.
7. cin >> hours;  In this program, we have to
inputs, hours and rates. The user
8. cout << "How much do you get paid per hour? "; enters 8 and 200.
9. cin >> rate;  The computer will calculate a
new value called, pay. The value
10. pay = hours * rate; of pay is equal to product of
hours and rates.
11. cout << "You have earned $" << pay << endl;
 The result of the program is
12. return 0; printed as the output of the
program. The program prints
13. }
$1600.
A sample program 5 to run in
the VS: RAM

5. int hours, rate, pay; hours

 Line number 5 defines 3 variables altogether in the same


statement. These variable are defined as integers.
 Remember that int is an abbreviation for integer, this name rate
“int” is saved in the std namespace.
 The 3 variables are created in different random locations in the
memory. The 3 locations contains no values yet after the
definition their corresponding variables.
pay
 Integer variables are representing the decimal number values
of no floating point. For example 42323 is an integer, but
312.2332 is not an integer.
A sample program 5 to run in
the VS: RAM

6. cout << "How many hours did you work? "; hours
7. cin >> hours;
8
 Line number 5 prints a text, this text asks the user of the
program to input a specific value.
 The next line, number 6, uses the command cin to enable the rate
user to input the value of the variable “hours”.
 In running of this program, if the user enters 8, then click
[enter], the program will save the value of 8 inside the variable
“hours”.
pay
 The command cin is followed by the input operator “>>” which
is the inverse of the output operator “<<” of the cout
command.
A sample program 5 to run in
the VS: RAM

8. cout << "How much do you get paid per hour? "; hours
9. cin >> rate;
8
 Line number 8 prints a text, this text asks the user of the
program to input another specific value.
 The next line, number 9, uses the command cin to enable the rate
user to input the value of the another variable “rate”.
200
 In running of this program, if the user enters 200, then click
[enter], the program will save the value of 200 inside the
variable “rate”.
pay
 Now the program enters the value of two variables, hours and
rate through the input from the user.
A sample program 5 to run in
the VS: RAM

10. pay = hours * rate; hours


11. cout << "You have earned $" << pay << endl;
8
 Line number 10 multiplies the value of hours by the value of
rate. The result of this multiplication is saved inside the
variable “pay”.
rate
 The value of the variable pay is calculated during the running
of the program and saved inside the integer variable pay. 200
 Pay = 8 * 200 = 1600
 This multiplication is an arithmatic operation that is executed
inside the AL unit of the computer. pay
 Notice that the multiplication of two integers is also an integer.
1600
 Finally, line 11 prints out a text, followed by printing the value
of the variable pay, followed by going to a new line.
A sample program 6 to run in
the VS:
1. // This program shows the size of variables.
2. #include <iostream>;
3. using namespace std;
4. int main(){
5. cout << "The size the integer variable is = " << sizeof(int) <<endl;
6. int x = 4;
7. cout << "The value of x is initialized by " << x << endl;
8. cout << "The size of the variable x is = " << sizeof(x) << endl;
9. x = 400000000;
10. cout << "The value of x is assigned by " << x << endl;
11. cout << "the size of the variable x still = " << sizeof(x) << endl;
12. return 0;
13. }
A sample program 6 to run in
the VS: RAM

5. cout << "The size the integer variable is = " << sizeof(int) <<endl; x:int

 Line number 5 prints out the size of data type “integer” of


name int. 4 bytes

 sizeof() is a function, its result is the size of thing between the


circular brackets (). The name “int” is between () is the input
of this function. The size of the integer variables inside the
memory is 4 bytes.
 When we define a variable of type integer, a space of 4 bytes is
allocated for this variable.
 The printed text here is “The size the integer variable
is = ” followed by printing out the value of sizeof(int)
Which is 4.
A sample program 6 to run in
the VS: RAM

6. int x = 4; x:int
7. cout << "The value of x is initialized by " << x << endl;
8. cout << "The size of the variable x is = " << sizeof(x) << endl;
4
4 bytes
 Line number 6 defines x as integer, and set the value of x by 4
in the same statement. This statement is named as an
initialization statement, the value of x is stated while the
variable is defined.
 The value of x is saved in a location in the memory, the size of
the memory allocated for x is 4 bytes because x is integer.
 Line 7 prints the value of x, while line 8 prints the size of x in
the memory.
A sample program 6 to run in
the VS: RAM

9. x = 400000000; x:int
10. cout << "The value of x is assigned by " << x << endl;
400000000

11. cout << "the size of the variable x still = " << sizeof(x) << endl;
4 bytes
 Line number 9 assigns a new different value of to x, this value
is 400000000. This statement is named as an assignment
statement.
 Line 10 prints the value of x, while line 11 prints the size of x
in the memory.
 Notice that the size of the x does not change, as the printed
size in line 8 and line 11 is the same. However the value of x in
line 11 is ( 400000000), which is much bigger than the value of
x in line 8 (4).
 The minimum value of any integer is -2,147,483,648 while the
maximum value is +2,147,483,647.
Introduction to
Computing

Lecture 3
Double and operations in C++

Dr. Mostafa Salama


A sample program 7 to run in
the VS:
1. #include <iostream>
2. using namespace std;
3. int main(){
4. int length, width, area;
5. cout << "This program calculates the area of a ";
6. cout << "rectangle.\n";
7. cout << "Enter the length and width of the rectangle ";
8. cout << "separated by a space.\n";
9. cin >> length >> width;
10. cout << "length = "<< length << ", width = " << width << endl;
11. area = length * width;
12. cout << "The area of the rectangle is " << area << endl;
13. return 0;
14. }
A sample program 7 to run in
the VS: RAM

9. cin >> length >> width; length


10. cout << "length = "<< length << ", width = " << width << endl;
11. area = length * width;
50
 Lines number 7 and 8 print a text, this text asks the user of the
program to input two specific values. Line 9 uses the command width
cin to receive two values of the two variables “length” and
“width”. The user should enter two numbers separated by a 78
space in the same line.
 In the running of this program, if the user enters 50 and 78,
then click [enter], the program will save these values inside area
the variables “length” and “width”.
 Then the instruction in line 11 calculates the value of the
3900
“area” variable, its value is the multiplication of the length by
the width, which is 3900.
A sample program 7 to run in
the VS:
9. cin >> length >> width;
11. area = length * width;

 What if the user enters 50.5 and 78.3?


 The program considers the length and width as integers.
This means that the program will consider the input of the
user by ignoring the fraction part.
 This means, after running line 10, the values of the
“length” and “width” are going to computed incorrectly.
This is because c++ does not expect a floating point in the
integer. This is called a run time error.
Program 8 : double

1. // The program uses another data type, double, in addition to integer


2. #include <iostream>
3. using namespace std;
4. int main(){
5. int integerLength = 3.3;
6. cout << "integerLength = 3.3 is actually = " << integerLength << endl;
7. double doubleLength = 3.3;
8. cout << "doubleLength = 3.3 is actually = " << doubleLength << endl;
9. cout << "size of an integer is " << sizeof(integerLength) << endl;
10. cout << "size of a double is " << sizeof(doubleLength) << endl;
11. return 0;
12. }
Program 8 : double

5. int integerLength = 3.3;


6. cout << "integerLength = 3.3 is actually = " << integerLength << endl;

 Line 5 is an initialization to the variable “integerLength” of


data type integer. However, the initial value assigned to this
variable is 3.3, which is not an integer.
 The integer values must not contain floating points, the value
after the floating point will be ignored. The actual value of the
“integerLength” is going to be 3, not 3.3. This is clear in the
output of line 6, in the printed part “is actually 3”, where 3
refers to the value of “integerLength”.
Program 8 : double

7. double doubleLength = 3.3;


8. cout << "doubleLength = 3.3 is actually = " << doubleLength << endl;

 Line 7 is an initialization to the variable “doubleLength” of


data type double. The double is a type of the data of fractions
that include floating point. The value “3.3” contains a floating
point, so it represents a fraction. The initial value assigned to
“doubleLength” is 3.3 as double, which is not an integer.
 The actual value of the “doubleLength” is going to be 3.3.
This is clear in the output of line 8, in the printed part “is
actually 3.3”.
Program 8 : double

9. cout << "size of an integer is " << sizeof(integerLength) << endl;


10. cout << "size of a double is " << sizeof(doubleLength) << endl;
1 byte
 Line 9 uses the function sizeof() to return the number of bytes
reserved for the input parameter between (). The value of 0 1 1 0 0 1 0 1
“sizeof(integerLength)” is 4, since the size of any integer
number in the memory is 4 bytes, which is 4*8 bits. int
 Line 10 uses the function sizeof() to return the number of bytes double
reserved for the “doubleLength” variable. The value of
“sizeof(doubleLength)” is 8, since the size of any double in
the memory is 8 bytes, which is 8*8 bits.
Program 9 : double

1. // This program discuss the relation between integers and doubles.


2. #include <iostream>;
3. using namespace std;
4. int main(){
5. int x = 4.2; //loss of data (0.2), x = 4.
6. double y = 5.5;
7. cout << "x + y = " << x+y << endl;
8. int z = x + y;
9. double g = x + y;
10. cout << "x (int) = " << x << ", y (double) = " << y << endl;
11. cout << "z (int) = " << z << ", g (double) = " << g << endl;
12. x = y;
13. y = x;
14. return 0;
15. }
Program 9 : double

5. int x = 4.2; //loss of data (0.2), x = 4.


6. double y = 5.5;
7. cout << "x + y = " << x+y << endl;
 Line 5 and 6 defines an integer and a double variables. Line 8
sums x and y. In Line 5, the value of 4.2 (which is double) is
converted to an integer of value 4. In line 6, the double value
of y is 5.5. int
 To apply any mathematical operations between two variables, double
then the two variables must be of the same data type. The
summation in line 7 is applied on two variables of two different
data types. In this case, the compiler will convert one of the
data types of the smallest size to the other one.
 The variable of the smallest size (int) is converted to the data
type of the largest size (double). The integer value of x is
converted to double value, 4.0, then added to the value 5.5.
Program 9 : double

8. int z = x + y;
9. double g = x + y;

 In line 8, the integer x is converted to double type then added


the double y. The result of this summation is 9.5, this result is
then assigned to the integer z. Since z is integer, the
summation result of data type double is converted to integer to int
match with z. The result of this conversion is that the value of double
z is 9.
 In line 9, the integer x is converted to double type then added
the double y. The result of this summation is 9.5, this result is
then assigned to the double g. Since g is double that is
matching to double data type in the right side (x+y), then no
conversion is required and the value of g becomes 9.5 as it is.
 Lines 10 and 11 are just printing the four values x, y, z and g.
Program 10 : cmath library

1. // This program discuss the use of another library (cmath).


2. #include <iostream>; // needed for using cout<< function
3. #include <cmath>; // needed for using pow() function
4. using namespace std;
5. int main(){
6. int x = 4, z = 3;
7. double y = 5.5;
8. double result = x + y * z; //Precedence
9. cout << "x + y * z = " << result << endl;
10. result = (x + y) * z; //Associativity
11. cout << "(x + y) * z = " << result << endl;
12. result = y + pow(x, z); //using function
13. cout << "y + pow(x, z) = " << result << endl;
14. return 0;
15. }
Program 10 : cmath library

2. #include <iostream>; // needed for using cout<< function


3. #include <cmath>; // needed for using pow() function

 Line 2 and 3 are including in your program two different


libraries. These libraries are existing in the IDE used by the
program like VS. These libraries are used whenever the
programmer needs. The library <cmath> is included in addition
to the <iostream> library.
 By default, these library are not included in your program, this
is because the size of the program increases as you include
more libraries.
 This program includes mathematical operations that not
existing in the usual operations {+, -, *, /, %). The used
operation here is pow(). This function “pow()” is used to
calculate the power of a number, for example: 23=8. This
function (or operation) exists in the library <cmath>.
Program 10 : cmath library

6. int x = 4, z = 3;
7. double y = 5.5;
8. double result = x + y * z; //Precedence

 Line 6 defines and initialize two integers in the same


statement, separated by a comma “,”. These variables are not
dependent, only sharing the same data type. The first integer
is x of value 4, and the second integer is z of value 3.
 The next line 7 defines a variable “y” of type double, then the
variable “y” is initialized by 5.5.
 Line 8, shows an initialization to a variable “result” by values
of another variables “x, y, and z”. The value of the operation
(x+y*z) is calculated and saved in the variable “result”.
Program 10 : cmath library

9. double result = x + y * z; //Precedence


10. cout << "x + y * z = " << result << endl;
11. result = (x + y) * z; //Associativity
12. cout << "(x + y) * z = " << result << endl;

 Line 9 calculates the value of (x + y * z) and save the result of this


operation in the variable “result”. The values of x, y and z are 4, 5.5, and
3 respectively.
 If the value of (x+y) is equal to 9.5, then this value is multiplied by z (3).
The resulted value should be 28.8, but this is not the output.
 However, the resulted output is 20.5, this is because of the concept of
precedence, multiplication and division come first. Actually, the value of y
is multiplied by the value of z first then the result 16.5, is added to x (4) to
be 20.5. This is the output of this line.
 Line 11, shows the use of association concept to overcome the precedence
concept. The association concept uses the circular brackets “(” to enforce
the calculation of some operations first. This line calculates ((x+y)=9.5)
first, then multiplies the result by z, (9.5*z=28.5), and this is the output.
Program 10 : cmath library

13. result = y + pow(x, z); //using function


14. cout << "y + pow(x, z) = " << result << endl;

 Line 13 calculates the value of (y + xz), however the x to the power z


is not a simple calculation in C++ like {+, -, *, and /.
 C++ allows the programmer to include a library called cmath. This
library is file that contains a list of mathematical functions like pow().
 A function is small program that include some instructions. The
function receives parameters between two circular brackets (). The
function pow(x,z) calculates xz. If x=4 and z=3, then pow(4,3)= 43
=64.
 So the statement, cout<<pow(x,z); prints 64.
 Line 13, calculates y+pow(x,z) and put the result in the variable
result. Since, y=5.5 and pow(x,z)=pow(4,3)=64, then y+pow(x,z)=69.5.
Finally, line 14 prints the value of result which is 69.5.
Program 11 : Operators

1. // This program discuss the division and modulus operators


2. #include <iostream>; // needed for using cout<< function
3. using namespace std;
4. int main() {
5. // Doing calculations inside cout directly
6. cout << "5/2 = " << 5 / 2 << endl; // integer/integer = integer
7. cout << "5.0/2 = " << 5.0 / 2 << endl; // double/integer = double
8. int x;
9. // The modulus % operator calculates the remainder
10. x = 4 % 1;cout << "4 % 1 = " << x << endl;
11. x = 4 % 2;cout << "4 % 2 = " << x << endl;
12. x = 4 % 3;cout << "4 % 3 = " << x << endl;
13. x = 4 % 4;cout << "4 % 4 = " << x << endl;
14. x = 6 % 4;cout << "6 % 4 = " << x << endl;
15. return 0;
16. }
Program 11 : Operators

5. // Doing calculations inside cout directly


6. cout << "5/2 = " << 5 / 2 << endl; // integer/integer = integer
7. cout << "5.0/2 = " << 5.0 / 2 << endl; // double/integer = double

 Lines 6 and 7 applies the calculation of 5/2 and 5.0/2 directly in the
cout function. It is not a must to save the calculation first in a variable
then print the variable.
 Line 6 divides 5 which is integer by 2 which is also integer. C++
recognizes that 5 and 2 are integers because they do not contain
floating points. The result of the division between two integers is also
integer. That is because the size of the double is greater than integer.
 Line 7 divides 5.0 which is double by 2 which is integer. C++ recognizes
that 5.0 is double because it contains a floating point. The result of
dividing a double by integer or integer by double is double.
 Not that the result of dividing a double by a double is a double.
Program 11 : Operators

8. // The mod % operator calculates the remainder


9. x = 4 % 1;cout << "4 % 1 = " << x << endl;
10. x = 4 % 2;cout << "4 % 2 = " << x << endl;
11. x = 4 % 3;cout << "4 % 3 = " << x << endl;
12. x = 4 % 4;cout << "4 % 4 = " << x << endl;
13. x = 6 % 4;cout << "6 % 4 = " << x << endl;

 First, notice that two statements are written in the same line, separated by
only the semicolon. You can add more statements as you like.
 The operator % calculate the remainder of the division operation. The
remainder from dividing 4 by 2 is zero, while the remainder from dividing 4
by 3 is one.
 The remainder of dividing any number by 1 is 0.
4 / 2 =2 4 / 3 =1 4 / 4 =1 6 / 4 =1
 2 4 3 4 4 4 4 6
4 3 4 4
4 % 1 = 0 4 % 3 = 1 4 % 4 = 0 6 % 4 = 2
Program 12 : Operators

1. // This program discuss simple way to use the operators


2. #include <iostream>; // needed for using cout<< function
3. using namespace std;
4. int main() {
5. int x;
6. x = 2;cout << "x = " << x << endl;
7. x = 2; x = x + 2;
8. cout << "x = 2; " << "x = x + 2 ==> x = " << x << endl;
9. x = 2; x += 2;
10. cout << "x = 2; " << "x += 2 ==> x = " << x << endl;
11. x = 2; x *= 2;
12. cout << "x = 2; " << "x *= 2 ==> x = " << x << endl;
13. x = 2;
14. cout << "x = 2; " << "x++ ==> x = " << x++ << " then x = " << x << endl;
15. x = 2;
16. cout << "x = 2; " << "++x ==> x = " << ++x << " then x = " << x << endl;
17. return 0;
18. }
Program 12 : Operators

6. x = 2; x = x + 2;
7. cout << "x = 2; " << "x = x + 2 ==> x = " << x << endl;
8. x = 2; x += 2;
9. cout << "x = 2; " << "x += 2 ==> x = " << x << endl;
 Line 6 initializes x by 2, then adds 2 to x. The value of x after running
these two statements is 4. Line 7 prints the details of this operation.
 Line 8 does the same operation but in a different way. The operation
(x=x+2) is replaced by (x+=2) that does the same calculation. The
statement (x += 2) is a simple way that does not repeat the variable
(x).
 This style of writing the addition operation is just for fasten the
program writing.
 x = x + 2; is the same as x += 2;
Program 12 : Operators

11. x = 2; x *= 2;
12. cout << "x = 2; " << "x *= 2 ==> x = " << x << endl;

 Line 11 initializes x by 2, then multiplies x by 2, and set the result to x. The


operation (x=x*2) is replaced by (x*=2) that does the same calculation.
 x = x * 2; is the same as x *= 2;. The value of x after running any of these two
statements is the same.
 The same thing happens when the program uses the other operator simple
operators, like {/}, {-}, or {%}.
1. x = 2;x /= 2;
2. cout << "x = 2; " << "x /= 2 ==> x = " << x << endl; ➔
3. x = 2;x -= 2;
4. cout << "x = 2; " << "x -= 2 ==> x = " << x << endl; ➔
5. x = 2;x %= 2;
6. cout << "x = 2; " << "x %= 2 ==> x = " << x << endl; ➔
Program 12 : Operators

13. x = 2;
14. cout << "x = 2; " << "x++ ==> x = " << x++ << " then x = " << x << endl;
15. x = 2;
16. cout << "x = 2; " << "++x ==> x = " << ++x << " then x = " << x << endl;
 Line 13 initializes x by 2. Then line 13 prints the value of “x++”.
 The operation x++; is called the incrementing operation. It increments
the value of x, means increase the value of x by 1.
 The statement (x = x + 1;) is the same as the statement x++; .
 Again, this is a way to simplify writing program. Instead of writing x =
x + 1;, the C++ provides a faster style which is x++;.
 Also this style can be applied on the subtraction operation x--; where
it decrements value of x, which means it decreases the value of x by
1.
Program 12 : Operators

13. x = 2;
14. cout << "x = 2; " << "x++ ==> x = " << x++ << " then x = " << x << endl;
15. x = 2;
16. cout << "x = 2; " << "++x ==> x = " << ++x << " then x = " << x << endl;
 What is the difference between line 14 and line 16?
 Line 14 prints the value of x first, then increments the value of x. So
the value printed will “x++ ==> x = 2”. Then in the next printed
part, the value of x is already incremented, so the value printed will
be “ then x = 3”. This is because the ++ operator comes after x.
 Line 16 increments the value of x first, then prints the value of x. So
the value printed will “++x ==> x = 3”. Then in the next printed
part, the value of x is already incremented, so the value printed will
be “ then x = 3”. This is because the ++ operator comes before x.
Program 13 : Review

1. // This program to review all the previous


2. #include <iostream>; // needed for using cout<< function
3. #include <cmath>; // needed for using cout<< function
4. using namespace std;
5. int main() {
6. double x = 4.4 / 2; cout << "x=" << x << endl;
7. int y = sizeof(x)%3; cout << "y=" << y << endl;
8. int z = pow(x, y); cout << "z=" << z << endl;
9. int v = z%y + x++ + ++x; cout << "v=" << v << endl;
10. int m = 6; m += m++; cout << "m=" << m << endl;
11. return 0;
12. }
Program 13 : Review
6. double x = 4.4 / 2; cout << "x=" << x << endl; //2.2
7. int y = sizeof(x)%3; cout << "y=" << y << endl; //2
8. int z = pow(x, y); cout << "z=" << z << endl; //4
9. int v = z%y + x++ + ++x; cout << "v=" << v << endl; //6

 Line 6 divides 4.4/2, the result of dividing a double by a integer is a


double. Dividing 4.4 by 2 is 2.2, and the result is saved in x.
 Line 7, The variable x is double, so the sizeof(x) is 8. And 8 modulus(%) 3
is 2, since the remainder of dividing 8 by 3 is 2. The value of 8%3=2 is
saved in y.
 Line 8, x to power y, or x^y, or xy is calculated by function pow in the
cmath library. pow(x,y) = pow(2,2)=4
 Line 9, the final result is v=0+2+4=6 because the following steps.
 z%y=4%2=0
 x=2 ➔x++=2, but after this part, the value of x becomes 3
 x=3➔++x=4,
Program 13 : Review
10. int m = 6; m += m++; cout << "m=" << m << endl;
11. return 0;

 Line 10,
 The value of m++ is 6, since m is not incremented yet. But after calculating
this part, the value of m becomes 7.
 m += (m++), the right side is calculated and is now 6, but the value of m is
7. So, m+=6 is the same as m = m + 6. On the other-side, m is now 7, then
m = m + 6 = 7 + 6 = 13.
 operator comes after x.

 Line 11 returns zero, the return statement is used to terminate the


function or the program you are writing. Then name of your function
(program) is main, and it returns 0 when it ends.
 Notice that the function header (int main()) starts by int, and also
the data type of the returned value 0 is also integer.
Introduction to
Computing

Lecture 4
Characters and strings in C++

Dr. Mostafa Salama


Program 14 : Float vs Double

1. //The program get from the user 3 float variables to print their average
2. #include <iostream>
3. #include <cmath>
4. using namespace std;
5. int main(){
6. float a, b, c; // To hold the scores
7. float average; // To hold the average
8. cout << "The size of any float variable is : " << sizeof(float) << endl;
9. cout << "Enter the first test score: "; cin >> a;
10. cout << "Enter the second test score: "; cin >> b;
11. cout << "Enter the third test score: "; cin >> c;
12. average = (a + b + c) / 3;
13. cout << "The average score is: " << average << endl;
14. return 0;
15. }
Program 14 : Float vs Double

6. float a, b, c; // To hold the scores


7. float average; // To hold the average
8. cout << "The size of any float variable is : " << sizeof(float) << endl;

 Float is another data type that allows fractional values. Any


variable of a float data type can contain floating points like the
double data type, except that the double data type is usually
twice as big as float.
 The double data type is used when the fractions in the program
are extremely large. While if the fractions defined in the program
are small, it is better use float data type instead.
 The printed size of the float data type in line 8 is 4 bytes only,
which is half the size of a double data type. Floats help in
decreasing the memory consumption, specially for programs that
does not compute extremely large values.
Program 14 : Float vs Double

9. cout << "Enter the first test score: "; cin >> a;
10. cout << "Enter the second test score: "; cin >> b;
11. cout << "Enter the third test score: "; cin >> c;

 Each line in Lines 9, 10, and 11 are printing a statement to the


user and waits for his input. The user enters the value of the first
score, then click enter, then the program asks him to enter the
second score, and so on until the three scores are entered.
 Note that the user inputs are 7, 8 and 7 which does not contain a
floating point. However, the variables a, b and c are of data type
float, so the input values are saved in the RAM as floats too.
12. average = (a + b + c) / 3;
13. cout << "The average score is: " << average << endl;
 The average score is then calculated as the sum of the three
values divided by the number of the values (3). The circular
brackets () is associating the summation to avoid the precedence
of the division operator. If you write a+b+c/3, the program will
calculate c/3 first then add the result to a+b, which is wrong.
Program 15 : Float vs Double

1. //This program the difference between a float and a double


2. #include <iostream>
3. using namespace std;
4. int main() {
5. double bigFraction = 3.142343; //double variable = double value
6. float smallFraction1 = 3.142343f; //float variable = float value

7. float smallFraction2 = 3.142343; //Warning: Truncation from 'double' to 'float‘


8. int integer1 = 3.142343; //Warning: conversion from 'double' to 'int', possible
loss of data
9. cout << "size of a double variable :" << sizeof(bigFraction) << endl;
10. cout << "size of a float variable :" << sizeof(smallFraction2) << endl;
11. cout << "size of a double value (3.142343):" << sizeof(3.142343) << endl;
12. cout << "size of a float value (3.142343f):" << sizeof(3.142343f) << endl;
13. cout << "size of an integer value (3):" << sizeof(3) << endl;

14. return 0;
15. }
Program 15 : Float vs Double

5. double bigFraction = 3.142343; //double variable = double value


6. float smallFraction1 = 3.142343f; //float variable = float value

 Lines 5 and 6 define and initialize two fraction variables of two


different data types. Both variables are fractions, but the double
is twice the size of the float.
double
 In assigning or initializing the value of double variable, the
float
assigned double value contains a floating point like (3.142343).
The compiler of the c++ detects that this value (3.142343) is a
double value and set it inside the double variable (bigFraction)
without a problem.
 In assigning or initializing the value of float variable, the assigned
float value contains a floating point like (3.142343f). The
compiler of the c++ detects that this value (3.142343f) is a float
value because it ends by (f). Then set it inside the float variable
(smallFraction1) without a problem.
Program 15 : Float vs Double

7. float smallFraction2 = 3.142343; //Warning: Truncation from 'double' to 'float‘


8. int integer1 = 3.142343; //Warning: conversion from 'double' to 'int',
possible loss of data

 Lines 7 defines a float variable (smallFraction2), it allocate 4


bytes in the memory for this variable, then it assigns the value
(3.142343) to this variable. The compiler of the c++ detects that
this value (3.142343) is a double value of size 8 bytes, this is double
because it does not contain (f) at its end like (3.142343f).
float
 So, line 7 assigns a value of double data type (8 bytes) to a
variable of a float data type (4 bytes). This conversion (casting) is int
not a problem for small values. But if this double value is very
large, then the saved value in the float variable will be truncated
to its size and so it will not be correct. C++ shows only a warning
to the programmer and not a compile time error.
 In line 8, the compiler detects that (3.142343) is double of 8
bytes, and shows a warning that this value is going to be
converted to 4 bytes of the integer data type.
Program 15 : Float vs Double

9. cout << "size of a double variable :" << sizeof(bigFraction) << endl;
10. cout << "size of a float variable :" << sizeof(smallFraction2) << endl;
11. cout << "size of a double value (3.142343):" << sizeof(3.142343) << endl;
12. cout << "size of a float value (3.142343f):" << sizeof(3.142343f) << endl;
13. cout << "size of an integer value (3):" << sizeof(3) << endl;

 Line 9 uses the function sizeof() to print the size of the


bigFraction variable of a double data type [8 bytes].
 Line 10 uses the function sizeof() to print the size of the
smallFraction2 variable of a float data type [4 bytes].
 Line 10 uses the function sizeof() to print the size of the
(3.142343, contains floating point and no f at its end)
value of a double data type [8 bytes].
 Line 10 uses the function sizeof() to print the size of the
(3.142343f , contains floating point and f at its end)
value of a float data type [4 bytes].
 Line 10 uses the function sizeof() to print the size of the (3, does
not contain a floating point) variable of an integer data type.
[4 bytes]
Program 16 : constants and
variables.
1. // This program introduces the use of constants
2. #include <iostream>
3. #include <cmath>
4. using namespace std;
5. int main(){
6. const double pi = 3.14159;
7. double area, radius;
8. cout << "This program calculates the area of a circle.\n";
9. cout << "What is the radius of the circle? ";
10. cin >> radius;
11. area = pi * pow(radius, 2.0);
12. cout << "The area is " << area << endl;
13. return 0;
14. }
Program 16 : constants and
variables RAM

6. const double pi = 3.14159; pi


7. double area, radius;
3.141
 Line 6 and line 7 define three doubles, line 6 defines a constant of a
data type double while line 7 defines two variables of a data type 8 byte

double.
area
 A named constant is like a variable, but its content is read-only, and
cannot be changed while the program is running.
 A const is the variable whose value can't be changed once it is 8 byte
initialized. During the program execution, the value of the area and
radius variables can be changed various times, while value of radius
constant pi can't be changed. In real life applications, a universal
value like pi (π) is well known and can not be modified.
8 byte
Program 16 : constants and
variables RAM

6. const double pi = 3.14159; pi


7. double area, radius;
3.141
 It looks just like a regular variable definition except that the word
const appears before the data type name, and the name of the 8 byte
variable is written in all uppercase characters.
area
 An initialization value must be given when defining a constant with
the const qualifier, or an error will result when the program is
compiled.
 So this code will be incorrect, it will cause compilation error 8 byte
 const double pi;
 pi=3.14159; ➔ compile time error radius
 If the programmer tries to change the value of pi later in the
program, the compiler will show a compile time error “expression
must be a modifiable”. 8 byte
Program 16 : constants and
variables RAM

10. cin >> radius; pi


11. area = pi * pow(radius, 2.0);
3.141
12. cout << "The area is " << area << endl;
8 byte
 Line 10 let the user to enter the value of the radius. When the user
enters the value (for example, 4), the value is saved in the double radius
variable radius.
 The next line 11 calculates the value of area, using the pow()
4
function in the <cmath> library. The result of this function is 8 byte
multiplied by the double constant pi (π), then saved in the area
variable. area

 Line 12 prints out the value of the calculated area variable. 50.2654

8 byte
Program 17 : characters and ASCII
code
1. // This program uses character letters and prints out their ASCII code.
2. #include <iostream>
3. using namespace std;
4. int main() {
5. char cl = 'A', sl = 'a', l;
6. cout << "Enter a letter you like? ";
7. cin >> l;

8. int x;
9. x = cl; cout << "The ASCII of letter " << cl << " is " << x << endl;
10. x = sl; cout << "The ASCII of letter " << sl << " is " << x << endl;
11. x = l; cout << "The ASCII of letter " << l << " is " << x << endl;
12. return 0;
13. }
Program 17 : characters and
ASCII code RAM

5. char cl = 'A', sl = 'a', l; cl

 Line 5 defines 3 new variables, the data type of these variables is A


the character data type. The word “char” is an abbreviation for 1 byte
the character type. The first two characters are initialized by 'A'
and 'a'., while the third character is kept un-initialized. sl
 Notice that characters cl and sl are different. The character saved
in cl is a capital letter, while the character saved in sl is a small a
letter. 1 byte

 A characters is any key that can be written in the keyboard like


capital and small letters, special characters. To assign a value l
(letter) to any variable of a data type character, the value must be
between single quotations as follows [char cl = 'A';]. It is
wrong to write [cl=A] or [cl="A"]. 1 byte

 The size of a character variable is one byte. If we try to print the


function sizeof(cl), then the output is going to be 1.
Program 17 : characters and
ASCII code RAM

5. char cl = 'A', sl = 'a', l; cl


6. cout << "Enter a letter you like? ";
7. cin >> l;
A
 Line 6 prints a statement, asking the user to enter the value of a 1 byte
letter.
sl
 Line 7, is a command cin>>, this command will cause the program to
pause until the user enter a value. The entered value by the user
should a character. The input of the character by the user in the a
console screen does not use the single quotations. 1 byte
 The user input is b directly without using the quotation “'” as
follows 'b'. l
 After the user input by line 7, the three character variables have
character values. However, the RAM in the computer can save only b
bits (0 or 1), the computer can not save the shape of the characters. 1 byte
Remember that computer is only an electronic machine.
Program 17 : characters and
ASCII code RAM

5. char cl = 'A', sl = 'a', l; cl


6. cout << "Enter a letter you like? ";
7. cin >> l;
65
 The characters are saved in the memory as binary data too, just like 1 byte
integers and doubles. However, the variables of the data type
character are first converted to ASCII code, then this code is sl
converted to a binary value to be saved in the RAM.
 The most commonly used method for encoding characters is ASCII, 97
which stands for the American Standard Code for Information 1 byte
Interchange. This encoding system is a universal system that is used
by different computer systems, find it in this link. When a character
is stored in memory, it is actually the numeric ASCII code that is l
stored.
 The ASCII code of the capital letters are ‘A’=65, ‘B’=66, …., ‘Z’=90.
98
And the ASCII code of the small letters are ‘a’=97, ‘b’=98, …., 1 byte
‘z’=122. And the ASCII code of the numbers are ‘1’=49, ‘2’=50, …,
9=‘57’.
Program 17 : characters and
ASCII code RAM

8. int x; cl
9. x = cl; cout << "The ASCII of letter " << cl << " is " << x << endl;
10.
11.
x =
x =
sl;
l;
cout << "The ASCII of letter " << sl << " is " << x << endl;
cout << "The ASCII of letter " << l << " is " << x << endl;
65
1 byte
 Line 8 defines a variable x
sl
 The first statement in line 9 assigns the value of character cl to the
variable x. The value of x is going to be the ASCII code of character
cl, since x is already integer. If cl is ‘A’, then the ASCII is 65, then 97
the value of x is going to be 65. 1 byte

 The second statement in line 9 prints the value of character cl as A,


then prints the value of integer x as 65. l

 Lines 10 and 11 have the same description as line 9. The values of cl 98


and sl are assigned by the programmer in the code, while the value
1 byte
of l is assigned by the user during the program execution.
Program 18 : characters and ASCII
code
1. // This program uses character letters
2. #include <iostream>;
3. using namespace std;
4. int main() {
5. cout << "Enter any capital letter? " ;
6. char c; cin >> c;
7. int x = 32;
8. c += x;
9. cout << "The small letter of your character is : " << c << endl;
10. cout << "The next small letter in alphabet is : " << ++c << endl;
11. cout << "The size of variable c is " << sizeof(c) << endl;
12. return 0;
13. }
Program 18 : characters and
ASCII code
5. cout << "Enter any capital letter? " ;
6. char c; cin >> c;
7. int x = 32;
8. c += x;
9. cout << "The small letter of your character is : " << c << endl;
 Lines 5 prints out a request from user to enter a capital letter. Line 6,
defines a variable of data type character and receive the value of this
character from the user.
 Line 7 defines a variable x of data type integer and initialize its value by
32.
 Line 8, adds the value of x to the character c using the += operator, so
value of c = c + x = c + 32.
 If the user enters ‘A’ (65) to variable c, then the value of c after adding 32 is
97 which is the ASCII of a.
 If the user enters ‘B’ (65) to variable c, then the value of c after adding 32 is
98 which is the ASCII of ‘b’. And so on for all capital letters.
 Lines 9 will print the value of c after adding 32 to its ASCII code value,
the printed letter will be corresponding small letter.
Program 18 : characters and
ASCII code
10. cout << "The next small letter in alphabet is : " << ++c << endl;
11. cout << "The size of variable c is " << sizeof(c) << endl;
 Line 10 increments the value of character c, then prints the new
incremented character.
 If character c has the value ‘a’, of the corresponding value ‘97’.
Then the incremented value becomes 98, which is corresponding to
the character ‘b’. If the character c has the value ‘g’, then the
incremented value is ‘h’.
 Line 11 prints the size of the character c. Any variable of data type
char has the size of one byte.
Program 19 : strings

1. // This program demonstrates the string data type.


2. // string is a complex data type, to define objects of text
3. #include <iostream>
4. #include <cmath>
5. using namespace std;
6. int main() {
7. string n1;
8. n1 = "Morad Samir Aly";
9. cout << "The name of student 1 is : " << n1 << endl;

10. string n2;


11. cout << "Enter the name of student 2 : ";
12. getline(cin, n2);
13. cout << "The name of student 2 is : " << n2 << endl;

14. string n3;


15. cout << "Enter the name of student 3 : ";
16. cin >> n3;
17. cout << "The name of student 3 is : " << n3 << endl;

18. return 0;
19. }
Program 19 : strings

6. string n1;
7. n1 = "Morad Samir Aly";
8. cout << "The name of student 1 is : " << n1 << endl;

 A string is a datatype to define text, a text is a group of characters


of a specific sequence. In other words, A string is sequence of
characters that represents a text.
 Because a char variable can store only one character in its memory
location, another data type is needed for a variable able to hold an
entire string.
 Integer, double, float and char are all primitive data types that does
not require a library to be included. A string is called a complex data
type because it is composite of more than one character. In order to
use a string properly, a string library is included in the program.
Program 19 : strings

6. string n1;
7. n1 = "Morad Samir Aly";
8. cout << "The name of student 1 is : " << n1 << endl;

 Line 6 defines a variable called (n1) of data type string. This


variable has a location in the memory, this memory can hold a series
of characters of a specific order.
 Line 7 assigns a text (string) of a value “Morad Samir Aly” to the
variable n1. The assigned text must be in-between two double
quotations. Remember that a character value must be in-between
two single quotations.
 Line 8 prints a text “The name of student 1 is : ” that is
written between double quotations, then prints the value of the
variable n1. Since n1 is a variable, it is written without a
quotations, and the printed text is the value of this variable
Program 19 : strings

9. string n2;
10. cout << "Enter the name of student 2 : ";
11. getline(cin, n2);
12. cout << "The name of student 2 is : " << n2 << endl;

 Line 9 defines a variable called (n2) of data type string. The next
two lines 10 and 11 receives the text value of this variable from the
user.
 Line 10 prints out a text using the “cout<<“ function to as the user
to enter the text value of variable n2.
 Line 11 gets the text value of the string variable n2 from the user.
The way of getting a text value from the user is different from the
way of getting any other primitive values.
 Instead of writing the command cin>>n2;, this command is replaced
by using the getline(cin, ) function. The reason of this
replacement is that a text may contain spaces.
Program 19 : strings

9. string n2;
10. cout << "Enter the name of student 2 : ";
11. getline(cin, n2);
12. cout << "The name of student 2 is : " << n2 << endl;

 Line 12 prints out the text entered by the user. Notice that the user
enters the text “Morad Samir Aly” which contains two spaces. And
the printed text is exactly as the user enters.
 If the programmer uses the command cin>>n2;, the program will not
correctly. This is because the compiler will consider the first part of
the text before the space “ ” as the value of the variable.
 The getline function reads the entire line, including leading and
embedded spaces, and stores it in a string variable.
Program 19 : strings

13. string n3;


14. cout << "Enter the name of student 3 : ";
15. cin >> n3;
16. cout << "The name of student 3 is : " << n3 << endl;

 Line 13 defines a third string variable n3, then line 14 prints out a
text asking the user to enter a text string value, the user enters the
text “Morad Samir Aly” which contains two spaces.
 The program here uses the command cin>>n3; in line 15 to receive
the value of the string variable n3. The program did not show a
compilation error, and executed normally.
 However, the printed string by line 16 is only the word “Morad” and
all the text after the space is ignored. This is because the compiler
will consider only the part of the text before the space “ ”. This is
called a run time error, where the program did not execute as
required.
Program 20 : strings

1. // This program demonstrates the string library.


2. #include <iostream>
3. #include <string>
4. using namespace std;
5. int main() {
6. string e_mail;
7. cout << "Enter the student's E-Mail : ";
8. cin >> e_mail; //[email protected]

9. int fn_length = e_mail.find('_');


10. string firstName = e_mail.substr(0, fn_length);
11. cout << "The student's First Name is : " << firstName << endl;

12. return 0;
13. }
Program 20 : strings

6. string e_mail;
7. cout << "Enter the student's E-Mail : ";
8. cin >> e_mail; //[email protected]

 Line 6 defines a string variable e_mail, where a the <string> library


is included in the beginning of this program.
 Line 7 prints out a statement that asks the user to enter the text
value of the string variable e_mail. This text represents the E-Mail
of a student in the university.
 Consider that the E-Mail must contain an underscore “_” to separate
between the student’s first name and his Identification number ID.
According to the E-Mail structure, the students’ E-Mails can not
include any spaces.
 Line 8 uses the usual cin>> function to get the E-Mail from the user
because the programmer is sure that it will not include any spaces.
Program 20 : strings

3. #include <string>;
9. int fn_length = e_mail.find('_');

 Line 3 has a # preprocessor directive to include a new library called


string. This library allows the programmer to work on a special data
type of text. A string is sequence of characters that represents a
text.
 The <string> library allows the programmer to have a full access on
the text within the string variables. It provides the programmer with
various functions that are required to work on the text.
 The functions that exists in the library are called member functions
that are related to the topic of this library. For example, one of the
member functions in the string library is the find() function.
 To use a member function like find() in the string library, the
programmer writes the name of the string variable (object) first
then the dot charcater “.” then the name of the function as follows:
e_mail.find();
0 5
Program 20 : strings

3. #include <string>;
9. int fn_length = e_mail.find('_');

 The member function find('_') is used to get the position of a


specific character like ‘_’ in the string variable (object).
 The function find() receives one parameters which is the character
that you are searching for, and returns an integer that refers to the
position of the first appearance of this character in the string. The
counting of the position starts from zero. If the character is not
found, then the returned value is -1.
 After running this line 9, the value of fn_length is 5. The position
of character ‘A’ is 0, and of character ‘h’ is 1, ‘m’ is 2, ‘e’ is 3, ‘d’ is
4, and ‘_’ is 5.
Program 20 : strings

10.string firstName = e_mail.substr(0, fn_length);


11.cout << "The student's First Name is : " << firstName << endl;

 The <string> library contains various functions that are all about the
text within the string variables. The variable e_mail is called also
an object since the data type string is not a primitive data type.
 The function substr(s, l) is another member function in the string
library. It is used to get a part of the string object. The length of
this part in the string is (l). And this part is starting from position
(s).
 In the above example, the required is to extract the first name
‘Ahmed’ from the E-Mail ‘[email protected]’. The first
name starts from position zero, and the length of the first name is
the number of characters in this name which is 5. The value of
fn_length is 5 since it refers to the position of the last character
after the first name which is the ‘_’.
Program 20 : strings

10.string firstName = e_mail.substr(0, fn_length);


11.cout << "The student's First Name is : " << firstName << endl;

 The function substr(0, 5) is returns the word “Ahmed” as sub-string


from the whole string “[email protected]”. The returned
sub-string “Ahmed” is saved in the string object firstName.
 Line 11 prints the text “The student's First Name is : ”
followed by the text string firstName.
 The <string> library contains
 Function find() that receive one input parameter between the circular
bracket () which is the character you are looking for.
 Function substr() that receive two input parameters that refers to the
part of the string you want to extract. The first parameter is the starting
position of this part, and the second parameter is the length of this part.
Programming So far :
writes
Program
Programmer
Using
User

Visual studio Computer


Runs Console
C++ Compiled the
data types Libraries
Compiler Machine code program Screen

• int • iostream • Check syntax


double • cout<< • Convert to
Primitive •
• float • cin>> executable
• char • cmath program
Complex • string • pow() 99

• String
• find()
• Substr()
Introduction to
Computing

Lecture 5
More about string and math libraries

Dr. Mostafa Salama


Program 21 : strings

1. //This program gets the full name (2 parts only). e.g. George Washington
2. //Then print his first name in a line George,
3. //followed by the second name Washington in the next line.
4. #include <iostream>
5. #include <string>
6. using namespace std;
7. int main(){
8. string username;
9. cout << "Enter your Name : "; getline(cin, username);

10. int startPosition = 0;


11. int midPosition = username.find(' ') + 1;
12. int fistLength = midPosition – startPosition - 1;
13. int secondLength = username.length() - midPosition;

14. string firstName = username.substr(startPosition, fistLength);


15. string secondName = username.substr(midPosition, secondLength);
16. cout << "First Name : " << firstName << endl;
17. cout << "Second Name : " << secondName << endl;
18. return 0;
19. }
Program 21 : strings

8. string username;
9. cout << "Enter your Name : "; getline(cin, username);

 Line 8 defines an object string “username” then get this string from
the user using the getline() method in line 9.
 A string is a list of characters, each character is a single primitive
variable. A string is not a variable, it is an object that includes
multiple variables.
 The getline function reads an entire input of the user. This function
has two paramters. (1) cin is the input stream we are reading from
and (2) username is the name of the string object receiving the
input. The user can include spaces in his input string and that is why
we are not using the usual cin>> method.
Program 21 : strings

10. int startPosition = 0;


11. int midPosition = username.find(' ') + 1;

 The index of the first character in any string is 0. Line 10 defines a


variable of value 0 to refer to the index of the first character in the
first name.
 Line 11 uses the member function username.find(' ') in the
string username. It returns the index of the first appearance of the a
space ‘ ’ in the text. It adds 1 to this index to get the index of the
first character in the second name.

startPosition=0 midPosition=7

George Washington
username.find(' ')=6
Program 21 : strings

12. int fistLength = midPosition – startPosition - 1;


13. int secondLength = username.length() - midPosition;

 Line 12 calculates the number of characters in the first name. It simply


subtracts the position of the last character in the first name
(midPosition-1) from the position of the first character
(startPosition).
 Line 13 uses a function in the string library called length(). The function
username.length() returns the number of character in the string
username. Note that any function must contain input parameter between
(), even if it does not contain input, the circular bracket must exist but
empty.
 Line 13 calculates the number of characters in the second name. It
subtracts the number of characters in the full name
(username.length()) from the position of the first character in the
second name (midPosition).
fistLength secondLength

George Washington
Program 21 : strings

14. string firstName = username.substr(startPosition, fistLength);


15. string secondName = username.substr(midPosition, secondLength);

 function substr() in the string library to return a part of the string.


Line 14 uses the username.substr() to return the first part of the
string username. This function returns a part of length
(fistLength) starting from index (startPosition). The number of
characters of the first part is equal to fistLength.
 Line 15 uses the username.substr() to return the second part of
the string username. This function returns a part of length
(secondLength) starting from index (midPosition). The number of
characters of the second part is equal to secondLength.
startPosition=0 midPosition=7

fistLength secondLength

George Washington
Program 22 : strings

1. //This program gets the full name (2 parts only) of small letters
2. //e.g. george washington
3. //Then the program prints the capital letters of the first name and the second name.
4. //e.g. GW
5. #include <iostream>
6. #include <string>
7. using namespace std;
8. int main(){
9. string username;
10. cout << "Enter full Name : "; getline(cin, username);
11. int startPosition = 0;
12. int midPosition = username.find(' ') + 1;
13. char firstCharacter = username.at(startPosition);
14. char secondCharacter = username.at(midPosition);
15. firstCharacter -= 32;
16. secondCharacter -= 32;

17. cout << "Full Name initials : " << firstCharacter << secondCharacter << endl;
18. cout << "ASCII : " << (int)firstCharacter << "#" << (int)secondCharacter << endl;
19. return 0;
20. }
Program 22 : strings

9. string username;
10. cout << "Enter full Name : "; getline(cin, username);
11. int startPosition = 0;
12. int midPosition = username.find(' ') + 1;
 The first two lines 9 and 10 in this program get from the user a text
that represents a full name of two parts.
 The requirement of this program is to extract the first small letter
in the first name and the first small letter in the second name, then
prints these two letters as capital letters.
 Line 11 defines a variable startPosition and assigns the value
zero to this variable to refer to the first character in the first name.
While line 12 defines a variable midPosition and assigns it to the
index of the character following the space (' ') in the username
string.
startPosition=0 midPosition=7
fistLength secondLength

george washington
Program 22 : strings

13. char firstCharacter = username.at(startPosition);


14. char secondCharacter = username.at(midPosition);

 Lines 13 and 14 uses the function at() in the string library to get a
character at a specific position.
 Line 13 defines a character variable firstCharacter, and assigns
it to the character at position startPosition=0 in the string
object username=“George washington”. The returned character
from username.at(0) is ‘g’.
 Line 14 defines a character variable secondCharacter, and assigns
it to the character at position midPosition=7 in the string object
username. The returned character from username.at(7) is ‘w’.

startPosition=0 midPosition=7
fistLength secondLength

george washington
Program 22 : strings

15. firstCharacter -= 32;


16. secondCharacter -= 32;
17. cout << "Full Name initials : " << firstCharacter << secondCharacter << endl;

 The values of firstCharacter and secondCharacter are ‘g’ and


‘w’, these values have the ASCII codes 103 and 119.
 Line 15 [firstCharacter -= 32;] which is the same as
[firstCharacter = firstCharacter - 32;]. This line subtracts
32 from the value of firstCharacter. This subtraction is applied to
change the case of this letter from small letter to capital letters.
Also line 16 applied this case change on the character
secondCharacter .
 The values of the two characters become 71 and 87 which are the
ASCII codes of ‘G’ and ‘W’.
startPosition=0 midPosition=7
fistLength secondLength

george washington
Program 22 : strings

17. cout << "Full Name initials : " << firstCharacter << secondCharacter << endl;
18. cout << "ASCII : " << (int)firstCharacter << "#" << (int)secondCharacter;

 Line 18 prints the ASCII code of the two characters G and W


separated by ‘#’ sign.
 The difference between lines 17 and 18 is that line 17 prints the
character itself, while line 18 prints the character after converting
it to an integer value. The integer value is the ASCII code of the
character.
 The addition of (int) before the character name converts the data
type of the character to an integer. It converts the character ‘G’ to
the corresponding integer, ASCII code, value which is 71. This type of
conversion is called explicit casting.
 The explicit casting here is as follows: the variable
firstCharacter='G' is of type char, while the expression
(int)firstCharacter=71 is of type int.
 The statement int x = firstCharacter; is called an implicit
casting, where the value of x is the ASCII code of the character in
firstCharacter.
Program 23 : strings

1. // This program receive the student E-Mail that is composed of the first
2. // name "e.g. Ahmed“ followed by the year of birth "e.g. 2002" followed by
3. // "@bue.edu.eg"
4. #include <iostream>
5. #include <string>
6. using namespace std;
7. int main() {
8. string e_mail;
9. cout << "Enter the student's E-Mail : ";
10. cin >> e_mail; //"[email protected]"

11. int existAt = e_mail.find("@bue.edu.eg");


12. string ID = e_mail.substr(0, existAt);
13. cout << "The student ID : " << ID << endl;

14. int idLength = ID.length();


15. string dateStr = ID.substr(idLength-4, 4);
16. cout << "The student's BirthDate : " << dateStr << endl;

17. int Age = 2020 - stoi(dateStr);


18. cout << "Student Age is : " << Age <<endl;

19. return 0;
20. }
Program 23 : strings

8. string e_mail;
9. cout << "Enter the student's E-Mail : ";
10. cin >> e_mail; //[email protected]

 Lines 8, 9 and 10 just receive the value of string object “e_mail”


from the user. Its value must be the first name “Ahmed” followed by
the year of birth “2003”, this part is the ID of the student. This ID
part is followed by “@bue.edu.eg” to form the E-mail string.
 The next step is to print the ID of the student in a separate string.
This program uses the substr() function to get the part of the ID in
the E-mail, then prints this part.
 The next step is to print the year of birth which is a part from the
string ID. This program uses the substr() function to get the year
part from the ID. This part is of a data type string.
 Convert this date string to integer
Program 23 : strings

11. int existAt = e_mail.find("@bue.edu.eg");


12. string ID = e_mail.substr(0, existAt);
13. cout << "The student ID : " << ID << endl;

 The find() function can find the index of a character or a string. Line
11 finds the index of the text “@bue.edu.eg” in the object string
“e_mail”. For example the E-mail is "[email protected]", the
index of "@bue.edu.eg" is 9. The value of this index is saved in an
integer existAt.
 The value of existAt refers to the number of character in the ID.
For the example, the number of characters in "Ahmed2003" is
existAt=9.
 Line 12 uses the e_mail.substr(0, existAt) function to extract
the part that contains the ID of the student only. It starts index 0,
and has the length of existAt characters. It saves this part in the
variable ID, then prints its value in line 13.
Program 23 : strings

14. int idLength = ID.length();


15. string dateStr = ID.substr(idLength-4, 4);
16. cout << "The student's BirthDate : " << dateStr << endl;

 Lines 14 uses the function length() to calculate the number of


characters in the string object “ID”. For example, if the string
object is ID=“Ahmed2003” which contains 9 characters, then the
function ID.length() returns 9 in the variable idLength.
 The next step is extract the year of birth dateStr=“2003” from the
string object ID=“Ahmed2003”. Line 15 uses the substr() function to
get the last 4 characters in the object ID, as the year contains four
digits. It starts before the last position by 4 digits (idLength-4) and
the length of the substring is 4 digits. Line 16 prints out the resulted
year of birth “2003”.
 The string object dateStr contains the text “2003”. C++ considers
this object “2003” as a text, where no mathematical operation, like
addition or subtraction, can be applied on this text.
Program 23 : strings

17. int Age = 2020 - stoi(dateStr);


18. cout << "Student Age is : " << Age <<endl;

 Lines 17 uses the function stoi(), this function converts the string
object to an integer. Stoi is an abbreviation, s in stoi refers to
string, then to, then i refers to integer.
 The value of stoi(dateStr) or stoi("2003")=2003 is the integer
(numerical) value of the text "2003". This integer year
stoi("2003") is subtracted from the current year 2020.
 The age of the student is calculated as the difference between the
current year “2020” and year of birth stoi(dateStr).
 Finally line 18 prints out the age of the student.
 Note that if the text in string object contains non-numerical values
like letters or special characters, a run time error occurs in the
program. The function converts the numerical text "2003" to
integer 2003.
Program 24 : More about cmath
library
1. // This program from the user three float values and
2. // prints the square root of the maximum value.
3. #include <iostream>
4. #include <algorithm>
5. #include <cmath>
6. using namespace std;
7. int main() {
8. float x, y, z;
9. cout<<"Enter three fractions : ";
10. cin >> x >> y >> z;
11. float maximum = max(x, max(y, z)); //In algorithm library
12. cout << "The maximum value is : " << maximum << endl;
13. float squareRoot = sqrt(maximum); //In cmath library
14. cout << "The squareRoot of the maximum value is : " << squareRoot << endl;
15. float lowerValue = floor(squareRoot); //In cmath library
16. cout << "The floor value of this fraction is : " << lowerValue << endl;
17. return 0;
18. }
Program 24 : More about cmath
library
7. float x, y, z;
8. cout<<"Enter three fractions : ";
9. cin >> x >> y >> z;
10. float maximum = max(x, max(y, z)); //In algorithm library
11. cout << "The maximum value is : " << maximum << endl;

 Lines 7, 8 and 9 define 3 fraction numbers of data type float. Then


get the values of these numbers from the user.
 Line 10 uses the function max() to find the maximum value of these
two numbers. The function max() in the cmath library can find the
maximum value of two numbers only. So, line 10 finds the maximum
value between y and z using max(y, z), then finds the final
maximum value after comparing the result to x.
 Line 11 prints the maximum value that is saved in the fraction
variable maximum.
 The cmath library contains function max(x, y) and function min(x, y)
to get the maximum and minimum values of two numbers.
Program 24 : More about cmath
library
12. float squareRoot = sqrt(maximum); //In cmath library
13. cout << "The squareRoot of the maximum value is : " << squareRoot << endl;
14. float lowerValue = floor(squareRoot); //In cmath library
15. cout << "The floor value of this fraction is : " << lowerValue << endl;

 Lines 12 uses the function sqrt() function in the cmath library to


calculate the square root of the maximum value. The input of this
function is one value maximum=87.9589, and it returns its square
root 9.37864 to be stored in the float variable squareRoot. Line
13 prints the squareRoot=9.37864.
 Lines 13 uses the function floor() function in the cmath library to
calculate the floor of a decimal number, the floor of 4.9 is 4, the
floor(squareRoot)=9. The inverse of this function in the cmath
library is ceif(), the ceil of 4.1 is 5.
Programming so far:
C++ Provides many primitive data types like int, double, float, char:
 The C++ compiler provides data types of small number of bytes:
 int: this data type represents the whole numbers, without a floating
point. The size of this data type is 4 bytes.
 float: this data type represents the fraction numbers that contain a
floating point. The size of this data type is 4 bytes.
 double: this data type represents the fractions of extremely big values.
The size of this data type is 8 bytes.
 char: this data type represents all the keyboard characters like letters,
special characters, numerical signs. The size of this data type is 1 byte.
The numerical value that is corresponding to every character is called
the ASCII code.
 The programmer can convert between these datatype using implicit and
explicit casting.
 Implicit casting: int g = 'a';➔ g=97
 Explicit casting: cout << (int)'a'; ➔prints 97

119
Programming so far:
C++ Provides many functions to help the programmer to write programs easier:
 The C++ compiler provides some general helpful functions:
 sizeof(): return the number of bytes of any variable or a datatype. e.g.
sizeof(int)=4.
 stoi(): returns the integer value of a text. e.g: stoi("2")=2.
 The cmath library provides many mathematical functions like:
 pow(): function, it calculates xz as pow(x, z). e.g: pow(2,3)=8;
 sqrt(x): calculates 𝑥
 floor(3.4)=3, ceil(3.4)=4, round(3.4)=3.
 The algorithm library provides many other functions like:
 min(x,y) and max(x,y) : calculates maximum and minimum values of x,y.
 The string library provides many functions:
string s; //defines an object that contains a text
s = "British university";
 find() : return the index of the first character or text in a string object. e.g:
s.find('I')=2 or s.find("ish")=4.
 substr(): returns a string that is a part (substring) from the string object. e.g:
s.substr(1, 3)="rit";
 at(): returns the character that exists in a specific location in a string object.
e.g: s.at(3)='t';
 length(): returns the number of characters in the string object. e.g:
120
s.length()=18;
Programming so far:
The programmer of C++ usually use functions:
 A function is a small program that has a specific task:
 A function has a specific task that is usually inferred from its name:
 int x; sizeof(x): returns the size of a variable
 A function must have a list of input parameters between brackets ():
 int x; sizeof(x): The input parameter of this function is only one: x.
 int x=2,y=3; max(x,y); This function has 2 input parameters.
 String s=“xyz“;s.length(); This function has zero input parameters.
 When a programmer uses a function, it is called, “a function call”. For
example:
 int x = max(4, 5);
 //function call : the programmer is calling the function max().
 The functions in the string library are applied on a specific object,
unlike c++ compiler and cmath library are called directly:
 string s=“xyz“; s.substr(0,2); //"xy“ the substr() is applied on the string s.
 The function substr() is prefixed by (s.) because it get substring from s.
121
 int x = max(4, 5); //the max() function is applied directly.
 The function max() is not prefixed by the dot (.) operator
Sample MCQ for Programming
So far :
1. What is the output of the following Program? 2. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. int main() { 3. int main() {
4. int n = 2.1; 4. int c = 'a';
5. double g = 4.30; 5. int f = sizeof(c) + sizeof('a') + c%sizeof(c);
6. float f = sizeof(n) + sizeof(4.3f); 6. cout << f++;
7. f += n + sizeof(g); 7. cout << ++f;
8. f += g; 8. return 0;
9. cout << f; 9. }
10. return 0; a) 79
11. } b) 46
a) Compile time error in line 6 c) 68
b) 13.4 d) 35
c) 22 e) 66
d) 22.3
e) 17.3
Sample MCQ for Programming
So far :
3. What is the output of the following Program? 4. What is the output of the following Program?
1. #include <iostream>
1. #include <iostream>
2. #include <string>
2. #include <string>
3. using namespace std;
3. using namespace std;
4. int main() {
4. int main() {
5. string sg1 = "Professional 20 Visual Studio";
5. string sg = "No 3 in America";
6. int g1 = sg1.find(' ') + 1;
6. int g = sg.at(3) + 1;
7. int k1 = sg1.length() - g1;
7. g--;
8. string sg2 = sg1.substr(g1, k1);
8. g /= 2;
9. int g2 = sg2.find(' ') + 1;
9. cout << g;
10. int k2 = sg2.length() - g2;
10. return 0;
11. string sg3 = sg2.substr(0, g2);
11. }
12. k2 += stoi(sg3);
a) 2
13. cout << k2;
b) 25
14. return 0;
c) 4
15. }
d) 27
a) 79
e) 3
b) 46
c) 6
d) 33
e) 66
Sample MCQ for Programming
So far :
5. What is the output of the following Program? 6. What will be the output of the following C++ code?
1. #include <iostream> 1. #include <iostream>
2. #include <cmath> 2. using namespace std;
3. using namespace std; 3. int main(){
4. int main() { 4. char c = 'A';
5. int g = 2, x = 1, y = 3, t = g, z1, z2, z3; 5. int x = 66;
6. z1 = x + y % t + g * x + y; 6. int g = 'B';
7. z2 = min(max(g, x), min(y, t)); 7. cout << (char)x << c + sizeof(c);
8. z3 = sizeof(g) + sizeof(2); 8. cout << 'A' + sizeof(float) / 4 << (char)g;
9. cout << z1 << z2 << z3; 9. return 0;
10. return 0; 10. }
11. } a) BBBB
a) 847 b) B6767A
b) 728 c) AB66B
c) 937 d) B6666B
d) 428 e) 66B66B
e) 826
Sample MCQ for Programming
So far :
7. What is the output of the following Program? 8. What will be the output of the following C++ code?
1. #include <iostream>
1. #include <iostream>
2. #include <cmath>
2. using namespace std;
3. using namespace std;
3. int main(){
4. int main(){
4. const int y = 4;
5. char g = 'A';
5. double d = 4;
6. double a = 2.45, b = 3.61, c = 1.1;
6. float r = 4.3;
7. g += 32;
7. int x = 4.2;
8. cout << floor(a) + round(b) + ceil(c);
8. y = d + r;
9. cout << g;
9. return 0;
10. cin >> g;
10. }
11. return 0;
a) Warnings in lines 5, 6 and 7, and an error in line 8
12. }
b) Warnings in lines 5 and 6, and an error in line 8
a) 6a
c) No warnings but an error in line 8
b) 7A
d) Warnings in lines 6, 7, and 8
c) 7a
e) Warnings in lines 6 and 7, and an error in line 8
d) 8Z
e) 8a
Sample MCQ for Programming
So far :
9. What is the output of the following Program? 10. What is the output of the following Program, in case the user enters the
1. #include <iostream> text “Artificial Intelligence” then enters the text “Information Technology”?
2. using namespace std;
3. int main(){
4. int y = 4; 1. #include <iostream>
5. const int d = 4.2; 2. #include <string>
6. char a = 'a'; 3. using namespace std;
7. y--; 4. int main(){
8. y--; 5. char a = 'n';
9. ++y; 6. string s1, s2;
10. y += a; 7. getline(cin, s1);
11. y -= 'a'; 8. cin >> s2;
12. y %= d; 9. cout << (char)(++a + s1.find(a));
13. cout << y; 10. cout << (--s2.at(6) + s2.length());
14. return 0; 11. return 0;
15. } 12. }
a) H106
a) Error in line 12
b) T107
b) Error in line 11 c) Run time Error
c) 1 d) T106
d) 2 e) n107
e) 3
Introduction to
Computing

Lecture 6
The boolean data type, expressions and
the If Conditions

Dr. Mostafa Salama


Program 25 : Logic in C++

1. //This program demonstrates the Boolean variables and logical conditions


2. #include <iostream>
3. using namespace std;
4. int main(){
5. bool boolValue;
6. boolValue = true;
7. cout << "boolValue(true) = " << boolValue << endl;

8. boolValue = false;
9. cout << "boolValue(false) = " << boolValue << endl;

10. int x = 5, y = 10;


11. boolValue = x < y;
12. cout << "The expression (x < y) is " << boolValue << endl;

13. boolValue = x == y;
14. cout << "The expression (x == y) is = " << boolValue << endl;

15. cout << "size of the boolValue is " << sizeof(boolValue) << endl;
16. return 0;
17. }
Program 25 : Logic in C++

5. bool boolValue;
6. boolValue = true;
7. cout << "boolValue(true) = " << boolValue << endl;
8. boolValue = false;
9. cout << "boolValue(false) = " << boolValue << endl;
 Lines 5 defines a variable boolValue of data type bool. Boolean
(bool) variables have only one of two values true(1) or false(0).
 The bool data type is a primitive data that is used when the value
of a variable is either true or false only. The value of true is stored
in the memory as 1, and the value of false is stored as 0.
 Line 6 assigns the value of true to the boolean variable boolValue.
And line 7 prints out the value of boolValue. The true value is
stored in the boolValue as 1.
 Lines 8 assigns the value of false to the boolean variable boolValue.
And line 9 prints out the value of boolValue. The false value is
stored in the boolValue as 0.
Program 25 : Logic in C++

6. boolValue = true;
8. boolValue = false;

 The (bool) is the same as all the other primitive data types like int,
float, double, and char. All the data types are stored in the memory
of the computer as binary data.
 The whole and decimal numbers are converted to binary, the
characters are converted to ASCII code that is converted to binary.
And finally, the true is 1 and the false is zero in boolean variables.
Convert from whole number to binary
int

double Convert from fraction number to binary


float
Binary
data
ASCII Convert from whole
char
Code number to binary

true or Convert true to 1


bool and false to 0
false
Program 25 : Logic in C++

10. int x = 5, y = 10;


11. boolValue = x < y;
12. cout << "The expression (x < y) is " << boolValue << endl;
 Lines 10 defines and initializes two integer variables. The variable x
has value 5 and variable y has value 10.
 Line 11 assigns the result of the relational expression (x < y) to the
variable boolValue. Since the value of x=5 is less than the value of
y=10, then the expression (x < y) is true. The value of boolValue
becomes true, and then the printed value in line 12 is 1.
 Here are available relational expressions in c++
 Expression What the Expression Means
 x>y Is x greater than y?
 x<y Is x less than y ?
 x >= y Is x greater than or equal to y ?
 x <= y Is x less than or equal to y ?
 x == y Is x equal to y ?
 x != y Is x not equal to y ?
Program 25 : Logic in C++

10. int x = 5, y = 10;


13. boolValue = x == y;
14. cout << "The expression (x == y) is " << boolValue << endl;
 The variable x has value 5 and variable y has value 10 . These two
values are not equal, so the expression (x==y) is false.
 Line 13 assigns the result of the relational expression (x == y) to the
variable boolValue. The value of boolValue becomes false, and then
the printed value in line 14 is 0.
 Among the relational expressions, is the reverse of the equality
condition (==). This is the not-equal condition (!=), where the mark
(!) is considered as (not).
 So (x!=y) check whether x is not equal to y. Sine x = 5 and y =
10 are not equal, then the expression (x!=y) is true. This condition
(x!=y) can be written in a different way, where the expression
(!(x==y)) is the same as (x!=y).
 Boolean Rule: !true=false and !false=true.
Program 25 : Logic in C++

15. cout << "size of the boolValue is " << sizeof(boolValue) << endl;

 The size of the Boolean variables, using the sizeof(bool) function, is


1 byte. One byte contains 8 bits, each bit is 1 or 0. For Boolean
variables, the first bit only in the 1 byte includes the value of the
variable. This leads to the consumption of useless 7 bits, however
the minimum size of memory can be read by a computer is byte.

Byte 1

bit 1 or 0
 Boolean has the smallest size among the other data types. Its
datatype can be converted to integer datatype by casting.
Program 26 : Logic in C++

1. //This program demonstrates different types of implicit casting


2. #include <iostream>
3. using namespace std;
4. int main() {
5. int x = 32.4; //Implicit casting from double to integer value [32].
6. int y = true; //Implicit casting from boolean to integer value [1].
7. int z = 'A'; //Implicit casting from character to integer(ASCII) value [65].
8. int r = x + y + z; //Adding the 3 casted values.
9. cout << "(r = x(32) + y(1) + z('A')) = " << r << endl; //'98'

10. char c = x + z;//Implicit casting from integer to character value ['a'].


11. cout << "(c = x(32) + z(65)) = " << c << endl; //'a'

12. bool b = true; //The value of true is not casted.


13. int i = 4; //The value of 4 is integer and not casted.
14. i += b; //Implicit casting of boolean to integer of value 1 added to 4.
15. cout << "(i = i(4) + b(1)) = " << i << endl; //5
16. }
Program 26 : Logic in C++
5. int x = 32.4; //Implicit casting from double to integer value [32].
6. int y = true; //Implicit casting from boolean to integer value [1].
7. int z = 'A'; //Implicit casting from character to integer(ASCII) value [65].
8. int r = x + y + z; //Adding the 3 casted values.
9. cout << "(r = x(32) + y(1) + z('A')) = " << r << endl; //'98'

 Line 5 assigns a double value (32.4) of size 8 byte to integer variable


x of size 4 bytes only. The value after the floating point is ignored.
This leads to a warning, not an error, for implicitly converting from
big to a smaller datatype and possible loss of data.
 Line 6 assigns a Boolean value (true) of size 1 byte to integer
variable y of size 4 bytes. This line implicitly converting from small
to a bigger datatype and wasting for resources (7 bits wasted).
 Also line 7 assigns a character value (‘A’) of size 1 byte to bigger
integer variable z. The compiler here saves the integer value of the
ASCII code corresponding to the character ‘A’.
 The corresponding integer value of each of these variables
(32.4➔32,true➔1, and ‘A’=65) are added and stored in the integer
variable r.
Program 26 : Logic in C++
10. char c = x + z;//Implicit casting from integer to character value ['a'].
11. cout << "(c = x(32) + z(65)) = " << c << endl; //'a'
12. bool b = true; //The value of true is not casted.
13. int i = 4; //The value of 4 is integer and not casted.
14. i += b; //Implicit casting of boolean to integer of value 1 added to 4.
15. cout << "(i = i(4) + b(1)) = " << i << endl; //5

 Line 10 sum the value of the integer x which is 32 to the value of


integer y which is 65.
 Line 12 and 13 defines and initializes a Boolean variable b=true and
integer variable i=4.
 Line 14 sum the value of integer i to the value of Boolean b. The
value of Boolean b is implicitly casted to integer first, then added
the value of i.
 Generally, the data type of bigger size is dominating the arithmetic
operation.
 For example int(4 bytes)+bool(1 byte)=int(4 bytes).
 For example int(4 bytes)+double(8 bytes)=double(8 bytes).
Program 27 : Logic in C++

1. //This program demonstrates the logical operators


2. #include <iostream>
3. using namespace std;
4. int main(){
5. bool boolValue;
6. int x = 5, y = 10, z = 15;

7. boolValue = x < y && y < z;


8. cout << "The expression (x < y && y < 15) is " << boolValue << endl;

9. boolValue = x < y || y == z;
10. cout << "The expression (x < y || y == z) is = " << boolValue << endl;

11. boolValue = x == y && x < y || y != z;


12. cout << "The expression (x == y && x < y || y != z) is = " << boolValue << endl;

13. cin >> boolValue;


14. return 0;
15. }
Program 27 : Logic in C++
5. bool boolValue;
6. int x = 5, y = 10, z = 15;
7. boolValue = x < y && y < z;
8. cout << "The expression (x < y && y < z) is " << boolValue << endl;

 Line 5 defines a boolean variable , and line 6 defines and initializes


3 integer variables.
 Line 7 uses a logical operator && to connect between two
expressions (x < y) and (y < z). The operators (&&), (||) and (!)
are called logical operators. The operator && to refers to the (and)
logical operation between two expressions, such that the two
expressions must be true for the overall expression to be true.
 The expression (x < y) is true and the expression (y < z) is also
true, this means that overall expression ((x < y) && (y < z)) is
true. Then the printed value in line 8 is 1.
 The truth table of the logical And operator:
 (true && true) = true
 (false && true) = false
 (true && false) = false
 (false && false) = false
Program 27 : Logic in C++
5. bool boolValue;
6. int x = 5, y = 10, z = 15;
9. boolValue = x < y || y == z;
10. cout << "The expression (x < y || y == z) is = " << boolValue << endl;

 Line 9 uses a logical operator || to connect between two


expressions (x < y) and (y == z). The operator || to refers to the
(or) logical operation between two expressions, such that any of the
two expressions must be true for the overall expression to be true.
 The expression (x < y) is true and the expression (y == z) is false,
this means that overall expression ((x < y) || (y == z)) is true.
Then the printed value in line 10 is 1.
 The truth table of the logical Or operator:
 (true || true) = true
 (false || true) = true
 (true || false) = true
 (false || false) = false
Program 27 : Logic in C++
5. bool boolValue;
6. int x = 5, y = 10, z = 15;
11. boolValue = y != z || x < y && x == y;
12. cout << "The expression (y != z || x < y && x == y) is = "<< boolValue << endl;

 Line 11 applies the logical operator && and || on three expressions


(y != z), (x < y) and (x == y).
 The expression (x != z) is true, the != is checking that the two
values are not equal. The sign ! means not, != means not equal.
 The expression (x < y) is true, and the expression (x == y) is true.
 The overall expression ((y!=z)||(x<y)&&(x==y)) is true.
 The operator && has the precedence over the operator ||,
 So the expression ((x<y)&&(x==y)) is evaluated first
((true)&&(false)) as false.
 Then the expression ((y!=z)||(false)) is evaluated next
((true)||(false)) as true.
Program 28 : Logic in C++

1. // This program shows how to read a boolean


2. // variable from user.
3. #include <iostream>
4. #include <cmath>
5. using namespace std;
6. int main() {
7. bool info1;
8. cout << "Are you African? \n if yes press 1, and if no press 0: ";
9. cin >> info1;

10. bool info2;


11. cout << "Are you Egyptian? \n if yes press 1, and if no press 0: ";
12. cin >> info2;

13. bool info = info1 && info2;


14. cout << "Then you African and Egyptian \n 1 for yes, 0 for no : " << info;

15. return 0;
16. }
Program 28 : Logic in C++

7. bool info1;
8. cout << "Are you African? \n if yes press 1, and if no press 0: ";
9. cin >> info1;

 Lines 57 defines a Boolean variable info1 of data type bool. Line 8


asks the user to answer by entering 0 or 1. The cin>> command
reads the value info1 of as 1 or 0.
 Generally, the Boolean variable printed to the user or entered by
the user as 1 or 0, and not as “yes” or “no” in a text form.
 The same for lines 10, 11 and 12. The program read the value of
info2 from the user as 1 or 0 only.
Program 28 : Logic in C++

13. bool info = info1 && info2;


14. cout << "Then you African and Egyptian \n 1 for yes, 0 for no : " << info;

 Lines 13 defines a Boolean variable info of data type bool. The


value of is equal to result of the and operation between info1 and
info2.
 If the user enters value 1 for info2 and enters the value 1 for
info2, then the value of info is 1. if info1=1 and info2=0, then
the value of info is 0. if info1=0 and info2=0, then the value of
info is 0.
 Line 14 shows that if the user is African and Egyptian, then the
output is going to be 1(one), and 0(zero) otherwise.
 What if you, as a programmer, needs to print a complete statement
according to the user input. For example, to print “You are Af and
Egyptian” or “You are not African and Egyptian”. In this case you
must use “If condition statement”.
Program 29 : Conditions in C++
Start

1. //This program shows if statement


Get SM
2. #include <iostream>;
3. using namespace std; SM>=50
false
true
4. int main(){
Print “Student passed”
5. int SM;
6. cout << "Enter Student Mark : "; End
7. cin >> SM;
8. if (SM >= 50) Flowchart
9. cout<<"The student passed the module";
10. return 0;
True
11. }

False
Program 29 : Conditions in C++
8. if (SM >= 50)
9. cout<<"The student passed the module";

 The value of SM is received from lines 5, 6 and 7.


 Lines 8 and 9 are corresponding to one statement which is the “if
statement”: false
SM>=50
 if(SM >= 50) cout<<"The student passed the module"; true

Print “Student passed”


 The “if statement” executes a statement in a condition that an
expression is true:
 If (expression)
Statement;//executed only if the expression is true.

false
expression
 If the value of the expression inside the parentheses () is true, the
true
very next statement is executed. Otherwise, it is skipped. The if
statement has two parts: Statement

 Here, if the expression (SM >= 50) is true, then the statement is
executed by printing the student passed the model. And if the
expression is false, then nothing is printed.
Flowchart
Program 29 : Conditions in C++
8. if (SM >= 50)
9. cout<<"The student passed the module";

 Here, if the expression (SM >= 50) is false, then the statement
[cout<<"The student passed the module";] doesn’t executed,
and the text "The student passed the module" is never false
SM>=50
printed. true

Print “Student passed”

➢ Notice also the visual representation (Flowchart);


false
expression
➢ The rumbas shape represents the expression, has two output true
arrows: true arrow and false arrow. Statement
➢ The true arrow points to the parallelogram that represents
the statement.
Flowchart
➢ The false arrow from the expression is skipping the
statement by pointing directly to what it points to.
Program 29 : Conditions in C++
8. if (SM >= 50)
9. cout<<"The student passed the module";

 Notice that no semicolon (;) after the statement If (expression).


This is because this statement is not ended yet. The if statement
ended only after the Statement. false
SM>=50
true
Alert  If the programmer adds by mistake a semicolon (;) after the
statement If (expression), the program will executes the Print “Student passed”
Statement regardless of the expression if the value of the
expression is true or false.

For example in following lines: the text "The student passed


expression
the module“ is printed if the value of expression is true (60>50) false
or false(40<50). true

8. if (SM >= 50); Statement


9. cout<<"The student passed the module";

expression
Flowchart
false
true

Statement
Program 29 : Conditions in C++
7. cin >> SM;
8. if (SM >= 50) Start
9. cout<<"The student passed the module";
Get SM
 The Flowchart is a visual representation of the program. It shows the
design of your program. The arrows in the flowchart shows how the
program flows from the start to the end. false
SM>=50
true
 The start and the end of the program is represented by a circle shape.
Print “Student passed”
Start End

End
 Line 7 gets the value of SM from the user, the corresponding shape of
any getting (input) or any printing (output) is the parallelogram
shape.
Get SM Flowchart
 Line 8 is the conditional expression (SM >= 50) of the if statement,
the corresponding shape in a flowchart of any conditional expression
is the rumbas shape.
SM>=50

 Line 9, is the statement that is executed only if the conditional


expression is true. The corresponding of any printing (output) is also
the parallelogram shape.
Print “Student passed”
Start

Program 30 : Conditions in C++ Get var1

var1<0
False
True
1. //This program demonstrates the if condition statement var1 = -var1
2. #include <iostream>
3. using namespace std;
Print var1
4. int main() {
5. int var1;
Get var2
6. cout << "Enter an integer value: ";
7. cin >> var1;
8. if (var1 < 0) False var1!=var2
9. var1 = -var1; //This line executes only if (var1<0)=true. True
10. cout << "The absolute value is " << var1 << endl;; Print not equal

11. int var2;


12. cout << "Enter another integer value: "; End
13. cin >> var2;
14. if (var1 != var2) Flowchart
15. cout << "The two integer values are not equal";

16. return 0;
17. }
Program 30 : Conditions in C++ Get var1

5. int var1;
6. cout << "Enter an integer value: "; var1<0
False
7. cin >> var1; True
8. if (var1 < 0) var1 = -var1
9. var1 = -var1;
10. cout << "The absolute value is " << var1 << endl;; Print var1

 Lines 5, 6 and 7 define an integer variable var1 and get its value from the user.

 Lines 8 and 9 are corresponding to one statement which is the “if statement”:
 if(var1<0) var1=-var1;

 This if statement calculates the absolute value |var1| of var1. This means that the
printed value of var1 is always positive whether the user entered a positive or a
negative value:
 if the value of var1 is a (negative value less than zero) : e.g: var1=-4<0;
 Then the value of var1 is equal to negative of the negative value of var1.
 Then the value of var1 is equal to the positive value of var1. e.g: var1=-(-4)=4;

 The assignment statement (var1 = -var1;) in line 9 is executed only if the conditional
expression (var1<0) is true. The corresponding shape of to any assignment statement is
the rectangle shape.
var1 = -var1
Program 30 : Conditions in C++
Get var2
11. int var2;
12. cout << "Enter another integer value: ";
13. cin >> var2; False var1!=var2
14. if (var1 != var2) True
15. cout << "The two integer values are not equal"; Print not equal

 Lines 11, 12 and 13 define an integer variable var2 and get its value from the user.
 Line 14 tests if the expression (var1 != var2) is true or not. This expression tests
whether the two values var1 and var2 are not equal. If these two values are not equal
then the statement in line 15 is executed, and if these two value are equal then line 15 is
skipped.

Alert  In case of testing whether var1 is equal to var2 using the expression (var1 == var2).
The programmer must not confuse between (=) for assigning the value and (==) for
testing the equality.
 For example: if (var1 = var2) cout << "The two integer values are equal";
 This expression (var1 = var2) is always true, because it assigns the value of var1
to var2 successfully. So the statement cout << "The two integer values are
equal"; is executed even if the value of var1 is not equal to var2.
Program 31 : Conditions in C++
Scenario 1: x>=0 and y!=0

1. //This program demonstrates the if condition statement


2. #include <iostream>
3. #include <cmath>
4. using namespace std; Scenario 2: x<0 and y!=0
5. int main() {
6. double x, y, z;
7. cout << "Enter the value of x: ";cin >> x;
8. cout << "Enter the value of y: ";cin >> y;

9. bool printed = false;


10. if (x >= 0 && y != 0){ Scenario 3: x>=0 and y==0
11. z = sqrt(x) / y;
12. cout << "z = the square root of x divided by y = ";
13. cout << z;
14. printed = true;
15. }
16. if (!printed) Scenario 4: x<0 and y==0
17. cout << "can not calculate the value of z";
18. return 0;
19. }
Program 31 : Conditions in C++
Scenario 1: x>=0 and y!=0

10. if (x >= 0 && y != 0){


11. z = sqrt(x) / y;
12. cout << "z = the square root of x divided by y = ";
13. cout << z;
14. printed = true;
15. }
𝑥
 This program is simply calculates the value of z = 𝑦
.
 In mathematics, the value of x can not be negative, because the square root
can not be calculated for negative values.
 In mathematics also, the value of y can not be zero, because the denominator
of the division operation can not be zero.

 If the programmer did not check the input from


the user like this code code, a run time error will
appear if the user violates the rules of mathematics.
This error is shown as (#IND) as indefinite value.
Program 31 : Conditions in C++
Scenario 1: x>=0 and y!=0

10. if (x >= 0 && y != 0){


11. z = sqrt(x) / y;
12. cout << "z = the square root of x divided by y = ";
13. cout << z;
14. printed = true;
15. }
 Lines 6, 7 and 8 defines two variables x and y, and get the values of x and y from the
user. Then line 9 defines and initializes the boolean variable printed as false.

 This program checks first if x is not a negative value (x >= 0) and y is not a zero
𝑥
value (y != 0) before calculating the equation z = 𝑦
. The program uses the and
operator (&&) to check that these two expression are correct, together. If the full
expression (x >= 0 && y != 0) is true, the block between { } directly after the if
statement is executed

 If the expression in line 10 is true, The lines 11, 12, 13, and 14 inside the block
between the two curly brackets { } , after the if() condition, are executed.
The condition is that the boolean
 The if statement may contain if ( expression ){ expression must true, to run the
statement1;
 one statement to execute statements between { and }.
statement2;
 Or multiple statements to execute between { and }. … 154
}
if is a C++ •If the expression is true, the statements between { and
reserved word } is executed.
Program 31 : Conditions in C++
Scenario 1: x>=0 and y!=0

10. if (x >= 0 && y != 0){


11. z = sqrt(x) / y;
12. cout << "z = the square root of x divided by y = ";
13. cout << z;
14. printed = true;
15. }
 Line 10 checks the expression (x >= 0 && y != 0).
 In case of scenario 1, the user enters x greater than zero and y has value not equal
to zero. In this case, the full expression (x >= 0 && y != 0) is true.
 Line 11 is executed successfully by calculating the Square of x then the result
is divided by y.
 Line 12 and 13 are executed by printing out the value of z.
 Line 14 sets the value of the boolean variable printed as true.
 Notice that the boolean variable printed is assigned as true, only if the condition
in line 10 is true.
16. if (!printed)
17. cout << "can not calculate the value of z";

 The conditional expression in line 16 (!printed) checks if the value of printed is


not true. Notice that if the value of printed is true, this means that the value of z
is calculated successfully and the statement “can not calculate the value of
z” should not be printed.
Program 31 : Conditions in C++
9. bool printed = false;
10. if (x >= 0 && y != 0){ … }

16. if (!printed)
17. cout << "can not calculate the value of z";
Scenario 2: x<0 and y!=0

 Line 9 defines and initializes a boolean variable printed as


false .
 Line 10 checks the expression (x >= 0 && y != 0).
 In case of scenarios 2, 3 and 4, the user enters x as negative
value or y has zero value. In this case, the full expression (x >=
0 && y != 0) is false. Scenario 3: x>=0 and y==0

 The lines 11, 12, 13, 14 are not executed.


 The value of the boolean variable printed is not
changed, and still has a false value.
 In case of scenarios 2, 3 and 4, the boolean variable printed
has the value false, the expression
Scenario 4: x<0 and y==0
(!printed)=(!false)=(true) in line 16 is true. Then the
condition in line 16 is true and the statement in line 17 “can
not calculate the value of z” should not be printed.
Program 32 : Conditions in C++
Start

Get n
1. //This program demonstrates the if else statements
2. #include <iostream> True False
n%2==0
3. using namespace std;
Print n is even Print n is odd
4. int main(){
5. int n;
End
6. cout << "Enter a number n : "; cin >> n;
7. if (n % 2 == 0)
Scenario 1: n is even
8. cout << "n is an even number.";
9. else
10. cout << "n is an odd number";
Scenario 2: n is odd
11. return 0;
12. }
Program 32 : Conditions in C++ condition1
false

true false
condition2
8. if (m <= 100 && m >= 50) statement1 true
9. cout << "Student succeeded the module, Well Done...";
statement2
10. else if (m < 50 && m >= 0)
statement3
11. cout << "Student failed the module, hard luck...";
12. else
13. cout << "inaccurate mark";

 The if-else-if statement provide multiple options to select from, rather than
the if statements and the if-else statements. In this program, the user has
three scenarios success, fail and otherwise.
 The new addition in the if-else-if statement, is that another if condition is
added after the else key word in the if-else statement.
 If (expression1)
Statement1;//executed if expression1 is true.
else If (expression2)
Statement2;//executed if expression1 is false and expression2 is true.
else
Statement3;//executed if expression1 is false and expression2 is false.

 If the mark m of the student in the range between 50 and 100, then the student
passed the module. And if the mark of the student in the range between 0 and
49, then the student failed the module. And finally, if the mark of the student is
not in any of these ranges, then the mark incorrect.
Program 32 : Conditions in C++ condition1
false

true

7. if (n % 2 == 0) statement1
8. cout << "n is an even number."; statement2
9. else
10. cout << "n is an odd number";

 The if-else statement provide two options to select from, rather than the if
statements. The if-else statement will execute one group of statements if the
expression is true, or another group of statements if the expression is false.
 The new addition in the if-else statement, is that another else part after the if
statement ends.
 If (expression1)
Statement1;//executed if expression1 is true.
else
Statement2;//executed if expression1 is false and expression2 is true.

 The expression in line 7 is (n % 2 == 0) tests whether the value of n%2 is zero (true)
or not (false). The value of n%2 is equal to the remainder of the division of n by 2. In
this program, the user has two scenarios even, and odd.
 If n/2 has no remainder where (n % 2 = 0), this means that n is divisible by 2,
which means that n is even.
 If n/2 has a remainder where (n % 2 = 1), this means that n is not divisible by
2, which means that n is even.
Program 32 : Conditions in C++
7. if (n % 2 == 0)
8. cout << "n is an even number.";
9. else
10. cout << "n is an odd number";

 The if part tests whether n is divisible by 2, where there is no remainder when apply
(n%2). If the condition is true, the statement after the if condition is executed and
the program prints “n is an even number.”.
 The else part at the end of the if statement specifies a statement that is to be
executed when the expression is false. When n% 2 does not equal 0, which means
that n is not divisible by 2, a message is printed “n is an odd number.”.

 Note that the words “if”, “else”, are reserved words to c++. The developer can not
create a variable of a name like any of these words.
Introduction to
Computing

Lecture 7
More about conditional statements

Dr. Mostafa Salama


Program 33 : Conditions in C++

1. // This program shows the if-else-if statements...


2. #include <iostream> Start
3. using namespace std;
4. int main(){
Get m
5. int m;
6. cout << "Enter the student's mark : ";
m <= 100
false
7. cin >> m;
m>=50

true false
8. if (m <= 100 && m >= 50) m<50
m>=0
9. cout << "Student succeeded the module, Well Done...";
10. else if (m < 50 && m >= 0) true
11. cout << "Student failed the module, hard luck..."; Print
12. else success Print
13. cout << "inaccurate mark"; failed Print
inaccurate

14. return 0;
15. }
End

Flowchart
162
Program 33 : Conditions in C++

1. // This program shows the if-else-if statements...


2. #include <iostream> Scenario 1: m <= 100 and m >= 50
3. using namespace std;
4. int main(){

5. int m;
6. cout << "Enter the student's mark : ";
7. cin >> m;
Scenario 2: m < 50 and m >= 0
8. if (m <= 100 && m >= 50)
9. cout << "Student succeeded the module, Well Done...";
10. else if (m < 50 && m >= 0)
11. cout << "Student failed the module, hard luck...";
12. else
13. cout << "inaccurate mark"; Scenario 3: otherwise

14. return 0;
15. }

Program
Scenarios
Program 33 : Conditions in C++ condition1
false

true false
condition2
8. if (m <= 100 && m >= 50) statement1 true
9. cout << "Student succeeded the module, Well Done...";
statement2
10. else if (m < 50 && m >= 0)
statement3
11. cout << "Student failed the module, hard luck...";
12. else
13. cout << "inaccurate mark";

 The if-else-if statement provide multiple options to select from, rather than
the if statements and the if-else statements. In this program, the user has
three scenarios success, fail and otherwise.
 The new addition in the if-else-if statement, is that another if condition is
added after the else key word in the if-else statement.
 If (expression1)
Statement1;//executed if expression1 is true.
else If (expression2)
Statement2;//executed if expression1 is false and expression2 is true.
else
Statement3;//executed if expression1 is false and expression2 is false.

 The if-else-if statement can be extended to hold more than 2 conditional


expressions. The else-if part can be repeated multiple times according to the
program needs.
Program 33 : Conditions in C++ condition1
false

true false
condition2
8. if (m <= 100 && m >= 50) statement1 true
9. cout << "Student succeeded the module, Well Done...";
statement2
10. else if (m < 50 && m >= 0)
statement3
11. cout << "Student failed the module, hard luck...";
12. else
13. cout << "inaccurate mark";

(m<0) (m>=0 && m<50) (m>=50 && m<=100) (m>100)

Otherwise Fail Success Otherwise


0 50 100

 If the mark m of the student in the range between 50 and 100, then the student
passed the module.

 And if the mark of the student in the range between 0 and 49, then the student
failed the module.

 And finally, if the mark of the student is not in any of these ranges, then the
mark incorrect.
Program 34 : Conditions in C++
Start

1. // This program shows the if-else-if statements...


2. #include <iostream>
Get mark m
3. using namespace std;
4. int main(){
false
5. int m; m>=90
6. cout << "Enter the student mark \n"; true
false
7. cout << "Enter m between 0 and 100: "; m>=80
8. cin >> m; true false
m>=70
9. if (m >= 90) true
10. cout << "Student grade is A";
Print ‘A’ Print ‘B’ Print ‘C’ Print ‘D’
11. else if (m >= 80)
12. cout << "Student grade is B";
13. else if (m >= 70)
14. cout << "Student grade is C";
15.
16.
else
cout << "Student grade is D";
End
Flowchart
17. return 0;
18. }

166
Program 34 : Conditions in C++
9. if (m >= 90)
10. cout << "Student grade is A";
11. else if (m >= 80)
12. cout << "Student grade is B";
13. else if (m >= 70)
14. cout << "Student grade is C";
15. else
16. cout << "Student grade is D";

 Here, the if-else-if statement is extended to hold 3 conditional expressions,


and 4 options (A, B, C and D). The else-if is repeated two times.
 This program considers that the user will enter the value of m between 0
and 100.
 if the value of m is greater than 90, then the student got A. The value
of m is between 90 and 100.
 if the value of m is not greater than 90 and greater than 80, then the
student got B. The value of m is between 80 and 90.
 if the value of m is not greater than 80 and greater than 70, then the
student got C. The value of m is between 70 and 80.
 Otherwise, if the value of m is not greater 70, then the student got D.
The value of m is between 0 and 70.
Program 35 : Conditions in C++

 Problem: Write a C++ program that asks that user to enter a character, than
the program interpret the type of the entered character according to its asci
code and print the type accordingly. So the program should check whether the
entered character is capital letter, small letter, digit or a special character.

 Use the following list as a help to do the program, this help may not be with
you in the exam. ASCII ranges:
 Scenario 1: 0-47 Special Characters Scenario 1
 Scenario 1: 58-64 Special Characters
 Scenario 2: 48-57 0-9
 Scenario 3: 65-90 A-Z
Scenario 2

 Scenario 4: 97-122 a-z

Scenario 3

Scenario 4
168
Program 35 : Conditions in C++

1. // This program shows the if-else-if statements...


2. #include <iostream>;
3. using namespace std;
4. int main(){
5. char ac;
6. cout << "Please enter a character: ";
7. cin >>ac;

8. if ((ac >= 0 && ac <= 47) || (ac >= 58 && ac <= 64))
9. cout << "This is a special character";
10. else if (ac >= 47 && ac <= 57)
11. cout << "This is a digit";
12. else if (ac >= 65 && ac <= 90)
13. cout << "This is a capital letter";
14. else if (ac >= 97 && ac <= 122)
15. cout << "This is a small letter";

16. return 0;
17. }

169
169
Program 36 : Conditions in C++

 Problem: For a quadratic equation ax2+bx+c = 0; Write a C++ program that asks that
user to enter the values a, b and c, then the program print out the value of x.
−b± b2 −4ac
 Use the following formula to find x; x =
2a

 There are three cases to find x, consider d = b2-4ac


−b+ d −b− d
1. if d>0; then x has two values; x1 = 2a
and x2 = 2a
−b
2. If d=0; then x has one value; x =
2a
−b ( −d) −b ( −d)
3. if d<0; then x has two complex values;x1 = +i and x2 = −i .
2a 2𝑎 2a 2𝑎

Scenario 1

Scenario 2

Scenario 3

170
Program 36 : Conditions in C++
1. #include <iostream>
2. #include <cmath>
3. using namespace std;
4. int main() {
5. float a, b, c, x1, x2, discriminant, realPart, imaginaryPart; −b± b2 −4ac
6. cout << "Enter coefficients a, b and c: "; x =
2a
7. cin >> a >> b >> c;
8. discriminant = b * b - 4 * a * c;
9. if (discriminant > 0) {
10. x1 = (-b + sqrt(discriminant)) / (2 * a);
11. x2 = (-b - sqrt(discriminant)) / (2 * a);
12. cout << "x has two values: " << endl;
13. cout << "x1 = " << x1 << endl;
14. cout << "x2 = " << x2 << endl;
15. }
16. else if (discriminant == 0) {
17. cout << "x has one value: " << endl;
18. x1 = -b / (2 * a);
19. cout << "x1 = x2 =" << x1 << endl;
20. }
21. else {
22. realPart = -b / (2 * a);
23. imaginaryPart = sqrt(-discriminant) / (2 * a);
24. cout << "x has two complex values: " << endl;
25. cout << "x1 = " << realPart << "+i(" << imaginaryPart << ")" << endl;
26. cout << "x2 = " << realPart << "-i(" << imaginaryPart << ")" << endl;
27. }
28. return 0; 171
29. }
Program 37 : Conditions in C++
Scenario Output

 Problem: Write a C++ program: user is asked to enter a


•year%4==0
year and this program checks whether the year •year%100==0
entered by user is leap year or not. •year%400==0

 All years which are perfectly divisible by 4 are


leap years except for century years (years ending
•year%4==0
with 00) which is leap year only it is perfectly •year%100==0
divisible by 400. •year%400!=0

 For example:
 2012, 2004, 1968 etc are leap year but, 1971, 2006 •year%4==0
etc are not leap year. •year%100!=0

 Similarly, 1200, 1600, 2000, 2400 are leap years

 but, 1700, 1800, 1900 etc are not.


•year%4!=0

172
Program 37 : Conditions in C++
Scenario Output
1. #include <iostream>
•year%4==0
2. using namespace std; •year%100==0
3. int main() { •year%400==0
4. int year;
5. cout << "Enter a year: ";cin >> year;
6. if (year % 4 == 0) { •year%4==0
7. if (year % 100 == 0) { •year%100==0
•year%400!=0
8. if (year % 400 == 0)
9. cout << year << " is a leap year.";
10. else •year%4==0
11. cout << year << " is not a leap year."; •year%100!=0
12. }
13. else
14. cout << year << " is a leap year.";
•year%4!=0
15. }else
16. cout << year << " is not a leap year.";
17. return 0;
18. }
Start

Program 38 : Conditions in C++ Get mark m

false
m>=50

true

1. // Version (a): The usual form of the if condition statements ...


s=‘s’ s=‘f’
2. #include <iostream>
3. using namespace std;
4. int main(){ Get mark m
5. char s; //student status (s: success or f: fail)
6. int m; //student mark (0 to 100)
End

Flowchart
7. cout << "Enter the student mark = ";
8. cin >> m;
9.
10. if (m>=50)
11. s = 's';
12. else
13. s = 'f';

14. cout << "Student status is " << s;


15.
16. return 0;
17. }

174
Start

Program 38 : Conditions in C++ Get mark m

false
m>=50

true

1. // Version (b): The conditional Operator works like if statements ...


s=‘s’ s=‘f’
2. #include <iostream>
3. using namespace std;
4. int main(){ Get mark m
5. char s; //student status (s: success or f: fail)
6. int m; //student mark (0 to 100)
End

Flowchart
7. cout << "Enter the student mark = ";
8. cin >> m;
9.
10. m>=50 ? s = 's' : s = 'f'; // Conditional Operator 10. if (m>=50)
11. 11. s = 's';
12. cout << "Student status is " << s; 12. else
13. 13. s = 'f';
14. return 0;
15. }

175
Start

Program 38 : Conditions in C++ Get mark m

false
m>=50

true

1. // Version (c): The conditional Operator works like if statements ...


s=‘s’ s=‘f’
2. #include <iostream>
3. using namespace std;
4. int main(){ Get mark m
5. char s; //student status (s: success or f: fail)
6. int m; //student mark (0 to 100)
End

Flowchart
7. cout << "Enter the student mark = ";
8. cin >> m;
9.
10. s = (m>=50 ? 's' : 'f'); // Conditional Operator 10. if (m>=50)
11. 11. s = 's';
12. cout << "Student status is " << s; 12. else
13. 13. s = 'f';
14. return 0;
15. }

176
Start

Program 38 : Conditions in C++ Get mark m

false
m>=50
(a) 10. if (m>=50) s = 's'; else s = 'f'; // If Conditions true

(b) 10. m>=50 ? s = 's' : s = 'f'; // Conditional Operator s=‘s’ s=‘f’

Get mark m

 Line 10 in these three programs (a, b and c) are doing the same task. The
End
three lines tests a boolean expression (m>=50), if this expression is true then
the value of s is ‘s’, and if this expression is false then the value of s is ‘f’.
 The first program (a) uses the usual if condition statement , while the
Flowchart
second program (b) uses what is called “conditional operator”. The
conditional operator creates short expressions that work like if/else 10. if (m>=50)
statements. 11. s = 's';
12. else
 The conditional operator consists of the question-mark (?) and the colon (:). 13. s = 'f';
Its format is:
 Expression ? Statement1: Statement2;

false
 This short form is corresponding to the following if-else statement : Expression
 if (Expression) true
Statement1;
else Statement1 Statement2

Statement2;
Start

Program 38 : Conditions in C++ Get mark m

false
m>=50
(a) 10. if (m>=50) s = 's'; else s = 'f'; // If Conditions true

(b) 10. m>=50 ? s = 's' : s = 'f'; // Conditional Operator s=‘s’ s=‘f’

Get mark m

 The conditional operator consists of the question-mark (?) and the colon (:).
End
Its format is: Expression ? Statement1: Statement2;
 The part of the conditional expression (Expression) that comes before
the question mark (?) is tested. It’s like the expression in the
Flowchart
parentheses of an if statement.
10. if (m>=50)
 If the expression (Expression) is true, then the part of the Statement1
11. s = 's';
between the (?) and the colon (:) is executed.
12. else
 Otherwise, the part of the Statement2 after the colon (:) is executed. 13. s = 'f';

false
Expression
 The statement : m>=50 ? s = 's' : s = 'f';
true
 Expression ➔ m>=50
Statement1 Statement2
 Statement1 ➔ s = 's'
 Statement2 ➔ s = 'f'
Start

Program 38 : Conditions in C++ Get mark m

false
m>=50
(a) 10. if (m>=50) s = 's'; else s = 'f'; // If Conditions true

(b) 10. m>=50 ? s = 's' : s = 'f'; // Conditional Operator s=‘s’ s=‘f’

(c) 10. s = (m>=50 ? 's' : 'f'); // Conditional Operator


Get mark m

 The conditional operator in program (b) contains two independent


End
statements to be executed according to the boolean expression (m>=50). The
two statements are [s='s';] and [s='f';].
 The conditional operator in program (c) assign the value ‘s’ or ‘f’ to s
Flowchart
according to boolean expression (m>=50). the selected value is assigned to s
as result of the conditional operator (m>=50 ? 's' : 'f'). 10. if (m>=50)
11. s = 's';
 Both lines (b) and (c) are the same, except that line (c) assigns the result 12. else
from the conditional operation to s, while line (b) does two assignments 13. s = 'f';
[s='s';] and [s='f';] separately.

false
Expression
 The statement : m>=50 ? 's' : 'f';
true
 Expression ➔ m>=50
Statement1 Statement2
 Statement1 ➔ 's'
 Statement2 ➔ 'f'
Sample MCQ for Programming
So far :
1. What is the output of the following Program? 2. What is the output of the following Program?
1. #include<iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. int main(){ 3. int main(){
4. int x = 0, y = 1, z = 2; 4. int nc = 0;
5. int a=1, b=1; 5. int nl = 0;
6. if (x++ < y) 6. char c;
7. if (y < z) 7. if (cin.get(c) && c != 'e')
8. a = (x > z ? y = z : x == y); 8. if (++c)
9. if (--a == 0) 9. if (c == 'a' || c == 'c')
10. b = y; 10. nl += ++nc;
11. cout << (x + y + z + a + b); 11. else
12. return 0; 12. nl *= ++nc;
13. } 13. cout << nl << "-" << nc;
14. return 0;
a) 2 15. }
b) 3 a) 1-1
c) 4 b) 0-0
d) 5 c) 1-0
e) 6 d) 0-1
e) 2-0
Sample MCQ for Programming
So far :
3. What is the output of the following Program? 4. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. int main(){ 3. int main(){
4. int i = -4; 4. double x = 1.432;
5. int j = 2; 5. switch (x){
6. float x = -0.01; 6. case 0: cout << "zero";
7. float y = 0.005; 7. case 1: cout << "one";
8. cout << (((x >= y) || (i<0)) && (j < 4)); 8. case 2: cout << "two";
9. cout << '-'; 9. default: cout << "nothing";
10. cout << 2 - 3 % 4 * 2 + 2 * (2 == 1); 10. }
11. return 0; 11. return 0;
12. } 12. }

a) 0-3
b) 0--3 a) one
c) 0--4 b) onetwo
d) 1--4 c) onetwonothing
e) 1--3 d) nothing
e) Error
Sample MCQ for Programming
So far :
5. What is the output of the following Program? 6. What is the output of the following Program?
1. #include<iostream> 1. #include<iostream>
2. using namespace std; 2. using namespace std;
3. int main(){ 3. int main(){
4. int x = 23; 4. int x = 5, y = 2, z = -2;
5. if (x++ % 2) cout << "1"; 5. z += (x % 2 == 1 ? --y + x : x%y);
6. if (++x % 2) cout << "2"; 6. cout << z;
7. if (x % 2) cout << "3"; 7. return 0;
8. bool z = true; cout << z; 8. }
9. return 0;
10. }

a) 231 a) 8
b) 23true b) 3
c) 2true c) 1
d) 1231 d) 4
e) 23true e) 5
Sample MCQ for Programming
So far :
7. What is the output of the following Program? 8. What is the output of the following Program?
1. #include<iostream> 1. #include<iostream>
2. using namespace std; 2. #include<string>
3. int main(){ 3. using namespace std;
4. int a = 9; 4. int main(){
5. int b = 4; 5. char i = 't', j = 68;
6. bool t1 = a > b; 6. string x = "Information vs Data";
7. bool t2 = a/2 == b; 7. string y = x.substr(2, 3);
8. bool t3 = a != b; 8. cout << (x.at(7)==i?x.find(j)+y.at(2) :y.at(2));
9. bool t4 = !(a == b); 9. cout << i;
10. if (t1 && t2 && t3 && t4) 10. return 0;
11. cout << "true, "; 11. }
12. else
13. cout << "false, ";
14. cout << t1 << ", " << t2;
15. cout << ", " << t3 << ", " << t4 ;
16. return 0;
17. }
a) true, 1, 0, 0, 1 a) 70t
b) false, 1, 0, 1, 1 b) 100t
c) false, 1, 1, 0, 1 c) 120t
d) false, 1, 1, 1, 1 d) 129t
e) true, 1, 1, 1, 1 e) 69t
Sample MCQ for Programming
So far :
9. What is the output of the following Program? 10. What is the output of the following Program?
1. #include<iostream> 1. #include<iostream>
2. using namespace std; 2. using namespace std;
3. int main(){ 3. int main(){
4. int j = 2.4; 4. bool t1 = true;
5. if (j = 3) 5. bool t2 = false;
6. if ((++j) == 4) 6. int i1 = 1;
7. if (--j == 3) 7. int i2 = 3;
8. cout << "Correct"; 8. double d1 = 2.2;
9. else 9. int x = t1 + t2 + i1 + (double)i2 + d1;
10. cout << "Not Correct"; 10. cout << x;
11. return 0; 11. return 0;
12. } 12. }

a) “Nothing is printed” a) 4
b) Correct b) 5
c) “Compile Time Error” c) 6
d) Not Correct d) 7
e) “Run Time Error” e) 8
Introduction to
Computing

Lecture 8
Looping statements: while statements

Dr. Mostafa Salama


Additional Resources for examples: https://www.w3resource.com/cpp-exercises/for-loop/index.php
Program 39 : Loops in C++

Start
1. //this program demonstrates the if conditional statement
2. #include <iostream> n=1

3. using namespace std;


4. int main() { n<5
false

5. int n = 0; true

6. if (n < 5) { Print Hello

7. cout << "Hello\n"; n++

8. n++;
9. }
Print that’s all
10. cout << "That's all!\n";
11. return 0; End

12. }
Flowchart
Program 39 : Loops in C++

Start
1. //this program demonstrates the while loop statement
2. #include <iostream> n=1

3. using namespace std;


4. int main() { n<5
false

5. int n = 1; true

6. while (n < 5) { Print Hello

7. cout << "Hello\n"; n++

8. n++;
9. }
Print that’s all
10. cout << "That's all!\n";
11. return 0; End

12. }
Flowchart
Program 39 : Loops in C++
5. int n = 1;
6. while (n < 5) {
7. cout << "Hello\n";
8. n++;
9. }

 A loop is a C++ statement that causes a statement or group of n=1


statements to repeat. The while loop statement is one type of the loop
statements.
false
 The syntax of the while loop n<5
while (expression) true
statement;(s)
Print Hello

false n++
❑ If the expression is true then expression
execute statements(s), then test true
the expression again.
❑ If the expression is false then Statement;(s)
Terminates the while statement
while loop statement terminates. and goes to the next statement

Terminates the while statement


and goes to the next statement
Program 39 : Loops in C++
5. int n = 1;
6. while (n < 5) {
7. cout << "Hello\n";
8. n++;
9. }

 The while loop statement has two important parts: n=1


 An expression between brackets () that is tested for a true or a
false value.
 The while block that comes after the expression: is either a false
n<5
single statement or a group of statements between the brackets
{ }. true

 In the while statement, each time “the expression is tested and the
Print Hello
{statements(s)} runs” is called an “iteration”.
false n++
expression

true

Statement;(s)
Terminates the while statement
and goes to the next statement

Terminates the while statement


and goes to the next statement
Program 39 : Loops in C++
5. int n = 1;
6. while (n < 5) {
7. cout << "Hello\n";
8. n++;
9. }
 The expression tests the value of variable called the “iterator”. The number
of iterations of the while loop is dependent on the value of the “iterator”. n=1
 In this example, the iterator of the while loop statement is n. The value of
iterator n will keep incrementing until the expression is false. The expression is
false
false when the value of iterator n is greater than 5. n<5

true
n=1
Print Hello

n=2 n=3 n=4 n=5 false


n<5 n<5 n<5 n<5 n<5 n++

true true true true

Print Hello Print Hello Print Hello Print Hello

Terminates the while


n++ n++ n++ n++ statement and goes
to the next
statement
First iteration First iteration First iteration First iteration
Program 39 : Loops in C++
5. int n = 1;
6. while (n < 5) { cout << "Hello\n"; n++; }

 The following steps traces the running of the while loop statements:
➢ When the while loop statement starts, the value of iterating
variable n is 1. The expression here is the condition whether n is
smaller than 5 or not.
n=1
➢ In the first iteration n=1, the expression (n < 5) is true. The
printing statement prints “Hello”, and the value of iterator n is
incremented to 2. false
n<5
➢ The while loop statement will repeat testing the expression (n<5) true
again for the second time. In the second iteration n=2, the
expression (n < 5) is true. The text “Hello” is printed and n is Print Hello
incremented to 3.
➢ In the third iteration, the text “Hello” is printed and n is n++

incremented to 4. Again in the fourth iteration, the text “Hello” is


printed and n is incremented to 5.
➢ Finally in the fifth iteration n = 5, the expression (n < 5) is false Terminates the while statement
and the while loop statement terminates without print anything and goes to the next statement
more.
Program 39 : Loops in C++
5. int n = 1;
6. while (n < 5) {
7. cout << "Hello\n";
8. n++;
9. }
 While loop statement must include an iterator to repeat the while
block {} for a definite number of times. The three important operations
must be applied on the iterator in any loop statement to define the Iterator initialized

number of iterations:
1. In line 5, the iterator n is initialized by 1. false
Iterator
2. In line 6, the iterator n is tested against 5. tested
3. In line 7, the iterator n is changed by 1. true

statements(s)
 If the while loop did not use an iterator or misses one of these 3 steps,
the loop will never stop (terminates). In this case, the loop is said to be
Iterator changed
infinite loop.
 For example, If the iterator is not changed during iteration, the
condition will never be false and so theint n=0
while loop will never
terminates. Terminates the while statement
5. int n = 1; and goes to the next statement
6. while (n < 5) { n<5
7. cout << "Hello\n"; Infinite true
8. } loop statements(s) Never
terminates
Program 39 : Loops in C++
5. int n = 1;
6. while (n < 5) {
7. cout << "Hello\n";
8. n++;
9. }

 The value of the iterator must vary in each iteration, no matter it is Iterator initialized
incremented or decremented.
 The iterator change in the above program is incrementing the iterator
false
in line 8. The iterator is incremented by 1, however the iterator can be Iterator
tested
incremented by 1 or 2 or any number.
true
 The iterator change can be decrementing too. For example the
following code prints the same output as the above code: statements(s)

5. int n = 5;
6. while (n > 0) { Iterator changed
7. cout << "Hello\n";
8. n--;
9. }
Terminates the while statement
and goes to the next statement
Program 40 : Loops in C++

Start
1. //The program the infinite loops.
2. //The program have to terminated by user manually.
3. #include <iostream>
n=2147483630
4. using namespace std;
5. int main() {
6.
n>0 unexpected
7. //The follow loop iterates until the maximum value an
termination
8. //integer which is "2,147,483,647". true

9. int n = 2147483630;
Print n
10. while (n > 0) {
11. cout << "n : " << n << endl;
n++
12. n++;
13. }

14. //The following while loop is an infinite loop that


15. //never terminates. true infinite loop
16. while (true) cout << " Hello "; true

17. return 0;
18. }

end

Flowchart
Program 40 : Loops in C++
7. //The follow loop iterates until the maximum value an
8. //integer which is "2,147,483,647".
9. int n = 2147483630;
10. while (n > 0) {
11. cout << "n : " << n << endl;
12. n++;
13. }
n= 2147483630

 Line 9 initializes the value of the iterator n by 1. The expression in line


10 tests if n>0 is true. If the expression is true, the value of iterator n
is incremented by 1. n>0
unexpected
true
 This expression is always true since the value of n is already greater termination
than 0, and its value is incremented in each iteration. In this case the Print n
loop should iterates for ever, but it will ends when n reaches the
maximum value of an integer “2,147,483,647”.
n++
 This loop iterates 18 times then terminates, not because the
expression (n > 0) is false, but because the value of n can not be more
than the maximum value of an integer.
This loop terminates because
 This loop terminates unexpectedly by the computer because the the integer n can not hold a
boundaries of the variable size. value bigger than its size.
Program 40 : Loops in C++
14. //The following while loop is an infinite loop that
15. //never terminates.
16. while (true) cout << " Hello ";

 The loop in line 14 is an infinite loop because the expression in the while
statement is always “true”.
 This means that the program will printing the word “Hello” for ever.
Nothing will stop the program except by external action. The external infinite loop
action can be a manual termination by the user, where the user stops the
whole program. Or the electricity goes off, so whole program terminates.

true
 Does the infinite loop important? true

This loop will never


terminates because the
expression is always true.
Program 41 : Loops in C++

1. //This program counts the number of digits in an integer input


2. #include <iostream>
3. using namespace std;
4. int main() {
5. int n;
6. int digitCounter = 0;
7. cout << "Enter an integer number : "; cin >> n;

8. while (n > 0) {
9. n /= 10;
10. digitCounter++;
11. }

12. cout << "Number of digits is : " << digitCounter << endl;
13. return 0;
14. }
Program 41 : Loops in C++
8. while (n > 0) {
9. n /= 10;
10. digitCounter++;
11. }

 The iterator in this example is the variable n. The value of iterator is


set (initialized) by the user before the start of the while loop in line 8.
 The iterator is tested in line 8 if its value is greater than 0.
 Then the iterator is changed in line 9 at each iteration until its value is
not greater than zero.
 The change in the iterator here is not by incrementing or decrementing
its value. The iterator is changed by dividing its value by 10 at each
iteration.
 For example:
 If the user enters n = “879843” digitCounter=0
 At iteration 1, n= 879843/10=87984.3=87984 digitCounter=1
 At iteration 2, n= 87984/10=8798.4=8798 digitCounter=2
 At iteration 3, n= 8798/10=879.8=879 digitCounter=3
 At iteration 4, n= 879/10=87.9=87 digitCounter=4
 At iteration 5, n= 87/10=8.7=8 digitCounter=5
 At iteration 6, n= 8/10=0.8=0 digitCounter=6
Program 42 : Loops in C++

1. // This program writes a table, the first column contains the numbers from 1 to 7
2. // The second column contains the power of corresponding number to 2.
3. // The second column contains the power of corresponding number to 3. Start

4. #include <iostream> n=1


5. #include <cmath>
6. using namespace std;
7. int main() { false
8. cout << "n" << "\t" << "n^2" << "\t" << "n^3"<<"\n"; n<=7
9. cout << "--------------------\n"; true
10. int n = 1;
11. while (n <= 7) { print n, n2, n3
12. cout << n << "\t" << pow(n, 2);
13. cout << "\t" << pow(n, 3) << "\n"; n++
14. n++;
15. }
16. return 0;
17. } Print that’s all

End

Flowchart
Program 42 : Loops in C++
10. int n = 1;
11. while (n <= 7) {
12. cout << n << "\t" << pow(n, 2) << "\t" << pow(n, 3) << "\n";
13. n++; Start
14. }
n=1

 Line 10 initializes the value of the iterator n by 1.


 Line 11 starts a while loop statement by testing the expression (n <=
false
7). The value of the iterator n is 1, so the expression (n <= 7) is true. n<=7
And since the expression is true, the while block between { } runs by true
printing the power row and incrementing the n by 1.
print n, n2, n3
 The while loop iterates for 7 times, at each time the condition on the
iterator n is tested in the expression (n <= 7) and then the iterator n is
n++
incremented by 1.
 The while loop terminates when the value of n is greater than 7. In this
case the value of the expression (n <= 7) is false.
Print that’s all

End

Flowchart
Program 43 : Loops in C++
Start

1. //The program calculate the average value of set of values. Get num
2. //The user is asked first to enter the number of these values.
3. //Then the user is asked to enter these values, one by one. n=0
4. //Finally, the program will print the average value. avg=0

5. #include <iostream> false


n<num
6. using namespace std;
true
7. int main() {
8. int num; Get var
9. cout << "Enter number of values: "; cin >> num;
10. float var, avg = 0.0;
avg += var
11. int n = 0;
12. while (n < num) {
13. cout << "enter a value : " ; cin >> var; n++

14. avg += var;


15. n++;
16. }
Print avg
17. avg /= num;
18. cout << "The average value is " << avg << endl;
End
19. return 0;
20. }
Flowchart
Program 43 : Loops in C++
Start
11. int n = 0;
12. while (n < num) {
Get num
13. cout << "enter a value : " ; cin >> var;
14. avg += var; n=0
15. n++; avg=0
16. }
false
 Line 11 initializes the value of the iterator n by 0. n<num

 Line 12 starts a while loop statement by testing the expression (n < true

num). The value of num is retrieved from the user. Get var

 In the first iteration, the value of iterator n is 0 which is test against the avg += var

value of num. The while block is executed for a number of times


according to the user input of num. n++

 Notice here that the number of iterations is dependent on the


initialization of the iterator n and the used conditional operator. To
repeat the while block for num times: Print avg
 If n is initialized by 0, then the used conditional operator in the
expression (n < num) is “<”. End

 But if n is initialized by 1, then the used conditional operator in the


expression (n <= num) like “<=”.
Flowchart
Program 44 : Loops in C++
Start

1. //This program calculates the power of the two numbers x and y. Get x and y
2. //This program does not use the cmath library.
3. #include <iostream> t=x
n=y
4. using namespace std;
5. int main() {
6. int x, y; false
n>1
7. cout << "Please, enter the value of x and y : ";
8. cin >> x >> y; true

9. int t = x; t *= x

10.
11. int n = y; n--
12. while (n > 1) {
13. t *= x;
14. n--;
15. } Print xy=t
16. cout << x << " to power " << y << " is : " << t << endl;
End
17. return 0;

Flowchart
18. }
Program 45 : Loops in C++

1. //This program prints to the user the English alphabet in capital letters.
2. #include <iostream>
Start
3. using namespace std;
4. int main(){
letter=‘A’ (65)
5. char letter = 65;
6. cout << "The English alphabet is: " << endl;
i=0

7. int i = 0; false
8. while (i < 26){ i<26

9. cout << letter++ << " ,"; true


10. i++;
11. } Print letter

12. return 0; Letter++


13. } i++

End

Flowchart
Program 46 : Loops in C++

1. //This program gets from the user a string, then the program calculates the
2. //number of capital letters in this string.
3. #include <iostream>;
4. #include <string>;
5. using namespace std;
6. int main(){
7. string userData;
8. cout << "Enter a text: ";
9. getline(cin, userData);
10. int n = 0, count = 0;
11. char c;
12. while (n < userData.length()){
13. c = userData.at(n);
14. if ((c >= 'A') && (c <= 'Z'))
15. ++count;
16. n++;
17. }
18.
19. cout << "The number of uppercase characters is : " << count << endl;
20. return 0;
21. }
Program 47 : Loops in C++

1. //This program calculates the factorial of any number.


2. //This program uses the while loop
3. //Example: factorial(1) is 1 = 1,
4. // factorial(2) is 2*1 = 2,
5. // factorial(3) is 3*2*1 = 6,
6. // factorial(4) is 4*3*2*1 = 24, .....
7. #include <iostream>
8. #include <string>
9. using namespace std;
10. int main(){
11. int n;
12. int factorial = 1;
13. cout << "Please enter the number: "; cin >> n;
14. int i = n;
15. while (i > 0){
16. factorial *= i;
17. i--;
18. }
19. cout << "Factorial("<<n<<") = "<<factorial<<endl;
20. return 0;
21. }
Program 48 : Loops in C++

1. //This program gets from the user a number.


2. //Then the program prints the corresponding binary number.
3. #include <iostream>
4. #include <string>
5. using namespace std;
6. int main() {
7. int n;
8. cout << "Please enter a decimal number : "; cin >> n;
9. cout << "The corresponding binary number is : ";
10. string s = "";
11. while (n != 0) {
12. if (n % 2 == 0)
13. s = "0" + s;
14. else
15. s = "1" + s;
16. n = n / 2;
17. }
18. cout << s;
19. return 0;
20. }
Program 49 : Loops in C++

1. //This program keeps taking positive integers from the user,


2. //until the user enters a negative number .
3. //Then the program prints the maximum value of the entered integers.
4. #include <iostream>
5. using namespace std; Start
6. int main(){
max = 0;
7. int x, max = 0;
8. cout << "please enter positive values: \n"; Get x
9.
false
10. cin >> x; x>0
11. while (x > 0){ true
12. if (x>max) false
x > max
13. max = x; true
14. cin >> x; max = x
15. }
16. cout << "The maximum is : " << max; Get x
17.
18. return 0; Print max
19. }

End
Program 50 : Loops in C++

1. //This program keeps taking positive integers from the user,


2. //until the user enters a negative number .
3. //Then the program prints the maximum value of the entered integers.
4. #include <iostream>
5. using namespace std; Start
6. int main(){ max = 0;
7. int x, max = 0;
8. cout << "please enter positive values: \n";
Get x
9.
10. do { false
11. cin >> x; x > max
true
12. if (x>max)
13. max = x; max = x
14. } while (x > 0);
15. cout << "The maximum is : " << max; True
16. x > 0
False
17. return 0;
18. } Print max

End
Program 50 : Loops in C++
Statement(s)

10. do {
11. cin >> x; true
expression
12. if (x>max)
13. max = x; false
14. } while (x > 0);

 The do-while loop is a posttest loop, which means its expression is tested after
each iteration. The do-while loop is a posttest loop. This means it does not test
its expression until it has completed an iteration. As a result, the do-while loop
always performs at least one iteration, even if the expression is false to begin
with.
 The do-while loop looks something like an inverted while loop. The syntax of the
while loop
do
Statement(s)
while (Expression);
 The Statement(s) are either a single statement or a group of statements within
braces. The Statement(s) will be repeated until the condition is false.
 The Statement(s) is(are) executed once then the Expression is tested, if it is true
then the Statement(s) executed again Otherwise it will end the while statement.
Introduction to
Computing

Lecture 9
Looping statements: for statements

Dr. Mostafa Salama


Additional Resources for examples: https://www.w3resource.com/cpp-exercises/for-loop/index.php
Program 51 : Loops in C++

1. //This program calculates the factorial of any number.


2. //This program uses for loop
3. //Example: factorial(1) is 1 = 1,
4. // factorial(2) is 2*1 = 2,
5. // factorial(3) is 3*2*1 = 6,
6. // factorial(4) is 4*3*2*1 = 24, .....
7. #include <iostream>
8. using namespace std;
9. int main(){
10. int n;
11. int factorial = 1;
12. cout << "Please enter the number: "; Program 50 : Loops in C++
13. cin >> n;
14. for (int i = n ; i > 0 ; i--){ 14. int i = n;
15. factorial *= i; 15. while (i > 0){
16. } 16. factorial *= i;
17. cout << "Factorial(" << n <<") is : “; 17. i--;
18. cout << factorial << endl; 18. }
19. cin >> n;
20. return 0;
21. }
Program 51 : Loops in C++
14. for (int i = n ; i > 0 ; i--){
15. factorial *= i;
16. }

 The for loop is the most know looping statement because it is easier to use.
It include the three operations applied on the iterator in one part. These
steps are applied on the iterator in any loop statement to define the Iterator initialized
number of iterations.
 The iterator is initialized to a starting value.
 The iterator is tested by comparing it to another value. When the Iterator false

tested
comparing expression is false, the loop terminates.
true
 The iterator is changed during each iteration. This is usually done by
incrementing or decrementing the variable. statements(s)

 The for loop do the same action as the while loop.


Iterator changed

 Syntax of the while loop


for (initialization; test; update)
statement(s); Terminates the while statement
and goes to the next statement
Program 51 : Loops in C++
14. for (int i = n ; i > 0 ; i--){
15. factorial *= i;
16. }

 Syntax of the while loop


for (initialization; test; update)
statement(s); Iterator initialized

 The order of execution of for loop is as follows; Iterator false


1. Step 1: Perform the initialization expression, run once. tested
2. Step 2: Evaluate the test expression. If it is true, go to Step 3. true
Otherwise, terminate the loop.
statements(s)
3. Step 3: Execute the body of the loop, statements(s)
4. Step 4: Perform the change expression, then go back to Step 2.
Iterator changed
Iterator initialized

Iterator Iterator Iterator Iterator false


tested
Terminates the while statement
tested tested tested
true
and goes to the next statement
true true

statements(s) statements(s) statements(s)

Iterator changed Iterator changed Iterator changed


Program 51 : Loops in C++
14. for (int i = n ; i > 0 ; i--){
15. factorial *= i;
16. }

 The for loop can be written just like the while loop as follows: Program 50 : Loops in C++
14. int i = n ; 14. int i = n;
15. for ( ; i > 0 ;){ 15. while (i > 0){
16. factorial *= i; 16. factorial *= i;
17. i--;
17. i--;
18. }
18. }

 This loop has the same processing exactly as the above loop.
 The initialization part in the for() loop statement is empty, because the
iterator it is already initialized.
for ( ; i > 0 ;)
 The changing part in for() loop statement is empty, because the iterator is
changing in line 17.
for ( ; i > 0 ; )
 If the testing part is empty, then the for() loop statement becomes an
infinite loop.
Program 52 : Loops in C++

1. //This program gets two number from the user.


2. //Then the program that displays the “even numbers” between these two numbers.
3. //Beside each printed number, prints also “the square of this number”.
4. //For example, the user enters 3 and 10,
5. // the program prints 4-16, 6-36, … 10-100.
6. #include <iostream>
7. using namespace std;
8. int main(){
9. int a, b;
10. cout << "Enter two numbers: "; cin >> a >> b;
11. if (a < b)
12. for (int i = a; i <= b; i ++){
13. if (i%2 == 0)
14. cout << i << "-" << i*i << endl;
15. }
16. else
17. cout << "Error: check your input" << endl;
18.
19. return 0;
20. }
Program 53 : Loops in C++

1. //This program gets from the user a sentence s, and a letter c.


2. //Then the program prints out the number of the occurrence of
3. //the letter c in the sentence s.
4. #include <iostream>
5. #include <string>
6. using namespace std;
7. int main(){
8. char c;
9. string s;
10. int occurrence = 0;
11. cout << "please enter the sentence: " ;
12. getline(cin, s);
13. cout << "please enter the letter: " ;
14. cin >> c;
15. for (int i = 0; i < s.length(); i++){
16. if (s.at(i) == c)
17. occurrence++;
18. }
19. cout << "The letter '" << c;
20. cout << "' occurred: " << occurrence << " times." << endl;
21. return 0;
22. }
Program 54 : Loops in C++

1. //This program gets from the user a text.


2. //Then the program reverse the order of characters inside the text.
3. #include <iostream>
4. #include <string>
5. using namespace std;
6. int main() {

7. string text, reversedText;


8. cout << "Please enter the text to be reversed : ";
9. getline(cin, text);

10. for (int i = text.length()-1; i >= 0; i--){


11. reversedText += text.at(i);
12. }
13. cout << "The reversed text is : " << reversedText;

14. return 0;
15. }
Program 55 : Loops in C++

1. //This program gets from the user a text.


2. //Then the program inverse the case of every letter in the text.
3. //If it is a capital letter, then inverse it to small letter. And the reverse.
4. //Anything else will be kept as it is, then finally print the nre inversed text.
5. #include <iostream>
6. #include <string>
7. using namespace std;
8. int main() {
9. string text, inversedText;
10. cout << "Please enter the text to be inversed : "; getline(cin, text);

11. for (int i = 0; i < text.length(); i++){


12. if (text.at(i)>='A' && text.at(i) <= 'Z')
13. inversedText += (char)(text.at(i) + 32);
14. else if (text.at(i)>='a' && text.at(i) <= 'z')
15. inversedText += (char)(text.at(i) - 32);
16. else
17. inversedText += text.at(i);
18. }
19. cout << "The inversed text is : " << inversedText;
20. return 0;
21. }
Program 56 : Loops in C++

1. //This program gets from the user a single number.


2. //Then the program prints out whether this number is prime or not
3. #include <iostream>
4. using namespace std;
5. int main(){
6. int x;
7. bool prime;
8. cout << "Enter a numbers: "; cin >> x;

9. prime = true;
10. for (int i = 2; i < x; i++){
11. if (x%i == 0){
12. prime = false;
13. break;
14. }
15. }

16. cout << "The number is "<< (prime?"":"not ") << "prime.";
17. return 0;
18. }
Program 56 : Loops in C++
9. prime = true;
10. for (int i = 2; i < x; i++){
11. if (x%i == 0){
12. prime = false;
13. break; prime=true
14. }
15. } i=2

false
 Line 9 sets the value of the boolean variable as true. Initially an i<x
value of x entered by the user is considered as true until the reverse true
as proved. The reverse is that x is not prime, If x is divisible by any false
value below x and greater than one. x%i=0
true
 The for loop in line 10 will do the for{block} at i=2, and at i=3, ..
until i=(x-1). At each iteration where the expression (i < x) is true, prime=false
the for{block} checks if x is divisible by i.
break
 If this check (x%i == 0) is false, then for{block} increments
the value i and goes to the next iteration. i++

 If the check (x%i == 0) is true, then x is divisible by the value


i at this iteration. Then the boolean variable prime is set to
false. And the for{block} uses the break statement to terminate
the loop even if the condition i<x is still true. Terminates the for statement
and goes to the next statement
Print prime
Program 56 : Loops in C++
9. prime = true;
10. for (int i = 2; i < x; i++){
11. if (x%i == 0){
12. prime = false;
13. break; prime=true
14. }
15. } i=2

false
 The break; statement in line 13 interrupts the loop when the i<x
expression (x%i == 0) is true. It terminates the loop before it true

goes through all its iterations. false


x%i=0
 Notice in the flowchart, the break box has no output arrow. As true
the loop is ended by this break; statement.
prime=false
 For example, if the user enters x = 9,
 At the first iteration, i = 2 break
 The expression (x%i == 0) is false
i++
 The value of i is incremented
 At the second iteration, i = 3
 The expression (x%i == 0) is true
 prime is set to false
 break; terminates the loop Terminates the for statement
 Loop is terminated without going to iterations at i=4, i=5, .. and goes to the next statement
i=x-1, and the program goes to line 16 following the loop . Print prime
Program 57: Loops in C++ Start

1. //This program shows the use of nested loops: Weeks=3

2. //A nested loop is of Inner loop inside an Outer loop.


Days=7
3. //This program prints out the list of days by a list of 3 weeks.
4. #include <iostream>
5. using namespace std; i=1

6. int main() { i<=Weeks


false

7. int weeks = 3, days_in_week = 7;


true
Outer loop
Print ‘Week’+i
8. for (int i = 1; i <= weeks; ++i) {
9. cout << "Week: " << i << endl;

Outer loop
Inner loop j=1

10. for (int j = 1; j <= days_in_week; ++j) {

Inner loop
j<=Days false
11. cout << " Day:" << j << endl;
true
12. }
13. } Print ‘Day’+j

++j
14. return 0;
15. }
++i

End
Program 57: Loops in C++
Outer loop
8. for (int i = 1; i <= weeks; ++i) {
9. cout << "Week: " << i << endl;
Inner loop
10. for (int j = 1; j <= days_in_week; ++j) { Initialize i

11. cout << " Day:" << j << endl;


false
12. } test i
13. } true

 A loop can be nested inside of another loop. C++ allows at least Statement (i)
256 levels of nesting.

Outer loop
Initialize j
 The syntax for a nested for loop statement in C++ is as follows:
for (initialization (i); test (i); update (i)){ //outer loop

Inner loop
test j
statement(i); false

for (initialization (j); test (j); update (j)){ //inner loop true

statement(j); Statement (j)


}
} update j

 The steps :
 1. Line 8 initializes i by 1, then tests the value of i.
update i
 2. Line 9 prints week 1
 3. Line 10 initializes j by 1, then tests the value of j.
 4. Line 11 prints day 1
 5. Line 10 update j to 2, then tests the value of j.
 6. Line 11 prints day 2.
 …
Program 58 : Loops in C++
1. //This program uses a nested for loop to find the prime numbers from 2 to 100
2. #include <iostream>
3. using namespace std;

4. int main() {
5. int i, j;

6. for (i = 2; i<100; i++) {


7. for (j = 2; j < i; j++){
8. if (!(i%j)){
9. break; // Terminates the inner loop only
10. }
11. }
12. if (j==i)
13. cout << i << " is prime\n";
14. }

15. return 0;
16. }
Program 58 : Loops in C++
6. for (i = 2; i<100; i++) {
7. for (j = 2; j < i; j++){
8. if (!(i%j)){
9. break; // Terminates the inner loop only
10. }
11. }
12. if (j==i)
13. cout << i << " is prime\n";
14. }
 Line 6 sets the value i to be tested if it prime or not.
 The inner for loop from line 7 to line 10 tests if i is not divisible by any number smaller
than it. The range of numbers that tested against i is {from 2 to i-1}.
 If i is divisible by j which is a number smaller than i and greater than 2, then the value
of (i%j) is equal to zero. The value of zero is corresponding to false in C++.
 The expression (!(i%j)) in if condition in line 8 has two cases:
 The variable i is divisible by j, then i%j is equal to zero, then the expression (i%j)=false, then the
expression (!(i%j))=true. Then according to the if condition in line 8, the break statement in
line 9 interrupts (terminates) the inner for loop in line 7.
 The variable i is not divisible by j, then i%j is not equal to zero, then expression (i%j)=true, then
the expression (!(i%j))=false. Then according to the if condition in line 8, the inner loop
continues its work.
 If the inner loop continues until the end of the loop without any break, then iterator j
has condition (j < i) is false which means that (j == i). This means that no number j is
found such that (i%j)=0, which means that i is a prime number.
Program 59 : Loops in C++
1. //This program gets from the user a number.
2. //Then the program prints a pyramid with an asterisk.
3. //The number of rows in the pyramid is number entered by the user.
4. #include <iostream>
5. #include <string>
6. using namespace std;
7. int main(){
8. int rows;
9. cout << "Display a pyramid with an asterisk:\n";
10. cout << "Input number of rows with pyramid : ";cin >> rows;

11. int spc = rows + 4 - 1;


12. for (int i = 1; i <= rows; i++){ //outloop
13. for (int k = 1; k <= spc; k++) //inner loop 1
14. cout << " ";

15. for (int j = 1; j <= i; j++) //inner loop 2


16. cout << "*" << " ";
17.
18. cout << endl;
19. spc--;
20. }
21. return 0;
22. }
Sample MCQ for Programming
So far :
1. What is the output of the following Program? 2. What is the output of the following Program?
1. #include <iostream> 1. #include<iostream>
2. using namespace std;
2. using namespace std;
3. int main() {
4. for (int i = 0; i < 4; i++){ 3. int main(){
5. for (int j = i; j > 0; j--) 4. int x = -1;
6. for (int k = j; k < i; k++) 5. for (int i = 3; i > 0; i--)
7. cout << i*j*k << ","; 6. for (int j = 0; j < i; j++)
8. } 7. x += (i + j);
9. return 0;
8. cout << x;
10. }
9. return 0;
a) 0,1,2,3,
10. }
b) 0,1,4,9
c) 0,1,8,21
a) 16
d) 1,1,8,16
b) 17
e) 2,12,3,6
c) 18
d) 19
e) Error
Sample MCQ for Programming
So far :
3. What is the output of the following Program? 4. What is the output of the following Program?
1. #include<iostream>
2. using namespace std; 1. #include<iostream>
3. int main(){ 2. using namespace std;
4. int x = 1, y = 7, z = 2022, k = 0; 3. int main(){
5. cout << (24 % 2 == 0); 4. int x = 1;
6. do{ 5. while (x < 3){
7. if (z%x == 0) 6. x++;
8. k += (y%x);
7. if (x % 2)
9. x++;
10. } while (x < 4); 8. x--;
11. cout << k; 9. }
12. return 0; 10. cout << x;
13. } 11. return 0;
12. }

a) 6
a) 1
b) 10
c) 12
b) 3
d) 22 c) 2
e) 0 d) 4
e) “Nothing is printed”
Sample MCQ for Programming
So far :
5. What is the output of the following Program? 6. What is the output of the following Program?
1. #include<iostream> 1. #include<iostream>
2. using namespace std;
1. #include<string>
3. int main(){
4. int x = 1, y = 7, z = 2022; 2. using namespace std;
5. while (x < 3){ 3. int main(){
6. x++; 4. string name = "Advanced Data Base";
7. --y; 5. for (int i = name.find('e'); i > 0; i--)
8. z = x++ + y--; 6. cout << name.at(i);
9. }
return 0;
10. cout << z;
11. return 0; 7. }
12. }

a) D decnavd
a) 6 b) ecnavd
b) 8
c) cnavd
c) 10
d) dvanced
d) 2030
e) 2028
e) dvance
Sample MCQ for Programming
So far :
7. What is the output of the following Program? 8. What is the output of the following Program?
1. #include <iostream> 1. #include <iostream>
2. using namespace std; 2. using namespace std;
3. int main() { 3. int main() {
4. int f = 1, i = 2; 4. int c = 10;
5. while (++i < 6) 5. while (c != 0)
6. f *= ++i; 6. if ((c-- % 3) == 0)
7. cout << f; 7. cout << "c = " << c << "; ";
8. return 0; 8. return 0;
9. } 9. }

a) 12
b) 24 a) c = 8; c = 5;
c) 6 b) c = 8; c = 5; c = 2;
d) 4 c) c = 9; c = 6; c = 3; c = 0;
e) 3 d) c = 8; c = 7; c = 5; c = 4; c = 2; c = 1;
e) c = 9; c = 7; c = 6; c = 4; c = 3; c = 1; c = 0;
Sample MCQ for Programming
So far :
9. What is the output of the following Program? 10. What is the output of the following Program?
1. #include<iostream> 1. #include <iostream>
2. using namespace std; 2. #include <string>
3. int main(){ 3. using namespace std;
4. char a = 'c'; 4. int main(){
5. int k = 'k'; 5. string birthDate = "04/09/2017";
6. int c = 0; 6. int x = 0;
7. while (k != a){ 7. do {
8. a++; 8. string temp = birthDate.substr(0,
9. --k; 9. birthDate.find('/'));
10. c++; 10. x += stoi(temp);
11. } 11. birthDate=birthDate.substr(birthDate.find('/')+1,
12. cout << c; 12. birthDate.size() - birthDate.find('/')-1);
13. return 0; 13. } while (birthDate.find('/') != -1);
14. } 14. x += stoi(birthDate);
15. cout<<x;
16. return 0;
a) 3 17. }
b) 4 a) 4
c) 5 b) 13
d) 6 c) 2030
e) Error d) 4047
e) Error
Introduction to
Computing

End of Programming,
part 1

Dr. Mostafa Salama

You might also like