PPS Unit 1
PPS Unit 1
Introduction
Introduction to algorithms
• Algorithm is a systematic logical approach which is a well-
defined, step-by-step procedure that allows a computer to
solve a problem..
• Pseudo code is a simpler version of a programming code in
plain English which uses short phrases to write code for a
program before it is implemented in a specific programming
language.
• A flowchart is a schematic representation of an algorithm
or the diagrammatic representation of way to solve the
given problem.
Algorithm
• This is the first step to solve a mathematical or computer problem.
• Breaking down the task.
• “A sequence of activities to be processed for getting desired output from a
given input.”
• A computer program can be viewed as an elaborate algorithm.
• While writing algorithms we will use following symbol for different
operations:
‘+’ for Addition
‘-’ for Subtraction
‘*’ for Multiplication
‘/’ for Division and
‘←’ for assignment
Pseudo code
• Pseudo code is an informal way of writing a program.
• It is not exactly a computer program.
• It represents the algorithm of the program in natural
language and mathematical notations.
• Usually, there is no particular code syntax to write a pseudo
code.
• Therefore, there is no strict syntax as a usual programming
language.
• It uses simple English language.
Flow chart
• A Flow chart is a Graphical representation of an Algorithm.
• Flowcharts are drawn using certain special purpose symbols
such as Rectangles, Diamonds, Ovals and small circles.
• These symbols are connected by arrows called flow lines.
• Flow chart simply a diagrammatic /pictorial representation of
way to solve the given problem.
• Flowcharts can be used to describe all sorts of processes:
business, educational, personal and of course algorithms.
• So, flowcharts are often used as a program planning tool to
visually organize step-by-step process of a program.
The following are the most common symbols used in
drawing flowcharts:
Example1: Algorithm to add two numbers
Step 1: Start
Step 2: Read values num1 and num2.
Step 3: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 4: Write/ Display sum
Step 5: Stop.
Example1: Pseudo code to add two numbers
Begin
Read: num1, num2;
Set sum = num1+num2;
Print sum;
End
Example1: Flowchart to add two numbers
Example 2 : Algorithm to find the largest among two
different numbers
Step 1: Start
Step 2: Declare variables a and b.
Step 3: Read values of a and b.
Step 4(a): If a greater than b then
Write/ Display a is the largest number.
Step 4(b): Else
Write/ Display b is the largest number.
Step 5: Stop
Example 2 : Pseudo Code to find the largest among two
different numbers
Begin
Read a and b
if a>b then
Print a is largest
else
Print b is largest
end if
End
Example 2: Flow chart to find the largest among two
different numbers
Example3: Algorithm to find the sum of individual digits of a
given positive integer.
Step 1: start
Step 2: read a positive integer called num
Step 3: declare and initialize variables:
sum←0, dig←0
Step 4: repeat steps 4.1, 4.2, 4.3 until num greater than zero
4.1: dig ← num mod 10
4.2: sum ← sum + dig
4.3: num ← num/10
Step 5: write/ display sum
Step 6: stop
Example 3: Pseudo code to find the sum of individual digits
of a given positive integer
Begin
Read num;
Set sum=0, dig=0;
While num>0 then
dig = num % 10
sum = sum + dig
num = num/10
End while
print sum
End
Example 3: Flow chart to find the sum of individual
digits of a given positive integer
Example 4: Algorithm to convert temperature Fahrenheit to
Celsius
Algorithm:
Step 1: Start
Step 2:Read Temperature in Fahrenheit F
Step 3: convert temperature to celsius
C← 5/9*(F-32)
Step 4: Print Temperature in Celsius: C
Step 5: Stop
Example 4: Pseudo code to convert temperature Fahrenheit
to Celsius
Begin
Read Fahrenheit
set Celsius = 5/9*(Fahrenheit -32)
Print Celsius
End
Example4: Flow chart to convert temperature Fahrenheit to
Celsius
Example 5: Algorithm to find roots of quadratic
equation
1. Start
2. Read a, b, c values
3. Compute d ← b*b-4*a*c
4. if value of d is greater than zero then
a. r1 ← b+ sqrt (d)/(2*a)
b. r2 ← b sqrt(d)/(2*a)
5. Otherwise, if d is zero then
a. Compute r1 ← -b/2a, r2 ← -b/2a
b. Display r1,r2 values
6. Otherwise, if value of d is less than zero then display roots are
imaginary
7. Stop
Example 5: Flow chart to find roots of quadratic
equation
Example 6: Algorithm for finding the minimum and
maximum numbers from a given set
1. Start
2. Initialize two variables, min_val to positive infinity and max_val
negative infinity, respectively.
3. Read set of numbers.
4. Iterate through each number in the given set:
4.1. If the current number is smaller than min_val, update min_val
with the current number.
4.2. If the current number is larger than max_val, update max_val
with the current number.
5. After processing all numbers in the set, display min_val and
max_val.
6. Stop.
Example 7: Algorithm for finding if a number is prime
number or not
1. Start
2. Input a positive integer 'n'.
3. If n is less than or equal to 1, display "Not a prime number" and end.
4. If n is equal to 2, display "Prime number" and end.
5. Initialize a variable ‘factor_count’ to 2.
6. Loop from ‘i’ = 2 to the ‘n-1’, incrementing 'i' by 1 in each iteration.
6.1. If 'n' is divisible by 'i'
a. incrementing ‘factor_count’ by 1
b. break out of the loop
7. If ‘factor_count’ is 2, display "Prime number";
8. otherwise, display "Not a prime number."
9. Stop.
Program design and
Structured
programming
Structured programming
#include<stdio.h>
void main()
{
printf("Hello, World! \n");
}
Output:
Hello, World!
C Tokens
• In a C program the smallest individual units known as C
tokens.
• C has 6 types of tokens namely:
1) Keywords
2) Identifiers
3) Constants
4) String literals
5) Operators
6) White spaces
C Tokens
• Keywords
– These are reserved words of the C language.
– There are 32 keywords in C, all the keywords are in small
case.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
• Identifiers
– An Identifier is a sequence of letters and digits, but must
start with a letter. Identifiers are case sensitive. Identifiers
specifies the names to the particular entity such as name
of variables, functions etc.
– Valid: Root, _getchar, __sin, x1, x2, x3, x_1, If
– Invalid: 324, short, price$, My Name
• Variable
– Indicates the name of the data value.
• Constants: It refers to fixed values that do not change during
the execution of program.
– Numeric constants: integer and real(float)
– Character constants: single character and strings
• String Literals
– A sequence of characters enclosed in double quotes as
“…”. For example “13” is a string literal and not number 13.
‘a’ and “a” are different.
– Ex: “GfG”, “hello world” etc.,
• Operators
– Arithmetic operators like +, -, *, / ,% etc.
– Logical operators like ||, &&, ! etc.
• White Spaces
– Spaces, new lines, tabs. These are used to separate the
adjacent identifiers, keywords and constants.
Data types
• Data type determines the type of data a variable will hold.
• C language has some predefined set of data types to handle
various kinds of data that we can use in our program.
• Primary data types:
– void: Has no values and no operations.
– character(char): Used to store character value.
– integer(int): Used to store whole numbers.
– Floating point(float, double): Used to store real numbers.
Data type
Type Storage Value range Format
size specifier
unsigned 1 byte 0 to 255 %c
char
signed char 1 byte -128 to 127 %c
short int 2 bytes -32,768 to 32,767 %d
unsigned 2 bytes 0 to 65,535 %u
short int
long int 4 bytes -2,147,483,648 to 2,147,483,647 %ld
unsigned 4 bytes 0 to 4,294,967,295 %lu
long int
float 4 bytes 3.4*E-38 to 3.4*E+38 %f
double 8 bytes 1.7*E-308 to 1.7*E+308 %lf
long double 10 bytes 3.4*E-4932 to 1.1*E+4932 %Lf
Derived and User defined data types
• The addition operator can be used with numerical data types and
character data type.
‘c’ + ‘r’ = ‘cr’
• The remainder of division operator is used with integer data type
only.
Priority of operators:
Ex:-
3–5*7/8+6/2
3 – 35 / 8 + 6 / 2
3–4+6/2
3–4+3
-1 + 3
2
Convert arithmetic statements to C
• AxB–CxD
A*B–C*D
• (M+N)(P-Q)
(M+N)*(P-Q)
• 3x2 + 5x + 2
3*x*x* + 5*x + 2
• A+B+C
E+D
(A+B+C) / (D+E)
Assignment Operators
• Assign right hand side value (Rvalue) to the left hand side variable (Lvalue).
• The assignment operator is used in different variants along with arithmetic
operators.
simple assignment operators short hand assignment operators
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
a=a*b a*=b
a=a/b a/=b
Increment & Decrement Operators
• The increment and decrement operators are called as unary
operators.
• (++a): pre-increment
• (--a): pre-decrement
• (a--): post-decrement
• (a++): post-increment
Pre-Increment and Pre-Decrement
Example:
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf(“++i = %d, --j = %d",++i,--j);
}
Output:
++i = 6, --j = 4
Post-Increment or Post-Decrement
Example:
#include <stdio.h>
void main()
{
int i = 5,j=5;
printf("i++ = %d, j-- = %d\n",i++,j--);
printf(“i = %d, j = %d\n” ,i,j);
}
Output:
i++ = 5, j-- = 5
i = 6, j = 4
Relational Operators
• They are used to compare or check the relationship between two values.
• Every relational operator has two results TRUE or FALSE.
• Relational operators are used to define conditions and take decisions in a
program.
Logical Operators
• The logical operators are used to combine multiple conditions into one
condition.
exp-1 exp-2 exp-1 && exp-2 exp-1 || exp-2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0 0 0 0
exp-1 !exp-1
non-zero zero
zero non-zero
Example:
10 + 4 * 3 / 2
4 * 3 => 12
12 / 2 => 6
10 + 6 => 16
Postfix Expression
• The expression in which operator is used after operands
is called as postfix expression.
• Structure of postfix expression:
• Example:
4 5*8+
4*5 =>20
20+8 =>28
Prefix Expression
• The expression in which operator is used before
operands is called as prefix expression.
• The structure of prefix notation:
• Example:
+ * 2 3/ 10 2
2*3 => 6
10/2 =>5
6+5 =>11
Type conversion
• Type Conversion: Conversion from one data
type to another.
• Two ways of type conversion are:
Implicit Type Conversion
Explicit Type Conversion
Implicit Type conversion
• Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external
trigger from the user.
• All the variables are upgraded to the data type of the
variable with largest data type. This is also known as type
promotion.
• bool -> char-> short int-> int -> unsigned int-> long->
unsigned long-> float -> double-> long double
Example program
#include<stdio.h>
void main()
{
char c='a';
int x=5;
x = x+c; //char is converted to int
float y=6.45;
y = y+x; //int is converted to float
printf("x=%d\n",x);
printf("y=%.2f\n",y);
}
Explicit Type Conversion
• This process is also called type casting and is user
defined.
• Here the user can type cast the result to make it of a
particular data type.
• The syntax in C:
(type) expression
• Type indicated the data type to which the final result
is converted.
Example program
#include<stdio.h>
void main()
{
int a=8;
float b=a/3;
printf("8/3 = %f\n",b);
b=(float)a/3;
printf("8/3 = %.2f",b);
}
Control Statements
Conditional Statements
• In c program, statements are executed sequentially, when no
options or repetitions are necessary.
• But the order of execution changes based on
– certain conditions
– repeats group of statements until certain condition is met
• This involves decision making to check whether a conditions has
occurred or not.
• Then direct the computer to execute some statements accordingly.
• Such decision making statements in C:
– if statement
– switch statement
– Conditional operator statement
if statement in c
• In c, if statement is used to make decisions based on a condition.
• The if statement verifies the given condition and decides whether a
block of statements are executed or not based on the condition
result.
• The if statement may be implemented in different forms depending
on the complexity of conditions to be tested. The different forms
are:
– Simple if statement
– if - else statement
– Nested if - else statement
– else if ladder(if-else-if statement )
Simple if statement
Syntax:
if (condition)
{
block of statement;
}
statement-x;
• In either case, either true block or false block will be executed, not both.
Example: c program to check whether given
number is even or odd
#include <stdio.h>
#include<conio.h>
void main()
{ Case 1:
int n ; Enter any integer: 100
printf("Enter any integer: ") ; 100 is EVEN
Case 2:
scanf("%d", &n) ;
Enter any integer: 99
if ( n%2 == 0 ) 99 is ODD
printf("%d is EVEN\n", n) ;
else
printf("%d is ODD\n", n) ;
}
Nested if-else statement
• When a series of decisions are involved, we use more than one if-else
statement in nested form.
• The nested if-else statement can be defined using any combination of
simple if and if-else statements.
Syntax: {
if (condition-1) statements 3;
{ }
if (condition-2) statement x;
{
statements 1;
}
else
{
statements 2;
}
}
else
Example: c program to check whether given
number is even or odd if it is below 100.
#include <stdio.h>
void main(){
int n ;
printf("Enter any integer: ") ;
scanf("%d", &n) ;
if ( n < 100 ) {
printf(“%d is below 100\n", n) ; Case 1:
if( n%2 == 0) Enter any integer: 55
printf("And it is 55 is below 100
EVEN") ; And it is ODD
else Case 2:
printf("And it is Enter any integer: 999
ODD") ; 999 is not below 100
}
else
printf(“%d is not below 100" ,
n);
else if ladder(if-else-if statement )
• When multi path decisions are involved, we use a chain of ifs in
which the statement associated with each else is an if.
• Syntax:
if (condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
else
statement 4;
statement x;
Example: C program to find the largest of three
numbers.
#include <stdio.h>
void main(){
int a, b, c ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
Output:
Enter any three integer numbers: 55 60 20
60 is the largest number
• When we use conditional control statement like if statement, condition
might be an expression evaluated to a numerical value, a variable or a
direct numerical value.
• If the expression value or direct value is zero the condition becomes
FALSE otherwise becomes TRUE.
• Examples:
– if(10) - is TRUE
– if(x) - is FALSE if x value is zero otherwise TRUE
– if(a+b) - is FALSE if a+b value is zero otherwise TRUE
– if(a = 99) - is TRUE because a value is non-zero
– if(10, 5, 0) - is FALSE because it considers last value
– if(0) - is FALSE
– if (a=0, x=10) – is TRUE because it considers last value
– if(a=10, b=15, c=0) - is FALSE because last value is zero
switch statement in C
• When one of the many options is to be selected, we can use if
statement to control the selection.
• The complexity increase with increase in number of options.
• Program becomes difficult to read and flow.
• C has a built-in multi-way decision statement known as
switch.
• The switch statement tests the value of a given expression
against a list of case values
• And when match is found, a block of statements associated
with that case is executed.
• The value of the 'expression' in a switch-case statement must
be an integer, char, short, long.
• expression can integer or character.
Syntax: • value1, value2 ... are constants (unique)
or constant expressions and are known as
switch (expression) case labels.
{ • block1, block2 ... are statement lists and
case value1: may contain zero or more statements.
block1
• No need of braces for blocks and case
break;
labels end with colon (:).
case value2:
block2 • If a case is found whose value matches
break; with the value of the expression, then the
......... block of statements that follows the case
......... are executed.
default: • The break statement signals the end of a
default block particular case and causes an exit from
break; switch.
} • The default is an optional case.
Statement-x;
Flow of execution
Example: c program to assign grades.
#include <stdio.h> break ;
void main(){ case 4: printf("Third division")
int n ; ;
printf("Enter CGPA: ") ; break ;
scanf("%d", &n) ; default: printf("Fail") ;
index = n/10 }
switch( n ) { }
case 10:
case 9: Case 1:
case 8: printf("Distinction") ; Enter marks: 85
break ; Distinction
case 7: Case 2:
case 6: printf("First Enter marks: 15
division") ; Fail
break ;
case 5: printf("Second
division") ;
The conditional operator
• Conditional operator is useful for making two-way decisions.
• This operator is a combination of ? and :, and takes 3 operands.
• Syntax:
conditional expression ? expression1 : expression2
• The conditional expression is evaluated first.
• If the result is non-zero, expression 1 is evaluated and its value is returned.
• Otherwise expression 2 is evaluated and its value is returned.
• For example:
if (x%2==0)
flag=1
else
flag=0
Can be written as
flag = (x%2==0) ? 1 : 0
• Using conditional operator is concise and efficient
• The conditional operator can be nested for evaluating more complex
assignment decisions.
• Example: consider the weekly salary of a sales girl who is selling some
domestic products. If x is the number of products sold in a week, her
weekly salary is given as:
4x +100 for x < 40
salary= 300 for x=40
4.5x+150 for x>40
• Using else-if ladder
if(x<40)
salary = 4*x + 100
else if (x>40)
salary = 4.5*x + 150
else
salary = 300
• This equation can be written as
salary = (x != 40) ? ((x<40) ? (4*x + 100) : (4.5*x + 150)) : 300
Loops
• Loops are used to repeat a set of statements.
• In looping, a sequence of statements are repeatedly
executed until some end condition is met.
• A program loop has
Body of the loop.
Control statement.
• Depending on the position of the control statement in
the loop, control structure has
– Entry controlled loop.
– Exit controlled loop.
• Entry controlled and exit controlled loop structure is
shown below:
• Do-while loops are sometimes useful if you want the code to output some sort of
menu to a screen so that the menu is guaranteed to show once.
Example #2: do.....while loop
#include<stdio.h> #include<stdio.h>
Void main() Void main()
{
{
double x,y;
double x,y; read:
read: if ( x > 0)
scanf(“%f”, &x); {
y = sqrt(x); scanf(“%f”, &x);
print(“%f %f\n”, x , y); y = sqrt(x);
print(“%f %f\n”, x , y);
goto read;
goto read;
} }
}