0% found this document useful (0 votes)
17 views

Chapter_1_Introduction to Algorithms and C

Uploaded by

sandipkalathoki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Chapter_1_Introduction to Algorithms and C

Uploaded by

sandipkalathoki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Course Instructor

Er. ANUJ GHIMIRE


Course Overview and
Objective
About Programming Fundamentals
 It is one of the most fundamental course of Computer
science.
 Will help to enable students to be acquainted with the
basic concept of programming methodology, using C
programming.
Objectives of Programming Fundamentals
 The main objective of the course is to:
 Develop the programming logic
 Teach the basic principle of programming.
 Develop skills for writing programming using C.
Evaluation Process
 Attendance
 Assignments
 Term Examinations
 MCQ
 Presentations or Report Submissions
DISCLAIMER
 This document does not claim any originality and
cannot be used as a substitute for prescribed textbooks.
 The information presented here is merely a collection
from various sources as well as freely available material
from internet and textbooks.
 The ownership of the information lies with the
respective authors or institutions.
Chapter 1: Introduction to
Algorithm and C

1.1: Fundamentals of Algorithms


Problem Solving Using Computer
 Problem is defined as the difference between an
existing situation and a desired situation.
 Solution is desired situation and has simplest form.
 If a problem is solved by computing using machine
called computer, then such process is called Problem
Solving using Computer.
Problem Solving Using Computer
 Steps in Problem Solving using Computer
 Problem Statement
 Algorithm
 Flowchart
 Coding
 Debugging and Testing
 Deployment
 Documentation
Algorithm
 It is a set of instructions or steps written in simple
language to perform a particular task.
 Features (Characterstics) of algorithm:
 Should be written in simple English language.
 Should be understandable and clear to any user
 Should be language independent (should not depend on
any particular programming language)
 Should consist of finite number of steps.
 Should not contain any ambiguous instructions or any
confusing statements.
 Should terminate after finite number of steps.
Algorithm
 Pseudocode
 English like steps that describe the solution.
 Pseudocode is an artificial and informal language that
helps programmers develop algorithms.
 Pseudocode is a ”text-based” detail (algorithmic) design
tool.
 The rules of Pseudocode are reasonably straightforward.
Algorithm
 Pseudocode to compute average grade of 10
students in a classroom.
 Set total to zero
 Set grade counter to one
 While grade counter is less than or equal to ten
 Input the next grade
 Add the grade into the total
 Set the class average to the total divided by ten
 Print the class average
Algorithm Example_1
Algorithm to add two numbers.
Step_1: Start
Step_2: Input two numbers as a and b
Step_3: sum = a + b
Step_4: Print the sum
Step_5: Stop
Algorithm Example_2
 Algorithm to compute average grade of 10 students in
a classroom.
Step_1: Start
Step_2: Set total to zero i.e. total=0.
Step_3: Set counter to one i.e. counter=1
Step_4: Read grade of a student.
Step_5: total=total+grade.
Step_6: Increase counter by 1 i.e. counter=counter+1
Step_7: Goto Step_4 until counter=10.
Step_8: Computer class average i.e. total/10
Step_9: Print class average
Step_10: Stop
Algorithm Example_3
 Algorithm to find Area and Perimeter of Square.
Step_1: Start
Step_2: Input side length of square say L
Step_3: Area = L x L
Step_4: Perimeter = 4 x L
Step_5: Display Area, Perimeter.
Step_6: Stop
Algorithm Example_4
 Algorithm to swap two numbers using temporary
variable.
Step-1: Start
Step-2: Input two numbers say N1,N2
Step-3: Display before swapping N1, N2
Step-4: TEMP = N1
Step-5: N1 = N2
Step-6: N2 = TEMP
Step-7: Display after swapping N1,N2
Step-8: Stop
Algorithm Example_5
 Algorithm to swap two numbers without using
temporary variable.
Step-1: Start
Step-2: Input two numbers say N1,N2
Step-3: Display before swapping N1, N2
Step-4: N1 = N1 + N2
Step-5: N2 =N1 - N2
Step-6: N1 = N1 - N2
Step-7: Display after swapping N1,N2
Step-8: Stop
Algorithm Example_6
 Algorithm to count positive number from set of
integers.
Step-1: Start
Step-2: Input the set of integers say integer[n]
Step_3: Set positive_number to zero i.e. positive_number=0.
Step_4: Set index to zero i.e. index=0
Step_5: Read integer[index].
Step_6: Check if integer[index]>0.
Step_7: Increase positive_integer by 1.
Step_8: Goto Step_5 until index=n-1.
Step_9: Print positive_integer.
Step_10: Stop
Algorithm Example_7
 Algorithm to find summation of set of
numbers.
Step-1: Start
Step-2: Input the set of numbers say num[n]
Step_3: Set sum to zero i.e. sum=0.
Step_4: Set index to zero i.e. index=0
Step_5: Read num[index].
Step_6: sum=sum + num [index].
Step_7: Goto Step_5 until index=n-1.
Step_8: Print sum as summation of set of integers.
Step_9: Stop
Algorithm Example_8
 Algorithm to reverse the digit of an integer
Step-1: Start
Step-2: Read the input number from the user say N
Step_3: Initialize a variable named ‘reverse’ to 0 (zero).
Step_4: While the input number is not equal to 0, repeat
Step_5 to Step_8
Step_5: Extract the last digit of the input number using the
modulo operator and store it in a variable named
‘digit'
Step_6: Multiply the 'reverse' by 10
Step_7: Add the ‘digit' to the 'reverse'
Step_8: Divide N by 10 to remove the last digit.
Step_9: Print the value of the 'reverse'
Step_10: Stop
Algorithm Example_9
 Algorithm to find smallest positive
divisor of an integer other than 1

Do Yourself !!!!
Algorithm Example_10
 Algorithm to find GCD and LCM of two number
Step-1: Start
Step-2: Read two number say A & B.
Step_3: If (A > B) then set N =A and D=B
else N=B and D=A
Step_4: Compute R= N/D.
Step_5: Repeat Step_5 until R not equal to 0 (zero)
N=D
D=R
R=N%D
Step_6: Print D as GCD.
Step_7: LCM = (A*B)/GCD
Step_8: Print LCM
Step_9: Stop
Algorithm Example_11
 Algorithm to find if a number is prime or
not

Do Yourself !!!!
Notations of Algorithms
 Analysis of Algorithms is a fundamental aspect of
computer science that involves evaluating performance of
algorithms and programs.
 Efficiency is measured in terms of time and space.
 Since memory is extensible but not time so the efficiency of
algorithm is determined on how efficiently it uses time.
 The running time of a program is a function of n, where n
is the size of input data.
 The rate at which the running time of an algorithm
increases as a result of an increase in the volume of input
data is called the order of growth of the algorithm.
Notations of Algorithms
 The order of growth of an
algorithm is defined by using big
O notation.
 The big O notation has been
accepted as a fundamental
technique for describing the
efficiency of an algorithm.
 The following table lists some
possible order of growths and
their corresponding big O
notation.
Notations of Algorithms
 Asymptotic Notation
 The Asymptotic efficiency of algorithms are concerned
with how the running program increases with the size of
the input ‘n’ the input limit as the size of the input
increases without bound.
 Several asymptotic notations
 Big-Oh notation(O)
 Omega notation(Ω)
 Theta notation(Ɵ)
Approaches of Programming
 Different approaches of programming are:
 Procedural Approach.
 Object Oriented Approach.
 Event Driven Approach.
Procedural Approach
 Procedural Programming can be defined as a
programming model which is derived from structured
programming, based upon the concept of calling
procedure.
 Procedures, also known as routines, subroutines or
functions, simply consist of a series of computational
steps to be carried out.
 During a program’s execution, any given procedure might
be called at any point, including by other procedures or
itself.
 Example: FORTRAN, ALGOL, COBOL, BASIC, Pascal
and C.
Object Oriented Approach
 Object-oriented programming can be defined as a
programming model which is based upon the concept of
objects.
 Objects contain data in the form of attributes and code in the
form of methods.
 In object-oriented programming, computer programs are
designed using the concept of objects that interact with the
real world.
 Object-oriented programming languages are various but the
most popular ones are class-based, meaning that objects are
instances of classes, which also determine their types.
 Example: Java, C++, C#, Python, PHP.
Event Driven Approach
 Event-driven programming (EDP) is a programming
paradigm where external events determine the flow of
program execution.
 These events come in different shapes: user actions (e.g.,
button clicks, keyboard inputs), system events (like a
finished file download), messages from other programs,
sensor outputs, etc.
Event Driven Approach
 Unlike procedural and object oriented programming
(which generally follow predefined execution steps or
sequences), in EDP, the program waits (listens) for events
and reacts to them as they occur, by using appropriate
event-handling procedures.
 This allows for greater flexibility and responsiveness in
applications.
 Example: Java framework JavaFX, Node. js
Introduction to C
 C is a general-purpose high level language that was
originally developed by Dennis Ritchie for the Unix
operating system.
 The Unix operating system and virtually all Unix
applications are written in the C language.
 C has now become a widely used professional language
for various reasons.
 Easy to learn
 Structured language
 It can be compiled on a variety of computers
C-Compiler
 When you write any program in C language then to run
that program you need to compile that program using a
C Compiler which converts your program into a
language understandable by a computer.
 This is called machine language (ie. binary format).
 So before proceeding, make sure you have C Compiler
available at your computer.
 Some examples of C compilers are Turbo C and
Borland C
Structure of C Program
 The basic structure of a C program is divided into 6 parts
which makes it easy to read, modify, document, and
understand in a particular format.
 C program must follow the below-mentioned outline in
order to successfully compile and execute.
 Debugging is easier in a well-structured C program.
 A C program basically has the following form:
 Documentation
 Preprocessor Section
 Definition
 Global Declaration
 Main() Function
 Sub Programs
Structure of C Program
 Documentation
 The documentation section consists of a set of comment
lines giving the name of the program, the author and
other details, which the programmer would like to use
later.
// description, name of the program, programmer name, date, time etc.

/*
description, name of the program, programmer
name, date, time etc.
*/
Structure of C Program
 Preprocessor Section
 All the header files of the program will be declared in the
preprocessor section of the program.
 Header files help us to access other’s improved code into
our code.
 A copy of these multiple files is inserted into our program
before the process of compilation.
 The link section provides instructions to the compiler to
link functions from the system library.
#include<stdio.h>
#include<math.h>
Structure of C Program
 Definition #define pi 3.1415
 The definition section defines all symbolic constants.
 The #define preprocessor is used to create a constant
throughout the program. Whenever this name is
encountered by the compiler, it is replaced by the actual
piece of defined code.
 Global Declaration
 The global declaration section contains global variables,
function declaration, and static variables.
 Variables and functions which are declared in this scope can
be used anywhere in the program.
Structure of C Program
 Main() Function
 Every C program must have a main function.
 The main() function of the program is written in this
section.
 Operations like declaration and execution are performed
inside the curly braces of the main program.
 The return type of the main() function can be int as well
as void too.
 void main () tells the compiler that the program will not
return any value. The int main() tells the compiler that
the program will return an integer value.
Structure of C Program
 Sub Programs
 User-defined functions are called in this section of the
program.
 The control of the program is shifted to the called
function whenever they are called from the main or
outside the main() function.
 These are specified as per the requirements of the
programmer.
Structure of C Program
Sample C Program
 Comments are used to give additional useful information
inside a C Program.
 All the comments will be put inside /*...*/ as given in the
example above.
 A comment can span through multiple lines.
 Note the followings:
 C is a case sensitive programming language. It means in C
printf and Printf will have different meanings.
 C has a free-form line structure.
 End of each C statement must be marked with a semicolon.
 Multiple statements can be one the same line.
 White Spaces (ie tab space and space bar) are ignored.
 Statements can continue over multiple lines.
Fundamentals of C Program
 These are concerned with the basic elements used to
construct simple C statements.
 These elements includes:
 C character set
 Identifiers and Keywords
 Constants, Variables and Arrays
 Data Types
 Declaration, Expressions and Statements.
C Character Set
 The characters that can be used to form words, numbers
and expressions during writing a C program are called C
Character Set.
 The characters in C are grouped into the following
categories:
 Letters
 Digits
 Special characters
 White spaces
Identifiers and Keywords
 Every C word is classified as either a keyword or an
identifier.
 All keywords have fixed meanings and these meanings
cannot be changed.
 Keywords serve as basic building blocks for program
statements.
Identifiers and Keywords
 Identifiers refer to the names of variables, functions and
arrays.
 These are user-defined names and consist of a sequence
of letters and digits, with a letter as a first character.
 Both uppercase and lowercase letters are permitted,
although lowercase letters are commonly used.
 The underscore character is also permitted in
identifiers.
 It is usually used as a link between two words in long
identifiers.
Identifiers and Keywords
 Rules for defining Identifiers:
 First character must be an alphabet (or underscore).
 Must consist of only letters, digits or underscore.
 Only first 31 characters are significant.
 Cannot use a keyword as an identifier.
 Must not contain white space.
Constants and Variables
 Constants in C refer to fixed values that do not change
during the execution of a program.
 C supports several types of constants as follows:
Constants and Variables
 A variable is an identifier that is used to represent
some specified type of information within a designated
portion of the program.
 A variable in C language is the name associated with
some memory location to store data of different types.
 Each variable in C has an associated data type which
specifies the type of data that the variable can store like
integer, character, floating, double, etc.
 Each data type requires different amounts of memory
and has some specific operations which can be
performed over it.
Constants and Variables
 For example, a 250 CC cup is a variable and the tea in
the cup is a data item.
 We can put other than the tea like water or coffee etc.
but characteristics of the cup remain the same.
 It means, the information (tea or water or coffee)
represented by the variable can change but the data type
associated (characteristics of the cup like size, color
etc.) with the variable can not be changed during the
execution of program.
Constants and Variables
 Rules for defining Variables names:
 First character must be an alphabet (or underscore).
 Must consist of only letters, digits or underscore.
 Only first 31 characters are significant.
 Cannot use a keyword as a variable name.
 Must not contain white space.
Data Types in C
 In computer science, a data type is defined as a name
or label for a set of values.
 These are used to defined the kind of data being stored
or manipulated.
 In programming, the data type specifies the range of
values that a variable or constant can hold and how that
information is stored in the computer memory.
 The variety of data types available allow the
programmer to select the type appropriate to the need
of the application as well as the machine.
Data Types in C
 Primitive Data Types
 Primitive data types are the most basic data types that are
used for representing simple values such as integers,
float, characters, etc.
 Derived Data Types
 The data types that are derived from the primitive or
built-in datatypes are referred to as Derived Data Types.
 Eg. Array, Pointers, Function
 User Defined Data Types
 he user-defined data types are defined by the programmer
for his convenience. Eg. Structure, Union, Enum.
Data Types in C
 Data type used in C programming :
Integer Data Type
 The integer datatype in C is used to store the integer
numbers (any number including positive, negative and zero
without decimal part).
 Syntax for integer data type int var_name;
 The integer data type can also be used as
 unsigned int: This data type in C is used to store the data
values from zero to positive numbers but it can’t store negative
values like signed int.
 short int: It is lesser in size than the int by 2 bytes so can only
store values from -32,768 to 32,767.
 long int: Larger version of the int datatype so can store values
greater than int.
 unsigned short int: Similar in relationship with short int as
unsigned int with int.
Integer Data Type
Character Data Type
 Character data type allows its variable to store only a
single character.
 The size of the character is 1 byte.
 Syntax for char data type char var_name;
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
Float Data Type
 In C programming float data type is used to store
floating-point values.
 Float in C is used to store decimal and exponential
values.
 It is used to store decimal numbers (numbers with
floating point values) with single precision.
 Syntax for char data type float var_name;
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f
Double Data Type
 A Double data type in C is used to store decimal
numbers (numbers with floating point values) with
double precision.
 It is used to define numeric values which hold numbers
with decimal values in C.
 The double data type is basically a precision sort of data
type that is capable of holding 64 bits of decimal
numbers or floating points.
 Syntax for char data type double var_name;
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf
Void Data Type
 The void data type in C is used to specify that no value is
present.
 It has no values and no operations.
 Void is used in multiple ways as function return type,
function arguments as void and pointers to void
 Size of Data Types in C
 The size of the data types in C is dependent on the size of
the architecture, so we cannot define the universal size of
the data types.
 For that, the C language provides the sizeof() operator to
check the size of the data types.
Scope of a Variable
 The scope of a variable in C is the block or the region in
the program where a variable is declared, defined, and
used.
 Outside this region, we cannot access the variable, and
it is treated as an undeclared variable.
 The scope is the area under which a variable is
visible.
 The scope of a variable is the part of the program
where the identifier may directly be accessible.
 We can only refer to a variable in its scope.
Scope of a Variable
 C scope rules can be covered under the following two
categories:
 Global Scope
 Local Scope
 The global scope refers to the region outside any block
or function.
 The variables declared in the global scope are called
global variables and are visible in every part of the
program.
Scope of a Variable
 The local scope refers to the region inside a block or a
function.
 It is the space enclosed between the { } braces.
 The variables declared within the local scope are called
local variables and are visible in the block they are
declared in and other blocks nested inside that block.
 Local scope is also called Block scope.
Scope of a Variable
End of Chapter 1
Thank You !!!!

You might also like