Module 1
Module 1
ALGORITHMS
In general terms, an algorithm provides a blueprint to writing a program to solve a particular
problem. It is considered to be an effective procedure for solving a problem in a finite number of
steps. That is, a well- defined algorithm always provides an answer, and is guaranteed to terminate.
Algorithms are mainly used to achieve software re-use. Once we have an idea or a blueprint of a
solution, we can implement it in any high-level language, such as C, C++, Java, and so on. In order
to qualify as an algorithm, a sequence of instructions must possess the following characteristics:
Be precise
Be unambiguous
Not even a single instruction must be repeated infinitely
After the algorithm gets terminated, the desired result must be obtained
The time complexity of an algorithm is basically the running time of a program as a function of
the input size. Similarly, the space complexity of an algorithm is the amount of computer memory
that is required during the program execution as a function of the input size.
1
SEQUENCE
Sequence means that each step of the algorithm is executed in the specified order. An algorithm to
add two numbers is given below. This algorithm performs the steps in a purely sequential order.
Step 0: Start
Step 1: Input the first number as A
Step 2: Input the second number as B Step 3: Set SUM = A + B
Step 4: Print SUM
Step 5: End
DECISION
Decision statements are used when the outcome of the process depends on some condition. For
example, if x=y, then print “EQUAL”. Hence, the general form of the if construct can be given as
if condition then process
An algorithm to check the equality of two numbers is shown below.
Step 0: Start
Step 1: Input the first number as A
Step 2: Input the second number as B
Step 3: If A = B Then Print "EQUAL" else PRINT "NOT EQUAL"
Step 4: End
REPETITION
Repetition, which involves executing one or more steps for a number of times, can be implemented
using constructs such as while, do-while, and for loops. These loops execute one or more steps
until some condition is true. An algorithm that prints the first 10 natural numbers as shown below.
Step 0: Start
Step 1: [INITIALIZE] SET i = 0, n = 10
Step 2: Repeat Step while i<=n
Step 3: PRINT i
Step 4: Set i= i + 1
Step 5: End
2
FLOWCHARTS
Symbols of flowchart
3
The symbols of a flowchart include:
Start and end symbols are also known as the terminal symbols and are represented as
circles, ovals, or rounded rectangles. Terminal symbols are always the first and the last
symbols in a flowchart.
Arrows depict the flow of control of the program. They illustrate the exact sequence in
which the instructions are executed.
Generic processing step, also called as an activity, is represented using a rectangle.
Activities include instructions such as add a to b, save the result. Therefore, a processing
symbol represents arithmetic and data movement instructions. When more than one process
has to be executed simultaneously, they can be placed in the same processing box.
However, their execution will be carried out in the order of their appearance.
Input/output symbols are represented using a parallelogram and are used to get inputs
from the users or display the results to them.
Conditional or decision symbol is represented using a diamond. It is basically used to
depict a Yes/No question or a True/False test. The two arrows coming out of it, one from
the bottom vertex and the other from the right vertex, correspond to Yes or True, and No
or False, respectively. The arrows should always be labelled. A decision symbol in a
flowchart can have more than two arrows, which indicate that a complex decision is being
taken.
Labelled connectors are represented by an identifying label inside a circle and are used in
complex or multisheet diagrams to substitute for arrows. For each label, the „outflow‟
connector must have one or more „inflow‟ connectors. A pair of identically labelled
connectors issued to indicate a continued flow when the use of lines becomes confusing.
4
Example 1: Draw a flowchart to calculate the salary of a daily wager
5
PSEUDOCODES
Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language. It is basically meant for human reading
rather than machine reading, so it omits the details that are not essential for humans. Such
details include variable declarations, system-specific code, and sub-routines.
Pseudocodes are an outline of a program that can be easily converted into programming
statements. They consist of short English phrases that explain specific tasks within a program‟s
algorithm. They should not include keywords in any specific computer language.
The sole purpose of pseudocodes is to enhance human understandability of the solution. They
are commonly used in textbooks and scientific publications for documenting algorithms, and
for sketching out the program structure before the actual coding is done. This helps even non-
programmers to understand the logic of the designed solution. There are no standards defined
for writing a pseudocode, because a pseudocode is not an executable program. Flowcharts can
be considered as graphical alternatives to pseudocodes, but require more space on paper.
Example
Write a pseudocode for calculating the price of a product after adding sales tax to its original price.
Solution
1. Read the price of the product
2. Read the sales tax rate
3. Calculate sales tax = price of the item × sales tax rate
4. Calculate total price = price of the product + sales tax
5. Print total price
6. End
Variables: price of the product, sales tax rate, sales tax, total price
Example
Write a pseudocode to read the marks of 10 students. If marks are greater than 50, the student
passes, else the student fails. Count the number of students who pass and the number who fail.
Solution
1. Set pass to 0
2. Set fail to 0
3. Set no of students to 0
4. WHILE no of students < 10
a. input the marks
b. IF marks >= 50 then Set pass = pass + 1
ELSE
Set fail = fail + 1 ENDIF
ENDWHILE
5. End
Variables: pass, fail, no of students, marks
6
PSEUDOCODES
Pseudocode is an informal list of steps in English like statements which is intended for
human reading.
It is used in planning of computer program development, for sketching out the structure of
the program before the actual coding takes place.
Advantages:
1. It can be written easily
2. It can be read and understood easily
3. Modification is easy
Disadvantages:
1. There is no standard form.
2. One Pseudocode may vary from other for same problem statement.
Examples:
1. Begin
2. Read two numbers a, b
3. Calculate sum = a+b
4. Display sum
5. End
1. Begin
2. Read the values of length, breadth
3. Calculate area = l x b
4. Display area
5. End
7
Types of Errors
1. Run Time Errors: It occurs when the program is being run executed. Such errors occur
when the program performs some illegal operations like
Dividing a number by zero
Opening file that already exists
Lack of free memory space
Finding Square of logarithm of negative numbers Run time errors may terminate program
execution
2. Compile Time Errors: It occurs at the time of compilation of the program. Such errors
can be classified as follows:
i. Syntax errors: They generated only when rules of programming language are violated
ii. Semantic errors: Which may comply with the rules of the programming language but
are not meaningful to the complier
3. Logical Errors: Logical errors are the errors in the program code that result in unexpected
and undesirable output.
4. Linker Errors: These errors occur when the linker is not able to find the function
definition for a given prototype
8
Introduction to C
Introduction
The programming language c was developed in the early 1970‟s by Dennis Ritchie at Bell
Laboratoriesto be used by the UNIX operating system. It was renamed „C‟ because many of
its features were derived from an earlier language. C was designed for developing portable
application software.
History of C
Examples of C:
Operating system
Language compilers
Assemblers
Text editors
Databases
Characteristics of C
C is high level language
C makes extensive use of function calls
C is well structured Programming
C is Stable Language
C facilitates low level language
C is Portable language
C is easy to learn.
C is core language
C is extensible language
C is often treated as second best language
C is a general purpose language.
It can extend itself.
Uses of C
C language was primarily used for system programming
C has been widely accepted by professionals that compilers, libraries and
interpreters ofother languages written in c.
C is widely used to implement end-user applications
C can be used as intermediate language
9
Structure of ‘C’ Program
The main( ) function is enclosed within flower brackets and the statements ends with semicolon.
Sub-program Section: It contains all the user defined functions that are called by main( )
function.
Documentation section
Link section
Definition section
Global declaration section
main( ) Section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2
-
-
Function n
10
Example:
#include <stdio.h>
int main()
{
// printf() displays the string inside quotation
printf("Hello, World! \n");
return 0;
}
Output
Hello, World!
11
Files used in C Program
Header files
When working with large projects, it is often desirable to separate out certain
subroutines from themain() function of the program. There also may be case that the
same subroutine has to be used indifferent programs. This is used by .h extension
Standard Header files are as follows:
Object files
Object files are generated by the compiler as a result o processing the source code file.
Object code filecontains a binary code of the source code. It is used with filename .obj
extension.
12
Using Comments
C supports two types of comments.
1. Single line Comment
2. Multiline Comment
Multiline Comment:
The symbol which is used for the multiline comment is /* and */
The type of the comment is a block comment. The multiple lines are commented by using
the abovesymbol. Note that commented statements are not executed by the compiler.
C – Tokens
Character set in C
A C character set defines the valid characters that can be used in a source program. The basic
C characterset are:
1. English Alphabetss:
Uppercase Letters: A,
B, C,…., ZLowercase
Letters: a, b, c,….., z
2. Digits: 0, 1, 2,….., 9
3. Special characters: ! , @. #, $, %, *, (, ),}, {, ;,:,”,‟,?,>,<,/,,,.,|,\,&,^, etc
4. White spaces: These characters are used to print a Blank space on the screen,
Horizontal tabspace (\t), carriage return, new line character (\n), form
feedcharacter.etc.
13
Keywords
Keywords are also called as reserved words.
They already have pre-defined meaning.
Keywords should always be written in lowercase.
The keywords meaning can‟t be changed.
Keywords cannot be used as identifiers.
There are 32 keywords in „C‟ program.
Identifiers
C language provides few basic data types as shown in the below table.
15
Primary/ Built-in/ Fundamental data type: These are the built in data types available in
C. There are5 types. Namely:
1. Integer (int)
2. Floating point (float)
3. Character (char)
4. Double precision floating point (double)
5. Void (void)
1. Integer type:
It is used to store whole numbers.
The keyword int is used to declare variable of integer type.
Int type takes 2B or 4B of storage depending on machine size.
The classes of integer are:
Unsigned Signed
Data type Keyword Size Data type Keyword Size
Short Integer short int 1B Signed short integer signed short int 1B
Integer int 2B Signed integer signed int 2B
Long Integer long int 4B Long integer long int 4B
3. Double:
It is used to store double precision floating point numbers.
The keyword double is used to declare variable of floating point data type.
Double type takes 8B of storage.
Double precision is related to accuracy of data.
4. Char:
It is used to store character type of data.
The keyword char is used to declare variable of character type.
Char type takes 1B of storage.
5. Void:
It is a special data type that has no value.
It doesn‟t have size.
It is used for returning the result of function that returns nothing.
16
Variables
A variable is defined as a meaningful name given to a data storage location in
computer memory.When using a variable, we actually refer to the address of the
memory where the data is stored.
The variable value will be changed during the execution of program.
A variable is a name given to memory location whose value changes during execution.
Declaration:
Example: int a;
Where, int is the built
in data typea
is variable
of type int.
Initialization:
Syntax: datatype
variable_name =
value;Where,
datatype Any built in data type
variable_name Identifier that specifies variable name.
value The data which will be stored in variable name.
Example: int a = 10;
Where,
int data type
a variable name
10 value
17
Numerical Variables
It can be used to store either integer values or floating values. While integer value whole
number withouta fraction part or decimal point, a floating point value can have a decimal
point.
They are also may be associated with modifiers, such as short, long, signed and un-
signed numericvariables.
Character variables
Character variables are just single characters enclosed within single quotes. These
characters variablescould be any character from the ASCII character set-letters („a‟, „A‟),
numerals („2‟) or special character(„&‟)
Declaring variables
To declare a variable, specify the data type of the variable followed by its name. The data
type indicatesthe kind of values that variable will store. Variable declared in a program
always ends with semicolon.
Syntax: datatypename variablename;
Example: int emp_num;
float salary;
char grade;
double balance
amount;
unsigned short
int acc_num;
Initializing variables
While decarting variables, we can initialize them with some value.
Syntax: datatypename variablename= value;
Example: int emp_num=7;
float
salary=21
56.35;
char
grade=‟A
‟;
double balance amount=100000000;
18
Constants
Constants are the values that don’t changes during the execution of a program.
A constant is an explicit data value specified by the programmer.
Constants are used to define the fixed values.
Integer Constant
Numeric
Constant
Real Constant
Constant
Single Character
Constant
Character
Constant
String Constant
Numerical Constant
Real Constant:
G C E M \0
NOTE:
Qualified Constant/ Memory Constant: These are created by using “const” qualifier.
Const meansthat something can only be read but not modified.
Syntax: const datatype variable_name = value;
Ex: const int a = 10;
const float pi = 3.14;
Symbolic Constants/ Defined Constant: These are created with the
help of definepreprocessor directive.
Ex: #define PT 3.142
During processing the PI in the program will be replaced with 3.142.
The name of constant is written in uppercase just to differentiate from the variables.
G C E M \0
20
Input Output statements in C
scanf()
Formatted input refers to an input data that has been arranged in particular format.
Ex: 152 Rajesh
In the above example the first part contains integer and the second part contains
characters. This ispossible with the help of scanf function.
where
The control string specifies the field form in which data should be entered
The arguments arg1, arg2,…..,argn specifies the address of the location
where the data isstored.
The width of the integer number can be specified using %wd.
Example-1:
– scanf(“%2d %2d”, &a, &b);
%2d two digit integer
%2d two digit integer 4567 25
a=45 b=67
Note: 25 is not at all stored
The input field may be skipped using * in the place of field width.
Example-2:
– scanf(“%2d %*d %2d”, &a, &b);
%2d two digit integer
%*d skip this
integer 45 25 63a=45
25 is skipped b=63
The scanf function can read single character or more than one character using %c or %s.
21
The below table shows the scanf format codes commonly used.
Code Meaning
%c Read a single character
%d Read a decimal integer
%e, %f, %g Read a floating point
value
%h Read a short integer
%i Read a decimal integer
%o Read a octal integer
%s Read a string
%u Read an unsigned
decimal integer
%x Read a hexadecimal
integer
%[ ] Read a string of word
The l can be used as a prefix for long integer. Ex: %ld
printf()
The printf function is used for printing the captions and results.
Where
The control string specifies the field form in which data should be printed.
The arguments arg1, arg2,…..,argn specifies the location where the data is
stored to beprinted on the screen
The below table shows the printf format codes commonly used.
Code Meaning
%c Print a single character
%d Print a decimal integer
%e Print a floating point value in
exponent form
%f Print a floating point value
without exponent
%g Print a floating point value
with or without exponent
%h Print a short integer
%i Print a decimal integer
%o Print a octal integer
%s Print a string
%u Print an unsigned decimal
integer
%x Print a hexadecimal integer
22
%[ ] Print a string of word
23
Operators
An operator is a symbol that tells the compiler to perform specific mathematical and
logicalfunctions. The different operators supported in „C‟ are:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Unary Operators Increment and Decrement
7. Ternary/ Conditional Operator
8. Special Operators
2. Relational Operators: These are used to compare two quantities. The output will be
either 0 (False)or 1 (True). The different relational operators are:
3. Logical Operators: These are used to test more than one condition and make decision.
The differentlogical operators are: NOT, AND, OR
Logical NOT (!) The output is true when input is false and vice versa. It
accepts only oneinput.
Input Output
X !X
0 1
1 0
24
Logical AND (&&) The output is true only if both inputs are true. It accepts
two or moreinputs.
Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1
Logical OR (||) The output is true only if any of its input is true. It accepts two or more
inputs.
Input Output
X Y X || Y
0 0 0
0 1 1
1 0 1
1 1 1
4. Assignment Operators: These are used to assign the result or values to a variable. The
different typesof assignment operators are:
Simple Assignment a = 10
Shorthand Assignment a += 10 a = a + 10
Multiple Assignment a = b = c = 10
5. Bitwise Operators: These works on bits and performs bit by bit operations. The
different types ofbitwise operators are:
i. Bitwise NOT (~)
ii. Bitwise AND (&)
iii. Bitwise OR (|)
iv. Bitwise XOR (^) Output is True when odd number of 1‟s are present.
v. Bitwise left shift (<<)
vi. Bitwise right shift (>>)
X ~X
0 1
1 0
25
Bitwise AND (&), Bitwise OR (|),Bitwise XOR (^)
Bitwise Left Shift (<<) Shift specified number of bits to left side.
X 0 1 0 0 0 1 1 0
X<<2 0 0 0 1 1 0 0 0
Bitwise Right Shift (>>) Shift specified number of bits to right side.
X 0 1 0 0 0 1 1 0
X>>2 0 0 0 1 0 0 0 1
Pre-increment Post-increment
First value of the operand is incremented First value of the operand is used for evaluation
(added) by 1 then, it is used for evaluation. then, it is incremented (added) by 1.
Ex: - -a Ex: a- -
26
7. Conditional Operator/ Ternary Operator (?:)
C Language has an unusual operator, useful for making two way decisions.
This operator is combination of two tokens ? and : and takes three operands.
This operator is known as ternary operator or conditional operator.
Syntax:
Expression1 ? Expression2 : Expression3;
Where,
Expression1 is Condition
Expression2 is Statement Followed if
Condition is TrueExpression3 is Statement
Followed if Condition is False
Meaning of Syntax:
1. Expression1 is nothing but Boolean Condition i.e. it results into either TRUE or FALSE
2. If result of expression1 is TRUE then expression2 is executed
3. Expression1 is said to be TRUE if its result is NON-ZERO
4. If result of expression1 is FALSE then expression3 is executed
5. Expression1 is said to be FALSE if its result is ZERO
27
Type Conversion
Converting the value of one data type to another type is called as Type Conversion.
It occurs when mixed data occurs.
There are two types:
Here, the operand/ variables of smaller data type is automatically converted to data
type of largersize.
char int long int float double long double
Ex: int a = 5;
float b=25,c; a b c
c=a/b 5 25.0 0.25
printf(“%f”,c);
28
Following table provides the Precedence and Associativity of operators:
* Multiplication
/ Division Left to right 3
% Modulus
+ Addition
Left to right 4
- Subtraction
<< Left shift
Left to right 5
>> Right Shift
< Less than
<= Less than or equal to
Left to right 6
> Greater than
>= Greater than or equal to
== Equality
Left to right 7
|= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
29
?: Conditional expression Right to left 13
=
*= /= %=
+= -= &= Assignment operators Right to left 14
^= |=
<<= >>=
30
31