Lecture Notes Introduction To Computing 2025-2026
Lecture Notes Introduction To Computing 2025-2026
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???
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
Lecture 2
Writing a Program in C++
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.
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(){ … }
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
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
Int x = 5;
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
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
5. cout << "The size the integer variable is = " << sizeof(int) <<endl; x:int
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++
8. int z = x + y;
9. double g = x + y;
6. int x = 4, z = 3;
7. double y = 5.5;
8. double result = x + y * z; //Precedence
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
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
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;
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
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.
Lecture 4
Characters and strings in C++
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
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;
14. return 0;
15. }
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;
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
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
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
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;
6. string n1;
7. n1 = "Morad Samir Aly";
8. cout << "The name of student 1 is : " << n1 << endl;
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
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
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]
3. #include <string>;
9. int fn_length = e_mail.find('_');
3. #include <string>;
9. int fn_length = e_mail.find('_');
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
• String
• find()
• Substr()
Introduction to
Computing
Lecture 5
More about string and math libraries
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);
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
startPosition=0 midPosition=7
George Washington
username.find(' ')=6
Program 21 : strings
George Washington
Program 21 : strings
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
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
george washington
Program 22 : strings
17. cout << "Full Name initials : " << firstCharacter << secondCharacter << endl;
18. cout << "ASCII : " << (int)firstCharacter << "#" << (int)secondCharacter;
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]"
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]
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
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;
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
8. boolValue = false;
9. cout << "boolValue(false) = " << 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
15. cout << "size of the boolValue is " << sizeof(boolValue) << endl;
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++
9. boolValue = x < y || y == z;
10. cout << "The expression (x < y || y == z) is = " << boolValue << endl;
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;
False
Program 29 : Conditions in C++
8. if (SM >= 50)
9. cout<<"The student passed the module";
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
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
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
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
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
16. if (!printed)
17. cout << "can not calculate the value of z";
Scenario 2: x<0 and y!=0
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
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++
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.
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";
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
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";
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 3
Scenario 4
168
Program 35 : Conditions in C++
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
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
For example:
2012, 2004, 1968 etc are leap year but, 1971, 2006 •year%4==0
etc are not leap year. •year%100!=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
false
m>=50
true
Flowchart
7. cout << "Enter the student mark = ";
8. cin >> m;
9.
10. if (m>=50)
11. s = 's';
12. else
13. s = 'f';
174
Start
false
m>=50
true
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
false
m>=50
true
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
false
m>=50
(a) 10. if (m>=50) s = 's'; else s = 'f'; // If Conditions true
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
false
m>=50
(a) 10. if (m>=50) s = 's'; else s = 'f'; // If Conditions true
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
false
m>=50
(a) 10. if (m>=50) s = 's'; else s = 'f'; // If Conditions true
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
Start
1. //this program demonstrates the if conditional statement
2. #include <iostream> n=1
5. int n = 0; true
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
5. int n = 1; true
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. }
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
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
true
n=1
Print Hello
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++
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. }
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
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
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. }
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
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
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
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
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
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++
End
Program 50 : Loops in C++
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
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 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++
14. return 0;
15. }
Program 55 : Loops in C++
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++
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
Outer loop
Inner loop j=1
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
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
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;
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;
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