UNIT 1 Introduction To Programmming and Problem Solving
UNIT 1 Introduction To Programmming and Problem Solving
UNIT – 1
INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING
HISTORY OF COMPUTERS
To perform computations we use machines.
The earliest tool is abacus, a device used in china and United States
today as a hand held calculator.
They require human involvement.
The first attempt was made by Charles Babbage in creating a
programmable computing machine in England in 1822.
Ada Byron the daughter of famous poet Lord Byron developed the
instruction set for the machine.
The machine that Babbage called it was analytical engine.
In 1937, Dr. John V Atanasoff and a graduate student, Clifford Berry
developed a machine called ABC using electrical components at Lowa
State University.
The goal internally was to store a set of instructions. In 1939, Dr.
John W Mauchly from Moore college of Engineering at Pennsylvania
University along with Presper Eckert developed a computer called
ENIAC( Electrical Numerical Integrator And Computer).
The fund was given by US government and was completed in 1946.
It consists of 18000 vacuum tubes and can perform 5000 additions
and 360 multiplications in one second.
At the same time Mark developed a computer by name Mark I at
Harvard University using mechanical relays and completed in 1944.
But it could perform only 6 multiplications in one second.
The final goal of storing the program in computer was achieved in
1949 at Cambridge University with the successful operation of
EDSAC(Electronic Delayed Storage Automatic Computer).
This contains memory where it could store data.
The principles for storing the data and retrieve data and instructions
has been proposed by John Von Neumann.
INPUT UNIT
Computers need to receive data and instruction in order to solve any
problem.
We need to input the data and instructions into the computers.
The input unit consists of one or more input devices.
Keyboard is the one of the most commonly used input device.
Other commonly used input devices are the Mouse, Scanner,
Microphone, etc.
All the input devices perform the following functions.
Accept the data and instructions from the outside world.
Convert it to a form that the computer can understand.
Supply the converted data to the computer system for further
processing
OUTPUT UNIT
The output unit of a computer provides the information and results of
a computation to outside world.
Printers, Visual Display Unit (VDU) are the commonly used output
devices.
Other commonly used output devices are Speaker, Headphone,
Projector, etc.
a) Primary Storage
Stores and provides very fast.
This memory is generally used to hold the program being currently
executed in the computer, the data being received from the input unit,
the intermediate and final results of the program.
The primary memory is temporary in nature.
The data is lost, when the computer is switched off.
In order to store the data permanently, the data has to be transferred
to the secondary memory.
The cost of the primary storage is more compared to the secondary
storage.
Therefore, most computers have limited primary storage capacity.
b) Secondary Storage
Secondary storage is used like an archive. It stores several programs,
documents, data bases etc.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
4
Introduction To Programming
The programs that you run on the computer are first transferred to
the primary memory before it is actually run.
Whenever the results are saved, again they get stored in the secondary
memory.
The secondary memory is slower and cheaper than the primary
memory.
Some of the commonly used secondary memory devices are Hard disk,
CD, etc.,
c) Memory Size
All digital computers use the binary system, i.e. 0’s and 1’s.
Each character or a number is represented by an 8-bit code.
The set of 8 bits is called a byte.
A character occupies 1-byte space.
A numeric occupies 2-byte space.
Byte is the space occupied in the memory.
The size of the primary storage is specified in KB (Kilobytes) or MB
(Megabyte).
One KB is equal to 1024 bytes and one MB is equal to 1024KB.
The size of the primary storage in a typical PC usually starts at 16MB.
PCs having 32MB, 48MB, 128MB, 256MB memory are quite common.
PROGRAM COUNTER
A register is a small place for data holding that the processor uses.
Program counter is just a small register that could hold 8 bit or 16 bit
data.
It depends on the processor that process data either 8 bit or 16 bit.
In computing, a program is a specific set of ordered operations for a
computer to perform.
An instruction is an order given to a computer processor by a
program.
Within a computer, an address is a specific location
in memory or storage.
MACHINE LANGUAGE
Machine language is referred as first generation languages.
It is also known as low level language.
It was introduced in the year 1940.
Computer is an electronic device that can understand only binary
codes hence the computer instructions and data are written using
binary codes 1 and 0.
The binary code is called machine code or machine language.
All computer designs are not same because they have their own
machine language and they cannot understand any language like
English, Telugu, Tamil etc except machine language.
There are some problems with the machine language.
It is difficult to understand and remember the various
combinations of 0’s and 1’s for instructions and data.
Writing error free instructions is a slow process.
The user cannot communicate with other machine because
every machine has its own machine language
Natural languages
These languages are known as fifth generation languages.
These languages are designed to make computer to behave like expert
and solve problems.
The programmer specifies both the problem and its constraints for
problem solving.
These languages are used to develop artificial intelligence and
expert systems.
The fifth generation languages allow users to communicate with the
computer in simple and easy manner.
Class is the basic building block of the OOP, a class consists data
attributes and methods that operate on data.
Object is runtime instance of the class. An object has a state, a defined
behavior and unique identity.
The state of the object is represented by the data defined in the class.
Class is template for object.
Abstraction, Encapsulation, Inheritance and Polymorphism are unique
features of OOP
Structure of Algorithm
The structure contains the following steps:
Input Step
Assignment Step
Decision Step
Repetitive Step
Output Step
Properties of Algorithms
Finiteness: An algorithm must terminate after a finite number of
steps.
Definiteness: The steps of the algorithm must be precisely defined or
unambiguously specified.
Generality: An algorithm must be generic enough to solve all
problems of a particular class.
Effectiveness: The operations of the algorithm must be effective such
that it must easily converted into machine code in a finite amount of
time.
Input-Output: The algorithm must have zero, one or more inputs and
one or more outputs.
FLOW CHARTS
Flow chart is diagrammatic representation of an algorithm.
It is built using different types of boxes of symbols.
The operation to be performed is written in the box.
Example:
PSUEDO CODE
The enhanced form of an algorithm that focuses on logic of the
program is called pseudo code.
It refers to false code written in a programming language.
It does not have any syntax for representation but normally used
structured English language for representation.
It helps programmer to understand the basic logic before writing the
final code in a particular language.
EXAMPLE
To add two numbers
1. DEFINE n1, n2, result
2. READ n1, n2
3. COMPUTE result – n1 + n2
4. DISPLAY result
5. EXIT
Compiling Programs
The job of the compiler is to convert the source file into machine
language.
There are two separate programs in C compiler:
Preprocessor
Translator
The preprocessor reads the source code and prepares it for the
translator. It scans for preprocessor commands and tell to replace the
code.
The result of preprocessing is translation unit.
The translator does the actual work of converting the program to
machine language. The translator reads translation unit and produce
object module as output
This is not yet ready to run because it needs required functions to
include.
Linking Programs
C program is made up of many functions, some we write and some
they are part of the source program
There are other functions like input/output and mathematical
libraries that are attached to source program
The linker assembles all these functions to make it finally executable.
Executing Programs
The program is ready for execution if it is linked with necessary
routines.
To execute the program we use OS command run to load the program
in main memory and execute it.
The loading activity is done by loader.
The program execution means
Reads data for processing from file or from user
Process the data
Prepare the output for the user
STRUCTURE OF A C PROGRAM
Every C program is made up one or more preprocessor commands, a
global declaration section and one or more functions
The global declaration section is before main function. It is visible to
all parts of the program
The work is carried out by its functions. One function is main(). It
indicates the beginning of the program.
All functions in the program including main are divided into two parts:
declaration and statements
Preprocessor Commands
They come at the beginning of the program.
They start with pound sign (#).
They are special instructions to the preprocessor to prepare the
program for compilation.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
17
Introduction To Programming
main()
The executable part of the program begins at this point.
The syntax is int main(void)
int specifies that the function returns an integer value to the
operating system
main is the name of the function
void means it has no parameters
Within main there are two statements: one that print message and the
other to terminate the program
The print function used library function printf to print the message on
the monitor. Where the message is a parameter in between the double
quotes to printf statement
The second statement is return 0 to terminate the program and
indicate the OS for successful execution of the program.
The main has two braces ‘{‘ opening brace and ‘}’ closing brace. The
opening brace indicates the beginning of the program and closing
brace indicates the ending of the program.
Comments
Comments are two types: block comment and line comment
Block comment is to span several lines. It uses opening and closing
comment tokens
A token is a symbol understood by the compiler.
Each comment token is made of two characters /* indicating the
beginning of the comment and */ indicating the ending of the
comment.
The comment should be in between /* and */
For example,
/* ---------------------------
---------------------------
---------------------------
--------------------------- */
A line comment uses two slashes to identify the comment. This does
not require end of the comment.
For example,
//-------------------------------
Comments cannot be nested. For example as shown below:
Void Type
The void type is specified by keyword void which means no value or no
operations
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
19
Introduction To Programming
Integral Type
C has three integral types: boolean, character and integer.
They contain only integral part but not fractional part
Boolean Type
In C99, we have boolean data type.
It was introduced by french mathematician George Boole.
It represents two values true and false
The boolean values: true represents non zero for positive or negative
and false represents zero.
The boolen type is referred by bool keyword.
In memory 0 is stored for false and 1 for true
Character Type
A character is any value represented for alphabets in computer known
as character set.
C has two characters types: char and wchar_t
The size of character type is one byte.
It can be signed or unsigned it takes one byte.
If signed its range is -128 to 127 and if unsigned it is 0 to 255.
The characters are grouped into letters, digits, special symbols and
punctuations.
The letters can be lower or upper case.
The difference between letter a and letter x is : the binary number to
store in memory and the ascii value fr them is 97 and 122.
To support non english characters we used wchar_t.
Integer Type
It is a number without fractional part.
It supports four types: short int, int, long int, long long int
sizeof(short)<sizeof(int)<sizof(long)<sizeof(long long)
They are machine dependent and if size is not known we use sizeof
operator to know the size.
Integer can be signed or unsigned. If signed then one bit is used for
sign representation.
C provides limits.h that contains size information about integers.
The unsigned integer can be used to store positive numbers.
Real Type
It contains both integral and fractional part.
C supports different real types are: float, double, long double
They can be organized from small to large
sizeof(float)<sizeof(double)<sizof(long double)
Imaginary Type
An imaginary number is a real number multiplied by square root of -1.
It can be of three different sizes: float imaginary, double imaginary
and long double imaginary.
Complex Type
It is a combination of real and imaginary number separated by a plus
sign.
It can be of three different sizes: float complex, double complex and
long double complex.
Size need to be same for real and imaginary.
VARIABLES
A variable is a named memory location that can be of type such as int,
float, char.
A variable is a data name which can be used to store a data value and
a variable may take different values at different times, during
execution.
Variable Declaration
Each variable in the program must declare before it is used.
The declared is used to name an object but definition is used to create
an object.
A variable can be defined and declared at the same time.
A variable cannot be of type void.
To create variables we first specify type and then its name.
The syntax is
datatype variable_name;
For example,
int n;
float x;
char y;
bool z;
Variable Initialization
The process of assigning a value to a variable is called intialization.
The process of giving a value to a variable is called initialization.
The process of presenting a value to a variable is called initialization.
The process of specifying a value to a variable is called initialization.
For example:
x = 10;
in the above statement the variable is “x” and the value is “10”. Here
the value 10 is given to the variable x by using assignment operator “=”.
Therefore if we want to assign a value to a variable then we need an
assignment operator. The variable here used “x” is called initialized variable.
For example:
int x=10;
float y=2.5;
char = ‘a’;
in the above statements the variables are initialized to values that are
of different data type. The variables are called initialized variables or
variables are said to be initialized.
CONSTANTS
Constants are fixed values that cannot be changed during program
execution.
Constants are data values that never changes during execution of a
program.
They have type like variables.
Constant Representation
The different types of constants are
Boolean constants
Character constants
Integer constants
Real constants
Complex constants
String constants
Boolean Constants
A boolean data type can take two values either true or false.
The boolean values we can have may be 1 for true and 0 for false.
We have to include stdbool.h header file
Character Constants
They are enclosed between two single quotes.
In addition we can use a backslash before a character known as
backslash character constant.
It is known as escape sequence.
The escape character says that what follows is not the normal
character but something else.
For example, \n represents new line feed.
It is of multiple symbols but represents always one character.
Wide character constants can be coded by prefixing a letter L. For
example, L ‘x’
The different backslash character constants are
Integer Constants
Integer constants are coded in simple way. For example the value 15
is coded as 15.
If we code the number as a series of digits, its type can be signed or
unsigned.
The types of integers are: int, short int, long int, long long int
The different ways to represents long int and long long int is l or L and
ll or LL.
For unsigned it is u or U.
To avoid confusion we represent capital letters only.
Real Constants
The default form of real value is double.
If we want the result to be float or long double then use f or F for float
and l or L for long double
Complex Constants
They are code as two parts: real part and imaginary part, separated by
a plus sign.
We should use complex.h header file.
The real value of complex has same rules as real constant and
imaginary is coded as real number times the imaginary constant
denoted as I.
String Constants
A sequence of zero or more characters enclosed between double
quotes is called string constant.
The difference between null string and empty string is shown below
‘\0’ is null string
“ “ is empty string
Coding constants
The different coding constants are
Literal constants
Defined constants
Memory constants
Literal Constants
It is an unnamed constant used to specify data.
They can be simply used in the statement if it does not need to be
changed
They are coded as a part of the statement as follows
a=b+5
Defined Constants
They are defined by using a preprocessor command.
They are placed at the beginning of the program.
For example,
#define PI 3.14
Memory Constants
They use C type qualifier denoted by const to indicate the data cannot
be changed.
For example,
const float cpi = 3.14
BASIC INPUT / OUTPUT
Streams
A stream is a source or destination for data.
Data is input to and output from a stream.
It is associated with physical device.
C uses two types of streams: text and binary.
A text stream consists of sequence of characters where each line is
terminated by new line.
A binary stream consists of sequence of data values such as integers,
float etc.
Terminal is associated with text stream, to take input by keyboard
and output by monitor.
The keyboard is standard input and monitor is standard output
For example
NEW DELHI
Then only the NEW of the string NEW DELHI will be read into the
address because after NEW there is blank space so the scanf() function
terminates reading the string.
Format Modifiers
The different types of format modifiers are as follows:
%d - decimals or integers
%f - floats
%c - characters
%s - strings
%e - exponentiation
%g - double
%o - octal
%h - hexa decimal
Left justification
Numbers displayed using printf() statement by using right justification
but if you want to get the output to be left justified then we have to use a (-)
sign format modifier.
printf(“%-10d”, 78);
produces output
78
Explicit Sign Display
Normally, the sign of a number is to display for negative numbers. But
for positive and negative numbers signs to be displayed we use a (+) format
modifier.
printf(“%+10d”, 78);
+78
OPERATIONS
An operator is a symbol that performs an operation like arithmetic
operations, logical operations, conditional operations, etc. These operations
are performed using different types of operators. They are listed below:
1. arithmetic operators
2. relational operators
3. logical operators
4. increment and decrement operators
5. conditional or ternary operators
6. assignment operators
7. bitwise operators
8. special operators
Arithmetic Operators
The arithmetic operators that we come across in ‘C’ language are +, -,
*, /and %.
If one of the operand is real and other is integer then the expression is
called mixed-mode arithmetic expression. Here only the real operation is
performed and the result is always in real form.
Relational Operators
The relational and equality operators are used to test or compare
values between two operands.
The relational and equality operators produce an integer result to
express the condition of the comparison.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
31
Introduction To Programming
Operator Meaning
== Is equal to
!= Is not equal to
Ex:
int x, y, z;
z=x<y;
z=x>y;
z=x<=y;
z=x>=y;
z=x==y;
z=x!=y;
Logical Operators
Logical operators are used to combine two or more relations.
The logical operators are called Boolean operators. Because the tests
between values are reduced to either true or false, with zero being
false and one being true.
Operator Meaning
|| Logical OR
! Logical NOT
a++ and ++a is the same when the statements are independent like
a=5; a=5;
a++; ++a;
In the both cases a value will be 6.
Ex:
y=(x>5? 3:4) is equivalent to if(x>5)
then
y=3;
else
y=4;
Assignment Operators
Values can be assigned to variables using the assignment operator ‘=’
as follows:
Variable_name=constant;
Ex: balance=1278;
Yes=’x’;
C permits multiple assignments in one line. For example,
balance=1278;Yes=’x’; are valid statements.
An assignment statement implies that the value of the variable on the
left of the ‘equal sign’ is set equal to the value of the quantity (or the
expression) on the right.
The statement year=year+1; means that the ‘new value’ of year is
equal to the ‘old value’ of year plus 1.
It is also possible to assign a value to a variable at the time the
variable is declared. This takes the below form:
Ex:
X+ = y is equivalent to x= x + y
x- = y is equivalent to x= x - y
x*=y is equivalent to x=x*y
x/=y is equivalent to x=x/y
x%=y is equivalent to x=x%y
Bitwise Operators
‘C’ has a distinction of supporting special operators known as
bitwise operators for manipulation of data at bit level.
These operators are used for testing the bits, or shifting them right or
left. Bitwise operators may not be applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ One's complement
Special Operators
‘C’ supports some special operators such as comma operator, sizeof
operator etc.
Ex: m=sizeof(sum);
n=sizeof(long int);
Structure of Algorithm
The structure contains the following steps:
Input Step
Assignment Step
Decision Step
Repetitive Step
Output Step
CHARACTERISTICS OF ALGORITHMS
Finiteness: An algorithm must terminate after a finite number of
steps.
Definiteness: The steps of the algorithm must be precisely defined or
unambiguously specified.
Generality: An algorithm must be generic enough to solve all
problems of a particular class.
EXAMPLES
Algorithm for adding two numbers
Step1: Start
Step2: Read two numbers a, b
Step3: Compute result=a + b
Step4: Display the result
Step5: Stop
BOTTOM UP APPROACH
It is one in which the smaller problems are solved, and then these
solved problems are integrated to find the solution to a bigger
problem.
Iit uses composition approach to do it.
It requires a significant amount of communication among different
modules.
It is generally used with object oriented programming paradigm such
as C++, Java, and Python.
Data encapsulation and data hiding is also implemented in this
approach.
The bottom-up approach is generally used in testing modules.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
40
Introduction To Programming
Analysis of Algorithms
It is a technique to compare efficiency of different algorithms
The speed of an algorithm can be different on different computers(time
taken will be different)
For example
Let us consider three program segments as follows:
Segment – A
x= x+1;
It is executed only once. Hence frequency count is 1.
Segment – B
for(i=1;i<n;i++)
{
printf(“%d”,i);
}
The frequency count is reprsented as
i=1 ---------------> 1
i<n ----------------> n+1
i++ ----------------> n
printf(“%d”,i) ----------------> n
1 + (n+1) + n + n
= 3n + 2
Segment – C
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(“%d”,i);
}
}
The frequency count is reprsented as for the first for loop the
frequency count is
1+(n+1) +n+n = 3n+2
Total frequency count is
(2n+2) * (3n+2)
= 6n2 + 4n + 6n + 4
= 6n2 + 10n + 4
Now computing time complexity is very freom frequency count.
for Segment – A it is O(1)
for Segment – B it is O(n)
for Segment – C it is O(n2)
For example:
6n2 + 10n + 4
The above equation remove constants and see the higher of n
representation. It is n2.
time complexity is O(n2)
Analyzing Algorithms
Suppose “M” is an algorithm, and suppose “n” is the size of the input
data. Clearly the complexity f(n) of M increases as n increases.
It is usually the rate of increase of f(n) with some standard functions.
The most common computing times are
O(1), O(log2 n), O(n), O(n log2 n), O(n2), O(n3), O(2n)
When we have two algorithms to perform the same task and if first
one time complexity is O(n) and second one is O(n2) then we prefer
first one since as n increases the time required for execution of second
one is taking more time than the first one.
Here we discuss about three cases for the efficiency of the algorithm.
Best case – 1
Worst case – n
Average case – (n+1)/2
If the algorithm takes minimum amount of time to run for its
completion then it is called best case time complexity
If the algorithm takes maximum amount of time to run for its
completion then it is called worst case time complexity
If the algorithm takes average amount of time to run for its completion
then it is called average case time complexity