0% found this document useful (0 votes)
15 views38 pages

Unit-1 Intro To Prog (AK23)

The document is a set of lecture notes for an Introduction to Programming course for B.Tech first-year students at Annamacharya Institute of Technology & Sciences. It covers the history of computers, basic computer organization, programming languages, and problem-solving techniques, detailing the evolution of computers through various generations and the components of a computer system. Additionally, it discusses programming concepts, types of software, and the differences between high-level and low-level programming languages.

Uploaded by

padhu6121985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views38 pages

Unit-1 Intro To Prog (AK23)

The document is a set of lecture notes for an Introduction to Programming course for B.Tech first-year students at Annamacharya Institute of Technology & Sciences. It covers the history of computers, basic computer organization, programming languages, and problem-solving techniques, detailing the evolution of computers through various generations and the components of a computer system. Additionally, it discusses programming concepts, types of software, and the differences between high-level and low-level programming languages.

Uploaded by

padhu6121985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

LECTURE NOTES

ON

INTRODUCTION TO PROGRAMMING
(Common to All Branches of Engineering)

2023 – 2024
B.Tech I-Year I-Semester
(Autonomous-AK23)

ANNAMACHARYA INSTITUTE OF TECHNOLOGY & SCIENCES, TIRUPATI


(Autonomous)

Approved by AICTE, New Delhi & Permanent Affiliation to JNTUA, Anantapuramu.


Two B.Tech Programmes (CSE & ECE) are accredited by NBA, New Delhi.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 1
INTRODUCTION TO PROGRAMMING
(Common to All Branches of Engineering)

UNIT 1
Introduction to Programming and Problem Solving
History of Computers, Basic organization of a computer: ALU, input-output units, memory, program counter,
Introduction to Programming Languages, Basics of a Computer Program-Algorithms, flowcharts (using Dia
Tool), pseudo code. Introduction to compilation and Execution, Primitive Data Types, Variables and
Constants, Basic Input and Output, Operations, Type conversion and Casting.
Problem solving techniques: Algorithmic approach, characteristics of algorithm, Problem solving strategies:
Top-down approach, Bottom-up approach, Time and space complexities of algorithms.

History of Computers (or) Evolution of Computers:

The history of computer begins with the birth of abacus which is


believed to be the first computer. It is said that Chinese invented Abacus
around 4,000 years ago. let us consider the development of a computer
through various stages.

1. Abacus:
* It was a wooden rack which has metal rods with beads mounted on them. 1. Abacus
* The beads were moved by the abacus operator according to some rules to
perform arithmetic calculations.
* Abacus is still used in some countries like China, Russia and Japan.

2. Napier’s Logs and Bone’s :


* Napier’s Bones was a manually operated calculating device and invented
by John Napier.
* This device used 9 different ivory strips (bones) marked with numbers to
multiply and divide for calculation.
* First machine to use the decimal point system for calculation.
2. Napier's Bones
3. Pascal’s Adding machine :
* Pascaline is also known as Arithmetic Machine or Adding Machine.
* First mechanical and automatic calculator by a French mathematician-
philosopher Biaise Pascal.
* It was a wooden box with a series of gears and wheels. When a wheel is
rotated one revolution, it rotates the neighbouring wheel. A series of
windows is given on the top of the wheels to read the totals. 3. Pascaline

4. Leibnitz wheel calculator :


* It was developed by a German mathematician-philosopher Gottfried
Wilhelm Leibnitz in 1673.
* He improved Pascal's invention to develop this machine. It was a digital
mechanical calculator which was called the stepped reckoner as instead of
gears it was made of fluted drums.
* It was able to perform multiplication & division.
4. Stepped Reckoner or Leibnitz wheel

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 2
5. Babbage’s Difference Engine :
* Charles Babbage developed a machine called difference engine In early
1820s.
* These machines calculate logarithmic tables to a high degree of precision.

6. Babbage’s Analytical Engine :


* Charles Babbage designs an analytical engine which begins a real model
of modern days computer in 1830.
* He included the concept of central process storage area, memory and
input/output.
5. Babbage’s Difference Engine
* Because of inventions of difference engine and analytical engine, Charles
Babbage has been considering as “Father of modern Computers”.
* It was a mechanical computer that used punch-cards as input. It was
capable of solving any mathematical problem and storing information as a
permanent memory.

7. Tabulating (or) Hollerith’s Machine :


* Herman Hollerith developed electro mechanical punched card in 1890,
that is used for input, output and storing of instructions.
* It could tabulate statistics and record or sort data or information. This
machine was used in the 1890 U.S. Census.
* Hollerith also started the Hollerith’s Tabulating Machine Company which
later became International Business Machine (IBM) in 1924. 6. Babbage’s Analytical Engine

8. Mark-1 :
* Howard Aiken contracted an electro mechanical computer named mark-1
In the year 1944.
* It could multiply two 10-digit number in 5-seconds.
* It was also the first programmable digital computer marking a new era in
the computer world.

9. ENIAC :
* Electronic Numerical Integrator and Calculator were built by Prof. Eckerit
and Mauchly. 7. Tabulating (or) Hollerith’s Machine
* It used about 19000 vacuum tubes and can perform about 300
multiplications per second.
10. EDSAC :
* Electronic Delay Storage Automatic Computer was developed by Maurice
willies.
* It has ability to input, output, staring the data.
* It also able to perform and control arithmetic calculations. 8. Mark-1
11. EDVAC :
* Electronic Discrete Variable Automatic Computer was developed by Prof.
Eckerit and Mauchly.
* In this both the data and instruction can be stored in binary form instead
of decimal number system.
12. UNIVAC :
* Universal Automatic Computer developed by Remington.
* It was cable of performing to access both numeric and alphabetic 9. ENIAC (Electronic Numerical
Integrator And Computer)
information.
13. UNIVAC-1:
* It is the first computer which is used for commercial purpose in 1954.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 3
Generations of Computers: .

Evolution of Modern Computers from the olden days is known as “Generation of Computers.”
Generations of computers are broadly classified based on the following characteristics:
* Increasing in storage capacity.
* Increasing in processing speed.
* Increasing reliability.
There are totally 5 generations of computers till today. They are,

First Generation Computers:


Period: (1945-1955)
Technology: Vacuum tubes
* The ENIAC was the first computer developed in this generation.
* It was capable of performing 5000 additions (or) 350 multiplications per second.

* It uses about 18000 vacuum tubes and it consumes 150 kw/hr.


Limitations:
The limitations of first-generation computers are as follows,
* Less operating capacity.
* High power consumption.
* Very large space requirement.
* Produce high temperature.
* Very costly.

Second Generation Computers:


Period: (1955-1965)
Technology: Transistors
* The second-generation computers use transistors as the main component in CPU.
* They are very small in size when compared to vacuum tubes and produce less heat.

* They are fast and reliable.


* By this invention of Transistors, the size, maintenance cost, power consumption has decreased.

* During this period magnetic storage devices have been started their development. Because of this,
speed and storage capacity has been increased.
* They are capable to perform 20,000 to 50,000 additions per second.

Third Generation Computers:


Period: (1965-1975)
Technology: Integra ted Circuits (IC)
* In this generation the computers used integrated circuits instead of Transistors
* IC is a miniature form of an electronic circuit made of silicon and enclosed in a metal package.
* These ICs are caused “chips.” The cost and size of the computers were greatly reduced.
* The magnetic disk technology has improved rapidly.
* It has capable to perform 10 million additions per second.

Fourth Generation Computers:


Period: (1975-1990)
Technology: Very Large Scale Integrated Circuit (VLSI)
* ICs packing nearly 10,000 transistors are grouped in to a single silicon chip known as
“microprocessor”.
* The computers which use microprocessors are called “Micro Computers”.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 4
* Intel Corporation invented the microprocessor in the year 1980 with this development the cost of
a computer has reduced a lot.
* The floppy disk technology was developed during this generation.

Fifth Generation Computers:


Period: (1990- till date)
Technology: Artificial Intelligence
* Artificial Intelligence is a technique by which we make
the computer to think and take decisions in its own.
* These computers are under research.
* Artificial Intelligence can be achieved by means of problem solving, Game playing, and Expert
systems.

Block Diagram of a Computer (or) Basic organization of a computer:


The word computer has been derived from the word “Compute” which means to calculate. It is an
electronic device which inputs the data, stores the data, processes the data and gives the result accurately
at a very high speed according to the instructions provided. (or)
A computer is an electronic machine that can be programmed to carry out sequences of arithmetic
or logical operations automatically that accepts raw data as input and processes it with a set of instructions
(a program) to produce the result as output.

Input Unit:
Computers need to receive data and instructions in order to solve any problem.
• The input unit consists of one or more input devices like keyboard, mouse, joystick etc.
• Regardless of the type of the input device used in a computer system, all input devices perform the
following functions.
o Accept the data
o Convert data to computer understandable form.
o Supply converted data for further processing.

CPU:
The actual processing of the data is carried out in the Central Processing Unit (CPU), which is the brain
of computer. The CPU stores the data and instructions in the primary memory of the computer, called the
Random Access Memory (RAM) and processes them from this location.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 5
• CPU stands for “Central Processing Unit.”
• CPU is like a computer Brain. It performs the following operations.
o It performs all calculations.
o It takes all decisions.
o It controls all units of computer.
• Control unit, Memory unit and Arithmetic logic unit of the computers are together known as central
processing unit.

The Control Unit (CU) and the Arithmetic Logic Unit (ALU) are the two subcomponents of the CPU.
The ALU carries out the arithmetic and logical operations while the CU retrieves the information from the
storage unit and interprets this information. The CPU also consists of circuitry devices called cache and
registers.

Control Unit:
• The control unit controls all other units in the computer.
• The control unit instructs the input unit where to store data after receiving it from the user.
• It also controls the flow of data and instructions from the memory unit to “ALU”.
• It controls the flow of results from ALU to output unit.

Arithmetic Logic Unit:


• All calculations are performed in ALU.
• It does comparisons and takes decisions.
• It can perform Basic Arithmetic operations like addition, subtraction as well as logical operations like
less than greater than.
• After performing calculations, the result is stored in memory unit.

Program Counter:
A program counter is a register in a
computer processor that contains the
address (location) of the instruction being
executed at the current time.
As each instruction gets fetched,
the program counter increases its stored
value by 1.

Memory Unit:
• Memory Unit of the computer holds data and instructions that we enter through the input unit.
• It is also used to preserve intermediate and final results before they are sent to the output unit.
• It is used to preserve the data for later usage.
• The various storage devices used for storage can be classified in to a categories namely,
o Primary Memory
o Secondary Memory
• Primary memory stores and provides information very fast but it loses the contents when we switch
off the computer.
• Secondary memory stores the data permanently. The program that we want to run on the computer
is first transferred to the primary memory from secondary.

Output Unit:
• The output unit of a computer provides information and results of an operation to the outside world.
• The output unit also converts Binary data to a form that uses can understand.
• The commonly used to output devices are Monitors, Printers, and Plotters.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 6
Introduction to Programming Languages: .
A programming language is a set of symbols, grammars and rules with the help of which one is able
to translate algorithms to programs that will be executed by the computer. The programmer communicates
with a machine using programming languages.
Program & Programming
• A program is a set of logically related instructions that is arranged in a sequence that directs the computer
in solving a problem.
• The process of writing a program is called programming.
• Software is a collection of computer programs and related data that provides the instructions for telling a
computer what to do and how to do it.
• Computer software broadly classified into two categories: a) System software and b) Application software
a) System Software:
• System software is a collection of programs that interfaces with the hardware.
• Categories of system software:

(or)

b) Application Software:
• Application software is written to enable the computer to solve a specific data processing task.
• Categories of application software:

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 7
Programming Language:
• A programming language is composed of a set of instructions in a language understandable to the
programmer and recognizable by a computer.
• Programming languages can be classified as,
(a) High-level language - BASIC, COBOL & FORTRAN (application programs)
(b) Middle level language - C (application & system programs)
(c) Low level language - assembly language (system programs)
• System programming language:
– It is designed to make the computer easier to use.
– For ex.: OS which control many other programs that control i/o devices, multiple tasks.
• Application programming language:
– It is designed for specific computer application such as payroll, inventory etc.
– Its 2 sub categories are:
• Business program
• Scientific Program

Low level & High level Languages:


• Machine Language (LOW):
– In these a sequence of instructions written in the form of binary number consisting of 1’s and 0’s to
which the computer responds directly. (it is also called as first generation language 1GL).
– For ex: 0011 1100 means, load A register with 7 value.
• Assembly language (LOW):
– When symbols such as letters, digits or special characters' are employed for operations, operands
& other parts of instruction code, the representation is called an assembly language instruction. It
is also 2GL.
– For Ex:- LD A 7 means, load A register with 7 value
• High Level Language:
– Having instruction that are similar to human languages and have a set grammar which makes
programmer to write program and identify and correct error in them.
– For Ex:- int a=7 means, a value is 7

COMPILER:
• For executing a program written in a high-level language, it must be first translated into a form the
machine can understand. This is done by a software called the compiler.
• The compiling process consists of two steps:
a) The analysis of the source program
b) Check for syntax error
• Compiler action:

INTERPRETER:
• During the process of translation There is another type of software that also does translation. This
is called an interpreter.
• Differences between compiler and interpreter:

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
Third, Forth & Fifth Generation Languages:
* The 3GLs are procedural in nature i.e., these languages specify “how to do”. Hence 3GLs require
the knowledge of complete steps to solve a problem.
* In case of 4GLs, they are non-procedural i.e., they specify “what to do”. Hence in 4GLs we need to
specify only what we required and rest gets done on its own
Advantages:
* Smaller code
* Reduced development time and maintenance cost
* Easy to programmers
* Doesn’t require a high knowledge on program GUI Based Languages
* With the invention of GUI based interfaces, many programming languages are developed
that help programmer to develop GUI applications.
* Some of the GUI based languages are,
* Visual Basic (VB)
* C#
* VB.Net
Classification of Programming Languages:

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 9
Basics of a Computer Program: .

Computer Programming is a set of instructions, that helps the developer to perform certain tasks that
return the desired output for the given valid inputs.

Example: Given below is a Mathematical Expression,

• Z = X + Y, where X, Y, and Z are the variables in a programming language.


• If X = 550 and Y = 450, value of X and Y are the input values that are called literals.
• To calculate the value of X+Y, which results in Z, i.e. the expected output.

A computer is a machine that processes information and this information can be any data that is
provided by the user through devices such as keyboards, mice, scanners, digital cameras, joysticks, and
microphones. These devices are called Input Devices and the information provided is called input.

The computer requires storage to store this information and the storage is called Memory. Computer
Storage or Memory is of Two Types. (i) Primary Memory or RAM (Random Access Memory): This is the
internal storage that is used in the computers and is located on the motherboard. RAM can be accessed or
modified quickly in any order or randomly. The information that is stored in RAM is lost when the computer
is turned off called as Volatile. (ii) Secondary Memory or ROM (Read-Only Memory): Information (data)
stored in ROM is read-only, and is stored permanently called as Non-Volatile. The ROM stored instruction is
required to start a computer.

Processing: Operations done on this information (input data) is called Processing. The Processing of
input is done in the Central Processing Unit which is popularly known as CPU.

Output Devices: These are the computer hardware devices that help in converting information into
human-readable form. Some of the output devices include Visual Display Units (VDU) such as a Monitor,
Printer, Graphics Output devices, Plotters, Speakers, etc.

Developers should have essential knowledge on the following concepts to become skilled in
Computer Programming,

1) Algorithm: It is a set of steps or instruction statements to be followed to accomplish specific tasks.


2) Source code: Source code is the actual text used to construct the program using C language.
void main()
{
// Steps to be performed
}
3) Compiler: Compiler is a software program that helps in converting the source code into binary code.
4) Data Type: Data of different types, integer, floating-point, character.
5) Variable: Variable is a space holder to store value in memory used in program. Example, int age = 25.
6) Conditionals: a certain condition should execute only if true or false to exit.
7) Array: Array is the variable that stores elements of a similar data type. Example: int a[10]
8) Loop: Loop is used to execute the series of code until the condition is true. Example, for, while, do-while.
9) Function: Functions or methods are used to accomplish a task in programming, a function can take
parameters and process them to get the desired output. Functions are used to reuse them whenever
required at any place repeatedly.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 10
Algorithms:

Definition:
An algorithm is defined as a finite set of steps that provide a chain of actions for solving a problem.
(or) An algorithm is a sequence of instructions that are carried out in a predetermined sequence in order to
solve a problem. (or) A step-by-step procedure used to solve a problem is called Algorithm. (or) An algorithm
(pronounced AL-go-rith-um) is a procedure or formula for solving a problem, based on conducting a sequence
of specified actions.

Procedure for writing an algorithm:


An Algorithm is a well-organized and textual computational module that receives one or more input
values and provides one or more output values.
• These well-defined steps are arranged in a sequence that processes given input into output.
• The steps of the algorithm are written using English like statements which are easy to understand.
• This will enable the reader to translate each step into a program.
• Every step is known as instruction.
• An algorithm is set to be accurate only when it provides the exact required output.
• If the procedure is lengthy then sub divided into small parts as it makes easy to solve the problem.

Analyzing an Algorithm:
When one writes an algorithm, it is essential to know how to analyses the algorithm.
• Analyzing the algorithm refers to calculating the resources such as computer memory, processing
time, logic gates and so on …..
• Time is most important resource because the program developed should be faster in processing.
• The analysis can also be made by reading the algorithm for logical accuracy, tracing the algorithm and
checking with the data.

Categories of Algorithm:
The steps in an algorithm can be divided into three categories, namely
• Sequence
• Selection and
• Iteration

Sequence
• The steps described in an algorithm are performed successively one by one without skipping any step.
• The sequence of steps defined in an algorithm should be simple and easy to understand.

Example: // adding two timings


Step 1: start
Step 2: read h1, m1, h2, m2
Step 3: m=m1+m2
Step 4: h= h1 + h2 + m/60
Step 5: m=m mod 60
Step 6: write h and m
Step 7: stop

Selection
• We understand that the algorithms written in sequence fashion are not reliable. There must be a
procedure to handle operation failure occurring during execution.
• The selection of statements can be shown as follows,

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 11
if(condition)
Statement-1;
else
Statement-2;
• The above syntax specifies that if the condition is true, statement-1 will be executed otherwise
statement-2 will be executed.
• In case the operation is unsuccessful. Then sequence of algorithm should be changed / corrected in
such a way that the system will re-execute until the operation is successful.

Example: // Person eligibility for vote


Step 1: start
Step 2: read age
Step 3: if age > = 18 then step_4 else step_5
Step 4: write “person is eligible for vote”
Step 5: write “person is not eligible for vote”
Step 6: stop

Iteration
• In a program, sometimes it is very necessary to perform the same action for a number of times.
• If the same statement is written repetitively, it will increase the program code.
• To avoid this problem, iteration mechanism is applied.
• The statement written in an iteration block is executed for a given number of times based on certain
condition.

Example: // sum of individual digits in the given number


Step 1: start
Step 2: read n
Step 3: repeat step 4 until n>0
Step 4: (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5: write s
Step 6: stop

Some more examples:


Algorithm to add two numbers: Algorithm to find largest among three Algorithm to reverse the number:
Step 1: START numbers:
Step 2: Declare integers a, b & c
Step 3: Define values of a & b Step 1: Start
Step 4: add values of a & b Step 2: Declare variables a,b and c.
Step 5: store output of step 4 to c Step 3: Read variables a,b and c.
Step 6: print c Step 4: If a > b
Step 7: STOP If a > c
Display a is the largest.
Algorithm to find odd or even number: Else
Step 1: Start Display c is the largest.
Step 2: [Take Input] Read: Number Else
Step 3: Check: If b > c
If Number%2 == 0 Then Display b is the largest.
Print : N is an Even Number. Else
Else Display c is the largest.
Print : N is an Odd Number. Step 5: Stop
Step 4: Exit

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 12
Flowcharts (using Dia Tool):

A flowchart is an alternative technique for solving a problem. Instead of descriptive steps, we use
pictorial representation for every step.

Definition:
Flowchart is a diagrammatic or pictorial representation of various steps involved in the Algorithm.

A complete flowchart enables us to organize the problem into a plan of actions i.e. it specifies what
comes first, second, third, . . . .
* Flowchart also represents the flow of data.
* It is an easy way to solve the complex problems because it makes the reader to flow the process
quickly from the flowchart incited of going through text.
* A flowchart is a set of symbols that indicates various operations in a program.
* For every process there is a corresponding symbol in the flowchart.
* Once the algorithm is written, its pictorial representation can be done using flowchart symbol.

Some of the commonly used flowchart symbols are listed below,

Note: (Name of the Symbols)


Oval, Diamond, Circle, Square (or) Rectangle, Parallelogram, hexagon shaped symbol, arrows (Data Flow
lines), Subroutine Symbol (rectangle with a line at each end of the shape).
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 13
Flowchart Example:
• Problem 1: Draw a flowchart to find the sum of two numbers.

• Problem 2: Draw a flowchart to calculate the average of three two numbers.

• Problem 3: Draw a flowchart to find the greatest of two numbers.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 14
• Problem 4: Draw a flowchart to swap two numbers.

Pseudo Code:

A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is intended
for human understanding rather than machine reading.

Pseudocode is the intermediate state between an idea and its implementation (code) in a high-level
language.

Algorithm and Pseudocode are the two related terms in computer programming. The basic difference
between algorithm and pseudocode is that an algorithm is a step-by-step procedure developed to solve a
problem, while a pseudocode is a technique of developing an algorithm.

What is the need for Pseudocode


Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem. Pseudocode is
an intermediate state between algorithm and program that plays supports the transition of the algorithm
into the program.

Pseudocode is an intermediate state between algorithm and program

Five important rules for writing pseudocode are:


1. Write one statement per line.
2. Initial keywords should be represented in capital case (READ, WRITE, IF, WHILE, UNTIL).
3. Indentation of pseudocode should be similar to the actual program to show hierarchy.
4. Ending the multiline structure is necessary.
5. Keep statements in simple language (English).

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 15
Difference between Algorithm and Pseudocode:
Algorithm Pseudocode
An Algorithm is used to provide a solution to a A Pseudocode is a step-by-step description of an
problem in form of a well-defined step-based form. algorithm in code-like structure using English text.
An algorithm only uses simple English words It uses reserved keywords like if-else, for, while, etc.
These are a sequence of steps of a solution to a These are fake codes as the word pseudo means
problem fake, using code like structure and plain English text
There are no rules to writing algorithms There are certain rules for writing pseudocode
Algorithms can be considered pseudocode Pseudocode cannot be considered an algorithm
It is difficult to understand and interpret It is easy to understand and interpret
Example 1:
To implement a simple program that calculates the average of three numbers using pseudo code in C:
Pseudo code:
1. Start
2. Input three numbers
3. Calculate the sum of the three numbers
4. Divide the sum by 3 to get the average
5. Display the average
6. End
7.

Example 2:
To find the Factorial value of the given number using pseudo code in C:
Algorithm to find Factorial of n: Pseudocode to Factorial of n: C program to find Factorial of n:

Step 1: start Start program #include<stdio.h>


Step 2: initialize fact = 1 Declare fact and n void main()
Step 3: input the user value n Enter number for n {
Step 4: for i=1 to i <= n repeat for i=1 to i <=n int n, fact=1,i;
the process Perform fact = fact * i printf("enter value for n: ");
Step 5: fact = fact * i Display fact scanf("%d", &n);
Step 6: i++ [increment i by one] End program for(i=1; i<=n; i++)
Step 7: print fact value { fact=fact*i; }
Step 8: stop printf("\n factorial is: %d", fact);
}
Example 3:
To find the Sum of Natural Numbers up to the given number using pseudo code in C:
Algorithm to find the Sum of pseudo-code to find the Sum of C program to find the Sum of
Natural Numbers up to n: Natural Numbers up to n: Natural Numbers up to n:

Step 1: start Start program #include<stdio.h>


Step 2: declare and initialize n, Declare variables n, sum=0 and i void main()
sum = 0 and i Enter the number for n {
Step 3: Input number n For i=1 to i<=n int n, sum=0, i;
Step 4: for i=1 to i<=n Perform operation sum = sum + i printf("enter no of terms: ");
Step 5: sum = sum + i Increment i value by one scanf("%d", &n);
Step 6: i++ [increment i by one] Print sum for(i=1; i<=n; i++)
Step 7: print sum End program { sum = sum+i; }
Step 8: stop printf("sum of series=%d",sum);
}

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 16
INTRODUCTION TO COMPILATION AND EXECUTION: .

(i) Compilation of the High Level Language:

Compilation process in C is also known as the process of converting Human Understandable Code (C
Program) into a Machine Understandable Code (Binary Code). Compilation process in C involves four steps:
pre-processing, compiling, assembling, and linking.
• The preprocessor tool helps in comments removal, macros expansion, file inclusion, and conditional
compilation. These commands are executed in the first step of the compilation process.
• Compiler software helps boost the program's performance and translates the intermediate file to an
assembly file.
• Assembler helps convert the assembly file into an object file containing machine-level code.
• Linker is used for linking the library file with the object file. It is the final step in compilation to
generate an executable file.

The compiling process consists of two steps: i) The analysis of the source program and ii) The synthesis
of the object program in the machine language of the specified machine.
• The analysis phase uses the precise description of the source programming language.
• A source language is described using a) lexical rules, b) syntax rules, and () semantic rules.

The Process of Compilation:

Block diagram of the Process of Compilation

(ii) Execution Steps of a Program:

The following are the execution steps of a program:


1. Translation of the program resulting in the object program.
2. Linking of the translated program with other object programs needed for execution, thereby
resulting in a binary program.
3. Relocation of the program to execute from the specific memory area allocated to it.
4. Loading of the program in the memory for the purpose of execution.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 17
Linker:
• Linking resolves symbolic references between object programs.
• It makes object programs known to each other.
• Linking makes the addresses of programs known to each other so that transfer of control from one
subprogram to another or a main program takes place during execution.
• In FORTRAN / COBOL, all program units are translated separately.

Relocation:
• Relocation is more than simply moving a program from one area to another in the main memory.
• Relocation means adjustment of all address-dependent locations, such as address constant,
correspond to the allocated space, which means simple modification of the object program so that
it can be loaded at an address different from the location originally specified.

Loader:
• Loading means physically placing the machine instructions and data into main memory, also known
as primary storage area.
a. Assignment of load-time storage area to the program
b. Loading of program into assigned area
c. Relocation of program to execute properly from its load time storage area
d. Linking of programs with one another

Program Execution:
• When a program is compiled and linked, each instruction and each item of data is assigned an
address.
• At execution time, the CPU finds instructions and data from these addresses.
• The program counter, is a CPU register that holds the address of the next instruction to be executed
in a program.
The CPU has random access capability to any and all words of the memory, no matter what their
addresses

The Process of Program Execution:

Block Diagram of the Process of Program Execution

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 18
PRIMITIVE DATA TYPES: .
Data Types:

Primary Data Type Size (in bytes) Range .


int 2 -32768 to 32767

unsigned int 2 0 to 65535

signed 2 -32768 to 32767

short 2 -32768 to 32767

unsigned short 2 0 to 65535

signed short 2 -32768 to 32767

long 4 -2147483648 to 2147483647

unsigned long 4 0 to 4294967295

signed long 4 -2147483648 to 2147483647

char 1 -128 to 127

unsigned char 1 0 to 255

signed char 1 -128 to 127

float 4 3.4E-38 to 3.4E +38

double 8 1.7E -308 to 1.7E +308

long double 10 34E -4932 to 34E +4932

Note:
• Float is a single precision value. ( After decimal 7 digits has been considered )
• Double is a double precision value. ( After decimal 14 digits has been Considered )
• In-Built data Types are supported by “C” compiler by default.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 19
1. Character (Denoted as "char" in C programming language)
Description: A character denotes any alphabet, digit or special symbol used to represent in formation and
it is used to store a single character.
Storage space: 1 byte
Format: %c
Range of Values: ASCII Character Set.

2. Integer (Denoted as "int" in C programming language)


Description: Integer type is used to store positive and negative integer.
Storage space: 2 bytes.
Format: %d
Range of values: -327687 to +32767.
( The storage space may vary depending on the operating system )

3. Float point (Denoted as "float" in C programming language)


Description: It is used to store real number, with single precision floating point number (precision of 6
digits after decimal points.)
Storage space: 4 bytes.
Format: %f
Range of values: -3.4*1038 to +3.4*1038.

4. Double (Denoted as "double" in C programming language)


Description: It stores real numbers with double precision. The use of double doesn't guarantee to double
the number of significant digits in our result, but it improves the accuracy of the arithmetic and reduces the
accumulation of rounding errors.
Storage Space: 8 bytes.
Format: %ld
Range of values: -1.7*10308 to +1.7*10308.

5. void:
Description: It is a special data type used for,
• To specify that a function doesn’t returns any value.
• To specify a function takes no arguments.
• To create generic pointers.
Eg: 1. void print (void)
1. void *ptr

VARIABLES AND CONSTANTS: .

VARIABLES:
Variable Names:
• A variable is an identifier that is used to store data elements.
• The data may be numerical quantity (or) a character constant.
• The data item must be assigned a value to the variable at some point in the program. Then data item
can be accessed by referring to the variable name.
• In other words, a variable is an identifier which changes its value during the execution of the program.

Rules for Constructing a Variable:


• A variable name is a combination of alphabets, digits and underscore.
• Other than the underscore no special characters is allowed.
• The first character in the variable name must be an alphabet.
• The variable name should not be of keyword.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 20
Declaration of a Variable:
• Any variable which is used in the program should be declared first.
• A declaration of a variable specifies two things:
o It tells the compiler about the name of the variable.
o It specifies about the type of data that a variable can hold.

Syntax: data type variable 1, variable 2 , . . . . . . . . variable;


Eg: int a, b, c;

• The above declaration results in declaring the variables a, b, c as integer data type.

CONSTANTS:
Constants and its types:
• These are fixed values that will not change during the execution of program.
• There are 4 basic types of constants in ‘C’. They are

Integer Constant:
An integer constant is an integer valued number. Rules for Constructing Integer Constant:
• It shouldn’t have a decimal point.
• An integer constant must have at least one digit.
• Commas, Blank spaces, special characters can’t be included with in the constants.
• The constant can be preceded by a minus sign if desired.
• The range of integer constants is -32,768 to 32,767

Types of Integer Constants:


• Integer Constants can be written in 3 different number systems, namely
o Decimal {Base = 10}
o Octal {Base = 8}
o Hexa Decimal {Base = 16}

Decimal Numbers:
o A Decimal integer constant can consist of any combinations of digits taken from the set 0-9.
o If the constant contains 2 (or) more digits, the first digit must be something other than zero.
Eg: 0, 1, 723, 32156

Octal Constants:
o An Octal integer constant can consist of any combination of digits taken from the set 0-7.
o The first digit must be zero in order to identify the constant as an octal number.
Eg: 0, 01, 0723.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 21
Hexa Decimal Numbers:
o A Hexa Decimal integer constant must begin with either 0x, (or) 0x.
o It can consist of the digits taken from the set 0-9, and a-f {upper case / lower case}.
o The letters a-f, represent the quantities 10-15 respectively.
Eg: 0x, 0x, 0x7.

Unsigned & Long Integer Constants:


o An Unsigned integer constant can be identified by appending the letter ‘u’. {either upper or
lower case}
o Long interval constants can be identified by appending the letter ‘L’ {either upper or lower
case} to the end of the constant.
o An unsigned long interval constant can be specified by appending the letters UL {either upper
case (or) lower case} to the end of the constants.
o Note that ‘u’ must precede the ‘L’.
Eg: 234U – Unsigned Decimal Constant
0427UL – Unsigned Long Octal Constant
0X72FL – Long Hexa Decimal Constant

Floating Point Constants:


o A floating-point constant is a decimal number that contains a decimal point.
Rules:
o Commas and Blank spaces can’t be included.
o It can contain of either decimal point (or) Exponent.
o The constant can be preceded by minus sign it desired.
Eg: 0, 1.0, 12.3.

Scientific Notation:
o When we want to represent very large values (or) very small values, instead of representing
the value of sequence of digits we can represent a floating-point constant value in a scientific
notation as follows,
Mantissa E (or) e exponent.
Eg: 1.2E + 3 => 1.2 * (10^3)
o Note that if no sign is represented after ‘E’ it will be treated as positive.
o Floating point constants are identified by appending the letter F {either upper case (or) lower
case} to the end of the constants.
Eg: 3E5F = 300000F.

Character Constants:
o A character constant is a single character enclosed in single quotation marks. The Max length
of character constant is “one”. The single character can be either alphabet (or) Digit (or) a
special symbol.
o Eg: ‘a’, ‘1’, ‘?’
Note: Most computers make use of the “ASCII” { American Standard Code for Information
Interchange }, character set, in which each individual character is numerically encoded.
o ASCII code is a 7-bit code. ASCII values ranges from 0-127.

String Constants:
o A string constant is an array of characters that has a fixed value enclosed within double
quotation marks ( “ “ ).
o String constant is a sequence of characters enclosed within a pair of double quotes.
o For example, “DataFlair”, “Hello world!”

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 22
BASIC INPUT AND OUTPUT: .

C language has standard libraries that allow input and output in a program. The stdio.h or standard
input output library in C that has methods for input and output.

Formated Input:

scanf()
The scanf() method, in C, reads the value from the console as per the type specified.

Syntax: scanf(“%X”, &variable of X Type);

where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of this
variable, stored at this address in the memory.

Formated Output:

printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.

Syntax: printf(“%X”, variable of X Type);

where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value of this
variable, stored at this address in the memory.

The basic type in C includes types like int, float, char, double. Inorder to input or output the specific
type, the X in the above syntax is changed with the specific format specifier of that type.

Example: C program to show input and output

#include <stdio.h>
int main()
{
int num; // Declare the variables
char ch;
float frac;
printf("Enter the integer: "); // Integer – i/o
scanf("%d", &num);
printf("\n Entered integer is: %d", num);

printf("\n Enter the float: "); // Float – i/o


scanf("%f", &f);
printf("\n Entered float is: %f", frac);

printf("\n Enter the Character: "); // Character – i/o


scanf("%c", &ch);
printf("\n Entered char is: %c", ch);

return 0;
}
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 23
Output:
Enter the integer: 10
Entered integer is: 10

Enter the float: 2.5


Entered float is: 2.500000

Enter the Character: A


Entered Character is: A

OPERATORS: .

An operator is a symbol that informs to the computer to perform a particular task.


• The data items that operators act upon are called “operands”.
• If the operator requires only one operant then it is called “unary operator”. If it requires two then it
is called “Binary Operator”.
‘C’ language supports a different set of operators,

i) Arithmetic Operators:

Operator Purpose Expression Examples


+ Addition a+b 7+2=
- Subtraction a-b 7–2=
* Multiplication a*b 7*2=
/ Division a/b 7/2=
% Modulo Division a%b 7%2=

Example 1: Write a C program to perform arithmetic operations.

#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c;
Output:
printf(“ Enter a, b values: ”); Enter a, b values:
scanf(“%d%d”, &a, &b); sum=
sub=
c = a + b; mul=
printf(“sum= %d \n”, c); div=
mod=

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 24
ii) Relational Oprators:
• Relational Operators are used to perform comparison between two values.
• These operators‟ returns true (1) if the comparison condition is true otherwise false (0).
• The operators used for comparison in ‘C’ are listed below,
Operator Description or Action Expression Example
< less than a<b 5 < 10
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

Example 1:
35 < 5 - false (0)
10 <= 10 - true (1)
45 > 5 -
11 >= 5 -
35 == 10 -
35 != 10 -
(10+5) == (5*3) - true (1)

Example 2: Write a program to use various relational operators and display their return values?
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\n Condition \t : Return values \n ");
printf("\n 10 != 10 \t : %5d", 10 != 10);

getch();
}

Output:
10 != 10 : 0
10 == 10 :
10 >= 10 :
10 > 5 :
10 <= 100 :
10 < 9 : 0

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 25
iii) Logical Oprators:
• To take a decision based on 2 (or) more conditions then use logical operators.
• There are three logical operators available in ‘C’
Operator Purpose Expression Example
&& Logical AND if(a<b) && (a<c) - false(0) a=5; b=10; c=3
|| Logical OR if(a<b) || (a<c) - a=5; b=10; c=3
! Logical NOT if(a != b) - a=5; b=10; c=3

Truth Table
A B A && B A B A || B A !A
F F F F F F F T
F T F F T T T F
T F F T F T
T T T T T T

Example 1: Write an example program using logical operators?


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("condition \t \t : Return values\n");
printf("\n 9>5 && 8<10 : %5d", 9>5 && 8<10);
printf("\n 10<9 && 3>7 : %5d", 10<9 && 3>7);
printf("\n 9>6 || 6<2 : %5d", 9>6 || 6<2);
printf("\n 14 != 14 : %5d", 14 != 14);
printf("\n 9 != 10 : %5d", 9 != 10);
getch();
}
Output:
Condition : Return values

iv) Increment / Decrement Operator ( ++ and - - )


• Increment operator increases value by 1. Decrement operator decreases value by 1.
• This operator can be used in two forms namely Prefix and Postfix.
• In case of Prefix notation, the operator precedes the operant {++a}.
• In case of Postfix notation, the operator is followed by operand {a++}.
• In Prefix notation increment operation will be given the highest priority i.e., first the value is
incremented by 1 and other operations are performed later.
• In Postfix notation, increment operator will be given the least priority i.e., the increment operation is
performed at last after all operations are performed.
• The above points are applicable to the decrement operator also.
Example: i/p int a = 5, c=0; int a = 5, c=0;
process c = ++a; c = a++;
o/p c=6, a=6 c=5, a=6.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 26
v) Bitwise Operators:
• Bitwise operators are one of the salient features of ‘C’ language.
• These are specially designed to manipulate the data at Bit level.
• The Bitwise operators are not applicable for float (or) Double data type.
• The following are the some of the Bit wise operators available in ‘C’ language.
Operator Meaning .
& Bitwise Logical AND
| Bitwise Logical OR
^ Bitwise Logical XOR
<< Left Shift
>> Right Shift
~ Bitwise Compliment [ 2's Complement = Bitwise 1’s Compliment number + 1 ]
vi) Assignment Operators:
• This operator is used to assign a constant value (or) the result of an expression to a variable.
• In this operation Right hand side expression is evaluated first and then the result is assigned to left
hand side variable.

Operator Meaning .
= - Assign Right Hand value to LHS value
+= - Value of LHS add to value of RHS and assign it back to the variable in LHS
Eg: a += 2; which means, a = a + 2;
-= - Value of RHS variable will be subtracted from the value of LHS and assign it back to
the variable in LHS. Eg: a -= 2; which means, a = a – 2;
*= - Value of LHS variable will be multiplied to the value of RHS and Assign it back to the
variable in LHS. Eg: a *= 2; which means, a = a * 2;
/= - Value of LHS variable will be divided by the value of RHS and Assign it back to the
variable in LHS. Eg: a /= 2; which means, a = a * 2;
%= - The Remainder will be stored back to the LHS after integer, division Is carried out
between the LHS variable and RHS variable. Eg: a %= 2 which means, a = a % 2.
Example:
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d\n", c); // c is 5
c += a;
printf("c = %d\n", c); // c is 10
c -= a;
printf("c = %d\n", c); // c is 5
c *= a;
printf("c = %d\n", c); // c is 25
c /= a;
printf("c = %d\n", c); // c is 5
c %= a;
printf("c = %d\n", c); // c = 0
return 0;
}
Output:
c=5 c = 10 c=5 c = 25 c=5 c=0

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 27
Expressions:
An expression is a combination of operators and operands which reduces to a single value. An
operator indicates an operation to be performed on data that yields a value. An operand is a data item on
which an operation is performed.
A simple expression contains only one operator for example 3+5 is a simple expression which yields
a value 8, -a is also a single expression. A complex expression contains more than one operator. An example
of complex expression is 6+2*7.
An expression can be divided into six categories based on the number of operators, positions of the
operands and operators, and the precedence of operator.

Primary Expressions:
In C, the operand in the primary expression can be a Name, a Constant, or a Parenthesized Expression.
Name is any identifier for a variable. A constant is the one whose value cannot be changed during program
execution. Any value enclosed within parenthesis must be reduced to single value. A complex Expression can
be converted into primary expression by enclosing it with parenthesis.
The following is an example,
( 3 * 5 + 8 ); ( c = a = 5 * c );

Postfix Expressions
The postfix expression consists of one operand and one operator. Example: A Function Call, The
function name is operand and parenthesis is the operator.
The other examples are post increment and post decrement. In post increment the variable is
increased by 1, a++ results in the variable increment by 1.
Similarly in post decrement, the variable is decreased by 1, a-- results in the variable decreased by 1.

Prefix Expressions
Prefix Expressions consists of one operand and one operator, the operand comes after the operator.
Examples of prefix expressions are prefix increment and prefix decrement i.e., ++a, --a.
The only difference between postfix and prefix operators is, in the prefix operator, the effect take
place before the expression that contains operators is evaluated. It is other way in case of postfix expressions.

Unary Expressions
A unary expression is like a prefix expression consists of one operand and one operator and the
operand comes after the operator.
Example: +a; -b; -c; +d;

Binary Expressions
Binary Expressions are the combinations of two operands and an operator. Any two variables added,
subtracted, multiplied or divided is a binary expression.
Example: a + b; c * d;

Ternary Expressions
Ternary Expressions is an expression which consists of a ternary operator pair “ ? : ” In the example, if exp1
is true exp2 is executed else exp3 is executed.

Syntax: exp1 ? exp2 : exp3;

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 28
Example 1:

#include <stdio.h>
int main()
{
int n1 = 5, n2 = 10, max;
max = (n1 > n2) ? n1 : n2;
printf("Largest number between %d and %d is: %d. ", n1, n2, max);
return 0;
}
Output: Largest number between 5 and 10 is: 10.

Example 2:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0;
}
Output: Enter your age: 12
You cannot vote

Example 3:
#include <stdio.h>
int main()
{
char operator = '+';
int num1 = 8;
int num2 = 7;
int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
printf("%d", result);
return 0;
}
Output: 15

PRECEDENCE AND ASSOCIATIVITY:

• Every operator has a precedence value. An expression containing more than one operator is known
as a complex expression.
• Complex expressions are executed according to precedence of operators.
• Associativity specifies the order in which the operators are evaluated with the same precedence in a
complex expression.
• Associativity is of two ways i.e., left-to-right and right-to-left.
• Left-to-right associativity evaluates an expression stating from left and moving towards right.
• Right-to-left associativity proceeds from right to left.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 29
The precedence and associativity of various operators in C are as shown in the following table,

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 30
TYPE CONVERSION AND CASTING: .
Type Conversion:
• In some situations, some variables are declared as integers and while performing an operation on
these variables we require the result as floating point type. In such situations we use type
conversion.
• The type conversion is used to convert the set of declared data types to some other required types.
Conversion can be carried out in 2 ways,
o Converting by using assignment (Implicit casting).
o Using cast operator (Explicit casting).
Converting by Assignment:
• The usual way of converting a value from one data type to another is by using the assignment
operator.
int a;
float b;
a=b;
• In this method, if a larger data type value is assigned to smaller data type then the value will be
truncated {cut off}. This method is called “Narrowing”.
Cast Operator:
• The cast operator is a technique to forcefully to convert one data type to another.
• The operator used to force this conversion is known as “Cast Operator” and the process is known as
type casting.
Syntax: x= (cast) expression Example of Cast Operator:
(or) #include <stdio.h>
X= cast (expression) int main()
{
Eg: int a, b; int sum= 17, count = 5;
float f; float mean;
f= (float) a/b; mean = (float) sum / count;
(or) printf("Value of mean : %f\n", mean );
f= float (a)/b; }
O/p: Value of mean : 3.400000
Explanation: The cast operator has precedence over division, so the value of sum is first converted to float
data type and finally it gets divided by count yielding a float value.

gets only integer output: wrong gets float output: but wrong gets float output w/o CAST: Correct
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() int main() int main()
{ { {
int sum = 17, count = 5; int sum = 17, count = 5; float sum= 17; int count = 5;
int mean; float mean; float mean;
mean = sum / count; mean = sum / count; mean = sum / count;
printf("Value of mean : %d\n", mean ); printf("Value of mean : %f\n", mean ); printf("Value of mean : %f\n", mean );
} } }
O/p: O/p: O/p:
Value of mean : 3 Value of mean : 3.000000 Value of mean : 3.400000

The actual output needed is 3.400000, The actual output needed is 3.400000, The actual output needed is 3.400000,
but the result is 3. So to get the correct but the result is 3.000000. So to get the also the result is 3.400000. Getting the
output one way is to change the data correct output one way is to change the correct output by declaring the correct
type of a given variable. data type of a given variable. data type of a given variable. (without
TYPE CONVERSION or CASTING)

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 31
PROBLEM SOLVING TECHNIQUES: .

An algorithm is a step-by-step procedure to solve a problem. A good algorithm should be optimized


in terms of time and space. Different types of problems require different types of algorithmic techniques to
be solved in the most optimized manner. There are many types of algorithms but the most important and
fundamental algorithms are under an Algorithmic approach.

Algorithmic approach:

There may be several methods under an approach. Example, Sorting is an approach and different
sorting techniques are methods each. An algorithm is a sequence of logical steps to solve a problem.

There are many types of algorithms but the most important and fundamental algorithms that you
must are discussed in this article.
• Brute Force Algorithm
• Recursive Algorithm
o Divide and Conquer Algorithm
o Dynamic Programming Algorithms
o Greedy Algorithm
o Backtracking Algorithm
• Randomized Algorithm
• Sorting Algorithm
• Searching Algorithm
• Hashing Algorithm

1. Brute Force Algorithm:


This is the most basic and simplest type of algorithm. A Brute Force Algorithm is the straightforward
approach to a problem i.e., the first approach that comes to our mind on seeing the problem. More
technically it is just like iterating every possibility available to solve that problem.

Example: If there is a lock of 4-digit PIN. The digits to be chosen from 0-9 then the brute force will be
trying all possible combinations one by one like 0001, 0002, 0003, 0004, and so on until we get the right PIN.
In the worst case, it will take 10,000 tries to find the right combination.

2. Recursive Algorithm:
This type of algorithm is based on recursion. In recursion, a problem is solved by breaking it into
subproblems of the same type and calling own self again and again until the problem is solved with the help
of a base condition.
Example: Some common problem that is solved using recursive algorithms are Factorial of a Number,
Fibonacci Series, Tower of Hanoi, DFS for Graph, etc.

a) Divide and Conquer Algorithm:


In Divide and Conquer algorithms, the idea is to solve the problem in two sections, the first
section divides the problem into subproblems of the same type. The second section is to solve the
smaller problem independently and then add the combined result to produce the final answer to the
problem.
Example: Some common problem that is solved using Divide and Conquers Algorithms are
Binary Search, Merge Sort, Quick Sort, Strassen’s Matrix Multiplication, etc.

b) Dynamic Programming Algorithms:

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 32
This type of algorithm is also known as the memoization technique because in this the idea is
to store the previously calculated result to avoid calculating it again and again. In Dynamic
Programming, divide the complex problem into smaller overlapping subproblems and store the result
for future use.
Example: The following problems can be solved using the Dynamic Programming algorithm
Knapsack Problem, Weighted Job Scheduling, Floyd Warshall Algorithm, etc.

c) Greedy Algorithm:
In the Greedy Algorithm, the solution is built part by part. The decision to choose the next
part is done on the basis that it gives an immediate benefit. It never considers the choices that had
been taken previously.
Example: Some common problems that can be solved through the Greedy Algorithm are Dijkstra
Shortest Path Algorithm, Prim’s Algorithm, Kruskal’s Algorithm, Huffman Coding, etc.

d) Backtracking Algorithm:
In Backtracking Algorithm, the problem is solved in an incremental way i.e., it is an algorithmic
technique for solving problems recursively by trying to build a solution incrementally, one piece at a
time, removing those solutions that fail to satisfy the constraints of the problem at any point of time.
Example: Some problems can be solved through the Backtracking Algorithm are the Hamiltonian
Cycle, M-Coloring Problem, N Queen Problem, Rat in Maze Problem, etc.

3. Randomized Algorithm:
In the randomized algorithm, we use a random number.it helps to decide the expected outcome. The
decision to choose the random number so it gives the immediate benefit
Example: Some common problems that can be solved through the Randomized Algorithm are Quicksort:
In Quicksort we use the random number for selecting the pivot.

4. Sorting Algorithm:
The sorting algorithm is used to sort data in maybe ascending or descending order. It’s also used for
arranging data in an efficient and useful manner.
Example: Some common problems that can be solved through the sorting Algorithm are Bubble sort,
insertion sort, merge sort, selection sort, and quick sort are examples of the Sorting algorithm.

5. Searching Algorithm:
The searching algorithm is the algorithm that is used for searching the specific key in particular sorted
or unsorted data.
Example: Some common problems that can be solved through the Searching Algorithm are Binary
search or linear search is one example of a Searching algorithm.

6. Hashing Algorithm:
Hashing algorithms work the same as the Searching algorithm but they contain an index with a key
ID i.e. a key-value pair. In hashing, we assign a key to specific data.
Example: Some common problems can be solved through the Hashing Algorithm in password
verification.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 33
Characteristics of an Algorithm:

There are some important characteristics which every algorithm should follow. They are as follows:

1. Clear and Unambiguous:


The algorithm should be unambiguous. Each of its steps should be clear in all aspects and must lead
to only one meaning.
2. Well-Defined Inputs:
If an algorithm says to take inputs, it should be well-defined inputs. It may or may not take input.
3. Well-Defined Outputs:
The algorithm must clearly define what output will be yielded and it should be well-defined as well.
It should produce at least 1 output.
4. Finiteness:
The algorithm must be finite, i.e., it should terminate after a finite time. An algorithm must terminate
after a finite number of steps in all test cases.
5. Feasible:
The algorithm must be simple, generic, and practical, such that it can be executed with the available
resources. It must not contain some future technology or anything.
6. Language Independent:
The Algorithm designed must be language-independent, i.e., it must be just plain instructions that
can be implemented in any language, and yet the output will be the same, as expected.
7. Effectiveness:
An algorithm must be developed by using very basic, simple, and feasible operations so that one can
trace it out by using just paper and pencil.
8. Modularity and reusability:
Algorithms may be modular, they may be divided into smaller subproblems or features that may be
reused in unique parts of the algorithm or in other algorithms.
9. Understandability:
Algorithms need to be designed with clarity and ease in mind, making them easy to apprehend and
implement.

PROBLEM SOLVING STRATEGIES: .

Structured programming is a programming paradigm aimed on improving the clarity, quality, and
development time of a computer program by making extensive use of subroutines. It is possible to do
structured programming in any programming language, though it is preferable to use something like a
procedural programming language. Example: ALGOL, Pascal, PL/I and Ada.

There are three main principles of structured programming,


1. Program design using top-down or bottom-up approach
2. Decomposition of program into components i.e. modular programming
3. Structuring of control flow

Top-down approach:

• Program design concentrates on planning the solution as a collection of sub solutions. During top-
down design the divide and conquer policy is followed.
• The problem is divided into smaller sub problems and these sub problems are further divided into
even smaller sub problems.
• In the top-down approach, the calling components is always designed before its sub component.
• Thus top-down design represents a successive refinement of functionality of the program.
Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 34
• It allows us to build solutions to a problem in a stepwise fashion.

For example, the following figure shows top-down approach,

(or)

Bottom-up approach:

The bottom-up design is the reverse of the top-down approach.


• Here the process starts with the identification of the smallest sub component of the total program
which can be easily implemented.
• Such smallest components are combined to reach to a more abstract level and plan components of
the higher level.
• This process is continued till the complete program does not get realized.
• The main drawback of this approach is that it is rarely possible to identify smallest sub component
needed for the program, especially for bigger program.

For example, the following figure shows bottom-up approach,

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 35
Deference between top-down and bottom-up approaches are,

Sl. TOP DOWN APPROACH BOTTOM UP APPROACH


In this approach We focus on breaking up the In this approach, we solve smaller problems and
1.
problem into smaller parts. integrate it as whole and complete the solution.
Mainly used by structured programming Mainly used by object oriented programming
2.
language such as COBOL, Fortran, C, etc. language such as C++, C#, Python.
Each part is programmed separately therefore Redundancy is minimized by using data
3.
contain redundancy. encapsulation and data hiding.
In this the communications is less among
4. In this module must have communication.
modules.
It is used in debugging, module documentation,
5. It is basically used in testing.
etc.
In top down approach, decomposition takes
6. In bottom up approach composition takes place.
place.
In this top function of system might be hard to In this sometimes we can not build a program from
7.
identify. the piece we have started.
8. In this implementation details may differ. This is not natural for people to assemble.

Time and Space complexities of Algorithms: .


An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence
the Complexity of an algorithm refers to the measure of the time that it will need to execute and get the
expected output, and the Space it will need to store all the data (input, temporary data, and output). Hence
these two factors define the efficiency of an algorithm.
The two factors of Algorithm Complexity are:
• Time Factor: Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.
• Space Factor: Space is measured by counting the maximum memory space required by the
algorithm to run/execute.
Therefore the complexity of an algorithm can be divided into two types:
1. Space Complexity: The space complexity of an algorithm refers to the amount of memory
required by the algorithm to store the variables and get the result. This can be for inputs, temporary
operations, or outputs.
How to calculate Space Complexity?
The space complexity of an algorithm is calculated by determining the following 2 components:

• Fixed Part: This refers to the space that is required by the algorithm. For example, input
variables, output variables, program size, etc.
• Variable Part: This refers to the space that can be different based on the implementation of
the algorithm. For example, temporary variables, dynamic memory allocation, recursion stack
space, etc.
Therefore, Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is
the variable part of the algorithm, which depends on instance characteristic I.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 36
2. Time Complexity: The time complexity of an algorithm refers to the amount of time required
by the algorithm to execute and get the result. This can be for normal operations, conditional if-else
statements, loop statements, etc.

How to Calculate, Time Complexity?


The time complexity of an algorithm is also calculated by determining the following 2 components:
• Constant time part: Any instruction that is executed just once comes in this part. For
example, input, output, if-else, switch, arithmetic operations, etc.
• Variable Time Part: Any instruction that is executed more than once, say n times, comes in
this part. For example, loops, recursion, etc.

Therefore, Time complexity of any algorithm P is T(P) = C + TP(I), where C is the constant time part and
TP(I) is the variable part of the algorithm, which depends on the instance characteristic I.

The analysis of Algorithms:


Algorithm analysis is an important part of computational complexity theory, which provides
theoretical estimation for the required resources of an algorithm to solve a specific computational
problem. Analysis of algorithms is the determination of the amount of time and space resources required
to execute it.
Analysis of algorithm is the process of analyzing the problem-solving capability of the algorithm in
terms of the time and size required (the size of memory for storage while implementation). However, the
main concern of analysis of algorithms is the required time or performance.
Generally, we perform the following types of analysis –
• Worst-case − The maximum number of steps taken on any instance of size a.
• Best-case − The minimum number of steps taken on any instance of size a.
• Average-case − An average number of steps taken on any instance of size a.
• Amortized − A sequence of operations applied to the input of size an averaged over time.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 37
Some Important sort outs:
Problem: Draw a flowchart to find the roots of a Problem: Write the PSEUDO CODE for checking
quadratic equation whether a given number is a prime number or not.

Introduction to Programming (AK23), J.Bala Murali Krishna, M.E., (Ph.D), Asst. Professor, Dept. of CSE pg. 38

You might also like