You are on page 1of 62

Introduction to Computers Lab First Year 2019– 2020

1
Problem 1
• Design an algorithm for computing factorial N (N!)
Where N! = 1*2*3*....N.

2
START

Problem 1: Solution Input num

BEGIN result=1
i=1
Input num
result = 1 True False
FOR (i=1, i<=num, i+1) i<=num

result = result * i
True
ENDFOR
result = result * i
Print result
END
Increment i

Print result

Stop
3
Problem 2
• Design an algorithm to find the sum of the first 50
natural numbers.

4
Problem 2: Solution
Start

BEGIN
Set Sum = 0, N = 0 Sum=0
N=0
DO
N=N+1 N=N+1
Sum = Sum + N
Sum=Sum+N
WHILE N < 50
ENDWHILE N
Yes

Print Sum <50


NO
END
Print Sum

END 5
Problem 3
• Design an algorithm for program that reads N
numbers. It displays the sum of even numbers only.

6
Problem 3: START

Solution Input N

BEGIN
Sum=0, Count=0
Input N
Sum = 0
FOR (Count = 0, Count < N, Count+1) Count<N False

Input Num True


IF Num%2 = 0 THEN
Input Num
Sum = Sum + Num
ENDIF False
ENDFOR Count+1 Num%2=0

Print Sum True

END Sum=Sum+Num

Print Sum

7
Stop
Problem 4
• Design an algorithm that prompts the user to enter
two positive integers and finds their greatest common
divisor.

• The greatest common divisor of integers 16 and 24 is


8. So , how do you find the greatest common divisor
?

• Let the two input integers be n1 and n2. Number 1 is a


common divisor, but it may not be the greatest
commons divisor.

• So, you can check whether k (for k = 2, 3, 4, and so


on) is a common divisor for n1 and n2, until k is greater
than n1 or n2.
8
START

Problem 4: Solution
Input N1,N2

BEGIN
Input N1, N2 gcd =1 , K =2

Set gcd = 1, K = 2
WHILE K<=N1 AND K<=N2 K<=N1
AND
False

IF N1%K=0 AND N2%K=0 THEN K<=N2

gcd= K True

ENDIF K=K+1
False N1%K=0
AND
K=K+1 N2%K=0

ENDWHILE True

Print gcd gcd=K

END
Print gcd

Stop 9
Problem 5
• Design an algorithm to read grades of 10 students
and display the top student.

10
Problem 5 : Solution START

Input x
BEGIN
Input x
Set max=x ,
Set max=x , counter = 1, n =10 counter = 1, n =10

WHILE counter<n false


Print max
Input x counter<n

True
counter = counter+1
IF x>max THEN Input x Stop
max = x
ENDIF counter=counter+1

ENDWHILE
false
Print max x>max
END True
max = x
11
Problem 6
• Algorithm for the electricity company, which
charges customers according to their usage rank
(1,2 or 3) and reading (watt).
In rank 1, customers pay 1 L.E./100 watt with
minimum 10 L.E.
In rank 2, customers pay 2 L.E./100 watt, but pay at
maximum 400 L.E.
In rank 3, customers pay 2.5 L.E./100 watt.
Program reads the usage rank and reading and
displays the charged amount.

12
Problem 6 : Solution
• Using case structure, with embedded IF statements
START

Input

rank, watt

Case of
rank
=1 =2 =3 Otherwise
charged = charged = charged = Print
watt/100 2*(watt/100) 2.5*(watt/100) “Invalid Rank”

False False True


charged charged charged =
<10 >400 400
True

charged =
10 Print
charged
13

END
BEGIN
Input rank, watt Problem 6: Pseudocode
CASE OF rank
=1:
charged = watt/100
IF charged <10 THEN
charged = 10
ENDIF
=2:
charged = 2*(watt/100)
IF charged > 400 THEN
charged = 400
ENDIF
=3:
charged = 2.5*(watt/100)
OTHERWISE
Print “Invalid Rank”
END-OF-CASE 14
END
Problem 7
• Design an algorithm for the bank withdrawal process.
First the program reads the customer balance and
withdrawal amount. The transaction is successfully
completed in case the balance covers the required
amount. If not, display message insufficient funds.
Finally, display the customer balance.
Problem 7: Solution
START
BEGIN Read balance,
Read balance, withdrawal withdrawal
IF Withdrawal <= balance THEN
balance = balance – withdrawal F Withdrawal T
<=
Print “Transaction Complete” balance?
ELSE Print
balance = balance
“Insufficient
Print “Insufficient Funds” Funds”
- withdrawal

ENDIF Print
“Transaction
Print balance Complete”
END
Print
balance
16
STOP
Problem 8
• Design an algorithm which represents a program
that calculates the absolute difference between
two numbers.

• Which statement is executed if the user enters


equal numbers?

17
Problem 8: Flowchart
START

Read x, y

F T
x<y

diff= x - y diff= y - x

Print diff
 If the user enters equal
numbers, the ELSE statement STOP

is executed.
18
Problem 8: Pseudocode
BEGIN
Read x, y
IF x<y THEN
diff= y - x
ELSE
diff= x - y
ENDIF
Print diff
END

19
Problem9
• Design an algorithm which represents a program that displays
the bonus for employees according to the number of years
worked. The bonus is calculated as a percentage of the
current salary as shown in table. The output should be in the
following form:

• Enter salary and number of years:2000 2

• The bonus is : 500


Number of Years Bonus
1 15%
2 25%
3 35%
Others 50%

20
Problem 9: Flowchart
START

Input Salary,

Year

Case of
Year
=1 =3 Otherwise
=2
Bonus= Bonus= Bonus= Bonus=
Salary*0.15 Salary*0.25 Salary*0.35 Salary*0.5

Print
Bonus
21

21
END
Problem 9: Pseudocode
BEGIN
Input Salary, Year
CASE OF Year
=1:
Bonus=Salary*0.15
=2:
Bonus=Salary*0.25
=3:
Bonus=Salary*0.35
OTHERWISE
Bonus=Salary*0.5
END-OF-CASE
Print Bonus
END

22
Problem 10
• Design an algorithm which represents a program that reads the
number of working years and displays the celebrated company
anniversary as shown in table. The program should also display
the raise amount for its employees, which is calculated as 10%
of the number of years the company has been in business. The
output should be in the following form:
o Enter number of years: 25
o Silver
o The raise is : 2.5
Number of Years Anniversary
10 Bronze
25 Silver
50 Golden
Others Unknown
Problem 10: Flowchart
START

Input

Year

Case of
Year

=10 =25 =50 Otherwise


Print Print Print
Print
“Bronze: “Silver: “Unknown”
“Golden:
The raise is 1.0” The raise is 2.5” The raise is 5.0”

END
24
Problem 10: Pseudocode
BEGIN
Input Year
CASE OF Year
=10:
Print “Bronze: The raise is 1.0”
=25:
Print “Silver: The raise is 2.5”
=50:
Print “Golden: The raise is 5.0”
OTHERWISE
Print “Unknown”
END-OF-CASE
END

25
Problem 11
• Design an algorithm which represents a program
that calculates the net salary of an employee
based on his job: ‘M’ for manager and ‘E’ for
employee.
• The salary of the manager=Salary + bonus
• The salary of the employee=salary - tax

• Which statement is executed if the user enters ‘A’


?

26
Problem 11: Flowchart
START

Read job

F T
Job =
‘M’
net = salary net = salary
- tax + bonus

Print net
 If the user enters ‘A’, the ELSE
STOP
statement is executed.
27
Problem 11: Pseudocode
BEGIN
Read job
IF job= ‘M’ THEN
net = salary + bonus
ELSE
net = salary - tax
ENDIF
Print net
END

28
Problem 12
• Design an algorithm for a program that simulates
the doctor diagnosis. It reads a child temperature
and displays what a doctor would recommend in
such case.
• Doctors assume the child is healthy when his
temperature is below or exactly 37ºC. Therefore,
they recommend normal activities.
• However, if the temperature is little higher than 37
ºC but still below 39 ºC, then the doctor
recommends careful observation.
• Otherwise, the doctors recommend that the child
should be admitted to hospital.

29
Problem 12: Solution
START

Read temp

F T
temp <=
37
Print “Normal
F
temp < Activities”
39
T
Print “Admitted Print “Careful
to Hospital” Observation”

STOP 30
Problem 12: Pseudocode
BEGIN
Read temp
IF temp<=37 THEN
Print “Normal Activities”
ELSE
IF temp < 39 THEN
Print “Careful Observation
ELSE
Print “Admitted to Hospital”
ENDIF
ENDIF
END

31
Problem 13
• Design an algorithm for a program that counts
down starting from 20 and when finished it displays
“Celebrate”.

32
Problem 13: Solution
Start

BEGIN
Set count = 20 Count =20

DO
Print count Print Count
count = count-1
WHILE count <> 0 Count=Count-1

ENDWHILE NO
Count
Print ”Celebrate” !=0
END Yes
Print
”Celebrate”

33
END
Problem 14
• Design an algorithm for program that reads N
numbers. It displays their product.

34
Problem 14: Solution START

Input N

Prod=1
BEGIN Count=0
Input N
prod = 1 Count<N
False

FOR (count = 0, count < N, count+1) True


Input Num Input Num
prod = prod * Num True
ENDFOR Prod=Prod*Num
Print prod Count=Count+1
END

Print prod

Stop
35
Microsoft Visual Studio
.Net

36
What is Visual Studio?
• Visual Studio is a complete set of development tools
for building ASP.NET Web applications, XML Web
Services, desktop applications, and mobile
applications.
• Visual Studio has different programming languages
i.e. Visual Basic, Visual C++, Visual C#, and Visual
J#.

37
Microsoft Visual Studio .Net 2013
• This is the IDE (Integrated Development Environment),
where we will edit and compile C++ programs.

38
Getting started with
Visual Studio
• When you start writing code in Visual Studio, you begin
with a project. A project contains all of the information
and files required to create and run a program.

• Visual Studio organizes projects into solutions. A solution


is a collection of projects that are associated with each
other.

• If you’re just getting started, a solution will probably only


contain one project.

• The output of a project is usually an executable program


(.exe), a dynamic-link library (.dll) file or a module

39
Program components
• Header Files : (file.h) contain constant, variable,
and function declarations needed by a program.

• Source Files : (file.cpp) consists of the program


statements comprising a C++ or other programming
language program.
Programming Using C++

41
1- Create a new project
- File -> New -> Project.
- choose “Visual C++” and “Win32 Console Application”.
- Select Location and specify a project name.

42
- Click Next,

- Select Empty Project option and


Click Finish.

43
Solution Explorer
- Solution Explorer:
The tree where all files in the project are listed
** if you didn’t find it when you open the VS go to: view\solution
explorer

44
2- Create Source File
- Right click on Source files -> Add -> New Item.
- Create a new source file (.cpp)

45
- Select “Code” from left tree and then select “C++ file (.cpp)” from right list,
- Specify a name and location for the file, normally its location is in the same folder
of the project.

46
3- Edit program

47
4- Build/Compile Project
Build/Compile project to produce (.0bj file)
Check for errors

48
Compiling / Building
(.cpp file)
source code
compiler
(.h files)
(.obj file)
object code
(machine Language Code) linked to
libraries
object code from
other source files executable file
(.exe file)
49
Build versus Compile
• Build (F6) means compile and link only the
source files that have changed since the last
build, while Rebuild means compile and link all
source files regardless of whether they
changed or not. Build is the normal thing to do
and is faster.

• Compile just compiles the source file currently


being edited. Useful to quickly check for errors
when the rest of your source files are in an
incomplete state that would prevent a
successful build of the entire project. Ctrl-F7 is
the shortcut key for Compile.
50
5- Run the program
Console
Application

51
Error, error… does not compute!
Syntax refers to the structure of a

• Syntax Errors (Typing Errors)


program and the rules about
that structure
o Errors in programming language rules.
o You can use the compiler or interpreter to uncover syntax
errors.
o You must have a good working knowledge of error messages
to discover the cause of the error.

• Logic or Meaning Errors


o Errors that indicate the logic used when coding the program
failed to solve the problem.
o You do not get error messages with logic errors.
o Your only clue to the existence of logic errors is the
production of wrong solutions.

• Run-time Errors (Exceptions)


o Code does something illegal when it is run (hence runtime)
52
• E.g., divide by zero
Program 1
• Create a program that displays Hello World.

#include <iostream>
using namespace std;
int main()
{
// This is my first C++ program
cout << "Hello World" << endl;
return 0;
}

53
What does the code mean?
N.B.: C++ is case sensitive.

• //Hello World Program.


o Comments are parts of the source code disregarded by the compiler.
o It can be a description for the program or a given snippet of code -
internal documentation for the code.
o For single line comment  //…………
o For multiple line comments  /* ……………
………… */
• #include <iostream>
o Lines beginning with a hash sign (#) are called pre-processor directives .
o They are not regular code lines with expressions but indications for the
compiler's preprocessor.
o The directive #include <iostream> tells the preprocessor to include the
iostream standard file.
o This specific file (iostream) includes the declarations of the basic standard
input-output library in C++, and it is included because its functionality is
going to be used later in the program.
54
What does the code mean?
• using namespace std;
o All the elements of the standard C++ library are declared
within what is called a namespace.
o Namespaces allows us to group a set of global classes,
objects and/or functions under a name.
o Namespace std contains all the classes, objects and
functions of the standard C++ library.
If you specify using namespace std
then you don't have to
put std:: throughout your code.

55
What does the code mean?
• int main()
o Remember, every C++ program is made of one or more
functions.
• A function is a piece of code that accomplishes one specific
task.

o Every executable C++ program has one function called main()


• This is where execution (the actual running) of the program
starts.

o main( ) function is the heart of the program and also called


program building block.

o When you run the program you are essentially telling the
computer to call this main() function
• Calling a function means to execute the code in 56the
function.
• int main()
o The int is the return type of the function.
• In other words when it finishes what kind of result does it
give back. A whole number? A character?

o int means a whole number.

o We want to give this number back to tell us if the program


was successfully completed

• int main()
o The brackets is the parameter list for this function.

o The parameter list indicates what this function needs to be


given from the outset for it to work.

57
o we give nothing to this function, we can also write:
int main (void)
What does the code mean?
• cout << “Hello World” << endl;

o This line tells the computer to print something to the screen.


o If you want to print something to the screen, use the cout function.
o The endl adds an “end line” and flushes the buffer.
o cout is the name of the standard output stream in C++, and the
meaning of the entire statement is to insert a sequence of
characters (in this case the Hello World sequence of characters)
into the standard output stream (cout, which usually corresponds to
the screen).
o cout is declared in the iostream standard file within the std
namespace, so that's why we needed to include that specific file
and to declare that we were going to use this specific namespace
earlier in our code.
o cout is used in conjunction with the insertion operator, which is
written as <<

o The << operator inserts the data that follows it into the stream. 58
What does the code mean?
• return 0;
o This is the last line in our program.
o It basically means that the program is now done.
o return means to go back to where the program was
called from.
• 0 is used to indicate that it was successfully
completed (a general convention)

Another method:
• write: void main( )  in this case, the function will
return void, means it returns nothing and so, we do
not need return statement.

59
What does the code mean?
• Note also that the code of main() is contained within
the { }

• These {} group code together.

• In this case it tells us that all the code between them are
part of the main function:
#include <iostream>
using namespace std;
int main(){
cout << “Hello World” << endl;
return 0;
}

 Also note that every command is terminated by a semi


colon ; 60
Program 2
• Create a program that displays information about
the student (ID, name and age), each displayed on
a separate line.

#include <iostream>
using namespace std;
int main()
{
cout << "ID: 23" << endl;
cout << "My name is Aly" << endl;
cout << "I am 19 years old" << endl;
return 0;
}
61
Thank You

62

You might also like