Imperative Programming Program Flow
Imperative Programming Program Flow
PROGRAMMING
(As per the Syllabus 2016-17 of Mumbai University for B.Sc. IT, Semester I)
Kiran Gurbani
B.E., MCA, M.Phil.
Head of Computer Science Department,
R.K. Talreja College, Ulhasnagar - 3.
Prajisha Jitesh
M.Sc. (CS)
VES College of Arts, Science and Commerce,
Chembur.
Published by : Mrs. Meena Pandey for Himalaya Publishing House Pvt. Ltd.,
“Ramdoot”, Dr. Bhalerao Marg, Girgaon, Mumbai - 400 004.
Phone: 022-23860170, 23863863; Fax: 022-23877178
E-mail: himpub@vsnl.com; Website: www.himpub.com
Branch Offices :
New Delhi : “Pooja Apartments”, 4-B, Murari Lal Street, Ansari Road, Darya Ganj, New
Delhi - 110 002. Phone: 011-23270392, 23278631; Fax: 011-23256286
Nagpur : Kundanlal Chandak Industrial Estate, Ghat Road, Nagpur - 440 018.
Phone: 0712-2738731, 3296733; Telefax: 0712-2721216
Bengaluru : Plot No. 91-33, 2nd Main Road, Seshadripuram, Behind Nataraja Theatre,
Bengaluru - 560 020. Phone: 080-41138821; Mobile: 09379847017,
09379847005
Hyderabad : No. 3-4-184, Lingampally, Besides Raghavendra Swamy Matham,
Kachiguda, Hyderabad - 500 027. Phone: 040-27560041, 27550139
Chennai : New No. 48/2, Old No. 28/2, Ground Floor, Sarangapani Street, T. Nagar,
Chennai - 600 012. Mobile: 09380460419
Pune : First Floor, “Laksha” Apartment, No. 527, Mehunpura, Shaniwarpeth (Near
Prabhat Theatre), Pune - 411 030. Phone: 020-24496323, 24496333;
Mobile: 09370579333
Lucknow : House No. 731, Shekhupura Colony, Near B.D. Convent School, Aliganj,
Lucknow - 226 022. Phone: 0522-4012353; Mobile: 09307501549
Ahmedabad : 114, “SHAIL”, 1st Floor, Opp. Madhu Sudan House, C.G. Road, Navrang
Pura, Ahmedabad - 380 009. Phone: 079-26560126; Mobile: 09377088847
Ernakulam : 39/176 (New No. 60/251) 1st Floor, Karikkamuri Road, Ernakulam,
Kochi - 682011. Phone: 0484-2378012, 2378016; Mobile: 09387122121
Bhubaneswar : 5 Station Square, Bhubaneswar - 751 001 (Odisha).
Phone: 0674-2532129; Mobile: 09338746007
Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank,
Kolkata - 700 010. Phone: 033-32449649; Mobile: 07439040301
DTP by : Sanhita
Printed at : M/s. Aditya Offset Process (I) Pvt. Ltd., Hyderabad. On behalf of HPH.
DEDICATION
I would like to dedicate this book to my Father Late Mr. Sahijram Bajaj for providing me with
quality education and for being a constant guide and mentor of my life, my family and to special
people who bless me each and every day by being a part of my life.
Mrs. Kiran Gurbani
I would like to dedicate this book to my Father Late Mr. Rajendra Shelar, my mom
Mrs. Rajeshree Shelar and brother Mr. Prabhanjan Shelar.
I express my sincere gratitude towards Mrs. Kiran Gurbani for her love, support and guidance in
writing this book. My sincere thank to Mrs.Vandana Valecha for her love and positive support in my
life. The belief of these two beautiful ladies in me has kept me motivated and inspired in darkest days
of my life.
Miss Shrutkirti Shelar
I would like to dedicate this book to my Father Mr. P.P. Narayan and mom Rajani Narayan and
my husband Mr. Jitesh for their never-ending support.
Mrs. Prajisha Jitesh
Last but not the least, we would like to thank to Mr. S.K. Srivastav, Himalaya Publishing House
Pvt. Ltd. for giving us encouragement and inspiration. We are grateful for his support and thank him
for his true blessings.
PREFACE
We are having great pleasure in presenting First Edition of this book “Imperative Programming”
to the students of F.Y. IT (F.Y. B.Sc. Information Technology). This book is written to cover all the
topics of syllabus prescribed by the University of Mumbai for F.Y. B.Sc. IT.
Imperative programming is a programming paradigm that uses statements that change a
program’s state. In much the same way that the imperative mood in natural languages expresses
commands, an imperative program consists of commands for the computer to perform. Imperative
programming focuses on describing how a program operates.
All machine language, procedural language, structural programming Fortran, BASIC, Pascal,
COBOL, ALGOL language for mathematical algorithms and C language, object oriented features are
added with C++, JAVA, Perl, Ruby, visual C++ are object oriented languages and Python language.
Imperative support event base languages like Visual Basic and PHP with Web Designing languages
and also object oriented languages are supported VB.Net & C#, J# and F# functional languages.
Here, in this book, we have considered C programming as imperative programming language.
The concept and theory of each topic is followed by the theoretical explanation. All practical questions
of C programming are provided at the end of this book, and along with those steps of program
execution is provided. Efforts have been made to make the text easy to read and understand. In this
book, we have covered all types of programs expected by University of Mumbai in practical
examination.
Constructive suggestion and comments from the users will be sincerely appreciated. We would
appreciate hearing from you about any textual errors or omissions which you identify. If you would
like to suggest improvements or to contribute in any way, we would be glad to hear from you.
Please send correspondence to kiranrktcollege@gmail.com., shelarshrutkirti@gmail.com and
prajish.jitesh@ves.ac.in
We would like to thank to Mr. S.K. Srivastav, Himalaya Publishing House Pvt. Ltd. for his
guidance, cooperation and encouragement to write this book.
Unit I
Chapter 1 Introduction 1 – 25
Chapter 2 Fundamentals 26 – 39
Unit II
Chapter 3 Operators and Expressions 40 – 51
Unit III
Chapter 5 Conditional Statements and Loops 62 – 79
Unit IV
Chapter 7 Program Structure 110 – 117
Unit V
Chapter 10 Pointers 133 – 149
Chapter
Introduction
1
Structure:
1.1 Introduction to Imperative Programming
1.2 Introduction to Programming Languages
1.3 Types of Programming Languages
1.4 History of C Programming Language
1.5 Features and Application
1.6 Simple Program Logic
1.7 Program Development Life Cycle
1.8 Pseudocode Statements and Flowchart Symbols
1.9 Sentinel Value to End a Program
1.10 Programming and User Environments
1.11 Evolution of Programming Models
1.12 Desirable Program Characteristics
5. Event Driven Programming languages are imperative style with object based events handlers
Like Visual Basic & PHP with Web designating languages.
6. Object Based Languages are programming languages with imperative style by introducing
pure object oriented concepts and object based concepts by introducing VB.Net & C#, J# & F#
functional languages.
C is the Mother of all imperative types of programming languages, since from c language BASIC
language is invented and from BASIC language Visual Basic & VB.Net languages are invented. From
C language C++, VC++, C#, J#, JAVA languages are invented.
Hence In this Book we are Considering C as a imperative Language & all examples are covered
considering C language only.
After a program’s source code is successfully translated to machine language, the computer can
carry out the program instructions. When instructions are carried out, a program runs, or executes.
some input will be accepted, some processing will occur, and results will be the output.
Compilers translate the entire program into machine language before executing any of the
instructions. Interpreters, on the other hand, proceed through a program by translating and then
executing single instructions, or small groups of instructions.
A compiler or interpreter is itself a computer program that accepts a high-level program (e.g. a C
program) as input data, and generates a corresponding machine – language program as output. The
original high-level program is called the source program, and the resulting machine-language program
is called the object program.
Every high-level language must have its own compiler or interpreter for a particular platform. It
is generally more convenient to develop a new program using an interpreter rather than a compiler.
Once an error-free program has been developed, a compiled version will normally be executed much
faster than an interpreted version.
Difference between compiler and interpreter
Sr. Compiler Interpreter
No.
1 Compiler translates entire program into Interpreter translates and interpretes line by
machine language at a time line into machine language.
2 It takes a large amount of time to analyze the It takes less amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
comparatively faster. slower.
3 Generates intermediate object code which No intermediate object code is generated,
further requires linking, hence requires more hence are memory efficient.
memory.
4 It generates the error message only after Continues translating the program until the
scanning the whole program. Hence first error is met, in which case it stops. Hence
debugging is comparatively hard. debugging is easy.
5 Errors are displayed after entire program is Errors are displayed for every instruction
checked and Intermediate Object Code is interpreted (if any) No Intermediate Object
Generated Code is Generated
6 Programming language like C, C++ use Programming language like Python, Ruby use
compilers. interpreters.
5. Its use quickly spread beyond Bell Labs in the late 70’s because of its long list of strong
features
Year Developed by
1960 ALGOL
International Group
1989 ANSI C
ANSI commitee
C language has evolved from three different structured language ALGOL, BCPL and B Language.
It uses many concepts from these languages and has introduced many new concepts such as data types,
struct, pointer.
In 1988, the language was formalized by American National Standard Institute (ANSI).
In 1990, a version of C language was approved by the International Standard Organization
(ISO) and that version of C is also referred to as C89.
Introduction 7
Portable Structured
Simple
Mid-level
Memory
Management C Language Rich library
Extensible
Pointers
Faster Recursion
1. C is a Case Sensitive Language: Case sensitivity indicates that it differentiates the characters
either upper case or lower case based on their ASCII value.
2. C is Mother of all Languages: C is mother of all languages because from c language BASIC
language is invented and from BASIC language Visual Basic & VB.Net languages are invented. From
C language C++, VC++, C#, J#, JAVA languages are invented.
3. Portable: C is highly portable this means that programs once written can be run on other
machines with little or no modification. if we write c program in turbo c we can run same program in
Borland or ANSI c without any modification on windows platform and also run it on gcc complier on
Linux Platform.
4. C is a Structured Programming Language: C is a structured programming language since it
follows fixed structure for writing any program, which should have compulsory main() function in the
structure.
5. Modularity in structured programming refers to the breakdown of large C Language into
small modules hence due to modularity, complication can be reduced & debugging is fast.
8 Imperative Programming
Space Research
Different operating system operation
Image Processing
Game Programming
Creating Computer applications
Used for Creating small Unix kernel
C language can be used for creating system programs, but it does not support Object concepts &
data hiding concept. Every variable and functions are public in scope, hence no data hiding concept
can be provided. C does not support object oriented concepts like Data encapsulation, Data
Polymorphism, Data Abstraction, Data Inheritance. To Provide these We will switch to C++ language
with powerful data hiding concepts.
The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C
being used.
Database systems
Graphics packages
Word processors
Spreadsheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters
1.6 Simple Program Logic
Understanding Simple Program Logic
A program with syntax errors cannot be fully translated and cannot execute. A program with no
syntax errors is translatable and can execute, but it still might contain logical errors and produce
incorrect output as a result. For a program to work properly, you must develop correct logic; that is,
you must write program instructions in a specific sequence, you must not leave any instructions out,
and you must not add extraneous instructions.
Suppose you instruct someone to make a Tea as follows:
Steps for Making a Tea are as follows:
1. Get a vessel & keep it on the gas
2. Switch the gas on
3. Put water
4. Put Tea
5. Put sugar
6. Allow to boil
7. Then put milk
8. Allow to boil
9. After 5 min Tea is Ready
10 Imperative Programming
Understand
the problem
Does she want to include people who have worked for the company on a month-to month contractual
basis over the past five years, or only regular, permanent employees?
Do the listed employees need to have worked for the organization for five years as of today, as of
the date of the dinner, or as of some other cutoff date?
What about an employee who worked three years, took a two-year leave of absence, and has been
back for three years?
The programmer cannot make any of these decisions; the user must address these questions to
manager.
For example, no one knew they wanted to play Angry Birds or leave messages on Facebook
before those applications were developed. Mobile app developers also must consider a wider variety
of user skills than programmers who develop applications that are used internally in a corporation.
Mobile app developers must make sure their programs work with a range of screen sizes and hardware
specifications because software competition is intense and the hardware changes quickly.
2. Planning the Logic
The main important part of the program is planning the program’s logic. During this phase of the
process, the programmer plans the steps of the program, deciding what steps to include. You can plan
the solution to a problem in many ways. The two most common planning tools used are flowcharts
and pseudocode.
You may hear programmers refer to planning a program as “developing an algorithm.” An
algorithm is the sequence of steps or rules you follow to solve a problem.
The programmer shouldn’t worry about the syntax of any particular language during the planning
stage, but should focus on figuring out what sequence of events will lead from the available input to
the desired output.
Planning the logic includes thinking carefully about all the possible data values a program might
encounter and how you want the program to handle each scenario. The process of walking through a
program’s logic on paper before you actually write the program is called desk-checking.
3. Coding the Program
After the logic is developed, only then can the programmer write the source code for a Program
in a respective programming language.
The logic developed to solve a programming problem can be executed using any number of
languages. Only after choosing a language must the programmer be concerned with correct syntax.
4. Using Software to Translate the Program into Machine Language
Even though there are many programming languages, each computer knows only one language—
its machine language, which consists of 1s and 0s. Computers understand machine language because
they are made up of thousands of tiny electrical switches, each of which can be set in either the on or
off state, which is represented by a 1 or 0, respectively
Languages like Java or Visual Basic are available for programmers because someone has written
a translator program (a compiler or interpreter) that changes the programmer’s English-like high-level
programming language into the low-level machine language that the computer understands.
Introduction 13
When you learn the syntax of a programming language, the commands work on any machine on
which the language software has been installed. However, your commands then are translated to
machine language, which differs in various computer makes and models.
If there are no
Write and correct Compile the syntax errors Executable
the program code program program
If there are
syntax errors
List of Program
syntax error output
messages
Writing Pseudocode
The following five statements constitute a pseudocode representation of a square of a number.
start
input myNumber
set myAnswer = myNumber * myNumber
output myAnswer
stop
Using pseudocode involves writing down all the steps programmers preface their pseudocode
with a beginning statement like start and end it with a terminating statement like stop.
The statements between start and stop look like English and are indented slightly so that start and
stop stand out.
Most programmers do not bother with punctuation such as periods at the end of pseudocode
statements, although it would not be wrong to use them if you prefer that style.
Similarly, there is no need to capitalize the first word in a statement, although you might choose
to do so.
Introduction 15
Drawing Flowcharts
Flowchart is a pictorial representation of the program, Drawing flowcharts to represent the logical
flow, because flowcharts allow programmers to visualize more easily how the program statements will
connect. Especially for beginning programmers, flowcharts are an excellent tool that helps them to
visualize how the statements in a program are interrelated.
A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or process.
Each step in the process is represented by a different symbol and contains a short description of the
process step. The flow chart symbols are linked together with arrows showing the process flow direction.
A flowchart typically shows the flow of data in a process, detailing the operations/steps in a
pictorial format which is easier to understand than reading it in a textual format.
Flowcharts are used in analyzing, designing, documenting or managing a process or program in
various fields
You can draw a flowchart by hand or use software, such as Microsoft Word and Microsoft
PowerPoint, that contains flowcharting tools. You can use several other software programs, such as
Visio and Visual Logic, specifically to create flowcharts.
The parallelogram is used for both input and output,
It is often called the input/output symbol or I/O symbol.
Fig. 1.3: Input Symbol Fig. 1.4: Processing Symbol Fig. 1.5: Output Symbol
To show the correct sequence of these statements, you use arrows, or flow lines, to connect the
steps. Whenever possible, most of a flowchart should read from top to bottom or from left to right on a
page. That’s the way we read English, so when flowcharts follow this convention, they are easier for
us to understand.
To be complete, a flowchart should include two more elements: terminal symbols, or start/stop
symbols, at each end. Often, you place a word like start or begin in the first terminal symbol and a
word like end or stop in the other. The standard terminal symbol is shaped like a racetrack; many
programmers refer to this shape as a lozenge, because it resembles the shape of the medication you
might use to soothe a sore throat.
Fig. 1.6 shows a complete flowchart for the program that doubles a number, and the pseudocode
for the same problem.
You can see from the Fig. that the flowchart and pseudocode statements are the same only the
presentation format differs.
16 Imperative Programming
Example of Flowchart
Flowchart Pseudocode
Start
Input myNumber
Start
Output myAnswer
Stop
Flowchart Symbols
Symbol Purpose Description
Flow line The arrow line used to indicate the flow of logic by
connecting symbols.
Terminal(Stop/Start) The oval shaped symbol to represent start and end
of flowchart.
Repeating Instructions
After the flowchart or pseudocode has been developed, the programmer only needs to:
(1) buy a computer, (2) buy a language compiler, (3) learn a programming language, (4) code the
program, (5) attempt to compile it, (6) fix the syntax errors, (7) compile it again, (8) test it with several
sets of data, and (9) put it into production.
write the program shown in Fig. 1.7 and execute the same steps 10,000 times. writing this
program would be very time consuming.
start
input myNumber
set myAnswer = myNumber * 2
output myAnswer
input myNumber
set myAnswer = myNumber * 2
output myAnswer
input myNumber
set myAnswer = myNumber * 2
output myAnswer
…and so on for 9,997 more times
Don’t Do It
Solution on this is through flowchart:
18 Imperative Programming
Start
input myNumber
Set myAnswer =
myNumber * 2
output myAnswer
Start
input myNumber
myNumber Yes
= 0? Stop
No
Set myAnswer =
myNumber * 2
output myNumber
Start
input myNumber
eof? Yes
Stop
No
Set myAnswer =
myNumber * 2
output myNumber
Text editor
Preprocessor
Compiler
Linker
A text editor is a program that you use to create simple text files. It is similar to a word processor,
but without as many features.
You can use a text editor such as Notepad that is included with Microsoft Windows.
The C Developing Environment is a screen display with windows and pull-down menus. The
program listing, error messages and other information are displayed in separate windows.
The menus may be used to invoke all the operations necessary to develop the program, including
editing, compiling, linking, and debugging and program execution.
If the menu bar is inactive, it may be invoked by pressing the [F10] function key. To select
different menu, move the highlight left or right with cursor (arrow) keys. You can also revoke the
selection by pressing the key combination for the specific menu.
file. Provide an appropriate and unique file name. You can save the program after compiling too but
saving it before compilation is more appropriate.
1, 0
Machine Language
Assembly Language
Procedure-oriented Language
Structured Programming Language
Object Oriented Programming
Software technology has a growth of a tree. Software evolution has a layer of growth. Each layer
representing an improvement over the previous one.
The oldest programming languages required programmers to work with memory addresses and to
memorize awkward codes associated with machine languages.
Newer programming languages look much more like natural language and are easier to use,
partly because they allow programmers to name variables instead of using unwieldy memory
addresses
Initially the programs are to be written in machine language but it is in the form of 0’s and First
hence difficult to remember.
Second layer of assembly language which has Mnemonics in the form of English language.
Language used by ALU section of the CPU.
24 Imperative Programming
Third layer is procedure oriented language (POP) language. In this a problem is viewed as a
sequence of Instructions. All functions or tasks are combined in one procedure program.
In the fourth layer the program is divided into functions. Instructions of the program is divided
into groups known as functions.
In multi function program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. In the fifth layer,
modularization is used with the help of functions and in large programs it is very difficult to identify
what data is used by which function. Hence data hiding concept can be provided using functions.
In object oriented, following characteristics are followed:
1. Large programs are divided into smaller programs known as functions called objects.
2. Data hiding concept is provided.
Currently, two major models or paradigms are used by programmers to develop programs and
their procedures:
Procedural programming focuses on the procedures that programmers create along with
modularization That is, procedural programmers focus on the actions that are carried out—for example,
getting input data for an employee and writing the calculations needed to produce a paycheck from the
data.
Object-oriented programming focuses on objects, or “things,” and describes their features (also
called attributes) and behaviors.
For example, object-oriented programmers might design a payroll application by thinking about
employees and paychecks, and by describing their attributes. Employees have names and Social
Security numbers, and paychecks have names and check amounts. Then the programmers would think
about the behaviors of employees and paychecks, such as employees getting raises and adding
dependents and paychecks being calculated and output. Object-oriented programmers would then
build applications from these entities.
Understanding the Evolution of Programming Models
1. The oldest computer programs were written in many separate modules.
2. Procedural programmers focus on actions that are carried out by a program.
3. Object-oriented programmers focus on a program’s objects and their attribute and behaviors.
3. Simplicity: The clarity readability of the program and accuracy of a program are usually
enhanced by keeping things as simple as possible, uniqueness and consistency should be
included with the overall program objectives. In fact, it may be desirable to sacrifice a certain
amount of computational efficiency in order to maintain a relatively simple, straightforward
program structure.
4. Efficiency: is concerned with execution speed and efficient memory utilization. Many
complex programs require a tradeoff between these characteristics. hence experience and
common sense are key factors are used to increase effiency of the program.
5. Modularity: Many programs can be broken down into a series of identifiable subtasks. It is
good programming practice to implement each of these subtasks as a separate program
module.
In C programming language, such modules are written as functions. The use of a modular
programming structure enhances the accuracy and clarity of a program, and it facilitates
future program alterations.
6. Generality: Program to be as general as possible, within reasonable limits. For example, we
may design a program to read in the values of certain key parameters rather than placing fixed
values into the program.
As a rule, a considerable amount of generality can be obtained with very little additional
programming effort. All programs should be written in a generalized manner.
Questions
1. What did you mean by imperative programming? Explain different types of imperative
programming.
2. What are features and application of C programming language?
3. What are applications of c Language?
4. What is machine language? How does machine language differ from high-level languages?
5. Name some commonly used high-level languages. What are the advantages of using high-
level languages?
6. What are different types of programming languages?
7. What is meant by compilation? What is meant by interpretation? How do these two processes
differ?
8. What are the general characteristics of C? Where was C originally developed and by whom?
What has been done to standardize the language?
9. Define Complier & interpreter. Differentiate between Complier & Interpreter.
10. What are the characteristics required for writing desirable program?
11. Explain program development life cycle in detail.
12. Explain flowchart with its symbols.
13. Explain Sentinel value to the program with example.
Chapter
Fundamentals
2
Structure:
2.1 Structure of a Program
2.2 Compilation and Execution of a Program
2.3 Character Set
2.4 Identifiers and Keywords
2.5 Data Types
2.6 Constants
2.7 Variables and Arrays
2.7.1 Array
2.8 Declarations
2.9 Expressions
2.10 Statements
2.11 Variable Definition
2.12 Symbolic Constants
2.1Structure of a Program
Structure of the Program
Documentation Section / Comment section
Definition section
Link Section / Include Section
Global Declaration
main( ) function section
{
Local declaration part
Executable part
}
1. The documentation section consists of only comments.
This section is also called the comment section, it is not compiled by the compiler, it is a user
section.
Fundamentals 27
01110
11011 output
Hardware
10100 (CPU)
00100
Writing programs at this “low level” is tedious and error-prone. Therefore, most programs are
written in a “high-level” programming language such as C. Since the instructions of such programs are
not in machine code that a CPU can execute, a translator program must be used.
There are two fundamental types of translators. One, called a compiler, translates programs
directly into machine code to be executed by the CPU.
program in a high-level machine code version
language of program
a = 10 01110
b = 20 11011
sum = a + b compiler Hardware 30
10100
print sum (CPU) (results)
00100