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

DD CP Chapter2

This document provides an introduction to computer programming and the program development process. It discusses that computers need step-by-step instructions in the form of programs to perform tasks. Programs are developed using programming languages that are understood by computers. The program development process involves analyzing the problem, designing an algorithm, coding the program, testing it for errors, and documenting it. Key steps are problem analysis, task analysis, designing the algorithm using tools like flowcharts, coding the program, testing and debugging it, and documenting the final program.

Uploaded by

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

DD CP Chapter2

This document provides an introduction to computer programming and the program development process. It discusses that computers need step-by-step instructions in the form of programs to perform tasks. Programs are developed using programming languages that are understood by computers. The program development process involves analyzing the problem, designing an algorithm, coding the program, testing it for errors, and documenting it. Key steps are problem analysis, task analysis, designing the algorithm using tools like flowcharts, coding the program, testing and debugging it, and documenting the final program.

Uploaded by

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

Computer Programming Unit II

UNIT - II

INTRODUCTION
Computer has emerged as the most useful machine in recent times. It can perform wide
variety of tasks like receiving data, processing it, and producing useful results. However, being
a machine, the computer cannot perform on its own. A computer needs to be instructed to
perform even a simple task like adding two numbers. Computers work on a set of instructions
called computer program, which clearly specify the ways to carry out a task. A computer takes
instructions, in the form of computer programs, and carries out the requested task.
The human beings use natural languages such as English, Spanish, or French to
communicate. Similarly, a user communicates with the computer in a language understood by
it. The instructions, provided in the form of computer programs, are developed using computer
or programming languages.

DEVELOPING A PROGRAM
A program consists of a series of instructions that a computer processes to perform, the
required operation. In addition, it also contains some fixed data, required to perform the
instructions, and the process of defining those instructions and data. Thus, in order to design a
program, a programmer must determine three basic rudiments:
1. The instructions to be performed.
2. The order in which those instructions are to be performed.
3. The data required to perform those instructions.
To perform a task using a program, a programmer has to consider various inputs of the
program along with the process, which is required to convert input into desired output. Suppose
we want to calculate the sum of two numbers, A and B, and store the sum in C, here A and B
are the inputs, addition is the process, and C is the output of the program.

A, B C=A+B C

Input Processing Output

PROGRAM DEVELOPMENT CYCLE


Before starting the process of writing a program (coding), the programmer has to
determine the problem that needs to be solved. There are different approaches to problem
solving. Most require breaking the problem into a series of smaller steps, independent of the

1
Computer Programming Unit II

programming language. One common technique is to use the program development cycle, with
the number of steps that may vary according to the person who has formalized the development.
Development cycle of a program includes the following phases.

Analyses Problem Documentation &


Implementation

Task Analysis Program Test & Debug


Development
Cycle

Designing Phase Coding

Algorithm Testing

1. Analyze/Define the Problem: The problem is analyzed precisely and completely. Based on
understanding, the developer knows about the scope within which the problem needs to be
analyzed.
2. Task Analysis: After analyzing the problem, the developer needs to develop various
solutions to solve the given problem. From these solutions, the optimum solution is chosen,
which can solve the problem comfortably and economically.
3. Designing Phase: After selecting the appropriate solution, algorithm is developed to depict
the basic logic of the selected solution. An algorithm depicts the solution in logical steps.
Further, algorithm is represented by flowcharts and pseudocodes. These tools make program
logic clear and they eventually help for coding. This phase is also known as design phase.
4. Testing the Algorithm for Accuracy: Before converting the algorithms into actual code, it
should be checked for accuracy. The main purpose of checking algorithm is to identify major
logical errors at an early stage, because logical errors are often difficult to detect and correct at
later stages.
5. Coding: After meeting all the design considerations, the actual coding of the program takes
place in the chosen programming language. Depending upon application domain and available
resources, a program can be written by using computer languages of different levels such as
machine, assembly or high-level languages.
6. Test and Debug the Program: It is common for the initial program code to contain errors,

2
Computer Programming Unit II

a program compiler and programmer-designed test data machine tests the code for syntax
errors. The results obtained are compared with results calculated manually from this test data.
Depending upon the complexity of the program, several rounds of testing may be required.
7. Documentation and Implementation: Once the program is free from all the errors, it is the
duty of the program developers to ensure that the program is supported by suitable
documentation. After documentation, the program is installed on the end user's machine.

PROBLEM SOLVING TECHNIQUES


Problem solving technique is a set of techniques and graphical tools that helps in
providing in logic for solving a problem. In other words, these tools are used to express the
logic of the problem by specifying the correct sequence of all instructions to be carried out.
Following sections; in discuss the various problem-solving tools, which are algorithms,
flowcharts, and pseudocodes.

ALGORITHMS
Algorithms are one of the most basic tools that are used to develop the problem solving
logic. An algorithm is defined as a finite sequence of explicit instructions that, when provided
with a set of input values produces an output and then terminates. In algorithm, after a finite
number of steps, solution of the problem is achieved. Algorithms can have steps that repeat
(iterate) or require decisions (logic and comparison) until the task is completed.
Different algorithms may accomplish the same task, with a different set of instructions,
in more or less the same time, space, and efforts. For example, two different recipes for
preparing tea, one ' add the sugar' while 'boiling the water' and the other 'after boiling the water'
produce the same result. However, performing an algorithm correctly does not guarantee a
solution, if the algorithm is flawed or not appropriate to the context. For example, preparing
the tea algorithm will fail if there were no tea leaves present; even if all the motions of preparing
the tea were performed as if the tea leaves were there. We use algorithms in our daily life.
For example, to determine the largest number out of three numbers A, B, and C, the
following algorithm may be used.
Step 1: Start
Step 2: Read three numbers say A, B, C
Step 3: Find the larger number between A and B and store it in MAX_AB
Step 4: Find the larger number between MAX_AB and C and store it in MAX
Step 5: Display MAX

3
Computer Programming Unit II

Step 6: Stop
The above-mentioned algorithm terminates after six steps. This explains the feature of
finiteness. Every action of the algorithm is precisely defined; hence, there is no scope for
ambiguity. Once the solution is properly designed, the only job left is to code that logic into a
programming language.

Algorithm Properties
The properties of Algorithm are:
1. There must be no ambiguity in any instruction.
2. There should not be any uncertainty about which instruction is to be executed next.
3. The algorithm should conclude after a finite number of steps. An algorithm cannot be open-
ended.
4. The algorithm must be general enough to deal with any contingency.

FLOWCHART
A flowchart is a pictorial representation of an algorithm in which the steps are drawn
in the form of different shapes of boxes and the logical flow is indicated by interconnecting
arrows. The boxes represent operations and the arrows represent the sequence in which the
operations are implemented. The primary purpose of the flowchart is to help the programmer
in understanding the logic of the program.
Flowcharts can be compared with the blueprint of a building. Just as an architect draws
a blueprint before starting the construction of a building, a programmer draws a flowchart
before writing a computer program. As in the case of the drawing of a blueprint, the flowchart
is drawn according to defined rules and using standard flowchart symbols prescribed by
,American National Standard Institute (ANSI). Some standard symbols that are frequently
required for flowcharts are shown below.

Symbol Symbol Name Description


Flow lines are used to connect symbols. These
Flow Lines lines indicate the sequence of steps and the
direction of flow of control.

4
Computer Programming Unit II

This symbol is used to represent the beginning


Terminal (start), the termination (end), or halt (pause) in the
program logic.
It represents information entering or leaving the
Input/Output system, such as customer order (input) and
servicing (output).

Process symbol is used for representing arithmetic


and data movement instructions. It can represent a
Processing
single step ('add two cups of flour'), or an entire
sub-process ('make bread') within a larger process.

Decision symbol denotes a decision (or branch) to


be made. The program should continue along one
Decision of the two routes (IF/ELSE). This symbol has one
entry and two exit paths. The path chosen depends
on whether the answer to a question is yes or no.

Connector symbol is used to join different flow


connector
lines.
Off-page This symbol is used to indicate that the flowchart
Connector continues on the next page.
Document is used to represent a paper document
Document
produced during the flowchart process.
Manual input symbol represents input to be given
Manual Input by a developer / programmer
.
Manual operation symbol shows that the process
Manual Operation
has to be done by a developer/programmer.
This symbol represents the online data storage
Online Storage such as hard disks, magnetic drums, or other
storage devices.

5
Computer Programming Unit II

Communication link symbol is used to represent


Communication
data received or to be transmitted from an external
Link
system
This symbol is used to represent data input or
Magnetic Disk output from and to a magnetic disk.

Guidelines for preparing flowcharts


The following guidelines should be used for creating a flowchart:
• The flowchart should be clear, neat, and easy to follow.
• The flowchart must have a logical start and finish.
• In drawing a proper flowchart, all necessary requirements should be listed in logical order.
• Only one flow line should come out from a process symbol.
• Only one flow line should enter a decision symbol. However, two or three flow lines (one
for each possible answer) may leave the decision symbol.
• Only one flow line is used with a terminal symbol.
• In case of complex flowcharts, connector symbols are used to reduce the number of flow
lines.

Benefits of-Flowcharts A flowchart helps to clarify how things are currently working and how
they could-be improved. The reasons for using flowcharts as a problem-solving tool are given
below.
• Makes Logic Clear: The 'main advantage of using a flowchart to plan a task is that it
provides a pictorial representation of the task, which makes the logic easier to follow. Even
less experienced personnel can trace the actions represented by a flowchart, that is, flowcharts
are ideal for visualizing fundamental control structures employed in computer programming.
• Communication: Being a graphical representation of a problem-solving logic, flowcharts
are better way of communicating the logic of a system to all concerned. The diagrammatical
representation of logic is easier to communicate to all the interested parties as compared to
actual program cede as the users may not be aware of all the programming techniques and
jargons.
• Effective Analysis: With the help of a flowchart, the problem can be analyzed in an
effective way. This is because the analyzing duties of the programmers can be delegated to

6
Computer Programming Unit II

other persons, who may or may not know the programming techniques, but they have a broad
idea about the logic.
• Useful in Coding: The flowcharts act as a guide or blueprint during the analysis and
program development phase. Once the flowcharts are ready, the programmers can plan the
coding process effectively as they know where to begin and where to end, making sure that no
steps are omitted. As a result, error free programs are developed in high-level language and
that too at a faster rate.
• Proper Testing and Debugging: By nature, a flowchart helps in detecting the errors in a
program, as the developers know exactly what the logic should do.
• Appropriate Documentation: Flowcharts serve as a good program documentation tool.
Since normally the programs are developed for novice users; they can take the help of the
program documentation to know what the program actually does and how to, use the program.

Limitations of Flowcharts Flowchart can be used for designing the basic concept of the
program in pictorial form but cannot be used for programming purposes. Some of the
limitations of the flowchart are given as follows:
• Complex: The major disadvantage in using flowcharts is that when a program is very large,
the flowcharts may continue for many pages, making them hard to follow.
• Costly: Drawing flowcharts are viable only if the problem-solving logic is straightforward
and not very lengthy. However, if flowcharts are to be drawn for a huge application, the time
and cost factor of program development may get out of proportion, making it a costly affair.
• Difficult to Modify: Due to its symbolic nature, any changes or modification to a flowchart
usually requires redrawing the entire logic again, and redrawing a complex flowchart is not a
simple task. It is not easy to draw thousands of flow lines and symbols along with proper
spacing, especially for a large complex program.
• No Update: Usually programs are updated regularly. However, the corresponding update
of flowcharts may not take place, especially in the case of large programs. As a result, the logic
used in the flowchart may not match with the actual program's logic.

PSEUDOCODE
Pseudocode (pronounced soo-doh-kohd) is made up of two words: pseudo and code.
Pseudo means imitation and code refers to instructions, written in a programming language. As
the name suggests, pseudocode is not a real programming code, but it models and may even

7
Computer Programming Unit II

look like programming code. Pseudocode uses plain English statements rather than symbols,
to represent the processes of a computer program. It is also known as PDL (Program Design
Language), as it emphasizes more on the design aspect of a computer program or structured
English, because usually pseudocode instructions are written in normal English, but in a
structured way.
If an algorithm is written in English, the description may be at such a high level that it
may prove difficult to analyze the algorithm and then to transform it into actual code. If instead,
the algorithm is written in code, the programmer has to invest a lot of time in determining the
details of an algorithm, which he may choose not to implement (since, typically, algorithms are
analyzed before deciding which one to implement). Therefore, the goal of writing pseudocode
is to provide a high-level description of an algorithm, which facilitates analysis and eventual
coding, but at the same time suppresses many of the details that are insignificant. For example,
the pseudocode given below calculates the area of a rectangle.

PROMPT the user to enter the height of the rectangle


PROMPT the user to enter the width bf the rectangle
COMPUTE the area by multiplying the height with width
DIS'PLAY the area
STOP

Pseudocode uses some keywords to denote programming processes. Some of them are:
• Input: READ, OBTAIN, GET, and PROMPT
• Output: PRINT, DISPLAY, and SHOW
• Compute: COMPUTE, CALCULATE, and DETERMINE
• Initialize: SET and INITIALISE
• Add One: INCREMENT

Pseudocode Guidelines Writing pseudocode is not a difficult task. Even if you do not know
anything about the computers or computer languages, you can still develop effective and
efficient pseudo codes, if you are writing in an organized manner.
Here are a few general guidelines for developing pseudocodes:
• Statements should be written in simple English and should be programming language
independent. Remember that pseudocodes only describe the logic plan to develop a
program, it is not programming.
• Steps must be understandable, and when the steps are followed, they must produce a

8
Computer Programming Unit II

solution to the specified problem.


• Pseudocodes should be concise.
• Each instruction should be written in a separate line and each statement in pseudocode
should express just one action for the computer.
• Capitalize keywords such as READ, PRINT, and so on.
• Each set of instructions is written from top to bottom, with only one entry and one exit.
• It should allow for easy transition from design to coding in programming language.

Benefits of Pseudocode Pseudocode provides a simple method of developing the program logic
as it uses everyday language to prepare a brief set of instructions in the order in which they
appear in the completed program. It allows the programmer to focus on the steps required to
solve a program rather than on how to use the computer language. Some of the most significant
benefits of pseudocode are:
• Since it is language independent, it can be used by most programmers.
• It is easier to develop a program from a pseudocode than with a flowchart.
• Often, it is easy to translate pseudocode into a programming language, a step which can be
accomplished by less experienced programmers.
• Unlike flowcharts, pseudocode is compact and does not tend to run over many pages. Its
simple structure and readability makes it easier to modify.

Limitations of Pseudocode Although pseudocode is a very simple mechanism to simplify


problem-solving logic, it has its limitations. Some of the most notable limitations are:
• It does not provide visual representation of the program's logic.
• There are no accepted standards for writing pseudocodes.
• Pseudocode cannot be compiled nor executed, and there is no real formatting or syntax
rules.

INTRODUCTION TO C
HISTORY OF C
C is a high level programming language. C language is derived from two languages
BCPL & B in 1960 at Cambridge University. C language is developed at Bell Laboratories in

9
Computer Programming Unit II

1972. Dennis Ritchie invented C language. C Language mainly evolved from ALGOL, BCPL
and B. C is developed for programming in OS called UNIX.

FEATURES OF “C” LANGUAGE


• C is a Structured Programming Language and powerful language.
• C is a versatile Language (i.e.,) it has features of both Low Level Languages and High
Level Languages.
• It is used in system programming. Compilers, packages, Operating System are written
using C.
• C is a highly portable language. Source Program written in one computer can be
compiled, executed and run on another computer with less modification.
• Users can develop program quickly with few mistakes.
• It increases the readability of Program. Program can be modified without affecting the
other parts of a program.
• C is a Case Sensitive Language. It differentiates both Upper Case and Lower Case
separately.
• Every statement in C ends with semicolon.
• Programmers can write additional functions of their own. C language has a C Compiler.
• C language has the ability to extend itself. C is also a free form language, because each
group of statements can be placed together on one line.
• C language is used for developing software packages, system software, database
systems, graphics packages, spread sheets, CAD/CAM applications, word processors,
office automation, scientific and engineering applications.

STRUCTURE OF C PROGRAM
Documentation Section
Header File Section / Link Section
Definition Section
Global (Variable) Declaration Section
main()
{

10
Computer Programming Unit II

Declaration(local variable) part


Executable part
}
sub program section
function 1
function 2


Function n

Documentation Section
Documentation section consists of set of command lines. It is included in the first line
of a C program. It consists of comments. There are two types of comments. They are Single
line Comments and Multi line comments. Comments are used to give a meaningful name to a
C Program.
Single line comments are specified with two backslash // or /*’ and ended with */ in a
same Line. Multi line comments are specified by a backslash ( / ) followed by an asterisk ( * )
symbol and ended with asterisk symbol ( * ) followed by Backslash ( / ).

Link section/Header File section


In this section we can declare the header files of the program. Header file consists of
predefined function definitions for frequently used functions. Some of the functions in C
programs was already and written, executed and stored in the header files. Whenever we need
to use the particular function, we should simply mention the name in the link section. Link
section provides instructions to compiler to link functions from system library.

Definition Section
It is used to define symbolic constants.

Global declaration section


Used to declare functions, variables or symbolic constants globally. Two types of
declaration are allowed in C Language. They are (1) Static variable and (2) Global variable. If
a variable is specified within main function then it is local variable. Local variable cannot be
used outside the main function. If a variable is specified outside the main function then it is
global variable.

11
Computer Programming Unit II

Global variable can be used inside and outside or anywhere within the program.
Variables must be declared before being used in a C program. clrscr() statement is used after
variable declaration and before the beginning of control statements. Declaration helps to define
a variable and use it in a Program. Sub program contains user defined function.
main( ) section
The execution of C program starts from the main function. Every C program must have
a main function. It contains two parts. They are declaration part and executable part.
Declaration part and executable part must appear between opening ‘ { ' and closing braces ‘ }’.
Opening brace specifies the beginning of C program and close brace specifies the logical end
of C program.

Declaration part
Declaration part is used to declare variables. Every variable must be declared before
using it in C program. Every variable are specified with their data type followed by a name. If
there are more variables of same data type then they must be separated by commas.

Execution part
Execution part contains program statements. There may or may not be a declaration
part but there must be an execution part. It includes input and output statements.

Sub program section


Sub program section consists of all user-defined functions. It is called from the main
function. It is placed before or after the main function. But generally placed after the main
function.

C CHARACTER SET
Character set denotes alphabet, digit or special character. Characters combine to form
variables. Characters in C are grouped into Letters, Digits, Special characters and White spaces.
Compiler generally ignores white space when it is not a part of string constant. White Space
may be used to separate words, but not used between characters of keywords or identifiers.
The character set in C Language can be grouped into the following categories.
1. Letters 2. Digits 3. Special Characters 4. White Spaces

Alphabets

12
Computer Programming Unit II

Letters Letters Digits


Upper Case A to Z Lower Case a to z 0 to 9

White Space Characters


It is used together with input and output statements. It has no meaning but it has the
control to decide the way an input has to be displayed.
1. Blank Space \b 2. Horizontal Tab \t
3. Carriage Return \r 4. New line \n
5. Form Feed \f 6. Vertical tab \v

Special Characters
& .Ampersand # .Number Sign
' .Apostrophe < .Opening Angle (Less than sign)
* .Asterisk . .Period ( Dot )
@ At symbol % .Percentage Sign
\ .Backslash + .Plus Sign
^ .Caret ? .Question Mark
> .Closing Angle (Greater than sign) " .Quotation Marks
: .Colon } .Right Flower Brace
, .Comma ) .Right Parenthesis
$ .Dollar Sign ] .Right Bracket
.= Equal to ; .Semicolon
! .Exclamation Mark / .Slash
( .Left Parenthesis ~ .Tilde
[ .Left Bracket _ .Underscore
{ .Left Flower Brace | .Vertical Bar

TOKENS
Among the group of text individual word, punctuation marks are called Tokens. It is a
smallest individual unit in a C program. C has 6 types of Tokens. They are
• Keyword
• Identifier
• Special symbols

13
Computer Programming Unit II

• Constant
• String
• Operators.
TOKENS

Keyword Identifier Constant String Special Operators


Symbol

Keywords
Every word in C language is a keyword or an identifier. Keywords in C language cannot
be used as a variable name. The compiler specifically uses them for its own purpose and they
serve as building blocks of a c program. The following are the Keyword set of C language.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue .for signed void
default goto sizeof volatile
do if static while

Identifiers
Identifier is a name given to program elements such as variables, functions, procedure,
arrays and soon. First character must be an Alphabet or Underscore. Identifier consists of
sequence of letters, digits or combination of both.

Rules for Identifier


• First character must be an Alphabet or Underscore( _ ).
• Special characters and embedded commas are not allowed.
• First 31 characters are given high priority or preference.
• Keyword cannot be used as Identifier.
• There should not be any white space.
• Both uppercase and lowercase letters are permitted.
• The underscore character is also permitted in identifiers.

14
Computer Programming Unit II

CONSTANT
Constant is a fixed value that doesn’t or does not change during the execution of a
program. It remains same throughout the program. Its value cannot be altered or modified in a
program. A variable is declared by the Keyword const. Constant is classified into three main
types.
Eg: const int a,b,c;
Constant is classified into three main types. They are described as follows.
1. Numeric Constant
2. Character Constant and
3. Symbolic Constant.

CONST

NUMERIC CHARACTER SYMBOLIC

INTEGE REA SINGLE STRING


CHARAC
TER
NUMERIC CONSTANT
Numeric Constant is further classified into two main types. They are
(i) Integer Constants and (ii) Real Constants
Integer Constants
Integer constant consist of sequence of digit without decimal point. It is normally a
whole number.
Real Constants
Real Constants are otherwise known as Floating Point Constants. Real Constant
consists of decimal number, exponent or combination of both. Real constant consist of two
forms. They are Fractional form and Exponential form.
CHARACTER CONSTANT

Character Constant is also known as single character constant. The Character constant
is mainly classified into three types. They are
i. Single character constants
Single character constant is also known as character constant. It contains single
character or number enclosed within a pair of single quotes. If number specified within single
quotes it is considered as character constant. It cannot be used with arithmetic expression.

15
Computer Programming Unit II

Strings are stored in memory as ASCII codes of characters. Each character is stored in one byte
or length of single character constant is one.
E.g:- Valid ‘A’ ‘m’ ‘’ ‘3’
Invalid “W” “ma”
Character M Y ” a g e i s
#
ASCII Code 77 121 34 97 103 101 35 105 115

Character % 2 blank ( t w o ) @

ASCII Code 37 50 32 40 116 119 41 41 64

ii. String constant


String constant consist of sequence of characters enclosed with double quotes. The
character may be letters, numbers, special characters and blank space. The end of string is
marked with NULL character ‘\0’. It uses two bytes. One for ASCII code and other for NULL
character.

Rules for String constant :


• String constant must be a single alphabet, special character or sequence of alphabets
or digits enclosed in double quotes.
• Every string constant ends with NULL character. It is automatically assigned.

E.g:- Valid “Manakula Vinayagar institute of Technology”


Invalid ‘school’

iii. Backslash Character constant.


Backslash Character constant starts with backslash ‘\’. It may consist of single or two
characters. Back slash character constant are also known as Escape sequences.

CONSTANT MEANING CONSTANT MEANING


\a Audible alert. \r Carriage return.
\b Back space. \t Horizontal tab.
\f Form feed. \v Vertical tab.
\n New line. \\ Back slash.
\’ Single quote \’’ Double quote.
\? Question mark. \0 Null.

SYMBOLIC CONSTANT

16
Computer Programming Unit II

It represent numeric/character string constant. It is defined as follows.


#define<scname><sctext>.
Here scname stands for Symbolic Constant name and sctext stands for Symbolic
Constant text. scname is usually written in capital letters.
Example :-
#define PI 3.14
const int pi=3.14

VARIABLE
Variable is a name given to Memory location in which data is stored. Variable acts as
value, which changes during the execution of program. Variable may take different value at
different times during execution.
The general format of any declaration
datatype v1, v2, v3, ……….. vn
where v1, v2, v3 are variable names. Variables are separated by commas. A declaration
statement must end with a semicolon.
Eg: int sum;
double average, mean;
VARIABLE ASSIGNMENT
It is another format of variable declaration. The general form is
data-type variable name [=value];
Here data type refers to the type of value used in the C program. Variable name is a
valid name. Square brackets [ ] denotes that the value may or may not be used or
specified within the program.
Eg: int a; (or) int a=10;
Here if the value of a is assigned 10 the value remains the same throughout the program.
If no value is specified then the value keeps on changing.

SIMPLE VARIABLE ASSIGNMENT


To assign a single value to a variable ‘=’ equality operator is used. The syntax is
variable-name = value;
Eg: X=10; y=30;

17
Computer Programming Unit II

COMPOUND VARIABLE ASSIGNMENT


variable-name = expression
This type of variable declaration can be used together with combination of characters,
numbers or an expression. Here ‘=’ equality operator is used.
Eg: Y=x+5; Z=((x+1)(y-2)*x)

Declaring a variable as constant


Variable is declared as constant by using the keyword or qualifier ‘const’ before the
variable name. This can be done at the time of initialization.
Eg: Const int class_size = 40;

Volatile Variable
A variable is volatile if the value gets changed at any time by some of the external sources.
Eg: volatile int num;
when we declare a variable as volatile the compiler will examine the value of the variable each
time it is encountered to see if an external factor has changed the value.

DATA TYPES
Data Type is used to define the type of value to be used in a Program. Based on the type
of value specified in the program specified amount of required Bytes will be allocated to the
variables used in the program. Data types are broadly classified into three main types. They are
as follows.
• Primary data type ( Fundamental Data Types)
• Derived data type
• User defined data type.
Primary Data Type
Integers are represented as int, character are represented as char, floating point value
are represented as float, double precision floating point are represented as double and finally
void are primary data types. Primary data type offers extended data types. longint, long double
are extended data types.
Integer Data Type
Integer data type can store only the whole numbers.

18
Computer Programming Unit II

Name C Representation Size Range Format


(bytes) Delimiter
Integer int 2 -32768 to 32767 %d
Short Integer short int / short 2 -32768 to 32767 %d
Long Integer long int / long 4 -2147483648 to %ld
2147483647
Signed Integer signed int 2 -32768 to 32767 %u
Unsigned Integer unsigned int 2 0 to 65535 %d
Signed Short unsigned short int / 2 -32768 to 32767 %d
Integer short
Unsigned Short unsigned short int / 2 0 to 65535 %u
Integer short
Signed Long Integer signed long int / long 4 -2147483648 to %ld
2147483647
Unsigned Long unsigned long int / long 4 0 to 4294967295 %lu
Integer

Floating Point Data Type


Floating Point data types are also known as Real Numbers. It can store only the real
numbers (decimal numbers) with 6 digits precision.
Name C Representation Size Range Format
(bytes) Delimiter
Float float 4 3.4 e-38 to 3.4 e+38 %f
Double double 8 1.7e-308 to 1.7e+308 %f
Long Double long double 10 3.4 e-4932 to 3.4 e+4932 %lf

Character Data Type


Normally a single character is defined as char data type. It is specified by the keyword
char. Char data type uses 8 bits for storage. Char may be signed char or unsigned char.
Name C Representation Size Range Format
(bytes) Delimiter
Character char 1 -128 to 127 %c
Signed Character signed char 1 -128 to 127 %c
Unsigned Character unsigned char 1 0 to 255 %c

19
Computer Programming Unit II

Empty Data Type


VOID is the empty data type. This data type is used before main function in a C
Language. The word void refers no return data type. It is used before the main function to
specify the type of function. If a function is of type void it does not return any value to the
calling function.
OPERATORS
Operator is a Symbol that tells or instructs the Compiler to perform certain
Mathematical or Logical manipulations (Calculations). Operators are used in a program to
work on data and variables. Operators in general form a part of Mathematical or Logical
expression.
Operators are generally classified into different types. They are described one below
another as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Special Operators
7. Bitwise operators
8. Increment and decrement operators
9. Unary operators
10. Equality operators

ARITHMETIC OPERATORS
Arithmetic operators are used to perform Arithmetic operations. They form a part of
program. Programs can be written with or without operators. But calculations are performed
only using operators. Operators act along Operand to produce result.

Operator Meaning Details


+ Addition Performs addition on integer numbers, floating point numbers. The
variable name which is used is the operand and the symbol is operator.
- Subtraction Subtracts one number from another.
* Multiplication Used to perform multiplication
/ Division It produces the Quotient value as output.

20
Computer Programming Unit II

% Modulo It returns the remainder value as output.


Examples of arithmetic operators are
x+y x-y x*y x/y x%y
Here x, y are known as operands. The modulus operator is a special operator in C
language that evaluates the remainder of the operands after division.

RELATIONAL OPERATOR
Relational Operators are used to compare two same quantities. There are six relational
operators. They are mentioned one below another as follows.
Operator Meaning Operator Meaning
< is less than >= is greater than or equal to
<= is less than or equal to == is equal to
> is greater than != is not equal to

The general form is


(exp1 relational operator exp2)
where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them. Given below is a list of examples of relational expressions and evaluated
values.
6.5 <= 25 TRUE -65 > 0 FALSE 10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C language such as
if, while and for statements to decide the course of action of a running program.

LOGICAL OPERATORS
Logical Operators are used when we need to check more than one condition. It is used
to combine two or more relational expressions. Logical Operators are used in decision making.
Logical expression yields value 0 or 1 i.e.,( Zero or One) . 0 indicates that the result of logical
expression is TRUE and 1 indicates that the result of logical expression is FALSE.

Logical Operator Meaning


&& Logical AND
|| Logical OR
! Logical NOT

21
Computer Programming Unit II

Logical AND ( && )


The result of the Logical AND operator will be TRUE If both value is TRUE. If any
one of the value is false then the result will be always False. The result is similar to basic
Binary multiplication.
Eg: a > b && x = = 10
The expression is true only if both expressions are true i.e., if a is greater than b and x
is equal to 10.

Logical OR ( || )
If any of the expression is true the result is true else false otherwise. The result is similar
to basic Binary addition.
The logical OR is used to combine 2 expressions or the condition evaluates to true if
any one of the 2 expressions is true.
Eg: a < m || a < n
It evaluates to true if a is less than either m or n and when a is less than both m and n.

Logical NOT ( ! )
It acts upon single value. If the value is true result will be false and if the condition is
false the result will be true. The logical not operator takes single expression and evaluates to
true if the expression is false and evaluates to false if the expression is true.
Eg (!a)

EQUALITY OPERATOR
Equality operator ( = ) is used together with condition. The value of the expression is
one or zero. If the expression is true the result is one, if false result is zero.
Operator Meaning
== Equal to
!= Not equal to
Example :
x = 1 and y = 2 then
x = =2 is false , x = = 1 true , y != 3 true

22
Computer Programming Unit II

ASSIGNMENT OPERATORS
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression. The general form is
identifier = expression
Eg: x = a + b;
Here the value of a + b is evaluated and substituted to the variable x. ‘=’ equal to is used in
Assignment operators. It is of two types. They are

(i) Simple assignment operator


In Simple assignment operator only one ‘=’ equal to operator is used. It is used to assign
a value to variable or expression. The general form is
identifier = expression
Eg: y=35; x=ax+b-c;

(ii) Shorthand assignment operator


Shorthand assignment operator must be an arithmetic operator or bitwise operator. The
general form is
identifier <operator> = expression
The operator must be an arithmetic operator or bitwise operator.
Operator Meaning Example Example
Simp. Assign Shorthand
+= Assign sum x=x+1 x+ =1
-= Assign difference y=y-1 y-=1
*= Assign product z=z*(x+y) z*=(x+y)
/= Assign quotient y=y/(x+y) y/=(x+y)
%= Assign remainder x=x%z x%=z
~= Assignone’s complement
<<= Assign left shift x = x << z x << = z
>>= Assign right shift
&= Assign bitwise AND y = y&x y&=x
|= Assign bitwise OR
^= Assign bitwise X - OR z = z^y z^=y

23
Computer Programming Unit II

CONDITIONAL OPERATORS
Conditional Operator Ternary operator is also known as “Ternary operator”. The
general form of Conditional Operator is
(exp1)?(exp2):(exp3);

where exp1 is the condition which is to be checked and exp2 is the true value and exp3 is the
false value. If the condition in exp1 is false then statement in exp3 will be automatically
executed.
Eg:
#include<stdio.h> Output:
void main() Enter the value of a and b: 125 100
{ The biggest value is 125
int x,y,z;
clrscr(); Enter the value of a and b: 25 100
printf(“Enter the value of a and b :”); The biggest value is 100
scanf(“%d %d”,&x,&y);
z=((x>y)?x:y);
printf(“The biggest value is %d”,z);
getch();
}

SPECIAL OPERATORS
Special operators are known as separators or punctuators. Special operators are
Ampersand ( & ) Braces ( { } ) Colon ( : ) Ellipsis ( … )
Asterisk ( * ) Brackets ( [] ) Comma ( , ) Hash ( # )
Parenthesis ( () ) Semicolon ( ; )

Ampersand ( & )
It is also known as addresss operator. It is specified before the identifier name. i.e.,
variable name. It indicates memory location of the identifier.

Asterisk ( * )
Asterisk ( * ) is also known as indirection operator. It is specified before identifier name.
It indicates creation of pointer variable. It is also a unary operator.
Braces ( { } )

24
Computer Programming Unit II

The opening brace ( { ) and closing brace ( } ) specify the start and end of compound statement
in a function. Here semicolon ( ; ) is not necessary. Semicolon ( ; ) is used only in structure
declaration.
Brackets
Brackets [] also referred as array subscript operator. It is used to indicate single and
multi dimensional arrays.
Eg: int x[10]; float l[10][20];
Colon ( : )
Colon ( : ) is used in labels. It is used in unconditional control statement i.e., in goto
statement.
Eg: goto d;

Comma Operator ( , )
It is used to link expressions together. It is used together with variables to separate one
variable from another. It is used in for loop. It has the lowest precedence among operators
Eg: for(n=1,m=10;n<=m; n++, m++)
int a,b,c;
sum= (x=5,y=3,x+y);

Ellipsis ( … )
Ellipsis ( … ) are three continuous dots with no white spaces between them. It is used
in function prototype. It indicates that the function can have any number of arguments.
Eg: void fun(char s,int n, float f, …);

Hash ( # )
Hash ( # ) is also known as pound sign. it is used to indicate preprocessor directives.
Eg: #include“stdio.h”

Parenthesis ( () )
Parenthesis ( () ) is also known as function call operator. It is used to indicate the open
and end of function prototypes, function call, function parameters, …. Parentheses are used to
group expressions.

Semicolon ( ; )

25
Computer Programming Unit II

Semicolon ( ; ) is a statement delimiter. It is used to end a C statement.


Eg: g=d+h;
BITWISE OPERATORS
Bit wise operator is used to manipulate with bits within a word of memory. Bit wise
operator operates only on integer and character but not on float and double.
Operator Meaning Operator Meaning
~ One’s Complement & Bitwise AND
<< Left shift | Bit wise OR
>> Right shift ^ Bit wise x-or

One’s Complement Operator ( ~ )


One’s Complement makes the bits of operand inverted. Here one becomes zero and
zero becomes one.
Eg: x = 7 i.e., x = 0000 0111
One’s complement of t is 248 ( i.e., ~x = 1111 1000 = 248 )

Left shift Operator ( << )


Left shift operator ( << ) shifts each bit of the operand to left. The general form is
Variable << number of bit positions
Eg: x =7 ( i.e., 0000 0111 = 7 )
y = x <<1 is 14. ( i.e., 0000 1110 = 14 )

Right shift Operator ( >> )


Right shift operator shifts each bit of the operand to right. The general form is
Variable >> number of bit positions
Eg: x = 7 ( 0000 0111 = 7 )
y = x >> 1 is 3 ( i.e., 0000 011 = 3 )

SIZE-OF OPERATOR
This operator is used to return the size of string or character. It cannot be used in
together with Integers. The syntax is
sizeof(variable-name);
Eg:

26
Computer Programming Unit II

#include<stdio.h>
Output:
void main()
The value of x is 2
{
int x;
clrscr();
printf(“The value of x is %d”,sizeof(x));
getch();
}

PRECEDENCE OF OPERATORS
• Outermost Parenthesis is evaluated first.
• Then innermost parenthesis.
• If there is two or more parenthesis, then the order of execution is from left to right.
• Next Multiplication and Division are performed.
• Finally Addition and Subtraction.

INCREMENT and DECREMENT OPERATORS


Increment Operators
It is used to increase the value of the Operand by 1. There are two types of Increment
Operators in C Language. They are pre Increment operator and post Increment operator.

Pre Increment Operator


It is used to increase the value of the variable by 1. Here the value of 1 is added to the
variable first along with the given variable value.
Eg: ++g -> pre increment

Post Increment Operators


It is used to increase the value of the variable by 1. Here the value of 1 is added to the
variable first along with the given variable value.
Eg: g++ -> post increment

Decrement Operators
It is used to decrease the value of the Operand by 1. There are two types of Decrement
Operators in C Language. They are pre decrement operator and post decrement operator.

27
Computer Programming Unit II

Pre decrement Operator


It is used to decrease the value of the variable by 1. Here the value of 1 is subtracted to
the variable first along with the given variable value.
Eg: --g ------> pre decrement
Post Decrement Operator
It is used to decrease the value of the variable by 1. Here the value of 1 is subtracted to
the variable first along with the given variable value.
Eg: g-- ----> post Decrement

main() {
int a = 21;
int c ;

// Value of a will not be increased before assignment.


c = a++;
cout << "Line 1 - Value of a++ is :" << c << endl ;

// After expression value of a is increased


cout << "Line 2 - Value of a is :" << a << endl ;

// Value of a will be increased before assignment.


c = ++a;
cout << "Line 3 - Value of ++a is :" << c << endl ;
return 0;}
Line 1 - Value of a++ is :21
Line 2 - Value of a is :22
Line 3 - Value of ++a is :23

UNARY OPERATORS
Unary operators act on single operand to produce new value. It proceeds with operands.
Unary minus denotes subtraction. Subtraction operators require two operands but unary minus
require one operand. The operand used with this operator must be a single variable.
Operator Meaning

+ Unary plus operator; indicates positive value (numbers are positive without this, however)

- Unary minus
++ Increment by 1
-- Decrement by 1

28
Computer Programming Unit II

sizeof Return the size of operand


Eg:
-786 -0.64 -5e-8 -(a+b) -6*(f+b) -45.878
When operator is used before variable then it is prefix notation. When operator is used
after variable then it is postfix notation.

Eg:
Expression Result
++x 4
x++ 3
--x 2
x-- 3

INPUT OUTPUT FUNCTIONS


We know that input, process, output are the three essential features of computer
program. The program takes some input data, processes it and gives the output.

We have two methods for providing data to the program

• Assigning the data to the variable in a program


• By using the Input/output statements

In ‘C’ language, two types of Input/output statements are available, and all input and
output operation are carried out through function calls. Several functions are available for
input/output operations in ‘C’. These functions are collectively known as the standard I/O
library

1. Unformatted Input/output Statements


2. Formatted Input/output Statements

Unformatted Input/output Statements

These statements are used to Input/output a single/group of characters form/ to the


input/output devices. Here the user cannot specify the type of data that is going to be
input/output.

Input and Output Functions

Unformated I/O Statments Formated I/O Statments

29
Computer Programming Unit II

Input Output
Input Output
scanf() printf()
getchar() putchar()

getc() putc()

gets() puts()

The following are the unformatted Input/Output statements available in ‘C’

Input Output

getchar() putchar()

getc() putc()
i) Single Character gets() puts() Input-getchar( ) function

A Single character can be given to the computer using ‘C’ input library function getchar()

Syntax char variable=getchar();

Description char : datatype;

variable : Any valid ‘C’ variable

Example char x; x=getchar();

The getchar() function is written in standard I/O library. It reads a single character
from a standard input device. This function do not require any arguments, through a
pair of empty parentheses, must follow the statements getchar().

The first statement declares x as a character type variable. The second statement causes
a single character to be entered from the standard input device and then assigned to variable x.

ii) Single Character Output-putchar() function

The putchar() function is used to display one character at a time on the standard output device.
This function does the reverse operation of the single character input function as discussed
above

Syntax putchar(character variable);

Description Character variable is the valid ‘C’ variable of the type of char
data type

Example char x; putchar(x);

30
Computer Programming Unit II

iii) The getc() function

This is used to accept a single character from the standard input to a character variable

Syntax character variable=getc();

Description Character variable is the valid ‘C’ variable of the type of char
data type

Example char c; c=getc();;

iv) The putc() function

This is used to display a single character in a character variable to standard output device.

Syntax putc(character variable);

Description Character variable is the valid ‘C’ variable of the type of char
data type

❖ The getc() and putc() function are often used in file processing
Example char c; put(c);

v) The gets() and puts() function

The gets() function is used to read the string (string is a group of characters) from the standard
input device (keyboard)

Syntax gets(char type of array variable)

Description Valid ‘c’ variable declared as one dimension char type

Example gets(s);

The puts() function is used to display/write the string to the standard output device.

Syntax puts(char type of array variable)

Description Valid ‘c’ variable declared as one diamension char type

31
Example put(s);
Computer Programming Unit II

❖ The gets() and puts() function are similar to scanf() and printf() function but the
difference is in the case of scanf() input statement, when there is a blank space in input
text, then it takes the space as an ending of the string the remaining string are not been
taken.

Formatted Input/output Statements

Formatted Input/output refers to input and output, that has been arranged in a
particular format

Eg : LAK 3977

This line contains two parts of data that is arranged in a format, such data can be read
to the format of its appearance, as the first data should be read into a variable char, the second
into int. Such operation can be made possible in ‘C’ language by using the formatted
Input/output statements. Using these statements, the user must specify the type of data, that is
going to be accessed(Input/output)

The following are the formatted Input/output statements

Input Output

scanf() printf()

i) The scanf() function

Input data can be entered into the computer using the standard input ‘C’ library function
called scanf(). This function is used to enter any combination of input.

The scanf() function is used to read information form the standard input
device(keyboard), scanf() function starts with a string arguments and may contain
additional arguments. Any additional argument must be pointer

32
Computer Programming Unit II

Syntax scanf(“control string”,&var1,&var2,……&varn);

The Control String consists of character groups, Each character


group must begin with a percentage sing ‘%’. The character
group contains percentage sign, followed by conversion character
as specified in table below.
Description
var1,var2….varn – are the arguments or variables in which the
data is going to be accepted

Example int n;

scanf(“%d”,&n);

Control String:

It is the type of data that the user going to accept via the input statements, this can be
formatted and always preceded with a ‘%’ sign. The below table illustrates code formats
(control strings) in Input/Output statements.

Format Meaning
String
%c Read single character.
%d Read a decimal integer.
%e Read a floating point value in Exponential form.
%f Read a floating point value.
%g Read a floating point value.
%h Reads a short integer.
%i Read a decimal, hexadecimal or octal integer.
%o Reads an octal integer.
%s Reads an string.
%u Reads an unsigned decimal integer.
%x Reads an Hexadecimal integer. (Unsigned) using lower case a – f
%[..] Reads a string of word(s).
%X Reads a hexadecimal integer (Unsigned) using upper case A – F
%u Reads a unsigned integer.
%U Reads a unsigned long integer.
%p Reads a pointer value
%hx Reads hex short
%lo Reads octal long
%ld Reads long

Each variable name (argument) must be preceeded by an ampersand(&). The (‘&’) symbol
gives the meaning “ address of” the variable.

33
Computer Programming Unit II

The scanf control string or placeholder consists of % at the beginning and type indicator at the
end. Apart from that it can have *, a maximum field width indicator and a type indicator
modified.

Rules for writing scanf() function

1. The control string must be preceded with (%) sign and must be within quotations, i.e.,
the address of variable should be passed.

2. If there is an number of input data items, items must be separated by commas and must
be preceded with (&) sign except for string input

3. The control string and the variables going to input should match with each other

4. It must have termination with semicolon


5. The scanf() reads the data values until the blank space in numeric input or maximum
number of character have been read or an error is detected

ii) The printf() function

Output data or result of an operation can be displayed from the computer to a standard
output device using the library function printf(). This function used to output any combination
of data. It is similar to the input function scanf(), except that it display data rather than input.

Syntax printf(“control string”,var1,var2,……varn);

Control string is any of the following.


a) Format code character
b) Execution character set or Escape sequences
c) Characters/String that will be displayed
Description var1,var2,varn are the arguments or variables from which the data
is going to output. Here the variables need not to be preceded
with ‘&’ sign.

Example printf(“Result is ….%d”,n);


printf(“%f”,f);
printf(“%s”,s);

Rules for writing printf() function

1. Place appropriate heading in the output


2. The variables must be separated by commas, and need not be preceded with ‘&’ sign
3. The control string and the variables must match in their order

34
Computer Programming Unit II

4. The control string must be in quotations and there we can also use any other text to print
with data
5. Provide blank space in between the numbers for better readability
6. Print special messages wherever required in output

Difference between scanf and printf function.

Scanf printf
Used to accept data Used to display data
Control string and & operator is used Control string only used.
It end with semicolon It end with semicolon
Number of input specified with format Number of input specified with format
String and enclosed within double string and separated by commas.
quotes.
The Input variables are specified using The output variables are specified by
Address operator (&) is separated by their name and separated by commas.
commas.

Difference between getchar() and gets()

getchar() gets()
Used to receive a single character Used to receive a string with white spaces and blanks
Does not require any argument It require a single argument

Difference between scanf() and gets()

scanf() gets()
Strings with white spaces cannot be Strings with any number of spaces can be
accessed until ENTER key is pressed accessed
Spaces and tabs are not acceptable as a Spaces and tabs are acceptable as a part of
part of the input string input string.
Can receive any number of characters and Only one string can be received at a time.
integers.
Format string and input variable name is Format string and address is specified.
specified.
All data types can be accessed Only character data types can be accessed

35
Computer Programming Unit II

Difference between puts() and printf()

puts() printf()
It can display only one string It can display any number of characters, integers or strings
at a time. at a time.
All data types are considered Each data type is considered separately, depending upon
as characters. the conversion specifications.

36

You might also like