Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

UNIT 1 Introduction To Programmming and Problem Solving

Uploaded by

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

UNIT 1 Introduction To Programmming and Problem Solving

Uploaded by

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

Introduction To Programming

UNIT – 1
INTRODUCTION TO PROGRAMMING AND PROBLEM SOLVING
HISTORY OF COMPUTERS
 To perform computations we use machines.
 The earliest tool is abacus, a device used in china and United States
today as a hand held calculator.
 They require human involvement.
 The first attempt was made by Charles Babbage in creating a
programmable computing machine in England in 1822.
 Ada Byron the daughter of famous poet Lord Byron developed the
instruction set for the machine.
 The machine that Babbage called it was analytical engine.
 In 1937, Dr. John V Atanasoff and a graduate student, Clifford Berry
developed a machine called ABC using electrical components at Lowa
State University.
 The goal internally was to store a set of instructions. In 1939, Dr.
John W Mauchly from Moore college of Engineering at Pennsylvania
University along with Presper Eckert developed a computer called
ENIAC( Electrical Numerical Integrator And Computer).
 The fund was given by US government and was completed in 1946.
 It consists of 18000 vacuum tubes and can perform 5000 additions
and 360 multiplications in one second.
 At the same time Mark developed a computer by name Mark I at
Harvard University using mechanical relays and completed in 1944.
 But it could perform only 6 multiplications in one second.
 The final goal of storing the program in computer was achieved in
1949 at Cambridge University with the successful operation of
EDSAC(Electronic Delayed Storage Automatic Computer).
 This contains memory where it could store data.
 The principles for storing the data and retrieve data and instructions
has been proposed by John Von Neumann.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
1
Introduction To Programming

BASIC ORGANIZATION OF A COMPUTER


A computer is an electronic device that takes data and instructions as
input, processes data and provides output.
BLOCK DIAGRAM OF COMPUTER

CENTRAL PROCESSING UNIT (CPU)


 The ALU and the CU of a computer system are jointly known as the
central processing unit.
 You may call CPU as the brain of any computer system.
 It is just like brain that takes all major decisions, makes all sorts of
calculations and directs different parts of the computer functions by
activating and controlling the operations.

ARITHMETIC LOGICAL UNIT (ALU)


 After you enter data through the input device it is stored in the
primary storage unit.
 The actual processing of the data and instruction are performed by
Arithmetic Logical Unit.
 The major operations performed by the ALU are addition, subtraction,
multiplication, division, logic and comparison.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
2
Introduction To Programming

 Data is transferred to ALU from storage unit when required.


 After processing the output is returned back to storage unit for further
processing or getting stored.

CONTROL UNIT (CU)


 The next component of computer is the Control Unit, which acts like
the supervisor seeing that things are done in proper fashion.
 Control Unit is responsible for coordinating various operations using
time signal.
 The control unit determines the sequence in which computer
programs and instructions are executed.
 Things like processing of programs stored in the main memory,
interpretation of the instructions and issuing of signals for other units
of the computer to execute them.
 It also acts as a switch board operator when several users access the
computer simultaneously.
 Thereby it coordinates the activities of computer’s peripheral
equipment as they perform the input and output.

INPUT UNIT
 Computers need to receive data and instruction in order to solve any
problem.
 We need to input the data and instructions into the computers.
 The input unit consists of one or more input devices.
 Keyboard is the one of the most commonly used input device.
 Other commonly used input devices are the Mouse, Scanner,
Microphone, etc.
 All the input devices perform the following functions.
 Accept the data and instructions from the outside world.
 Convert it to a form that the computer can understand.
 Supply the converted data to the computer system for further
processing

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
3
Introduction To Programming

OUTPUT UNIT
 The output unit of a computer provides the information and results of
a computation to outside world.
 Printers, Visual Display Unit (VDU) are the commonly used output
devices.
 Other commonly used output devices are Speaker, Headphone,
Projector, etc.

MEMORY OR STORAGE UNIT


 The storage unit of the computer holds data and instructions that are
entered through the input unit, before they are processed.
 It preserves the intermediate and final results before these are sent to
the output devices.
 It also saves the data for the later use.
 The various storage devices of a computer system are divided into two
categories.

a) Primary Storage
 Stores and provides very fast.
 This memory is generally used to hold the program being currently
executed in the computer, the data being received from the input unit,
the intermediate and final results of the program.
 The primary memory is temporary in nature.
 The data is lost, when the computer is switched off.
 In order to store the data permanently, the data has to be transferred
to the secondary memory.
 The cost of the primary storage is more compared to the secondary
storage.
 Therefore, most computers have limited primary storage capacity.

b) Secondary Storage
 Secondary storage is used like an archive. It stores several programs,
documents, data bases etc.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
4
Introduction To Programming

 The programs that you run on the computer are first transferred to
the primary memory before it is actually run.
 Whenever the results are saved, again they get stored in the secondary
memory.
 The secondary memory is slower and cheaper than the primary
memory.
 Some of the commonly used secondary memory devices are Hard disk,
CD, etc.,

c) Memory Size
 All digital computers use the binary system, i.e. 0’s and 1’s.
 Each character or a number is represented by an 8-bit code.
 The set of 8 bits is called a byte.
 A character occupies 1-byte space.
 A numeric occupies 2-byte space.
 Byte is the space occupied in the memory.
 The size of the primary storage is specified in KB (Kilobytes) or MB
(Megabyte).
 One KB is equal to 1024 bytes and one MB is equal to 1024KB.
 The size of the primary storage in a typical PC usually starts at 16MB.
 PCs having 32MB, 48MB, 128MB, 256MB memory are quite common.

PROGRAM COUNTER
 A register is a small place for data holding that the processor uses.
 Program counter is just a small register that could hold 8 bit or 16 bit
data.
 It depends on the processor that process data either 8 bit or 16 bit.
 In computing, a program is a specific set of ordered operations for a
computer to perform.
 An instruction is an order given to a computer processor by a
program.
 Within a computer, an address is a specific location
in memory or storage.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
5
Introduction To Programming

 A program counter is a register in a computer processor that contains


the address (location) of the next instruction being executed by the
processor.
 As each instruction gets fetched, the program counter increases its
stored value by 1.
 After each instruction is fetched, the program counter points to the
next instruction in the sequence.
 When the computer restarts or reset, the program counter normally
reverts to 0.
 It is used to keep track of all instructions that are to be processed.

INTRODUCTION TO PROGRAMMING LANGUAGES


 The computer operations are controlled by a set of instructions called
computer program. These instructions are written to tell the
computer about
 What operation to perform
 Where to locate data
 How to present the results
 When to make certain decisions
 Programming is the process of writing the instructions that the
computer can respond to and that the other programmers can
understand.
 The set of instructions that are used to construct a program are
programming languages.
 The communication between two parties needs language. The
language used to communicate the computer instructions is known as
programming language.
 There are different levels of programming languages. They are
 Machine language (low level languages)
 Assembly level language(symbolic languages)
 Procedure oriented language(high level languages)
 Object Oriented Languages

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
6
Introduction To Programming

MACHINE LANGUAGE
 Machine language is referred as first generation languages.
 It is also known as low level language.
 It was introduced in the year 1940.
 Computer is an electronic device that can understand only binary
codes hence the computer instructions and data are written using
binary codes 1 and 0.
 The binary code is called machine code or machine language.
 All computer designs are not same because they have their own
machine language and they cannot understand any language like
English, Telugu, Tamil etc except machine language.
 There are some problems with the machine language.
 It is difficult to understand and remember the various
combinations of 0’s and 1’s for instructions and data.
 Writing error free instructions is a slow process.
 The user cannot communicate with other machine because
every machine has its own machine language

ASSEMBLY LANGUAGE (SYMBOLIC LANGUAGES)


 The assembly language is referred as second generation languages.
 It was introduced in 1950.
 In assembly language, the machine language 0’s and 1’s are replaced
by mnemonic codes.
 The assembly language consists of series of instructions and
mnemonics.
 These mnemonics corresponds to executable instructions which are
followed by zero or more operands.
 The mnemonic code is called operation code or opcode which
specifies the operation to be performed based on given operands.
 During the execution of the program, an assembler is used.
 The assembler is a software program that takes assembly level
language program as input and produces machine code as output.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
7
Introduction To Programming

 The programmers even today they prefer assembly language for


performing various tasks.
 To initialize and test the system hardware
 To write patches for disassembling viruses
 To attain optimization
 For direct interaction with hardware
 To maximize limited resource utilization
 For high security

Advantage of assembly language over machine language


 easy to debug because we can locate and identify syntax
 easy to develop computer application
 operates very efficiently

HIGH LEVEL LANGUAGES


 These languages easily modify the program to reduce the number of
operations.
 They are easy to use, portable and abstract when compared to low
level languages.
 They use logic to solve the problem.
 The high level languages are executed by using a compiler or an
interpreter.
 The high level languages are classified into three categories.
 Procedure oriented languages (third generation)
 Problem oriented languages (fourth generation)
 Natural languages (fifth generation)

Procedure oriented languages


 The high level languages designed to solve general purpose problems
are called procedural languages or third generation languages.
 They are designed to express logic and procedure of a problem.
 The advantage of third generation languages is they are portable.
 We can use any compiler or interpreter and create object code.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
8
Introduction To Programming

 The third generation languages are considered as domain specific


because they are designed to develop specific applications.

Problem oriented languages


 These languages are used to solve specific problems.
 They are also known as fourth generation languages.
 These languages have reduced programming efforts and over all cost
of software development.
 These languages use visual or text environments.
 A single statement in fourth generation is equivalent to multiple
statements in third generation for a task.
 The programmer uses drag and drop toolbar for creating various
items.
 These languages are used to facilitate faster environment for
application development.

Natural languages
 These languages are known as fifth generation languages.
 These languages are designed to make computer to behave like expert
and solve problems.
 The programmer specifies both the problem and its constraints for
problem solving.
 These languages are used to develop artificial intelligence and
expert systems.
 The fifth generation languages allow users to communicate with the
computer in simple and easy manner.

OBJECT ORIENTED PROGRAMMING LANGUAGES


 It focuses on developing software based on their component objects.
 The components interact with each other to provide functionality of the
software.
 In OOP, the software is broken down into components consists of data
attributes and methods that operate on data.
 The components are complete by themselves and are re-usable. The
terms that commonly associated with OOPS are
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
9
Introduction To Programming

 Class is the basic building block of the OOP, a class consists data
attributes and methods that operate on data.
 Object is runtime instance of the class. An object has a state, a defined
behavior and unique identity.
 The state of the object is represented by the data defined in the class.
 Class is template for object.
 Abstraction, Encapsulation, Inheritance and Polymorphism are unique
features of OOP

BASICS OF A COMPUTER PROGRAM


ALGORITHMS
 An algorithm is defined as a finite sequence of instructions each
of which has a clear meaning and can be performed with a finite
amount of effort in a finite amount of time.
 An algorithm is a method of finding solution in solving a problem.
 An algorithm is step by step procedure to solve a problem.
 Algorithms are used to find right solution to variety classification
problems.
 The algorithm word originated from the Arabic word “Algorism”
which is linked to the name of the Arabic mathematician AI
Khwarizmi.
 He is considered to be the first algorithm designer for adding
numbers.
 In algorithm all steps must unambiguous.

Structure of Algorithm
The structure contains the following steps:
 Input Step
 Assignment Step
 Decision Step
 Repetitive Step
 Output Step

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
10
Introduction To Programming

Properties of Algorithms
 Finiteness: An algorithm must terminate after a finite number of
steps.
 Definiteness: The steps of the algorithm must be precisely defined or
unambiguously specified.
 Generality: An algorithm must be generic enough to solve all
problems of a particular class.
 Effectiveness: The operations of the algorithm must be effective such
that it must easily converted into machine code in a finite amount of
time.
 Input-Output: The algorithm must have zero, one or more inputs and
one or more outputs.

Algorithm for adding two numbers


Step1: Start
Step2: Read two numbers a, b
Step3: Compute result=a + b
Step4: Display the result
Step5: Stop

Algorithm for to check even or odd


Step1: Start
Step2: Read the value n
Step3: Compute if n modulo division by 2 is equal to 0 then goto step 4 &
then to step step 6 otherwise goto step 5
Step4: Display even number
Step5: Display odd number
Step6: Stop

FLOW CHARTS
 Flow chart is diagrammatic representation of an algorithm.
 It is built using different types of boxes of symbols.
 The operation to be performed is written in the box.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
11
Introduction To Programming

 All symbols are interconnected by arrows to indicate the flow of


information and processing.

Example:

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
12
Introduction To Programming

Oval Terminal Start/stop/begin/end symbol

Making data available for


processing (input) or recording
Parallelogram Input/Output
of the processed information
(output).
Any processing to be
performed. An assignment
Rectangle Process
operation normally
represented by this symbol.
Decision or switching type of
operations that determines
Diamond Decision
which of the alternative paths
is to be followed.
Used for connecting different
Circle Connecter
parts of flow chart.

Joins two symbols and also


Arrow Flow
represents executions flow.

Bracket with Descriptive comments or


Annotation
broken line explanations

Double sided Predefined Modules or subroutines given


rectangle process elsewhere.

PSUEDO CODE
 The enhanced form of an algorithm that focuses on logic of the
program is called pseudo code.
 It refers to false code written in a programming language.
 It does not have any syntax for representation but normally used
structured English language for representation.
 It helps programmer to understand the basic logic before writing the
final code in a particular language.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
13
Introduction To Programming

EXAMPLE
To add two numbers
1. DEFINE n1, n2, result
2. READ n1, n2
3. COMPUTE result – n1 + n2
4. DISPLAY result
5. EXIT

Advantages of Pseudo Code


1. It is easier to modify the program logic when necessary.
2. It takes less time for writing it
3. It takes less effort for writing it
4. Converting it to programming code is easier.
5. It does not have any syntax therefore we can write it as we like.

Disadvantages of Pseudo Code


1. A graphic representation of program logic is not available.
2. There is no standard rule for representation of it.
3. Several programmers follow different styles to write it.
4. Communication problem occurs due to lack of standards.
5. For beginners it is difficult to follow.

INTRODUCTION TO COMPILATION AND EXECUTION


 The procedure for converting a program written in C language into
machine language is shown below.
 The responsibility of programmer is to write and test the program.
 There are four steps in this process:
 Writing and editing program
 Compiling the program
 Linking the program with required libraries
 Executing the program

Writing and Editing Programs


 Text editor is software used for writing the programs.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
14
Introduction To Programming

 It helps to enter, change and store character data.


 The main difference between text processing and program writing is
programs are written using lines of code and text processing is done
with characters and lines.
 The text editor is a word processor which is included in the compiler
 The features of text editor are
 Search
 Replace
 Copy
 Paste
 Formatting and alignments
 After writing a program we save it on the disk which is input to the
compiler and it is known as source file.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
15
Introduction To Programming

Compiling Programs
 The job of the compiler is to convert the source file into machine
language.
 There are two separate programs in C compiler:
 Preprocessor
 Translator
 The preprocessor reads the source code and prepares it for the
translator. It scans for preprocessor commands and tell to replace the
code.
 The result of preprocessing is translation unit.
 The translator does the actual work of converting the program to
machine language. The translator reads translation unit and produce
object module as output
 This is not yet ready to run because it needs required functions to
include.

Linking Programs
 C program is made up of many functions, some we write and some
they are part of the source program
 There are other functions like input/output and mathematical
libraries that are attached to source program
 The linker assembles all these functions to make it finally executable.

Executing Programs
 The program is ready for execution if it is linked with necessary
routines.
 To execute the program we use OS command run to load the program
in main memory and execute it.
 The loading activity is done by loader.
 The program execution means
 Reads data for processing from file or from user
 Process the data
 Prepare the output for the user

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
16
Introduction To Programming

STRUCTURE OF A C PROGRAM
 Every C program is made up one or more preprocessor commands, a
global declaration section and one or more functions
 The global declaration section is before main function. It is visible to
all parts of the program
 The work is carried out by its functions. One function is main(). It
indicates the beginning of the program.
 All functions in the program including main are divided into two parts:
declaration and statements

 Declaration part contains all the declarations of the variables used in


the program called local declarations. They are visible to only that
function.
 Statements part contains all executable instructions to the computer
to do something.
 The simple C program is shown below to illustrate various features

Preprocessor Commands
 They come at the beginning of the program.
 They start with pound sign (#).
 They are special instructions to the preprocessor to prepare the
program for compilation.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
17
Introduction To Programming

 The most important preprocessor command is include which tells


preprocessor to include selected libraries known as header files.
 The complete syntax for this command in this example is
#include<stdio.h> tells to include input / output library file to the
program

main()
 The executable part of the program begins at this point.
 The syntax is int main(void)
 int specifies that the function returns an integer value to the
operating system
 main is the name of the function
 void means it has no parameters
 Within main there are two statements: one that print message and the
other to terminate the program
 The print function used library function printf to print the message on
the monitor. Where the message is a parameter in between the double
quotes to printf statement
 The second statement is return 0 to terminate the program and
indicate the OS for successful execution of the program.
 The main has two braces ‘{‘ opening brace and ‘}’ closing brace. The
opening brace indicates the beginning of the program and closing
brace indicates the ending of the program.

Comments
 Comments are two types: block comment and line comment
 Block comment is to span several lines. It uses opening and closing
comment tokens
 A token is a symbol understood by the compiler.
 Each comment token is made of two characters /* indicating the
beginning of the comment and */ indicating the ending of the
comment.
 The comment should be in between /* and */

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
18
Introduction To Programming

 For example,
/* ---------------------------
---------------------------
---------------------------
--------------------------- */
 A line comment uses two slashes to identify the comment. This does
not require end of the comment.
 For example,
//-------------------------------
 Comments cannot be nested. For example as shown below:

PRIMITIVE DATA TYPES


 A type is defined as set of values and set of operation to be performed
on those values.
 C language has defined with a set of types. There are four types:
 Void
 Integral
 Floating point
 Derived
 The diagrammatic representation types is shown below:

Void Type
 The void type is specified by keyword void which means no value or no
operations
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
19
Introduction To Programming

 Void type is very useful when function has no parameters


 It can be used to define that a function has no return values.
 It can used to define pointer to generic data.

Integral Type
 C has three integral types: boolean, character and integer.
 They contain only integral part but not fractional part

Boolean Type
 In C99, we have boolean data type.
 It was introduced by french mathematician George Boole.
 It represents two values true and false
 The boolean values: true represents non zero for positive or negative
and false represents zero.
 The boolen type is referred by bool keyword.
 In memory 0 is stored for false and 1 for true

Character Type
 A character is any value represented for alphabets in computer known
as character set.
 C has two characters types: char and wchar_t
 The size of character type is one byte.
 It can be signed or unsigned it takes one byte.
 If signed its range is -128 to 127 and if unsigned it is 0 to 255.
 The characters are grouped into letters, digits, special symbols and
punctuations.
 The letters can be lower or upper case.
 The difference between letter a and letter x is : the binary number to
store in memory and the ascii value fr them is 97 and 122.
 To support non english characters we used wchar_t.

Integer Type
 It is a number without fractional part.
 It supports four types: short int, int, long int, long long int

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
20
Introduction To Programming

 We can refer them as short, int, long, long long.


 They can be organized from small to large.

sizeof(short)<sizeof(int)<sizof(long)<sizeof(long long)

 They are machine dependent and if size is not known we use sizeof
operator to know the size.
 Integer can be signed or unsigned. If signed then one bit is used for
sign representation.
 C provides limits.h that contains size information about integers.
 The unsigned integer can be used to store positive numbers.

Floating Point Types


 There are three floating point types: real, imaginary and complex.
 C provides float.h that contains size information about floating point
 Real type values are signed.

Real Type
 It contains both integral and fractional part.
 C supports different real types are: float, double, long double
 They can be organized from small to large

sizeof(float)<sizeof(double)<sizof(long double)

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
21
Introduction To Programming

Imaginary Type
 An imaginary number is a real number multiplied by square root of -1.
 It can be of three different sizes: float imaginary, double imaginary
and long double imaginary.

Complex Type
 It is a combination of real and imaginary number separated by a plus
sign.
 It can be of three different sizes: float complex, double complex and
long double complex.
 Size need to be same for real and imaginary.

VARIABLES
 A variable is a named memory location that can be of type such as int,
float, char.
 A variable is a data name which can be used to store a data value and
a variable may take different values at different times, during
execution.

Variable Declaration
 Each variable in the program must declare before it is used.
 The declared is used to name an object but definition is used to create
an object.
 A variable can be defined and declared at the same time.
 A variable cannot be of type void.
 To create variables we first specify type and then its name.
 The syntax is
datatype variable_name;
 For example,
int n;
float x;
char y;
bool z;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
22
Introduction To Programming

Rules for Constructing Variable Names


1. A variable name is any combination of alphabets, digits and the
underscore character. ANSI standard recognizes a length of 32
characters. However, the length should not be normally more than 8
characters, since only the first 8 characters are treated as significant
by many compilers.
2. The first character in the variable name must be an alphabet.
3. No commas or blank spaces allowed.
4. No special symbol other than an underscore can be used. Ex:
bas_pay, net_salary, month etc.
5. Uppercase and lowercase are significant. That is, the variable Amount
is not the same as amount or AMOUNT.
6. Variables name should not be a keyword.

Variable Initialization
 The process of assigning a value to a variable is called intialization.
 The process of giving a value to a variable is called initialization.
 The process of presenting a value to a variable is called initialization.
 The process of specifying a value to a variable is called initialization.
 For example:
x = 10;
in the above statement the variable is “x” and the value is “10”. Here
the value 10 is given to the variable x by using assignment operator “=”.
Therefore if we want to assign a value to a variable then we need an
assignment operator. The variable here used “x” is called initialized variable.
For example:
int x=10;
float y=2.5;
char = ‘a’;
in the above statements the variables are initialized to values that are
of different data type. The variables are called initialized variables or
variables are said to be initialized.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
23
Introduction To Programming

CONSTANTS
 Constants are fixed values that cannot be changed during program
execution.
 Constants are data values that never changes during execution of a
program.
 They have type like variables.

Constant Representation
The different types of constants are
 Boolean constants
 Character constants
 Integer constants
 Real constants
 Complex constants
 String constants

Boolean Constants
 A boolean data type can take two values either true or false.
 The boolean values we can have may be 1 for true and 0 for false.
 We have to include stdbool.h header file

Character Constants
 They are enclosed between two single quotes.
 In addition we can use a backslash before a character known as
backslash character constant.
 It is known as escape sequence.
 The escape character says that what follows is not the normal
character but something else.
 For example, \n represents new line feed.
 It is of multiple symbols but represents always one character.
 Wide character constants can be coded by prefixing a letter L. For
example, L ‘x’
 The different backslash character constants are

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
24
Introduction To Programming

Integer Constants
 Integer constants are coded in simple way. For example the value 15
is coded as 15.
 If we code the number as a series of digits, its type can be signed or
unsigned.
 The types of integers are: int, short int, long int, long long int
 The different ways to represents long int and long long int is l or L and
ll or LL.
 For unsigned it is u or U.
 To avoid confusion we represent capital letters only.

Real Constants
 The default form of real value is double.
 If we want the result to be float or long double then use f or F for float
and l or L for long double

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
25
Introduction To Programming

Complex Constants
 They are code as two parts: real part and imaginary part, separated by
a plus sign.
 We should use complex.h header file.
 The real value of complex has same rules as real constant and
imaginary is coded as real number times the imaginary constant
denoted as I.

String Constants
 A sequence of zero or more characters enclosed between double
quotes is called string constant.
 The difference between null string and empty string is shown below
‘\0’ is null string
“ “ is empty string

Coding constants
The different coding constants are
 Literal constants
 Defined constants
 Memory constants

Literal Constants
 It is an unnamed constant used to specify data.
 They can be simply used in the statement if it does not need to be
changed
 They are coded as a part of the statement as follows
a=b+5
Defined Constants
 They are defined by using a preprocessor command.
 They are placed at the beginning of the program.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
26
Introduction To Programming

 For example,
#define PI 3.14
Memory Constants
 They use C type qualifier denoted by const to indicate the data cannot
be changed.
 For example,
const float cpi = 3.14
BASIC INPUT / OUTPUT
Streams
 A stream is a source or destination for data.
 Data is input to and output from a stream.
 It is associated with physical device.
 C uses two types of streams: text and binary.
 A text stream consists of sequence of characters where each line is
terminated by new line.
 A binary stream consists of sequence of data values such as integers,
float etc.
 Terminal is associated with text stream, to take input by keyboard
and output by monitor.
 The keyboard is standard input and monitor is standard output

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
27
Introduction To Programming

Formating Input / Output


 We receive text streams through keyboard and send text streams to
monitor
 In C there are two formating functions: printf for output formating and
scanf for input formating
 The printf converts data stored in the program to text stream for
output to monitor
 Scanf converts the text stream from keyboard of data values and store
them in program variables.

Input formatting: scanf()


 The scanf() function is used to enter the data into the program while
the program is executing.
 It is also used to read the input using format specifications.
 The general format of scanf() function is
scanf(“control string”, list of parameters);
in the above syntax of scanf() function the first argument is the control
string. It tells the function the type of data being input.
 Following the control string we have list of parameters. For example
scanf(“%d”, &n);
in the above example, %d indicate that it is representing integer and &
indicate address operator.
 The data is not read directly hence we use address operator before the
variable to get the address of that variable to read the value.
 Using scanf() function we can read any number of data like integers,
floats and characters. For example
scanf(“%d%f%c%s”, &n, &m, &p, q);
In the above statement %d represents integers, %f represents floats,
%c represents character and %s represents strings data.
 The problem with scanf() function is that it terminates its input on the
first white space it finds.
 A white space may a blank, tabs, carriage return, form feed and new
lines.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
28
Introduction To Programming

 For example
NEW DELHI
Then only the NEW of the string NEW DELHI will be read into the
address because after NEW there is blank space so the scanf() function
terminates reading the string.

Output formatting: printf()


 The printf() function is used to print the data and formats the data
and sends it to the standard display device (monitor).
 It prints out whatever data is provided by the program. Inputting data
or messages to the function is called passing data to the function.
 The syntax is
printf(“control strhey ing”, list of arguments);
printf(“hello C Programming”);
In the above example the hello C Programming present in double
quotes in the parenthesis of printf() statement is called message and it is
printed. The data present in the parenthesis is called function argument.
 The printf() function can be controlled by field width specifiers
included at the type conversion place in the printf() function.
 For example,
printf(“%3d”, 8);
the above statement produces the output 8 in a field width of three
spaces. In this case 8 is printed after two blank spaces.

Format Modifiers
The different types of format modifiers are as follows:
%d - decimals or integers
%f - floats
%c - characters
%s - strings
%e - exponentiation
%g - double
%o - octal

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
29
Introduction To Programming

%h - hexa decimal

Left justification
Numbers displayed using printf() statement by using right justification
but if you want to get the output to be left justified then we have to use a (-)
sign format modifier.
printf(“%-10d”, 78);
produces output
78
Explicit Sign Display
Normally, the sign of a number is to display for negative numbers. But
for positive and negative numbers signs to be displayed we use a (+) format
modifier.
printf(“%+10d”, 78);
+78

OPERATIONS
An operator is a symbol that performs an operation like arithmetic
operations, logical operations, conditional operations, etc. These operations
are performed using different types of operators. They are listed below:
1. arithmetic operators
2. relational operators
3. logical operators
4. increment and decrement operators
5. conditional or ternary operators
6. assignment operators
7. bitwise operators
8. special operators

Arithmetic Operators
 The arithmetic operators that we come across in ‘C’ language are +, -,
*, /and %.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
30
Introduction To Programming

 All of these operators are called ‘binary’ operators as they operate on


two operands at a time.
 Each operand can be an int or float or char.
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division.
Ex:
int x, y, z;
z=x+y;
z=x-y;
z=x*y;
z=x/y;

If both operands are integers, then the expression called an integer


expression and the operation is called integer arithmetic. Integer arithmetic
always yields an integer value.

If both operands are real, then the expression is called a real


expression and the operation is called real arithmetic. A real operand may
be either in decimal or exponential notation. Real arithmetic always yields a
real value. The modulus (%) operator cannot be used for real operands.

If one of the operand is real and other is integer then the expression is
called mixed-mode arithmetic expression. Here only the real operation is
performed and the result is always in real form.

Relational Operators
 The relational and equality operators are used to test or compare
values between two operands.
 The relational and equality operators produce an integer result to
express the condition of the comparison.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
31
Introduction To Programming

 If the condition is false then the integer result is 0. If the condition is


true then the result is non-zero.

Operator Meaning

< is less than

<= Is less than or equal to

> Is greater than

>= Is greater than or equal to

== Is equal to

!= Is not equal to

Ex:
int x, y, z;
z=x<y;
z=x>y;
z=x<=y;
z=x>=y;
z=x==y;
z=x!=y;

Logical Operators
 Logical operators are used to combine two or more relations.
 The logical operators are called Boolean operators. Because the tests
between values are reduced to either true or false, with zero being
false and one being true.

Operator Meaning

&& Logical AND

|| Logical OR

! Logical NOT

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
32
Introduction To Programming

 The expressions can be connected like the following:


(expression 1) &&/|| (expression 2)
Operands Results
Exp 1 Exp 2 Exp 1 && Exp 2 Exp 1 || Exp 2
0 0 0 0
0 Non zero 0 1
Non zero 0 0 1
Non zero Non zero 1 1

Increment and Decrement Operators


 The increment (++) and Decrement (--) operators are add one and
subtract one.
 These are unary operators since they operate on only one operand.
 The operand has to be a variable.
 The increment or decrement of the value either before or after the
value of the variable is used.
 If the operator appears before the variable, it is called a prefix
operator.
 If the operator appears after the variable, it is called a postfix operator.
Operator Meaning
a ++ Post increment
++a Pre increment
a-- Post decrement
--a Pre decrement

a++ and ++a is the same when the statements are independent like
a=5; a=5;
a++; ++a;
In the both cases a value will be 6.

 When the prefix ++ (or--) is used in an expression, the variable is


incremented (or decremented) first and then the expression is
evaluated using with the new value of the variable.
 Where as the postfix ++ (or --) is used in an expression, the expression
is evaluated first using with the original values of the variables and
then the variable is incremented (or decremented) by one.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
33
Introduction To Programming

 Consider the following:


a=5;
b=a++;
In this case the value of a would be 6 and b would be 5.If we write the
above statement as
a=5;
Operator Meaning
b=++a;
a = a+1 or Adds one to a and In this case the
a+=1 Assigns the value to a value of ‘a’ would be 6
a = a -1 or Decrements a by 1 and ‘b’ would be 6.
a-=1 And assigns it to a
a = a /(b+5) or Divides a by b+5 and
a / = (b+5) Assigns result to a
a = a *(b+5) or Multiplies b+5 with a
a * = b+5 And assigns result to a

Conditional Operator (Or) Ternary Operator


 The conditional operator pair “? and :” are sometimes called ternary
operator since they take three operands, and it is condensed form of
an if-then-else C statement.
 The general form is:
exp 1? exp 2: exp 3;
 The operator ?: works as follows: exp1 is evaluated first. If it is
nonzero(true), then the expression exp2 is evaluated. If exp1 is false,
exp3 is evaluated. Note that only one of the expression is evaluated.

Ex:
y=(x>5? 3:4) is equivalent to if(x>5)
then
y=3;
else
y=4;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
34
Introduction To Programming

Assignment Operators
 Values can be assigned to variables using the assignment operator ‘=’
as follows:
Variable_name=constant;
 Ex: balance=1278;
Yes=’x’;
 C permits multiple assignments in one line. For example,
balance=1278;Yes=’x’; are valid statements.
 An assignment statement implies that the value of the variable on the
left of the ‘equal sign’ is set equal to the value of the quantity (or the
expression) on the right.
 The statement year=year+1; means that the ‘new value’ of year is
equal to the ‘old value’ of year plus 1.
 It is also possible to assign a value to a variable at the time the
variable is declared. This takes the below form:

Data type var_name=constant;

 Assignment operators are used to assign the result of an expression to


a variable, usual assignment operator is ‘=’. In addition C has a set of
‘shorthand’ assignment operators.
 Syntax:
V op= exp
Here V is a variable, exp is an expression and op is a binary arithmetic
operator. The operator op = is known as the shorthand assignment operator.
The following are the shorthand assignment operators.
+= add assignment operator
-= minus assignment operator
*= multiply assignment operator
/= divide assignment operator
%= modulus assignment operator

Ex:
X+ = y is equivalent to x= x + y

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
35
Introduction To Programming

x- = y is equivalent to x= x - y
x*=y is equivalent to x=x*y
x/=y is equivalent to x=x/y
x%=y is equivalent to x=x%y

Bitwise Operators
 ‘C’ has a distinction of supporting special operators known as
bitwise operators for manipulation of data at bit level.
 These operators are used for testing the bits, or shifting them right or
left. Bitwise operators may not be applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ One's complement
Special Operators
 ‘C’ supports some special operators such as comma operator, sizeof
operator etc.

The Comma Operator


 The comma operator can be used to link the related expressions
together.
 A comma-linked list of expressions is evaluated left to right and the
value of right-most expression is the value of the combined
expression.
 Ex: value = (x=10,y=5,x+y);
Here first assigns the value 10 to x, then assigns 5 to y, and finally
assigns 15 to value.

The Sizeof Operator


 The sizeof() is a compile time operator and, when used with an
operand, it returns the number of bytes the operand occupies.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
36
Introduction To Programming

 Ex: m=sizeof(sum);
n=sizeof(long int);

TYPE CONVERSION AND CASTING


 It is a process of converting two different types of values into a
common type.
 It is needed to manipulate expressions.
 It is also called as type casting.
 These are 2 types.
 Implicit type conversion
 Explicit type conversion

Implicit type conversion


When the types of the two operands in a binary expression are
different, C automatically converts one type to another. This is known as
implicit type conversion.

Explicit type conversion


It is a type of conversion, which is explicitly defined within a program.
Conversion will be done with force.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
37
Introduction To Programming

PROBLEM SOLVING TECHNIQUUES


ALGORITHMIC APPROACH
An algorithm is defined as a finite sequence of instructions each
of which has a clear meaning and can be performed with a finite
amount of effort in a finite amount of time.
 An algorithm is a method of finding solution in solving a problem.
 An algorithm is step by step procedure to solve a problem.
 Algorithms are used to find right solution to variety classification
problems.
 The algorithm word originated from the Arabic word “Algorism”
which is linked to the name of the Arabic mathematician AI
Khwarizmi.
 He is considered to be the first algorithm designer for adding
numbers.
 In algorithm all steps must unambiguous.

Structure of Algorithm
The structure contains the following steps:
 Input Step
 Assignment Step
 Decision Step
 Repetitive Step
 Output Step

CHARACTERISTICS OF ALGORITHMS
 Finiteness: An algorithm must terminate after a finite number of
steps.
 Definiteness: The steps of the algorithm must be precisely defined or
unambiguously specified.
 Generality: An algorithm must be generic enough to solve all
problems of a particular class.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
38
Introduction To Programming

 Effectiveness: The operations of the algorithm must be effective such


that it must easily converted into machine code in a finite amount of
time.
 Input-Output: The algorithm must have zero, one or more inputs and
one or more outputs.

EXAMPLES
Algorithm for adding two numbers
Step1: Start
Step2: Read two numbers a, b
Step3: Compute result=a + b
Step4: Display the result
Step5: Stop

Algorithm for to check even or odd


Step1: Start
Step2: Read the value n
Step3: Compute if n modulo division by 2 is equal to 0 then goto step 4 &
then to step step 6 otherwise goto step 5
Step4: Display even number
Step5: Display odd number
Step6: Stop

PROBLEM SOLVING STRATEGIES


TOP DOWN APPROACH
 In the top-down approach, a bigger problem is divided into smaller
modules.
 It uses the decomposition approach to do it.
 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.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
39
Introduction To Programming

 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.
 In this top function of system might be hard to identify.
 In this implementation details may differ.
 The below diagrammatic representation shows the top down approach
method

BOTTOM UP APPROACH
 It is one in which the smaller problems are solved, and then these
solved problems are integrated to find the solution to a bigger
problem.
 Iit uses composition approach to do it.
 It requires a significant amount of communication among different
modules.
 It is generally used with object oriented programming paradigm such
as C++, Java, and Python.
 Data encapsulation and data hiding is also implemented in this
approach.
 The bottom-up approach is generally used in testing modules.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
40
Introduction To Programming

 The below diagrammatic representation shows the bottom up


approach method

TIME AND SPACE COMPLEXITIES OF ALGORITHMS


 The performance of algorithm can be measured in terms of:
 Time
 Space
 The performance is the amount of memory needed and time required
to run it.
 We have two methods to determine the performance of the program.
 Analytical – in analysis
 Experimental – in measurement
 Time Complexity: The time complexity of an algorithm or a program
is the running time of the program as a function of input size.
 Space Complexity: The space complexity of an algorithm or program
is the amount of computer memory required for program execution as
a function of input size.

Analysis of Algorithms
 It is a technique to compare efficiency of different algorithms
 The speed of an algorithm can be different on different computers(time
taken will be different)

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
41
Introduction To Programming

 For solving a problem, the time is expressed in terms of


mathematical function of input size.
 Two algorithms are compared based on rate of growth of that
function
 If rate of growth is higher then the algorithm takes more time as
input size increases.
 The mathematical functions are represented by using asymptotic
notations
 It depends on how the program works efficiently.
 Efficiency means less space and less time required for execution.
 Hence time and space are the factors that determine the efficiency of
the program.
 We cannot compute time in terms of seconds for the execution of the
program because of several factors.
 Therefore we consider frequency count as time taken for execution of
the program.
 The frequency count is defined as the total number of times each
statement is being executed.

For example
Let us consider three program segments as follows:
Segment – A
x= x+1;
It is executed only once. Hence frequency count is 1.
Segment – B
for(i=1;i<n;i++)
{
printf(“%d”,i);
}
The frequency count is reprsented as
i=1 ---------------> 1
i<n ----------------> n+1
i++ ----------------> n

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
42
Introduction To Programming

printf(“%d”,i) ----------------> n
 1 + (n+1) + n + n
= 3n + 2
Segment – C
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(“%d”,i);
}
}

The frequency count is reprsented as for the first for loop the
frequency count is
1+(n+1) +n+n = 3n+2
 Total frequency count is
(2n+2) * (3n+2)
= 6n2 + 4n + 6n + 4
= 6n2 + 10n + 4
Now computing time complexity is very freom frequency count.
 for Segment – A it is O(1)
 for Segment – B it is O(n)
 for Segment – C it is O(n2)

The above time complexity is obtained by removing constans in the


equations. It is expressed in terms of big “O” notation.

For example:
6n2 + 10n + 4
The above equation remove constants and see the higher of n
representation. It is n2.
 time complexity is O(n2)

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
43
Introduction To Programming

Analyzing Algorithms
 Suppose “M” is an algorithm, and suppose “n” is the size of the input
data. Clearly the complexity f(n) of M increases as n increases.
 It is usually the rate of increase of f(n) with some standard functions.
 The most common computing times are
O(1), O(log2 n), O(n), O(n log2 n), O(n2), O(n3), O(2n)
 When we have two algorithms to perform the same task and if first
one time complexity is O(n) and second one is O(n2) then we prefer
first one since as n increases the time required for execution of second
one is taking more time than the first one.
 Here we discuss about three cases for the efficiency of the algorithm.
 Best case – 1
 Worst case – n
 Average case – (n+1)/2
 If the algorithm takes minimum amount of time to run for its
completion then it is called best case time complexity
 If the algorithm takes maximum amount of time to run for its
completion then it is called worst case time complexity
 If the algorithm takes average amount of time to run for its completion
then it is called average case time complexity

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
44

You might also like