0% found this document useful (0 votes)
15 views

Imperative Programming Program Flow

The document is a syllabus for an Imperative Programming course designed for B.Sc. IT students at Mumbai University. It covers various topics including programming languages, program structure, data types, control statements, and functions, with a focus on C programming. The book aims to provide a comprehensive understanding of imperative programming concepts and includes practical exercises for students.

Uploaded by

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

Imperative Programming Program Flow

The document is a syllabus for an Imperative Programming course designed for B.Sc. IT students at Mumbai University. It covers various topics including programming languages, program structure, data types, control statements, and functions, with a focus on C programming. The book aims to provide a comprehensive understanding of imperative programming concepts and includes practical exercises for students.

Uploaded by

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

IMPERATIVE

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.

Shrutkirti Rajendra Shelar


M.Sc. (IT), M.M.S. (IT)
R.K. Talreja College, Ulhasnagar - 3.

Prajisha Jitesh
M.Sc. (CS)
VES College of Arts, Science and Commerce,
Chembur.

ISO 9001:2008 CERTIFIED


© Authors
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the
publisher.

First Edition : 2016


Second Revised Edition : 2017

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.

Kiran Gurbani Shrutkirti Shelar Prajisha Jitesh


kiranrktcollege@gmail.com shelarshrutkirti@gmail.com prajish.jitesh@ves.ac.in
Mob.: 7769979964/ 9637128628 Mob.: 9665183382 Mob.: 9821754190
SYLLABUS
Unit Details Lectures
Unit I Introduction: Types of Programming languages, History, features and
application. Simple program logic, program development cycle,
pseudocode statements and flowchart symbols, sentinel value to end a
program, programming and user environments, evolution of programming
models, desirable program characteristics. 12
Fundamentals: Structure of a program. Compilation and execution of a
program, Character set, identifiers and keywords, data types, constants,
variables and arrays, declarations, expressions, statements, variable
definition, symbolic constants.
Unit II Operators and Expressions: Arithmetic operators, unary operators,
relational and logical operators, assignment operators, the conditional
operator, library functions.
12
Data Input and Output: Single character input and output, entering input
data, scanf function, printf function, gets and puts functions, interactive
programming.
Unit III Conditional Statements and Loops: Decision Making within a Program,
Conditions, Relational Operators, Logical Connectives, If Statement, If-
Else Statement, Loops: While Loop, Do While, For Loop. Nested Loops,
Infinite Loops, Switch Statement
Functions: Overview, defining a function, accessing a function, passing 12
arguments to a function, specifying argument data types, function
prototypes, recursion, modular programming and functions, standard
library of C functions, prototype of a function: formal parameter list,
return type, function call, block structure, passing arguments to a function:
call by reference, call by value.
Unit IV Program Structure: Storage classes, automatic variables, external
variables, static variables, multifile programs, more library functions,
preprocessor: Features, #define and #include, Directives and Macros. 12
Arrays: Definition, processing, passing arrays to functions,
multidimensional arrays, arrays and strings.
Unit V Pointers: Fundamentals, declarations, Pointers, Address Operators,
Pointer Type Declaration, Pointer Assignment, Pointer Initialization,
Pointer Arithmetic, Functions and Pointers, Arrays And Pointers, Pointer
Arrays, passing functions to other functions.
12
Structures and Unions: Structure Variables, Initialization, Structure
Assignment, Nested Structure, Structures and Functions, Structures and
Arrays: Arrays of Structures, Structures Containing Arrays, Unions,
Structures and pointers.
PAPER PATTERN
Maximum Marks : 75 Time : 2 ½ Hours
All questions are compulsory:
Q. 1 From Unit I
Attempt any three of following 15 Marks
(a) …….. 5 marks
(b) …….. 5 marks
(c) …….. 5 marks
(d) …….. 5 marks
(e) …….. 5 marks
(f) …….. 5 marks
Q. 2 From Unit II
Attempt any three of following 15 Marks
(a) …….. 5 marks
(b) …….. 5 marks
(c) …….. 5 marks
(d) …….. 5 marks
(e) …….. 5 marks
(f) …….. 5 marks
Q. 3 From Unit III
Attempt any three of following 15 Marks
(a) …….. 5 marks
(b) …….. 5 marks
(c) …….. 5 marks
(d) …….. 5 marks
(e) …….. 5 marks
(f) …….. 5 marks
Q. 4 From Unit IV
Attempt any three of following 15 Marks
(a) …….. 5 marks
(b) …….. 5 marks
(c) …….. 5 marks
(d) …….. 5 marks
(e) …….. 5 marks
(f) …….. 5 marks
Q. 5 From Unit V
Attempt any three of following 15 Marks
(a) …….. 5 marks
(b) …….. 5 marks
(c) …….. 5 marks
(d) …….. 5 marks
(e) …….. 5 marks
(f) …….. 5 marks
Note: Internal choice should be given.
CONTENTS

Unit I
Chapter 1 Introduction 1 – 25

Chapter 2 Fundamentals 26 – 39

Unit II
Chapter 3 Operators and Expressions 40 – 51

Chapter 4 Data Input and Output 52 – 61

Unit III
Chapter 5 Conditional Statements and Loops 62 – 79

Chapter 6 Functions 80 – 109

Unit IV
Chapter 7 Program Structure 110 – 117

Chapter 8 Preprocessor 118 – 121

Chapter 9 Arrays 122 – 132

Unit V
Chapter 10 Pointers 133 – 149

Chapter 11 Structures and Unions 150 – 173

Error Handling in C Language 174 – 179

Practicals of Imperative Programming 180 – 238


Unit I

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

1.1 Introduction to Imperative Programming


Definition of Imperative Programming
 The imperative (or procedural) paradigm is the closest to the structure of actual computers.
 It is a model that is based on moving bits around and changing machine state
 Imperative programming is a programming paradigm that uses statements that change a
program’s state from compilation to running.
 In imperative language natural languages can be used to express commands for the computer
to perform.
 Imperative programming focuses on describing how a program operates.
 In contrast to it, Declarative programming, which focuses on what the program should
accomplish without specifying how the program should achieve the result.
2 Imperative Programming

Programming Languages based on the Imperative Paradigm have the Following


Characteristics
 The basic unit of abstraction is the PROCEDURE, whose basic structure is a sequence of
statements that are executed in succession, abstracting the way that the program counter is
incremented, so as to proceed through a series of machine instructions residing in sequential
hardware memory cells.
 The sequential flow of execution can be modified by conditional and looping statements (as
well as by the very low-level goto statement found in many imperative languages), which
abstract the conditional and unconditional branch instructions found in the underlying
machine instruction set.
 Variables play a key role, and serve as abstractions of hardware memory cells. Typically, a
given variable may assume many different values of the course of the execution of a program,
just as a hardware memory cell may contain many different values. Thus, the assignment
statement is a very important and frequently used statement.

Imperative Programming can be Different Types of:


1. Machine and Assembly languages ie. Low level imperative language.
2. Procedural languages ie. High level imperative language.
3. Structural & modular languages
4. Object oriented languages
5. Event Driven programming languages
6. Object Based Languages
1. Machine and Assembly Languages are native languages of a computer for hardware
implementation it is designed and written in imperative style to execute in native code.
2. Procedural Programming is a type of imperative programming in which the program is built
from one or more procedures (also termed subroutines or functions). Procedural programming could
be considered a step towards declarative programming. A programmer can often tell, simply by
looking at the names, arguments, and return types of procedures (and related comments), what a
particular procedure is supposed to do, without necessarily looking at the details of how it achieves its
result. At the same time, a complete program is still imperative since it fixes the statements to be
executed and their order of execution to a large extent.
3. Structured Programming is a programming with a specific structure of the program and
modular programming is added with structured language to add different functions. These are high
level imperative languages with assignment statements, calculative statements, evaluation statements
to execute complex expressions which may have arithmetic, relational & logical operators and
function evaluations, and the assignment of the resulting value to memory. Looping statements like
while, do while, for loop, etc. used to execute sequence, conditional branching, switch case statements
and looping statements and subroutine or procedure call.
Imperative languages are like Fortran, BASIC, Pascal, COBOL, ALGOL language for
mathematical algorithms and C language,
4. Object Oriented Programming are imperative in style, but added features to support objects.
C++ , JAVA, Perl, Rubey, visual c++ are object oriented languages & Python languages
Introduction 3

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.

1.2 Introduction to Programming Languages


Programming Language is a language used to communicate with the computer by writing
programs.
Programming language is widely used in the development of operating systems. An Operating
System (OS) is a software (collection of programs) that controls the various functions of a computer.
Also it makes other programs on your computer work. For example, you cannot work with a word
processor program, such as Microsoft Word, if there is no operating system installed on your computer.
Windows, Unix, Linux, Solaris, and Mac OS are some of the popular operating systems. The
same way to run the programs in a particular programming language we need a language complier.
You write computer instructions in a computer programming language such as Visual Basic, C#,
C++, or Java. Just as some people speak English and others speak Japanese, programmers write
programs in different languages.
The instructions you write using a programming language are called program code; when you
write instructions, you are coding the program. Every programming language has rules governing its
word usage and punctuation.
These rules are called the language’s syntax. Mistakes in a language’s usage are syntax errors.
After a computer program is typed using programming language statements and stored in memory, it
must be translated to machine language that represents the millions of on/off circuits within the
computer.
Your programming language statements are called source code, and the translated machine
language statements are object code.
Each programming language uses a piece of software, called a compiler or an interpreter, to
translate your source code into machine language. Machine language is also called binary language,
and is represented as a series of 0s and 1s.
The compiler or interpreter that translates your code tells you if any programming language
component has been used incorrectly. Syntax errors are relatively easy to locate and correct because
your compiler or interpreter highlights them. If you write a computer program using a language such
as C++ but spell one of its words incorrectly or reverse the proper order of two words, the software
lets you know that it found a mistake by displaying an error message as soon as you try to translate the
program.
4 Imperative Programming

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.

1.3 Types of Programming Languages


Language Levels
1. Machine Level language
2. Assembly language
3. Procedural language (High Level Language)
1. Machine Language: Every computer has its own language called machine language. It
depends on the specific Hardware of the computer. A machine language is also known as low level
language also called machine understandable language.
Computer understands & executes the program only in machine level language. This low level
language is in the form of (1’s and 0’s) binary code
Low Level Language requires memorizing or looking up numerical codes for every instruction
that is used.
These are machine dependent languages.
These are used for simulation languages, and LISP, artificial intelligence applications.
2. Assembly Language: Assembly language is the mnemonic language written in some specific
symbolic codes, such as ADD, SUB etc. An assembly language program is first translated into
machine language instruction by system program called assembler, before it can be executed. These
are languages understandable by CPU & ALU section of Computer Assembly languages are called
low level languages.
3. High Level Language: A High level language is a simple English like language. A High level
lay program also needs to be transferred into machine language instructions before it can be executed
because computer understands only machine level language.
Rules for programming in a particular high-level language are much the same for all computers,
so that a program written for one computer can generally be run on many different computers with
little or no alteration.
This translation, called compilation is done by a systems program called a compiler.
The original program written in High level language is called source program and its translation
i.e., machine code is called object program.
Some popular High Level languages are Basic, Fortran, Cobol, Pascal, C & C++.
High-level language offers three significant advantages over machine language: simplicity,
uniformity and portability (i.e., machine independence).

Compilers and Interpreters


A program written in a high level language must be translated into machine language before it
can be executed. This is known as compilation or interpretation, depending on how it is carried out.
Introduction 5

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.

1.4 History of C Programming Language


History of C Programming Language
1. C is a programming language which was born at “AT & T’s Bell Laboratory” of USA in 1972.
2. C was written by Dennis Ritchie, that’s why he is also called as father of c programming
language.
3. C language was created for a specific purpose i.e designing the UNIX operating system
(which is currently the base of many UNIX based OS).
4. From the beginning, C was intended to be useful to allow busy programmers to get things
done because C is such a powerful, dominant and supple language.
6 Imperative Programming

5. Its use quickly spread beyond Bell Labs in the late 70’s because of its long list of strong
features

Why the Name “C” was given to Language?


1. Many of C’s principles and ideas were derived from the earlier language B. (Ken Thompson
was the developer of B Language.)
2. BCPL and CPL are the earlier ancestors of B Language
3. CPL is common Programming Language. In 1967, BCPL Language ( Basic CPL ) was
created as a scaled down version of CPL
4. As many of the features were derived from “B” Language thats why it was named as “C”.
5. After 7-8 years C++ came into existence which was first example of object oriented
programming.

C Programming Language Timeline

Year Developed by

1960 ALGOL
International Group

1967 BCPL Martin Richard

1970 B Ken Thompson

1973 Traditional C Dennis Ritchie

1989 ANSI C
ANSI commitee

ANSI/ISO C ISO commitee


1990

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

1.5 Features and Application


Features of C Language
C is a structured programming language, which means that it allows you to develop programs
using well-defined control structures (you will learn about control structures in the articles to come),
and provides modularity (breaking the task into multiple sub tasks that are simple enough to
understand and to reuse).
C is often called a middle-level language because it combines the best elements of low-level or
machine language with high-level languages.

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

6. C is a Middle Level Language: C is also used to do low level programming. It is used to


develop system applications such as kernel, driver etc. It also supports the feature of high level
language. That is why it is known as mid-level language.
7. C has Inbuilt Library Functions: C has inbuilt Library functions & packages bundled into
header files, Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.
8. C allows us to Create user Defined Functions: Apart from using inbuilt functions, c allows
us to create our own defined functions depending on the requirement.
9. C has its own Complier: The C compiler combines the capabilities of an assembly language
with features of a high-level language.
10. C is used for creating Powerful System Programs, since with the help of c programming
system programs and kernel coding for Linux operating system can be written.
11. C is a flexible & Powerful language.
12. C has 32 Keywords or Reserved Words which are identifiers, reserved only for c language
and can not be used for variable declaration & function declaration.
13. C supports Graphics.
14. Robust Language: It is a robust language with a rich set of built-in functions and operators
that can be used to write any complex program.
15. Memory Management: it supports the feature of dynamic memory allocation. In C
language, we can free the allocated memory at any time by calling the free() function.
16. Pointer: C provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, array etc. C supports
different functions, structures, arrays with powerful data structures like stack, Linklist, Queue, Trees.
17. Efficient and Fast: Programs Written in C are efficient and fast. This is due to its variety of
data type and powerful operators.
18. Extensible: In c language, New features can be added by the programmer, hence it is
Extensible.
19. Recursion: In c, we can call the function within the function. It provides code reusability
for every function.
C’s ability to communicate directly with hardware makes it a powerful choice for system
programmers. In fact, popular operating systems such as Unix and Linux are written entirely in C.
Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and
BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is
also used to develop any kind of application, including complex business ones.
The following is a partial list of areas where C language is used i.e. Applications:
 Embedded Systems
 Systems Programming
 Artificial Intelligence
 Industrial Automation
 Computer Graphics
Introduction 9

 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

Syntax & Logical wise the statements are correct.


But if steps are as follows:
1. Get a vessel & keep it on the gas
2. Switch on the gas
3. Put water
4. Put sugar
5. Allow to boil
6. Then put milk
7. Allow to boil
8. After 5 min Tea is Ready
Here is Logical error, since if I forgot to put Tea, hence Result is not a tea it is Milk.
1. Get a vessel & keep it on the gas
2. Switch on the gas
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
Here is Logical error, since if I forgot to put Milk, hence Result is a black tea.
After algorithm, you can write program in a respective programming language. May be C, C++,
Java, Visual Basic etc.

1.7 Program Development Life Cycle


Program Development Cycle
Programmer for developing the program can not directly start any program or project,
Programmer has to understand whole program or project, has to analyze the sequence and flow of the
program.
Introduction 11

Understand
the problem

Maintain the Plan the


program logic

Put the program Write the


into production code

Test the Translate


program the code

Fig. 1.1: The Program Development Cycle

Diagram referred from programming logic and design by Joyce Farrell.


Fig. 1.1 illustrates the program development cycle, which can be broken down into at least
seven steps:
1. Understand the problem.
2. Plan the logic.
3. Code the program.
4. Use software (a compiler or interpreter) to translate the program into machine language.
5. Test the program.
6. Put the program into production.
7. Maintain the program.
1. Understanding the Problem
Professional computer programmers write programs to accomplish the requirements of users or
end users.
Examples of end users include payroll management system, they needs a printed list of all
employees, a Billing department that wants a list of clients who are 30 or more days overdue on their
payments, they need their deduction information.
Since programmers are providing a service to these users, programmers must first understand
what the users want. When a program runs, you usually think of the logic as a cycle of input-
processing-output operations, but when you plan a program, you think of the output first. After you
understand what the desired result is, you can plan the input and processing steps to achieve it.
Suppose the manager needs a list of all employees who have been here over five years, because
we want to invite them to a special thank-you dinner. On the surface, this seems like a simple request.
An experienced programmer, however, will know that the request is incomplete. For example,
you might not know the answers to the following questions about which employees to include: Does
the manager want a list of full-time employees only, or a list of full and part-time employees together?
12 Imperative Programming

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.

Data that the


program uses

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

Fig. 1.2: Creating an Executable Program


Diagram referred from programming logic and design by Joyce Farrell.
If you write a programming statement incorrectly the translator program doesn’t know how to
proceed and issues an error message identifying a syntax error.
Typically, a programmer develops logic, writes the code, and compiles the program, receiving a
list of syntax errors. The programmer then corrects the syntax errors and compiles the program again.
Correcting the first set of errors frequently reveals new errors that originally were not apparent to the
compiler.
5. Testing the Program
A program that is free of syntax errors is not necessarily free of logical errors.
A logical error results when you use a syntactically correct statement but use the wrong one for
the current context.
Input myNumber
set myAnswer = myNumber * 2
output myAnswer
If you execute the program, provide the value 2 as input to the program, and the answer 4 is
displayed, you have executed one successful test run of the program. Testing of logical errors,
syntactically errors are done.
6. Putting the Program into Production
Once the program is thoroughly tested and debugged, it is ready for the organization to use.
Putting the program into production might mean simply running the program once, if it was written to
satisfy a user’s request for a special list then we can finalize the program.
14 Imperative Programming

7. Maintaining the Program


After programs is comleted making necessary changes is called maintenance.
Maintenance can be required for many reasons:
for example, because new tax rates are legislated, the format of an input file is altered, or the end
user requires additional information not included in the original output specifications. you make
changes to existing programs, you repeat the development cycle. That is, you must understand the
changes, then plan, code, translate, and test them before putting them into production.

1.8 Pseudocode Statements and Flowchart Symbols


When programmers plan the logic for a solution to a programming problem, they often use one of
two tools: pseudocode (pronounced sue-doe-code) or flowcharts.
Before writing pseudocode while planning we can write Algorithms also:

Points to be Considered for Writing Good Algorithm


 All Inputs and outputs should be defined precisely.
 It should be sequential stepwise representation of the program.
 Each steps in algorithm should be simple and clear.
Ø An algorithm shouldn’t have computer code. Instead, the algorithm should be written in
such a way that, it can be used in similar programming languages.
Pseudocode is an English-like representation of the logical steps it takes to solve a problem.
Pseudocode simply means false code, or sentences that appear to have been written in a computer
programming language but do not necessarily follow all the syntax rules of any specific language.
A flowchart is a pictorial representation of the program to be implemented.

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.

input Set myAnswer = Output


myNumber myNumber * 2 myAnswer

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

Set myAnswer = input myNumber


myNumber * 2
Set myAnswer = myNumber * 2

Output myAnswer

Stop

Fig. 1.6: Flowchart and Pseudocode of Program that Doubles a Number


Diagram referred from programming logic and design by Joyce Farrell.

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.

Input/output It is often referred to as the I/O Shape shows the


Inputs to and Outputs from a process.

Processing Used to illustrate a process, action or an operation,


eg arithmetic operations and data-manipulations.

Decision This object is always used in a process flow to as a


question to represent the operation in which there
are two alternatives, true and false.
Introduction 17

Connector Used to join different flow line

Predefined Process/Function This shape takes two names - ‘Subroutine’ or


‘Predefined Process’. Used to represent a group of
statements performing one processing task.

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

Diagram referred from programming logic and design by Joyce Farrell.

1.9 Sentinel Value to End a Program


Using a Sentinel Value to End a Program
The logic in the flowchart for doubling numbers, shown in Fig. 1.8, has a major flaw—the
program contains an infinite loop.
If, for example, the input numbers are being entered at the keyboard, the program will keep
accepting numbers and outputting their doubled values forever. Of course, the user could refuse to
type any more numbers. But the program cannot progress any further while it is waiting for input;
meanwhile, the program is occupying computer memory and tying up operating system resources.
Any infinite loop in a program has a problem that you can input values infinite time , processing
will be done, result will be displayed. Loop will be continued infinite times. Solution to stop is turn off
your computer, Solution is to somewhere Refuse input value or stop accepting input value.
A better way to end the program is to set a predetermined value for myNumber that means “Stop
the program!” For example, the programmer and the user could agree that the user will never need to
know the double of 0 (zero), so the user could enter a 0 to stop. The program could then test any
incoming value contained in myNumber and, if it is a 0, stop the program.
Testing a value is also called making a decision.
You represent a decision in a flowchart by drawing a decision symbol, which is shaped like a
diamond. The diamond usually contains a question, the answer to which is one of two mutually
exclusive options—often yes or no.
The question to stop the doubling program should be “Is the value of myNumber just entered
equal to 0?” or “myNumber = 0?” for short. The complete flowchart will now look like the one shown
in Fig. 1.9.
Introduction 19

Start

input myNumber

myNumber Yes
= 0? Stop

No

Set myAnswer =
myNumber * 2

output myNumber

Diagram referred from programming logic and design by Joyce Farrell.

Flowchart with sentinel value equal to zero


One drawback to using 0 to stop a program, of course, is that it won’t work if the user does need
to find the double of 0. In that case, some other data-entry value that the user never will need, such as
999 or –1, could be selected to signal that the program should end.
A preselected value that stops the execution of a program is often called a dummy value because
it does not represent real data, but just a signal to stop. Sometimes, such a value is called a sentinel
value because it represents an entry or exit point, like a sentinel who guards a fortress.
For one thing, an input record might have hundreds of fields, and if you store a dummy record in
every file, you are wasting a large quantity of storage on “non data.” Additionally, it is often difficult
to choose sentinel values for fields in a company’s data files. Any balance Due, even a zero or a
negative number, can be a legitimate value, and any customerName, even “ZZ”, could be someone’s
name. Fortunately, programming languages can recognize the end of data in a file automatically,
through a code that is stored at the end of the data. Many programming languages use the term eof (for
end of file) to refer to this marker that automatically acts as a sentinel.
Here In this example, therefore, uses eof to indicate the end of data whenever using a dummy
value is impractical or inconvenient. In the flowchart shown in Fig. 1.10, the eof question is shaded.
20 Imperative Programming

Start

input myNumber

eof? Yes
Stop

No

Set myAnswer =
myNumber * 2

output myNumber

Fig. 1.7: using eof

Diagram referred from programming logic and design by Joyce Farrell.

1.10 Programming and User Environments


Understanding Programming Environments
You can type a program into one of the following:
 A plain text editor
 Turbo c Editor
A text editor that is part of an integrated development environment

Hand written program

Text editor

C Source code (PR1.C)

Preprocessor

Expanded Source code (PR1.I)

Compiler

Object code (PR1.OBJ)

Linker

Executable Code (PR1.EXE)


Introduction 21

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.

Invoking the Turbo C IDE


The default directory of Turbo C compiler is c:\tc\bin. So to invoke the IDE from the windows
you need to double click the TC icon in the directory c:\tc\bin.
The alternate approach is that we can make a shortcut of tc.exe on the desktop.
Opening New Window in Turbo C
To type a program, you need to open an Edit Window. For this, open file menu and click “new”.
A window will appear on the screen where the program may be typed.
Writing a Program in Turbo C
When the Edit window is active, the program may be typed. Use the certain key combinations to
perform specific edit functions.
Saving a Program in Turbo C
To save the program, select save command from the file menu. This function can also be
performed by pressing the [F2] button. A dialog box will appear asking for the path and name of the
22 Imperative Programming

file. Provide an appropriate and unique file name. You can save the program after compiling too but
saving it before compilation is more appropriate.

Making an Executable File in Turbo C


The source file is required to be turned into an executable file. This is called “Making” of the .exe
file. The steps required to create an executable file are:
1. Create a source file, with a .c extension.
2. Compile the source code into a file with the .obj extension.
3. Link your .obj file with any needed libraries to produce an executable program
All the above steps can be done by using Run option from the menu bar or using key combination
Ctrl+F9 (By this linking & compiling is done in one step).

Understanding User Environments


Compiling and linking in the Turbo C IDE
In the Turbo C IDE, compiling and linking can be performed together in one step. There are two
ways to do this: you can select Make EXE from the compile menu, or you can press the [F9] key
Correcting Errors in Turbo C
If the compiler recognizes some error, it will let you know through the Compiler window. You’ll
see that the number of errors is not listed as 0, and the word “Error” appears instead of the word
“Success” at the bottom of the window. The errors are to be removed by returning to the edit window.
Usually these errors are a result of a typing mistake. The compiler will not only tell you what you did
wrong, they’ll point you to the exact place in your code where you made the mistake.
Executing a Programs in Turbo C
If the program is compiled and linked without errors, the program is executed by selecting Run
from the Run Menu or by pressing the [Ctrl+F9] key combination.
Introduction 23

Exiting Turbo C IDE


An Edit window may be closed in a number of different ways. You can click on the small square
in the upper left corner, you can select close from the window menu, or you can press the Alt+F3
combination. To exit from the IDE, select Exit from the File Menu or press Alt+X Combination.

1.11 Evolution of Programming Models


Software Evolution (Evolution of Programming Language)

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.

1.12 Desirable Program Characteristics


These characteristics apply to programs that are written in any programming language :-
1. Integrity: This refers to the accuracy of the calculations. Integrity is needed to perform
correct calculations if any enhancement is done otherwise there will be no use of
enhancement and all enhancement will be meaningless Thus, the integrity of the calculations
is an absolute necessity in any computer program.
2. Clarity: refers to the overall readability of the program, with specific logic.
If a program should not be complicated it should be clearly written, it should be possible for
another programmer to follow the program logic without much effort. It should also be
possible for the original author to follow his or her own program after being away from the
program for an extended period of time. One of the objectives in the design of C is the
development of clear, readable and disciplined approach to programming.
Introduction 25

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

The Single line comment can be written by // (double slash) &


Multi line comment
Comment can be written by
/*-------
------------*/
Comments (remarks) may appear anywhere within a program, as long as they are placed within
the delimiters /* and */ (e.g., /* this is a comment */). Such comments are helpful in identifying the
program’s principal features or in explaining the underlying logic of various program features.
2. Definition Section: All the symbolic constants are written in definition section. Macros are
known as symbolic constants.
3. The Link section provides instruction to the compiler to take function from system Library.
E.g. To use the input & output functions we use #include<stdio.h>, this is a link file, Please note that
the character (#) should be in the first column and there is no semicolon at the end of this line.
4. In the Global Declaration section the variable used in more than one function can be declared
in Global section.
Within the main function section the declaration part declares the variables used in executable
part. There is at least one statement in the executable part.
5. Every C program consists of one or more function, one of which must be called the main. The
program will always begin by executing the main function, which may access other functions. Any
other function definitions must be defined separately, either ahead of or after main.
Each function must contain:
1. A function heading, which consists of the function name, followed by an optional list of
arguments, enclosed in parentheses.
2. A list of argument declarations, if arguments are included in the heading.
3. A compound statement, which comprises the remainder of the function.
The arguments are symbols that represent information being passed between the function and
other parts of the program. (Arguments are also referred to as parameters.)
Each compound statement is enclosed within a pair of braces, i.e. { }. The braces may contain
one or more elementary statements (called expression statements) and other compound
statements. Thus compound statements may be nested, one within another.
Each expression statement must end with a semicolon (;).
The C program may contain one or more sections
Both the parts must be placed between opening &closing braces. The program execution
begins with the opening braces of main function. Thus the closing brace of main function is
the logical end of the program.
Rules for writing the Program:
1. Every function in a program has a unique name and is designed to perform a specific task.
The task is defined by a group of instruction.
2. main () is always the first function which is called when a program execution begins.
3. Each instruction in a function is written as a separate statement.
4. The statements within a function i.e. function body should be enclosed within a pair of braces
{ }. The closing brace of the main function signals the end of the program.
5. All C statements are terminated by semicolon (;)
6. No blank spaces are allowed within a word. However two words may be separated by blank
spaces to improve the readability of the statement.
28 Imperative Programming

A Simple Program for printing message.


#include<stdio.h>
void main()
{
printf(“Programming is fun.”) ;
}
Output
Programming is fun.
Working Methodology of ‘ C’:
Source Code Object Code Linked Code
.C .Obj .Exe

2.2 Compilation and Execution of a Program


A compiler is a translator program that translates programs directly into machine code to be
executed by the CPU. An interpreter executes program instructions in place of (“running on top of”)
the CPU.
Program Translation
A central processing unit (CPU) is designed to interpret and execute a specific set of instructions
represented in binary form (i.e., 1s and 0s) called machine code. Only programs in machine code can
be executed by a CPU.

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

Program Execution by use of a Compiler


The other type of translator is called an interpreter, which executes program instructions in place
of (“running on top of”) the CPU.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy