Module 1 (Algorithms)
Module 1 (Algorithms)
Module 1 (Algorithms)
LESSON 1: ALGORITHMS
Algorithm
C.S. View
2 phases:
Language design
Translation
Foundation of Algorithms
Analysis of Algorithms
Know the behavior of the algorithm.
This includes the pattern and performance profile of an algorithm, that
can be measured in terms of its execution time and the amount of
space consumed.
Requirements:
Information given (input) and the results to be produced (output)
must be explicitly specified.
Understand the problem.
Design:
Write an algorithm that will solve the problem according to the
requirement.
Analysis:
Trying to come up with another algorithm and compare it with the
previous one.
Verification:
Consist of 3 aspects:
Program
Proving
Testing and Debugging
Example 1:
Requirement:
Input: Set of N integers
Output: Sum of N integers
Design:
Set a temporary variable to 0.
For each value entered, add the value to the temporary
variable.
tempsum = 0;
for(i=1; i<=n; i++)
{
scanf(x);
tempsum=tempsum + x;
}
Two Phases:
1. Priori Estimates:
Example:
Use of arrays vs. linked-list
Algorithms:
Scenario: You have a friend arriving at the airport and your friend needs to
get from the airport to your house.
Here are four different algorithms that you might give your friend for getting
to your home:
7 * ( 10 + ( 6 - 2 ))
A
Algorithm:
1. 6 - 2 = 4 (A) 1. Subtract A3 to A4.
2. 10 + 4 = 14 (B) 2. Add A2 and A.
3. 7 *14 = 98 3. Multiply A1 by B.
A1 A2 A3 A4 B1 B2 B3
(75 + ( 3 * ( 2 + 3 ) ) ) / ( 6 * ( 2 + 3 ) )
A D
B
E
C
ARRAYS
Array – collection of similar data elements. It is a data structure stored in
memory.
Syntax:
data_type_array[size];
Examples:
int num[5];
char name[80];
float area[3];
Graphical Representation
int grade[7];
95 88 93 91 90 87 93
/*This code will accept 5 integers /*This code will print the value of
from the user.*/ num[5]*/
/*This array program gets the sum of 10 numbers inside the array*/
#include<stdio.h>
main(){
printf("Enter 5 numbers:");
for(x=0;x<5;x++)
{
scanf("%d",&num[x]);
sum = sum + num[x];
}
printf("%d",sum);
}
#include<stdio.h>
main(){
int x,num[5],min,max;
for(x=0;x<5;x++)
{
scanf("%d",&num[x]);
}
min=num[0];
max=num[0];
for(x=0;x<5;x++)
{
if(min>num[x])
min = num[x];
else
if(max<num[x])
max=num[x];
}