Unit – I
Introduction to Programming and Problem Solving
Syllabus
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.
1. History of Computers
What is a Computer?
A computer is an electronic machine that takes input from the user, processes the given
input and generates the output in the form of useful information.
Generations of Computers
The computer generations are classified into five generations
1. First generation (1946-1955) uses vacuum tubes.
2. Second generation (1956-1965) use transistors.
3. Third generation (1966-earlyy 1975) use integrated circuit.
4. Fourth generation (early 1976-1985) use LSI and VLSI.
5. Fifth generation (1986 – at present) use ULSI and artificial intelligence.
First generation (1946-1955) uses vacuum tubes
The first generation computers were vacuum tubes based machines. The characteristics of these
machines are;
Characteristics of First generation computers
These computers are developed using vacuum tube technology.
In these computers vacuum tubes are used for processing and magnetic drums are used for
data storing.
These computers were unreliable
These are the fastest computing devices of their times.
These computers are very large in size and it occupies more space.
It consumes more power and it produces more heat.
The troubleshooting is more complicated.
They are programmed only in machine language. So it is very difficult to program and use.
In these computers the input is based on punched cards and paper tapes and output was in
the form of printouts.
Examples: ENIAC, EDVAC,UNIVAC
ENIAC (Electronic Numerical Integrator and Calculator)
EDVAC (Electronic Discrete Variable Automatic Computer)
UNVAC(Universal Automatic Computer)
Advantages
- Able to execute complex mathematical problems in an efficient manner.
Disadvantages
- These are not easy to program
- Very large in size and occupies more space
- It consumes more power and produces more heat
- Difficult to move from one place to another
Second Generation (1956-1965) use transistors:
In second generation computers transistors replaced vacuum tubes. Which were superior to
vacuum tubes. A transistor is made up of semiconductor material like germanium and silicon.
Characteristics of second generation computers
These machines were based on transistors.
These were smaller in size compared to first generation.
It consumes less power and produces less heat compared to first generation.
The processing time of these computers was reduced from milliseconds to microseconds.
Assembly language was used to write the program.
Example: PDP-8, IBM 1401 and IBM 7090.
Third Generation (1966-earlyy 1975) use integrated circuit
In third generation computers the transistors are replaced by integrated circuit(IC). It
consistsofhuge number of transistors and other components. The IC was invented by jack kilby.
Characteristics of third generation computers
These computers are based on integrated circuits(IC).
The processing time of these computers was reduced from micro seconds to nanoseconds.
It is portable in size and more reliable.
These computers are consumed less power and generated less heat.
These computers the users are interacted through keyboards and monitors.
These computers were capable of running many programs simultaneously.
These computers also understand high level language. So the users are easy to interact to
the computers.
Examples NCR 395, and B6500.
Fourth generation (early 1976 - 1985) use LSI and VLSI.
The fourthgeneration computers are extension of third generation computers.
Fourthgenerationcomputers were marked by the use of very largescale integrated
circuits.Microprocessors were used tobuild computers.
Characteristics of forth generation computers
Fourth generation computers are microprocessor based systems.
These computers are very small in size.
These computers were very cheap among all other generations.
They are very portable and more reliable.
These machines generate negligible amount of heat.
Interconnection of computer was possible.
The production cost was very low.
Example. Apple11, Altair 8800 and CRAY-11
Fifth generation (1986 – on word) use ULSI and artificial intelligence
The period of fifth generation is 1980-till date. In the fifth generation, VLSI technology
became ULSI(Ultra Large Scale Integration) technology.
Characteristics of Fifth Generation Computers
This generation is based on parallel processing hardware and AI (Artificial Intelligence)
software
All the high-level languages like C and C++, Java, .Net etc., are used in this generation.
Development of true artificial intelligence
Development of Natural language processing
Advancement in Parallel Processing
Advancement in Superconductor technology
More user-friendly interfaces with multimedia features
Availability of very powerful and compact computers at cheaper rates.
2. Basic organization of a computer
A computer is an electronic device which may be used to perform various computations involving
arithmetic and logical operations. The following figure shows the major components of a
computer.
As seen in the figure, the major components in a computer are the central processing unit (CPU),
input device(s), output devices(s) and the memory. These components interact with each other
using buses
Central Processing Unit (CPU)
The CPU is the unit in which all processing activities take place. The CPU is a classic
example of a very large scale integrated (VLSI) electronic circuit that consists of the
arithmetic and logic unit (ALU), the control unit (CU) and some registers.
The following figure shows the layout of a CPU.
The ALU contains circuits using which various arithmetic and logical operations may be
executed. These circuits include adders (for addition), subtractors (for subtraction),
comparators (for comparison of operands), etc.
The CPU, also known as the brain of a computer, is the unit which is responsible for
generating control signals. These control signals control the working of the various
components within a computer.
The registers present inside the CPU may be considered to be a set of high-speed storage
devices. Some of these registers are assigned the task of holding special data or
instructions. Such registers are known as special purpose registers, whereas others are
known as general purpose registers.
The units present inside the CPU interact with each other through an internal bus.
Signals generated by the CPU also control the activities of the various components within
the CPU.
Apart from the internal bus, three other buses also interface the CPU. The control bus
carries control signals generated by the CPU to the memory and all the peripherals.
The address bus carries an address to locate a word in the memory. Finally, the data bus is
used to carry data and information to and from between the components of the computer.
In addition to the units mentioned so far, modern day CPUs are also equipped with high-
speed, on-chip memory units known as the cache memory.
Input Devices
Input devices are the ones through which users are allowed to input data and other instructions to
the computer. The most popular choices for input devices are the keyboard and the mouse. Other
examples include scanners, readers, etc.
Output Devices
Just as input devices are used to convey messages to the computer, output devices are used by the
computer to convey messages back to the users. The most common output device that almost all
computers have is the monitor. The monitor is used to display the results of computations,
messages, etc. Other examples of output devices are printers, speakers, plotters, etc.
The input and the output devices are sometimes known as peripheral devices. These auxiliary
devices may be connected to a computer and used. They are auxiliary because their existence
within a computer is not mandatory unlike the CPU or the memory.
Memory
Memory/storage unit is the component of a computer that serves data storage purposes. These
units are of varying access speeds and volatility. Access speed refers to the time taken to
store/retrieve data from the memory. Volatility refers to the duration of time or the conditions
under which data is stored in the memory. Based on these characteristic features, the computer’s
memory may be categorized into different types. The following figure shows the classification of
the computer’s memory.
As shown in the figure, the memory is broadly classified into primary memory and
secondary memory.
The primary memory, also known as the main memory, is so called because the CPU can
directly interact with it through the data bus and the address bus. The main memory is of
two major types, the random access memory (RAM) and the read only memory (ROM).
The RAM is a volatile memory that stores instructions and data related to the program
currently being executed. The RAM is volatile because it would lose all the information
stored in it as soon as the power to the computer is switched off.
The ROM is a read-only, non-volatile memory. The ROM does not permit any write
operation and is non-volatile because the information stored in it would be retained even
after the computer has been switched off. Apart from other important routines, the ROM
houses the boot strap loader. The boot strap loader is a system software that is responsible
for loading the operating system from the secondary memory into the RAM.
The secondary memory, also known as auxiliary memory, is a large depository of non-
volatile storage space that can store information for as long as we want. The secondary
memory is slower compared to the access time of the primary memory. The hard disk,
flash drives, etc. are some examples of secondary memory.
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 in order to fetch the next instruction in the sequence. When
the computer restarts, the program counter normally reverts to 0.
3. Introduction to Programming Languages
Programming languages are used to write computer programs and applications, and to control and
manipulate computer systems. There are many different programming languages, each with its
own syntax, structure, and set of commands. Some of the most commonly used programming
languages include C, C++, Java, Python, JavaScript, and C#. The choice of programming language
depends on the specific requirements of a project, including the platform being used.
A computer program is a set of instructions which when executed in sequence performs a task. For
example we may write a program to add two integer numbers. It is clear that this program would
contain three sets of instructions; the first set would enable users to input the data, the second set
to add the numbers and the third set to display the result.
However, more often than not, the problems which a computer is supposed to solve would be more
complex than this. Such complex problems would invariably require complex solutions. These
solutions involve a lot of complex arithmetic operations and logical decision making. Hence, the
need of the hour here is a tool which would enable us to represent the logic required in the
program and make it possible to transform the logic to an equivalent set of instructions which
when executed by the computer would solve the problem. Algorithms and flowcharts are two such
tools. These tools are independent of the programming language as well as the target machine.
Thus, the logic represented using one of these tools may be used to write programs in any
language of the programmer’s choice.
4. Algorithm
An algorithm is a finite set of unambiguous instructions which, when executed, performs a task
correctly. There are three characteristics of an algorithm. They are:
The number of steps required to perform the task should be finite.
Each of the instruction in the algorithm should be unambiguous in nature; meaning on the
execution of each such instruction, the outcome should be definite and predictable.
Finally, the algorithm should solve the problem correctly.
An algorithm can be represented using English like statements, or using pseudo code or even using
a flowchart. However, the most popular convention is the pseudo code.
Example 1: Develop an algorithm to find the average of three numbers
Algorithm AVERAGE
Example 2: Develop an algorithm to divide one number by another and find the quotient.
Example 3: Develop an algorithm to find the maximum of two numbers.
Example 4: Develop an algorithm to find the sum of the first N natural numbers
5. Flowchart
A flow chart is a pictorial or graphical representation of an algorithm. Just like the algorithm, the
flowchart is also a tool to represent logic. Unlike the algorithm, the flowchart uses some standard
notation to graphically represent the logic. The following table shows various symbols used in a
flowchart.
Example 1: Draw the flowchart to find the average of three numbers
Example 2: Draw the flowchart to divide one number by another and find the quotient.
Example 3: Draw the flowchart to find the maximum of two numbers.
Example 4: Draw the flowchart to find the sum of the first N natural numbers
6. Pseudocode
Pseudocodes are a means to represent an algorithm in a coded form. The specifications used in a
pseudocode are syntactically not stringent as in a program code. However, they represent the steps
of an algorithm in a coded form which very closely resembles program code. Given a pseudocode,
translation of the same into program code is relatively easy. A pseudocode may be considered to be
an intermediate code between an algorithm and program code. The pseudocode for the algorithm
in Example 4 is as follows:
7. Introduction to Compilation and Execution
The compilation is the process of converting the source code of the C language into machine
code. As C is a high-level language, it needs a compiler to convert it into an executable code so
that the program can run on our machine.
Executing a program written in c involves a series of steps. These are:
Creating the program.
Compiling the program.
Linking the program with functions that are needed from c library.
Executing the program.
Creating: we can create or write a c program using turbo c –IDE. In this, tc.exe will be there
double click on this we get blue screen then type the c program and save the file using F2 key with
an extension..c .
Compiling: In turbo C compiler use Alt+F9 to compile the c-program, to check whether the
source code contains any errors. If source contains errors then goto step1 to modify the source
program. Aftercompiling the source program we get .obj file.
Linking: This process is inbuilt in step2 in turbo Compiler. The .obj file is given as input to linker.
The linker checks for errors. If object code contains any errors then goto step1 to modify. If the
object code is error free then linker converts .obj files into .exe file.
Executing: CTRL+F9 in turbo C.
Pictorially the above steps can be shown as given below.
8. Primitive Data Types
Every variable in C has a data type. Data type specifies the size and type values that can be stored.
C language supports 2 different types of data types,
Primary data types or Primitive Data Types
o These are fundamental data types in C namely integer (int), floating(float),
character (char) and void.
Derived data types
o Derived data types are like arrays, functions, structures and pointers.
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
long int or signed long int 4 -2,147,483,648 to
2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Float type
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine.
Type Size(bytes) Range
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
Void type
void type means no value. This is usually used to specify the type of functions.
9. Variables and Constants
Variables
A variable is a data name that may be used to store a data value. A variable may take different
values at different times during execution.
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.
2. A variable name can start with the alphabet, and underscore only. It can't start with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Some examples of valid variable names are:
Invalid examples include:
Further examples of variable names and their correctness are given in the following table.
Declaration of variables
After defining variable names, we must declare them to the compiler. Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
The syntax for declaring a variable is
Data-type v1,v2,......vn;
Where v1,v2,......vn are the names of variables. Variables are separated by commas. A declaration
statement must end with a semicolon. For example, valid declarations are:
int a;
int number, total;
float area;
Initializing values to variables
Values can be assigned to variables using the assignment operator = as follows:
The syntax is:
Variable_name = value;
E.g.: int a=20;
bal=75.84;
yes=‟x‟;
Note: We can also initialize more than one variable in one statement using multiple assignment
operators.
e.g.: a=b=c=10;
Constants
Constants in C refer to fixed values that do not change during execution of a program. The
following figure shows categorization of constants.
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers namely
decimal integers, octal integers and hexadecimal integer.
1. Decimal integers consists of a set of digits 0 to 9 preceded by an optional – or + sign.
Valid examples of decimal integer constants are:
123 -321 0 654321
Invalid Examples: 15 750 20,000 $1000
2. Octal integers consist of any combination of digits from set 0 to 7, with a leading 0.
Examples: 037 0 0435 0551
3. Hexadecimal integers are a sequence of digits preceded by 0x or 0X. This may also
include alphabets A to F(represents numbers from 10 to 15).
Examples: 0x2ef, 0X, 0XABD
Real constants
Integer numbers are inadequate to represent quantities that vary continuously, such as distances,
heights, temperatures and so on. These quantities are represented by numbers containing fractional
parts like 17.548. Such numbers are called as real constants.
Examples: 0.0083 -0.75 435.36 +247.0
A real number can be expressed in exponential notation.
Mantissa e exponent
i. The mantissa is either a real number expressed in decimal notation or an integer
ii. The exponent is integer number with optional plus or minus sign.
iii. The letter e separating the mantissa and the exponent can be written in either lowercase or
uppercase i.e., 0.65e4, 12E-2
Character constants
A character constant consists of a single character enclosed in single quotes.
Example: ‘a’ ‘c’ ‘D’
String constants: A string constant is a sequence of characters enclosed in double quotes.
Example: “Gudlavalleru” “23481A0501” “a”
Declaration of constants
We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.
Syntax:
const data_type var_name = value;
Example program:
#include <stdio.h>
void main()
{
const int int_const = 25;
const char char_const = 'A';
const float float_const = 15.66;
printf("Printing value of Integer Constant: %d\n", int_const);
printf("Printing value of Character Constant: %c\n", char_const);
printf("Printing value of Float Constant: %f", float_const);
}
10. Basic Input and Output Operations
Formatted and Unformatted I/O
scanf():
Formatted input refers to an input data that has been arranged in a particular format.
Ex: 15.73 123 john
The above line contains three pieces of data, arranged in a particular form. Such data has to be
read conforming to the format of its appearance.
The first part of the data should be read into a variable float, the second into int, the third part into
char. This is possible in C using the scanf() is:
scanf(“Control String”, arg 1, arg 2,..............arg n);
The control string specifies the field format in which the data is to be entered and the arguments
arg1, arg2,................arg n specify the address of locations where the data is stored.
Control string and arguments are separated by comma(,). Control string contains field
specifications, which direct the interpretation of input data. It may include:
Field specifications consisting of the conversion character %, a data type character, and
optional number specifying the field width.
Blanks, tabs, or newlines.
Blanks, tabs and newlines are ignored. The data type character indicates the type of data that is to
be assigned to the variable associated with the corresponding argument. The field width
specifier(w) is optional.
By using scanf() statement we can read three types of values. They are:
1. Inputting Integer numbers: The field specification for reading an integer number is %wd.
2. Inputting Real numbers: The field specification for reading a real number is %wf.
3. Inputting character strings: The field specification for reading a character or string is %wc
or %ws.
printf():
The use of printf function for printing captions and numerical results. It is highly desirable that the
outputs are produced in such a way that they are understandable and are in an easy-to-use form.
The general form of printf statement is:
printf(“Control String”, arg 1,arg 2,............arg n);
Control String consists of three types of items:
Characters that will be printed on the screen as they appear.
Format specifications that define the output format for displaying of each item.
Escape sequence characters such as \n, \t, \b.
The control string indicates how many arguments follow and what their types are. The arg1,arg
2,..........arg n are the variables whose values are formatted and printed according to the
specifications of the control string. The arguments match in number, order and type with the
format specifications.
By using printf statement we can produce four types of values. They are:
Output of Integer Numbers: The format specification for printing an integer number is %wd.
Output of Real Numbers: The output of a real number may be displayed in decimal notation
using the following format specification is %wf.
Printing of a String Character: A single character can be displayed in a desired position using
the format %wc.
Printing of strings: The format specification for outputting strings is similar to that of real
number. The format specification is %ws
11. Type conversion
The conversion from one data type to another data type is known as Type Conversion. C provides
two types of Type Conversion techniques.
1. Implicit type conversion or Automatic type conversion.
2. Explicit type conversion.
Implicit or Automatic type conversion
When an operator has operands of different types, they are converted to a common type according
to semantic rules of a language. This is known as “automatic type conversion”, because it is done
by the compiler on its own, without any external trigger from the user. In general, the only
automatic conversions are those that convert a “narrower” operand into a “wider” one without
losing information.
Example: converting an integer to floating point value.
Explicit type conversion
The process of local conversion is known as Explicit conversion or Casting a value. The general
form of a cast is:
(type_name) expression;
Where type_name is one of the standard C data types. The expression may be a constant, variable
or an expression.
Example:
#include<stdio.h>
main()
{
float x=1.2;
int sum;
sum=(int)x+1;
printf(“sum=%d”,sum);
}
Output:
Sum=2
12. Problem solving techniques
There are typically two primary ways to approach problem-solving - "top-down approach" and
"bottom-up approach".
Top-down approach
Top-Down Approach is an approach to design algorithms in which a bigger problem is broken
down into smaller parts. Thus, it uses the decomposition approach. This approach is generally
used by structured programming languages such as C, COBOL, FORTRAN.
The drawback of using the top-down approach is that it may have redundancy since every part of
the code is developed separately. Also, there is less interaction and communication between the
modules in this approach.
The implementation of algorithm using top-down approach depends on the programming
language and platform. Top-down approach is generally used with documentation of module and
debugging code.
Bottom-up approach
Bottom-Up Approach is one in which the smaller problems are solved, and then these solved
problems are integrated to find the solution to a bigger problem. Therefore, it uses composition
approach.
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.
Time and Space Complexities of Algorithms
Time Complexity
Time complexity is defined as the amount of time taken by an algorithm to run, as a function of
the length of the input. It measures the time taken to execute each statement of code in an
algorithm and then the total execution time of an algorithm is obtained.
Space complexity
Space complexity refers to the total amount of memory space used by an algorithm/program,
including the space of input values for execution. Calculate the space occupied by variables in an
algorithm/program to determine the space complexity.