Algorithm
Algorithm
PROGRAMMING
INTRODUCTION TO ALGORITHMS
Unit 1
Example
Algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
Functions:
Functions:
Function is a sub program which consists of block of code(set of
instructions) that performs a particular task.
For complex problems, the problem is been divided into smaller
and simpler tasks during algorithm design.
Benefits of Using Functions
Reduction in line of code
code reuse
Better readability
Information hiding
Easy to debug and test
Improved maintainability
Example for functions
Example:
Algorithm for addition of two numbers using
function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
sub function add()
Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Example
Write an algorithm to find area of a rectangle
Step 1: Start
Step 2: get l,b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop
Exercises
Write algorithm for the following:
1. Calculating simple interest
2. Greatest of two numbers
3. Even or odd
4. Leap year or not
5. Positive or negative
6. Greatest of three numbers
7. Print all natural numbers upto n
8. Positive or negative or zero
9. Print n odd numbers
10. Print square of a number
11. Print cube of a number
Simple interest
Step 1: Start
Step 2: get P, n, r value
Step3:Calculate
SI=(p*n*r)/100
Step 4: Display S
Step 5: Stop
Greatest of two numbers
Step 1: Start
Step 2: get a,b value
Step 3: check if(a>b) print a is greater
Step 4: else b is greater
Step 5: Stop
Leap year or not