0% found this document useful (0 votes)
11 views98 pages

Fundamentals of Programming I - Week 01&02

Uploaded by

mengesh85
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)
11 views98 pages

Fundamentals of Programming I - Week 01&02

Uploaded by

mengesh85
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

Fundamentals of

Programming I
Week 1 & 2
Fundamentals of Programming Language
Problem Solving and Algorithms

ITU Cyber Security Vocational School – Instructor Anıl Suat Terliksiz


COMPUTER

 A computer is an electronic device designed to process, store, and manage


data.
 It performs calculations and executes instructions to accomplish a wide range
of tasks at a great speed with a high degree of accuracy.
COMPUTER SYSTEM

 A computer system consists of several key components:


 Central Processing Unit (CPU): Often referred to as the "brain" of the
computer, the CPU carries out instructions from programs and performs basic
arithmetic, logical, control, and input/output operations.
 Memory: This includes both volatile memory (like RAM, which stores data
temporarily while the computer is running) and non-volatile memory (like
hard drives or SSDs, which store data long-term).
 Motherboard: The main circuit board that houses the CPU, memory, and
other essential components, and allows them to communicate with each
other.
 Input Devices: Devices like keyboards, mice, and scanners that allow users to
input data into the computer.
 Output Devices: Devices like monitors and printers that display or produce
the results of the computer's processing.
 Storage: Hard drives, solid-state drives, or other storage media where data is
kept for long-term use.
 Power Supply: Provides electrical power to all the components of the
computer.
 Software: Programs and operating systems that instruct the hardware on
what tasks to perform and how to execute them.
COMPUTER PROGRAM

 A computer program is a set of instructions written in a programming


language that tells a computer how to perform specific tasks or operations.
 These instructions guide the computer's hardware to execute functions and
processes to achieve a desired outcome.
SOFTWARE

Software is a broader term that encompasses


all types of computer programs, as well as
associated data, documentation, and
configuration files. It includes not just the
executable code but also the accompanying
resources needed for the program to operate
effectively.
BIT and BYTE

 A bit, short for “BInary digiT," is the smallest unit of data in computing and digital
communications.
 It can represent one of two values: 0 or 1.
 Bits are the building blocks for all types of data in a computer.
 Information Storage: Bits are used to store data in memory, such as text, images,
and other media. The arrangement of bits determines the information stored.
 Digital Communication: In digital communication, bits are transmitted over
various media (e.g., cables, radio waves) and are used to encode and decode
information.
 A byte is a unit of digital information that consists of 8 bits. It is a fundamental
building block in computer systems and is used to represent a wide range of data
types.
UNITS OF DIGITAL INFORMATION

 Kbyte (Kilobyte): 1,024 bytes = 210 bytes.


 MByte (Megabyte): 1,024 kilobytes = 220 bytes (approximately 1 million bytes).
 GByte (Gigabyte): 1,024 megabytes = 230 bytes (approximately 1 billion bytes).
 TByte (Terabyte): 1,024 gigabytes = 240 bytes (approximately 1 trillion bytes).
BINARY NUMBERS

 We have learned and use the decimal numbering system simply because
humans are born with ten fingers!
 But with digital systems, we need a 2-value system (binary). We could
attribute this to the fact that computers only have open or closed switches
(or one finger, if you prefer).
 This means, we have to learn the binary system in addition to the decimal
system. We also will discuss the octal and hexadecimal systems because
conversion to/from binary is easy and numbers in these systems are easier to
read than binary numbers for humans.
BINARY NUMBERS

 Digital and computer technology is based on the binary number system, since
the foundation is based on a transistor, which only has two states: on or off.
 Each digit of the number is called a bit or which is a short for binary digits.
 An 8-bit group is referred to as a Byte.
 An 4-bit group is referred to as a nibble.
 Each bit is weighted based on its position in the sequence (powers of 2) from
the Least Significant Bit (LSB) to the Most Significant Bit (MSB).
 Each bit must be less than 2 which means it has to be either 0 or 1.
BINARY NUMBERS
BINARY NUMBERS
BINARY NUMBERS
OCTAL AND HEXADECIMAL NUMBERS

 Octal (base 8) and hexadecimal (base 16) are numeral systems used to
represent numbers, with octal using digits 0-7 and hexadecimal using digits 0-
9 and letters A-F.
 These number systems are used by humans as a representation of long strings
of bits since they are:
 Easier to read and write, for example (347)8 is easier to read and write than
(011100111) 2.
 Easy to convert (Groups of 3 or 4)
 Today, the most common way is to use Hex to write the binary equivalent;
two hexadecimal digits make a Byte (groups of 8-bit), which are basic blocks
of data in Computers.
OCTAL AND HEXADECIMAL NUMBERS
HEXADECIMAL NUMBERS
BINARY CODE

 Binary codes are used to translate human symbols to one and zeros.
 The most important of the symbols is the alphabet used for human
communications. So every key and character has to have a unique binary
code.
 The minimum number of bits required to uniquely identify all the keys on the
keyboard must meet the following condition:
2Number of Bits ≥ Number of keys
BINARY CODE
 ASCII code is used to represent alphanumeric and control characters with 8 bits. The ASCII code table is
shown below:
MACHINE LANGUAGE

 Machine language, also known as machine code, is the lowest level of


programming language that a computer's CPU (Central Processing Unit) can
directly understand and execute.
 It consists of binary code, which is a sequence of 0s and 1s, that corresponds
to the fundamental instructions of the CPU.
PROGRAMMING LANGUAGES

 Programming language is a vocabulary and set of grammatical rules for


instructing a computer or computing device to perform specific tasks.
 In other word it is set of instructions for the computer to solve the problem.
 Programming languages can be classified in various ways based on their
characteristics, level of abstraction, and usage.
 They can be classified as low-level languages, mid-level and high-level
languages according to their level of abstraction (i.e. by how closely they
align with human perception and understanding).
PROGRAMMING LANGUAGES
 Low-Level Languages: These languages are closer to machine code and offer minimal
abstraction from hardware. They include:
 Machine Language: The binary code (0s and 1s) directly understood by a computer's CPU.
 Assembly Language: A human-readable representation of machine code using mnemonics and
symbols. It is still closely tied to the hardware and often requires detailed knowledge of the
CPU’s architecture.
 Mid-Level Languages: Mid-level languages strike a balance between low-level control and
high-level abstractions. They provide some abstraction from the hardware while still allowing
detailed control over system resources. (C, C++)
 High-Level Languages: These languages provide a greater level of abstraction from
hardware, making them easier for humans to read and write. They include:
 Procedural Languages: Focus on procedures or routines (e.g., Pascal).
 Object-Oriented Languages: Emphasize objects and classes (e.g., Java).
 Functional Languages: Focus on mathematical functions and immutability (e.g., Haskell, Lisp).
 Scripting Languages: Often used for automating tasks and can be interpreted rather than
compiled (e.g., Python, JavaScript).
PROGRAMMING LANGUAGES
SOURCE CODE AND OBJECT CODE

 Source code refers to the human-readable instructions written in a


programming language. It is the raw code that programmers write to create
software applications, and it is designed to be understandable by humans.
 Object code is the output of the compilation process, which is a lower-level,
machine-readable code that the computer can execute. It is typically
generated by a compiler or assembler from the source code.
TRANSLATORS

 Translator is a broad category that encompasses any tool or program that


translates code written in one form into another form.
 In the context of programming languages, translators specifically convert
source code into machine-readable code or an intermediate form.
 The two main types of translators are:
 Compiler
 Interpreter
COMPILER
 A compiler is a specialized software tool that translates source code written in a high-level
programming language into machine code or an intermediate code. The output of a compiler is
typically an executable file that a computer can run directly.
 Key Functions:
 Translation: Converts the entire source code into machine code (binary) or intermediate code (such as
bytecode) all at once.
 Error Checking: Analyzes the source code for syntax and semantic errors before generating the
executable. Errors are reported during the compilation process.
 Optimization: Applies various optimization techniques to improve the performance and efficiency of the
generated code, such as reducing execution time and memory usage.
 Code Generation: Produces machine code or intermediate code that the computer’s processor can
execute. This code is typically stored in an executable file.
LINKING

 Linking is the process of taking one or more object files produced by a


compiler and combining them into a single executable file or library. It
resolves references to external symbols and ensures that all parts of the
program are properly connected.
INTERPRETER
 An interpreter translates and executes source code in real-time, allowing for immediate execution of
commands and interactive programming.
 Key Characteristics:
 Line-by-Line Execution:
 Process: Reads and executes the source code one line or statement at a time, translating it into machine code during
runtime.
 Immediate Feedback: Provides immediate results and feedback, which is useful for testing and debugging.
 No Intermediate File:
 Direct Execution: Unlike compilers, interpreters do not produce a separate executable file. Instead, they execute code
directly from the source file.
 Dynamic Execution: Executes code dynamically, which can be beneficial for scripting and interactive tasks.
 Error Handling:
 Runtime Errors: Errors are typically detected and reported during execution, which can help with debugging but might affect
performance.
 Flexibility:
 Interactive Development: Allows for interactive programming and scripting, making it easier to test and modify code on the
fly.
 Portability: Source code can often be run on any platform with the appropriate interpreter, making it portable across
different systems.
INTERPRETER
DIFFERENCE BETWEEN
COMPILER AND INTERPRETER
INTEGRATED DEVELOPMENT
ENVIRONMENT (IDE)
 An Integrated Development Environment (IDE) is a software application that
provides comprehensive tools for developers to write, debug, test, and manage
code.
 An IDE typically includes:
 Code Editor: A text editor designed for writing and editing source code. It usually has
features like syntax highlighting, auto-completion, and error detection.
 Compiler/Interpreter: The tool that converts your code into machine-readable form
(binary) or directly executes the code.
 Debugger: A tool that helps you identify and fix bugs in your code. It often allows you to
set breakpoints, inspect variables, and step through the code line by line.
 Build Automation Tools: Tools that help automate common development tasks such as
compiling code, packaging, and testing.
 Version Control Integration: Some IDEs have built-in support for version control systems
like Git, allowing developers to track changes and collaborate with others.
 Popular IDEs are: Visual Studio, IntelliJ IDEA, PyCharm, Eclipse, Xcode
PROBLEM SOLVING

 Problem solving is the systematic approach to define the problem and


creating number of solutions.
 The problem solving process starts with the problem specifications and ends
with a correct program.
 When writing a computer program to solve a problem, two fundamental issues
need to be addressed:
1. How the problem will be represented.
2. How the solution will be expressed
PROBLEM REPSESENTATION

 Computers are fundamentally designed to perform operations on numbers;


therefore, the range of things they can understand is quite limited.
 Determining how the entities constituting the problem will be represented means
creating a model for the problem.
 The first and most important step in solving the problem is to create a correct and
sufficiently detailed model.
 How you model the problem is crucial because what you solve is not the problem
itself but the model you have designed to represent that problem.
 If your model is too far from the actual problem, no matter how well you apply a
solution, the results you get will be meaningless.
 On the other hand, the level of detail needed in the model is determined by the
requirements of the problem you want to solve. If you prepare a model with more
detail than necessary, you might achieve a better result, but the extra effort or
the cost of implementing the solution might not justify the improvement.
SOLUTION EXPRESSION

 You need to be able to explain the solution you have devised for a problem to
someone else (whether a person or a computer). A solution described step by
step, outlining which operations are to be performed, is called an algorithm.
 For an algorithm to be executable by a computer, it must meet two important
criteria:
 Each step must be clearly defined with no ambiguity, requiring no interpretation.
 The algorithm must consist of a finite number of steps, and it must either find a
solution or indicate that no solution is possible.
DATA

 The quantities used in your model constitute the data of the program.
 Each quantity is represented in the program by a variable.
 A variable is essentially nothing more than a symbolic name given to that
quantity.
 Variables take on values during the execution of the program.
 Considering that variables are stored in memory, a variable can be thought of
as the name of a memory cell, and the value is the content of that cell.
VARIABLES

 The process of assigning a value to a variable is called assignment.


 On the left side of the assignment operator is a variable name, and on the
right side is an expression.
 An expression can be defined as a computation that produces a value. An
expression can be a single value or a variable, or it can be composed of these
and various operations involving them.
x=5
x and y are variables. = is assignment operator (NOT EQUAL IN MATH)
x=y+5
SWAP

 In computer science, swap refers to the process of exchanging the values of two
variables or data elements.
 This operation is fundamental in various algorithms, particularly those involving
sorting and data manipulation.
 Basic Swap Operation: The basic concept of swapping involves temporarily using a
third variable (often called a temporary or temp variable) to hold one of the
values during the exchange.
x = 10;
y = 20;
temp = x;
x = y; SWAP
y = temp;
SWAP

 Swapping of two numbers without using third/temp variable.

x = 10;
y = 20;
x = x + y; //This will modify x=30 & y=20
y = x - y; //This will modify y value i.e. y=10 & x=30
x = x - y; //This will modify x value i.e. x=20 & y=10
CONSTANTS

 In programming, constants are values that are fixed and do not change during
the execution of a program.
 They provide a way to name and use values that remain the same, improving
code readability and maintainability.
BASIC TYPES

In programming, basic data types refer to the fundamental types of data that a
programming language provides to represent various kinds of information.
 Integer: Represents whole numbers without any decimal points. It is used for
counting items, indexing arrays, performing arithmetic operations.
 Floating-Point Number: Represents numbers with fractional parts, using decimal
points. It is used for measurements, calculations requiring precision (e.g.,
scientific calculations).
 Boolean: Represents a value that can be either true or false. It is used for
conditional statements, logical operations (e.g., checking if a condition is met).
 Character: Represents a single symbol or letter. It is used for storing single
characters, representing individual symbols.
 String: Represents a sequence of characters (text).It is used for handling textual
data, user input, displaying messages.
OPERATORS

 Operators are special symbols or keywords in programming languages that


perform operations on variables and values.
 They are fundamental to creating expressions and performing computations in
code.
 Here’s a breakdown of the common types of operators and their uses:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
ARITHMETIC OPERATORS

OPERATOR OPERATION DESCRIPTION


+ Addition Adds two operands
Substraction Substracts second operand
-
from the first
* Multiplication Multiplies both operands
Division Divides numerator by de-
/
numarator
Exponentiation Raise the value to the power
**
of an exponent
Modulus This gives remainder of an
%
integer divison
ARITHMETIC OPERATORS
ORDER OPERATOR(S) OPERATION(S)
1 ( ) Parantheses
2 ** Exponentiation
3 * / % Multiplication, Modulus, Division
4 + - Addition, Substraction

 NOTE: If there are operations with the same precedence in a


mathematical expression coded in computer language, the computer
performs these operations from left to right (from beginning to end)
except exponentiation operator which will be performed from right to
left.
ARITHMETIC OPERATORS

EXAMPLE
What will be the value of the following expressions for a=1, b=2, c=3, d=4, e=-2
1. a+d/b+d**2+2a*b*c/d+e
2. (a+b)/c+d**2+2a*b*c/(d+e)
ARITHMETIC OPERATORS
RELATIONAL OPERATORS
Relational operators take typically two numerical values as input and produce
a logical value as output.
OPERATOR OPERATION
== Equal To
!= Not Equal To
< Less Than
> Greater Than
<= Less Than Equal To
>= Greater Than Equal To

They return 1 or true if the result is true, and 0 or false if the result is false.

3 < 5 results in True or 1.


5 > 6 results in False or 0.
RELATIONAL OPERATORS

Order Operator(s) Operations


1 () Parantheses
2 < <= > >= Relational
3 == != Equality

NOTE: If there are operations with the same precedence, the computer
performs these operations from left to right (from beginning to end).
LOGICAL OPERATORS
DESCRIPTION OPERATOR
Logical and AND & &&
Logical or OR | ||
Logical not NOT !
Logical
XOR ^
Exclusive or

X Y X&&Y X Y X||Y X Y X XOR Y X !X


0 0 0 0 0 0 0 0 0 0 1
0 1 0 0 1 1 0 1 1 1 0
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0
LOGICAL OPERATORS

ORDER OPERATOR(S) OPERATION(S)


1 () Parantheses
2 NOT ! Logical not
3 AND & && Logical and
4 OR | || Logical or

NOTE: If there are operations with the same precedence, the computer performs
these operations from left to right (from beginning to end).
RELATIONAL AND LOGICAL OPERATORS

EXAMPLE
Given A=5 and B=4, what is the evaluation of the expression
(A<5) OR (B>=A) AND (A==5)
RELATIONAL AND LOGICAL OPERATORS
ASSIGNMENT OPERATORS

NOTE: All simple and compound-assignment operators have equal precedence.


They are evaluated right to left.
OPERATOR PRECEDENCE
Order Category Operator Associativity
1 Parantheses () Left to right
2 Exponential ** Right to left
3 Multiplicative * / % Left to right
4 Additive + - Left to right
5 Relational < <= > >= Left to right
6 Equality == != Left to right
7 Logical NOT ! Left to right
8 Logical AND && Left to right
9 Logical OR || Left to right
10 Assignment = += -= *= /= %= **= Right to left
BLOCK-STRUCTURED PROGRAMMING

 Block-structured programming is built around the concept of blocks.


 A block is essentially a group of commands or instructions that are logically
connected to perform a specific task.
 In programming, we use blocks to structure code in a way that’s easy to
follow and maintain.
 Each algorithm consists of multiple blocks that are linked together, allowing
us to control how the program flows. There are three main ways in which
blocks can be organized and executed:
1. Sequence
2. Selection
3. Iteration
BLOCK-STRUCTURED PROGRAMMING

 In a sequence, blocks are executed one after another in the exact order they
are written—starting from the top and moving downwards.
 This is the simplest form of block execution and it highlights the importance
of the order in which commands are written.
 For example, imagine you have three steps to swap the values of two
variables. If the order of those steps is altered, the swap won’t work
correctly. This shows that in sequence structures, even a small change in the
order of operations can lead to completely incorrect outcomes.
BLOCK-STRUCTURED PROGRAMMING

 Selection is about making decisions.


 It allows the program to choose between different blocks of
code depending on whether a given condition is true or false.
 This is also called a conditional statement.
 For instance, if the condition evaluates to true, one block of
code is executed; if the condition is false, a different block (or
no block) is executed
 Selection structures allow you to control the flow of the
program based on conditions.
BLOCK-STRUCTURED PROGRAMMING

 Iteration refers to repeating a block of code as long as a certain condition holds


true.
 This is commonly known as a loop.
 In many cases, loops are used when you need to perform a repetitive task, like
processing items in a list or repeatedly checking a condition until it’s no longer
true.
 As shown in the flowchart, a loop keeps running until a certain condition is no
longer satisfied. For a loop to terminate, there must be a command inside the
block that eventually changes the condition. Otherwise, the loop will continue
forever, leading to what we call an infinite loop.
 There are also loops where the condition is checked at the end of the block,
meaning the block is always executed at least once, even if the condition is false
at the beginning.
ALGORITHM

 An algorithm is a finite number of clearly described, unambiguous steps that can be


systematically followed to produce a desired result for given input in a finite amount of
time.
 Algorithms are the initial stage of problem solving.
 The word algorithm is derived from the ninth-century Turkish mathematician, Al-
Khwarizmi (El-Harezmi).
BENEFITS OF PREPARING AN ALGORITHM

 Simplifies program coding.


 Reduces coding errors.
 Facilitates program control.
 Shortens the time spent on writing the program.
 Makes future adjustments easier.
QUALITIES OF A GOOD ALGORITHM

 The following are the primary factors that are often used to judge the quality of the
algorithms.
 Time – To execute a program, the computer system takes some amount of time.
The lesser is the time required, the better is the algorithm.
 Memory – To execute a program, computer system takes some amount of memory
space. The lesser is the memory required, the better is the algorithm.
 Accuracy – Multiple algorithms may provide suitable or correct solutions to a
given problem, some of these may provide more accurate results than others, and
such algorithms may be suitable.
NOTATIONS OF AN ALGORITHM

 A notation is a system of characters, expressions, graphics or symbols designs used


among each others in problem solving to represent technical facts, created to facilitate
the best result for a program.
 Algorithm can be expressed in many different notations, including:
 Natural language,
 Pseudo code,
 Flowcharts,
 Natural language tends to be verbose and ambiguous.
 Pseudocode and flowcharts are represented through structured human language
NOTATIONS OF AN ALGORITHM

Using natural language to describe algorithms involves expressing the steps and logic of the algorithm in
plain, conversational language. This approach is often used in documentation, tutorials, or when
explaining algorithms to non-programmers.
1. Start.
2. Boil water:
1. Fill a kettle with water.
2. Turn on the kettle to boil the water.
3. Prepare the tea:
1. Place a tea bag in a cup.
4. Add hot water:
1. Once the water is boiled, pour it into the cup with the tea bag.
5. Steep the tea:
1. Let the tea bag sit in the water for 3-5 minutes (depending on desired strength).
6. Remove the tea bag.
7. Optional:
1. Add sugar, milk, lemon, or honey to taste.
8. Stir the tea.
9. Enjoy your tea.
10. End.
NOTATIONS OF AN ALGORITHM

 Pseudocode: Pseudocode is an informal high-level description of the operating


principle of a computer program or algorithm. It uses the basic structure of a normal
programming language, but is intended for human reading rather than machine reading.
 Pseudocode cannot be compiled nor executed, and there are no real formatting or
syntax rules.
 The pseudocode is written in normal English language which cannot be understood by
the computer.
 Example: Pseudocode to find sum of two numbers
READ num1,num2
sum=num1+num2
PRINT sum
NOTATIONS OF AN ALGORITHM

 Advantages of Pseudocode
 Can be done easily on a word processor
 Easily modified
 Implements structured concepts well
 It can be written easily
 It can be read and understood easily
 Converting pseudocode to programming language is easy as compared with flowchart
 Disadvantages of Pseudocode
 It is not visual
 There is no standardized style or format
NOTATIONS OF AN ALGORITHM

 Flowchart: A graphical representation of an


algorithm. Flowcharts is a diagram made up of
boxes, diamonds, and other shapes, connected by
arrows.
 Each shape represents a step in process and arrows
show the order in which they occur.
NOTATIONS OF AN ALGORITHM

 Advantages of Flowchart
 Communication: Flowcharts are better way of communicating the logic of the system.
 Effective Analysis: With the help of flowchart, a problem can be analyzed in more effective
way.
 Proper Documentation: Flowcharts are used for good program documentation, which is
needed for various purposes.
 Efficient Coding: The flowcharts act as a guide or blue print during the system analysis and
program development phase.
 Systematic Testing and Debugging: The flowchart helps in testing and debugging the
program
 Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part.
NOTATIONS OF AN ALGORITHM

 Disadvantages of Flowchart
 Complex Logic: Sometimes, the program logic is quite complicated. In that case
flowchart becomes complex and difficult to use.
 Alteration and Modification: If alterations are required the flowchart may require
redrawing completely.
 Reproduction: As the flowchart symbols cannot be typed, reproduction becomes
problematic.
ALGORITHMS-EXAMPLE 1

 Design an algorithm and draw its flowchart to calculate the sum of two
numbers entered from the keyboard.
1. Begin
2. Enter two numbers (num1, num2)
3. sum = num1 + num2
4. Print (sum)
5. End
DESICION STRUCTURES

 Decision structures are programming constructs that allow a program to make


choices based on specific conditions.
 They enable a program to execute different code blocks depending on
whether a given condition is true or false.
ALGORITHMS-EXAMPLE 2

 Design an algorithm and draw its flowchart to determine whether a student


passes or fails the course based on the entered midterm and final exam
grades. (midterm %40, final %60, 60 and above pass)
1. Begin
2. Enter midterm and final grade (mid, fin)
3. avr = mid*0.4+fin*0.6
4. If (avr>=60) then go to 7
5. Print ("fails")
6. Go to 8
7. Print ("passes")
8. End
ALGORITHMS-EXAMPLE 3

 Design an algorithm and draw its flowchart that determines


whether a number entered from the keyboard is odd or even
and prints the result on the screen.
1. Begin
2. Enter a number (num)
3. If num%2==0 then go to 6
4. Print ("odd")
5. Go to 7
6. Print ("even")
7. End
ALGORITHMS-EXAMPLE 4

 Design an algorithm and draw its flowchart to determine


whether a given integer is zero, positive, or negative.
1. Begin
2. Enter an integer (num)
3. If num==0 then go to 7
4. If num>0 then go to 9
5. Print("negative")
6. Go to 10
7. Print ("zero")
8. Go to 10
9. Print(("positive")
10. End
ALGORITHMS-EXAMPLE 5

 Design an algorithm and draw its flowchart for a program that finds
the largest of three integers entered from the keyboard and prints it
on the screen.
1. Begin
2. Enter an integer (num1,num2,num3)
3. If num1>=num2 && num1>= num3 then go to 7
4. If num2>=num3 then go to 9
5. Print (num3)
6. Go to 10
7. Print (num1)
8. Go to 10
9. Print (num2)
10. End
LOOPS

 Loops are programming constructs that allow a


block of code to be executed repeatedly until
a certain condition is met.
 They are essential for automating repetitive
tasks and performing calculations that involve
iteration.
ALGORITHMS-EXAMPLE 6

 Design an algorithm and draw its flowchart for a


program that prints your name 100 times on the
screen.
1. Begin
2. counter=0
3. If counter>=100 then go to 7
4. Print("ANIL")
5. counter=counter+1
6. Go to 3
7. End
ALGORITHMS-EXAMPLE 7
Design an algorithm and draw its flowchart to
print the odd numbers from 1 to 100.

1. Begin
2. counter=1
3. If counter>=100 then go to 8
4. If counter%2==0 then go to 6
5. Print(counter)
6. counter=counter+1
7. Go to 3
8. End
ALGORITHMS-EXAMPLE 7
Design an algorithm and draw its flowchart to print the
odd numbers from 1 to 100.

1. Begin
2. counter=1
3. If counter>=100 then go to 7
4. Print(counter)
5. counter=counter+2
6. Go to 3
7. End
ALGORITHMS-EXAMPLE 8

 Design an algorithm and draw its flowchart for a


program that calculates and prints the number of
chickens a farmer will have at the end of 12th year,
given that the farmer starts with 50 chickens and
the annual growth rate is 3%.
1. Begin
2. chickens=50, year=0
3. If year>=12 then go to 7
4. chickens= chickens*1.03
5. year=year+1
6. Go to 3
7. Print(chickens)
8. End
ALGORITHMS-EXAMPLE 9

 Design an algorithm and draw its flowchart to list the


numbers between two numbers entered from the
keyboard. (NOTE: It will be assumed that the first entered
number is smaller than the second entered number.)
1. Begin
2. Enter two numbers(num1,num2)
3. counter=num1
4. If counter>num2 then go to 8
5. print(counter)
6. counter=counter+1
7. Go to 4
8. End
ALGORITHMS-EXAMPLE 10
 Design an algorithm and draw its flowchart for a program
that continuously reads numbers from the keyboard until
the number 0 is entered, and then calculates and prints
the average of these numbers on the screen. (NOTE: It
will be assumed that at least one number other than 0
has been entered.)
1. Begin
2. counter=0, num=1, sum=0
3. If num==0 then go to 8
4. Enter a number(num)
5. sum=sum+num
6. counter=counter+1
7. Go to 3
8. average = sum/(counter-1)
9. Print(average)
10. End
ALGORITHMS-EXAMPLE 11
 Design an algorithm and draw its
flowchart for a program that finds and
prints all positive divisors of a positive
integer entered from the keyboard.
1. Begin
2. Enter a number (num)
3. counter=1
4. if counter>num then go to 9
5. if num%counter!=0 then go to 7
6. Print (counter)
7. counter=counter+1
8. Go to 4
9. End
SUBPROGRAM

 Instead of repeatedly writing and using a group of statements that perform


the same task in various parts of a program, using program fragments
composed of these statements prevents code redundancy and enhances
program readability.
 A subprogram (subroutine) is a part of a program that is called by a main
program or another subprogram and forms a complete unit within itself.
 Function, procedure or methods are types of subprogram.
ALGORITHMS-EXAMPLE 12

 Write the algorithm of a subprogram that calculates and returns the area of a
triangle given its base and height.
 Design an algorithm and draw its flowchart for a program that calculates and
displays the area of a triangle whose base and height are entered from the
keyboard using the subprogram you wrote.
1. Begin 1. CALCULATE_AREA (base,height)
2. Enter the base (base) 2. area = (base*height)/2
3. Enter the height (height) 3. Return area
4. result = CALCULATE_AREA (base,height)
5. Print(result)
6. End
ALGORITHMS-EXAMPLE 12
ALGORITHMS-EXAMPLE 13

 Write the algorithm of a subprogram that determines whether a given number


is a perfect number.
 Design an algorithm and draw its flowchart for a program that determines
whether a number entered from the keyborad is a perfect number using the
subprogram you wrote.
 NOTE: A perfect number is a positive integer that is equal to the sum of its
proper positive divisors, that is, the sum of its positive divisors excluding the
number itself.
ALGORITHMS-EXAMPLE 13

1. Begin 1. IS_PERFECT(num)
2. Enter a number (num) 2. sum=1, counter=2
3. If (IS_PERFECT(num)) then go to 6 3. If counter>num then go to 8

4. Print("not perfect number") 4. If num%counter!=0 then go to 6


5. sum+=counter
5. Go to 7
6. counter+=1
6. Print("perfect number")
7. Go to 3
7. End
8. If sum==num then go to 10
9. return false
10. return true
ALGORITHMS-EXAMPLE 13
RECURSIVE SUBPROGRAMS

 Recursion is a programming technique where a function calls itself directly or


indirectly.
 It's a powerful tool for solving problems that can be broken down into smaller,
similar subproblems.
 A recursive function typically consists of two main parts:
 Base Case: This is the condition that stops the recursion. When the base case is
reached, the function returns a value without making further recursive calls.
 Recursive Case: This is the condition where the function calls itself with a
modified input. The goal is to bring the input closer to the base case.
ALGORITHMS-EXAMPLE 14

 Design algorithm of a recursive subroutine that calculates and returns the


factorial of a number given as a parameter.
 Design the algorithm and draws its flowchart of a program that calculates the
factorial of a number entered from the keyboard using the subroutine you
designed.
1. Begin 1. FACTO(num)

2. Enter a number (num) 2. If num==1 then go to 4

3. factorial = (FACTO(num)) 3. return FACTO(num-1)*num

4. Print(factorial) 4. return 1

5. End
ALGORITHMS-EXAMPLE 14
ALGORITHMS-EXAMPLE 15

 Design algorithm of a recursive subroutine that takes an index as a parameter,


finds the corresponding element in the Fibonacci sequence, and returns it.
 Design an algorithm and draw its flowchart for a program that prints the first
N elements of the Fibonacci sequence using the recursive subroutine you
designed earlier. N is a number inputted by the user from the keyboard.
 NOTE: The first two elements of the Fibonacci sequence are 1. The values of
the third and subsequent elements are obtained by summing the two
preceding elements. (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …)
ALGORITHMS-EXAMPLE 15

1. Begin 1. FIBONACCI(index)
2. Enter number of elemens (N) 2. If index !=1 && index!=2 then go to 4
3. counter=1 3. return 1
4. If counter>N then go to 8 4. Return FIBONACCI(index-2)+FIBONACCI(index-1)
5. Print(FIBONACCI(counter))
6. counter+=1
7. Go to 4
8. End
ALGORITHMS-EXAMPLE 15
ARRAYS

 An array is a collection of related objects of the same type.


 The objects in the array are called elements.
 It is used to access data of the same type with a single name.
 All elements of an array are stored consecutively in memory.
 Using arrays, multiple variables can be accessed and operated on with the
same name.
 Arrays can be defined as either single-dimensional or multi-dimensional, and
the size of the array can be adjusted according to the need.
ARRAYS

 Now consider the following array:


int d[5];
 This array contains 5 elements of type int. Let the values of the elements be
as follows:

 Here, the first element of the array d[0] has a value of -45, and the last
element d[4] has a value of 36.
ARRAY DEFINITION

 You can access any element of an array using indices, which start at 0 and
continue up to the size of the array minus one.
 The first element of the array is d[0], the i-th element is d[i-1], and the last
element is d[dimension-1].
 Each element in the array is a variable, and the rules applicable to variables
also apply to array elements.
ASSIGNING VALUES TO ARRAYS

 Let's assign values to the elements of an array d[] as follows: assign 20 to the first
element, 100 to the second element, and 100 to the third element as well:
d[0]=20;
d[1]=100;
d[2]=d[1];
 For example, if a = 2 and b = 1, then with the command
d[a+b] =0 + 2;
the 4th element of the array will be assigned the value 2, which means d[3] = 2.
 Now, let's divide the 3rd element by 2 and assign the result to a variable x of type
float:
x=d[2]/2;
The value of x will now be 1.
ALGORITHMS-EXAMPLE 16
 Create an algorithm and a flowchart for a program that
calculates the sum of the elements in an array where the
number of elements and the elements themselves are
entered from the keyboard.
1. Begin
2. Enter number of elements of the array (N)
3. counter=0, sum=0
4. If counter>=N then go to 9
5. Enter the next element (Arr[counter])
6. sum+=Arr[counter]
7. counter+=1
8. Go to 4
9. Print(sum)
10. End
ALGORITHMS-EXAMPLE 17
 Create an algorithm and a flowchart for a program that finds the
largest element in an array where the number of elements and the
elements themselves are entered from the keyboard.
1. Begin
2. Enter number of elements of the array (N)
3. counter=0
4. If counter>=N then go to 8
5. Enter the following element (Arr[counter])
6. counter+=1
7. Go to 4
8. counter=1, max=Arr[0]
9. If counter>=N then go to 14
10. If max>=Arr[counter] then go to 12
11. max=Arr[counter]
12. counter+=1
13. Go to 9
14. Print(max)
15. End
REFERENCES

 Introduction to Programming Concepts with Case Studies in Python, Gökhan Üçoluk


and Sinan Kalkan, Springer, 2012
 Notes of Lesson Ge3151- Problem Solving and Python Programming, The Mohamed
Sathak A. J. College of Engineering, Chennai.
 Programlamaya Giriş Ders Notları, H. Turgut Uyar, Şubat 2004.
 Fahri Vatansever, Algoritma Geliştirme ve Programlamaya Giriş, Seçkin Yayıncılık
 Kaan Aslan, A’dan Z’ye C Kılavuzu, Pusula Yayıncılık
 Levent Terlemez, Bilgisayar Programlama ders notları
 https://faisalchughtai.com/media/resources/CH%3A%202%20%7C%20Theory%20not
es%20-
%20Paper%201%20%7C%20IT%20(9626)%20%7C%20A%20Level/Compiler_and_interpre
ter.pdf
 https://www.engrcs.com/courses/engr250/engr250lecture.pdf

You might also like