Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 56

10 Computer Camps oder Cs & Car ( RD ) Unit 2 und Main Memory 2 CE 10 tions c

sembler functions Merits and Demerits.


lain.
Merits and Demerits.
age and its advantages and COMPUTER PROGRAMMING:
Overview of C - Datatypes and I / O Statements t i pes d Application Software.
nit ( CPU ).
piler 2.
0 Computer Programming 2.
1 Basic Programming Concepts 2.
2 Algorithms 2.
3 Flowcharts 2.
4 Overview of C - An introduction 2.
5 Importance of C:
Why C .
.
.
.
?
2.
6 Sample C programs 2.
7 Basic Structure of C program 2.
8 Programming Style 2.
9 Executing a C program 2.
10 C tokens 2.
11 C Keywords 2.
12 Identifiers 2.
13 Constants 2.
14 Variables 2.
15 Declaration of Variables 2.
16 Datatypes 2.
17 Defining Symbolic Constants 2.
18 Assigning Values to Variables:
The As signment Statement 2.
19 Input and Output Statements 2.
20 Reading a Character 2.
21 Writing a Character 2.
22 Formatted Input statement:
scanf ( ) function 2.
23 Formatted Output Statement:
printf ( ) function 2.
24 Simple C programs PRO MI

BCA Computer Concepts & C Prog- IKUD Algorithms Flowcharts 102 Unit 2 2.
0 Computer Programming The basic structure of a computer and Von Neuman's stored
program concept revealed us that a computer has a storage unit called its memory:
It holds a set of instructions called a program to be executed and a set of data
to be processed.
In other words CPU reads one instruction at a time from the memory unit and
executes it on the relevant data.
Likewise, the execution continues from instruction to instruction.
At the end of last instruction execution, the results of computation will be
stored back in the memory and later they may be displayed on the output unit, the
display:
d screen.
► Therefore computer is termed as a General Purpose programmable machine.
In other words any specific work can be carried out by the computer at a given
time, just by instructing it to do so, but in a simple systematic step by step
procedural instructions that necessitates the computer programming both knowledge
and skills The language with which computer can understand the instructions and
proceed to execute the specified task - are the two important aspects of
programming the computer.
2.
1 Basic Programming Concepts Many of the devices, mechanical and electromechanical
machines can be operated and the specific work can be got done just by switching on
the machine, and / or by loading work piece in them.
Manual supervision of the functioning of the machines and timely hand operations
on the buttons and levers may lead to the production of good quality finished
products.
er Unlike all these machines, computer being an information processing machine
need clear cut guidance interms of sequence of instructional steps in order to
carry out the specified work, apart from switching on the computer and supplying
electricity to it! In other words, problem solving with computer involve preparing
a set of procedural instructions for determining the solution.
Using these instructions, computer can solve the problem to compute the results.
Therefore Computer programming is concerned with design ing a set of instruction
and expressing it using a precise notation known as a computer program.
A notation used for the precise description of the set of instructions is called a
computer programming language.
Thus computer programming involve the design, development and implementation of a
computer program in order to solve the given problem on a computer.
A finite set of instruction expressed using a precise notation is called a
computer program • Programming is both art as well as a science.
Because art of programming differs with different persons involved in computer
programming.
For example for the given ( same ) problem, three ( 3 ) persons may write 3
different computer programs with their own approaches.
These programs when executed give the same results.
Therefore programming is an Art.
• But the programs written by 3 persons ( programmers ) have the precise notation
also called scientific notation.
A specific scientific method or procedure may have to be used to design and write
each and every program.
Therefore a scientific approach to be followed and reasoning skills to be
incorporated while writing a program Thus programming is a science too.
7 Why programming language It is clear that a precise set of instruction called, a
computer programs is essential in order to solve the given problem.
Such compuier programs are written to instruct the computer that what operation to
perform?
( for example an arithmetic operation or a logizal operation ) Where and How to
locate data?
How to print the result?
When to take certain decisions?
and so on .
.
.
The computer being an electronic machine and the people working with computers,
( representing the external world ) are the two disjoin ends or the parties in
which a common understanding is required Then only both the computer and man can
establish a communicat on for problem solving e As nction nction
103 Par Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 105 5 O Computer being an electronic machine has
its own programming language called Machine language.
Any communication with the computer for problem solving must be in its machine
language.
Now computer can interpret and execute a set of a binary coded instructions called
its machine language instruction.
Writing a program for a computer machine consists of specifying directly or
indirectly, a sequence of machine instruction.
Machine instruction inside the computer form a binary pattern of O's and I's which
is difficult for people to work with and understand the machine language
programming.
Programming in machine language involve writing of computer programs that consists
of series of binary code patterns.
These binary streams of O's and I's forming a machine instruction consists of
instruction code also called the operation code and the operand address that
specify memory location to hold data operands.
Introductory Note # 1 Algorithms and Flowcharts are fundamental notations in the
context of computer programming.
Actually, the computer science branch is concerned with design and development of
Algorithms.
In fact in each and every stage of problem - solving, computer cannot be used to
solve the problem.
One has to devise a method and detailed procedure or a sequence of procedural
steps have to prepared.
This approach give rise to the concept of Algorithm pictorial representation of
which is a Flowchart.
Flowchart is used as an aid in preparing computer programs.
As algorithms and flowcharts assist the fundamental knowledge while preparing a
solution to the problem ( to be solved using computers ), a complete chapter is
dedicated to the detailed discussion on algorithms and flowcharts.
2.
2 Algorithms Algorithm consist of limited number of procedural steps, each the step
may perform one or more operation.
Therefore algorithe is a scientific procedure to solve a problem, thereby solution
to the particular problem is definitely achieved The word Algorithm comes from the
name of a persian mathem tician Abu Ja'far Mohammed ibn Musa al Khowarigmi.
He wrote text books on Mathematics.
Characteristics of Algorithms A well defined algorithm has the five basic
characteristics; They are 1.
Input:
Algorithim starts with procedural step to accept input data:
These data elements are processed by the subsequent steps on instructions in the
algorithm.
Therefore algorithm must accept one or more input data to be processed.
2.
Definite:
Each operational step or operation must be definite i.
e.
each and every instruction must specify clearly that, what should be done.
In other words there should not be any confusing instructions.
For example instructions such as i ) compute 5 = 0 ii ) Add 10 or -7 to x are not
allowed because it is not clear what the result is in case of 5/0.
Since ( infinity ) is not defined in computer.
Which of the two numbers ( 10 or -7 ) should be added to x.
Therefore there is no definiteness in these instructions.
In otherwords, procedural step or instruction must be precise and it should tell
in a definite manner What is to be done.
3.
Effective:
Each operation and hence procedural steps must be effective to carry out.
Effectiveness property of the Algorithm says that each operational step can at
least in principle be carried out by a person using a paper and pencil in a minimum
amount of time In otherwords operations must be simple and can be carried out a one
or more levels of complexity 4.
Terminate:
After some minimum number of operations algorithm must come to an end.
i.
e.
, the total time to carry out all the steps in algorithm must be limited
( finite ).
1 Algorithm Definition An algorithm can be defined as a finite number of well
defined procedural steps used to solve the problem.

104 I " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 106 choi itom o the ema.
Tote MI Ő PRI are:
ata; or One 5.
Output:
An algorithm is written to solve the problem therefore it must produce one or more
computed results or answers called as output.
In otherwords it should contain instructions to print the results on the output
unit.
In order to incorporate the definiteness property of the algorithm, algorithms
will be expressed using a precise notation called Programming languages.
Such computer programming languages are designed to assign ( simplicity ) clarity,
definiteness and effective ness to each of the instructions of the algorithm.
The languages a actually consists of all necessary features to support the
character istics of an algorithm.
Program:
Therefore a computer program is the expression of an algorithm using a programming
language.
A computer program is written to solve the problem on a computer.
Basic Control Structures in Algorithms Usually algorithm consists of finite set of
sequential procedural steps or instructions to be carried out to solve the given
problem.
Given a problem one has to take decisions, like a condition is True or False ( yes
or no ).
Depending upon this decisions execution takes place ( or continues ) by selecting
a particular group of procedural steps for execution.
There are also situations in which some of the instructions have to be executed
repeatedly ( again and again ) for a specific number of times or until a condition
is satisfied ( true ).
This is called as execution by repetition ( iteration ).
* To meet all the above situations of problem solving algorithm uses three basic
forms of control structures:
1.
Sequencing 2.
Selection ( branching ) 3.
Repetition.
These are also called as program structures used in developing a structured
programs.
1.
Sequencing:
The Sequence structure indicates the sequential flow of program logic ( a step by
step continuous flow or execution ).
This is shown in a flowchart form in the fig 1 ( a ).
Each box may stand for a Statement; it may stand for a whole module or even
collection of modules.
It indicates step by step sequence in which program execution has to continue.
For example in C language SEQUENCING can be illustrated with statements in series,
such as:
printf ( " enter two numbers \ n " ); ----- 1 statement1 scanf ( " % d % d ", &
P1, & P2 ); sum = P1 + P2; statement2 product - P1 * P2; printf ( " Sum = & d,
product = % d \ n ", sum, product ); ----- 5 Fig.
1 ( a ) A group or sequence of five statement in a C Program will be executed in
series one after another.
This is called SEQUENCING or sequential execution.
2.
Selection ( Branching ):
The IF_THEN ELSE statement indicate branching.
It defines conditional program flow.
The path of execution is selected depending upon whether a condition is true or
false.
For example.
if ( numl > num2 ) then print " first number is largest "; else print " first may
be equal to or less than second number ".
indicate a condition to be tested at if statement.
If the answer is true i - e.
, ( numl > num2 ) is true then the first print statement will be selected for
execution and else part of the statement will never be executed! Otherwise, if the
condition tested is false then the first print statement will never be executed but
the else part of the print statement is executed.
The Selection or Branching is shown in flowchart form in the figure 1 ( b ).
ald mg or in of ce d True False Path Selection Path Selection Two Fig:
1 ( b ) A Branch & Select

107 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts For example in C language BRANCHING can be
illustrated with an if - else statement, such as -- if ( age > 18 :
:
age == 18 ) printf ( " You are eligible to cast your valued vote \ n " ); else
printf ( " You are not eligible to cast vote! \ n ); Is Examples - of Algorithms
1 ) Consider the first example:
Given the problem, to compute the sum and average of 3 numbers, We shall write the
algorithm.
As we know that solution to the problem is given as sequence of procedural steps
and as per the characteristi of algorithr here are ructi numbers & instruction to
print the sum & average, the output.
Each operational step must be definite & effective to carry out, Please note that
each procedural step may be preceded by comment statement that explain the step or
instructions.
Thus algorithm to compute the sum & average of three numbers is written as
follows:
to input the If condition age > = 18 is true first printf statement will be
selected for execution; other wise second printf statement will be executed.
3.
Repetition:
The DO - WHILE statement indicate Repetition or looping.
That is repetitive execution of group of statements or program segment, takes
place as long as the loop condition is true.
The moment when the loop condition become false the loop or repetition will be
terminated.
This is shown in flow chart form in the fig 1 ( c ).
For example in C lan guage Repetition or looping can be performed with a do while
statement such as Algorithm To compute SUM & AVERAGE of three numbers Step 1 [ Read
the three numbers Read nl, n2, n3 Step 2:
[ Add the numbers to compute sum ] Sum + ( nl + n2 + n3 ) Step 3 [ Compute the
average of three numbers ] Average + Sum / 3 Step 4 [ Print the computed results:
SUM & AVERA Write Sum, Average.
Step 5:
[ Finished! - end of Algorithm ) Exit.
do printf ( " Count down:
Ad \ n ", count ); count - count -1; } while ( count > 0 ); R F P E Statements
Test loop True Condition As long as count > 0 is true the loop statements will be
executed repetitively to print count down say Count down:
3 Count down 2 Count down:
1 When count > 0 is false i.
e.
, when count = 0 .
the looping will be terminated! False ** Observe algorithmic notations:
Every procedural step or it tion starts with step number; each step is preceded by
a explancton comment.
Every algorithm has a title that specify task 0:
32 performed.
Last step consist usually a Exit or stop instruction specify the TERMINATE
characteristic of an Algorithm.
Algorith may or may not contain instructions to input the data.
Usually the first instructions are for input.
Algorithm always have instru to print the results.
Comments for each step are included to square brackets Exit The Loop Fig.
1 ( c ) A Repetition

109 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 110 A In the above algorithm nl, n2, n3 are
three numbers to be read ( input ).
The results are stored in Sum & Average ( output ).
The operational step 2 adds the three numbers with following instruction Sum ( nl
+ n2 + n3 ) here ( leftwords arrow ) specify the assignment.
i.
e.
, sum of nl, n2, & n3 is assigned to ( stored ) sum ( a variable name that hold the
result ) The symbol is equivalent to =.
The above instruction is as good as writing sum = ( nl + n2 + n3 ) But in
algorithmic notations = is replaced by + symbol.
2 ) Consider a second example:
( 6.
4.
2 ) Given the problem:
to find largest of given three numbers.
We shall write the algorithm with the assumption that the three numbers A, B and C
are read and biggest among these, is assigned to BIG.
Thus the BIG holds Biggest among A, B, & C numbers, at the end Given 3 numbers say
for example A = 10 B = 30 C = 20 Biggest can be found by assuming the first number
as Biggest i.
e.
, BIG = A ( BIG = 10 ).
► Now by making pairwise comparisons with remaining numbers B & C, if either B or
C is greater than BIG, then contents of BIG ( i.
e.
, 10 ) have to be replaced with B or C.
- > In other words if B > BIG is true i.
e.
, 30 > 10 then BIGB is true.
:
.
BIG = 30 now next if C > BIG is true i.
e.
, 20 > 30 False then BIG C i.
e.
,:
C = 20 is not stored in BIG :
:
Biggest of 10, 30, 20 is 30 only BIG = 30 is still valid.
Algorithm:
LARGEST OF THREE NUMBERS Step 1:
[ Read 3 numbers ] Read A, B, C Step 2:
[ Assume that first number A is BIGGEST initially let BIG A Step 3:
[ Compare BIG with the remaining two numbers to find the Biggest ) if B > BIG then
BIG B if C > BIG then BIG C Step 4:
[ Print the Largest number ] write " LARGEST of 3 Numbers is ", BIG Step 5:
[ End of procedure ] Stop In the above algorithm a simple method or technique is
adapted to compute the Biggest.
2.
3 Flowcharts Flow chart - the definition " A Flow chart can be defined as the
pictorial for graphical ) represen tation of an Algorithm ".
► In the content of problem solving with computer, first the given problem is
analysed; a sequence of procedural steps are formulated called an algorithm.
Algorithm specify the sequence of operations to be performed to arrive at the
solution.
Now this agorcnm expressed in a programming language, is called program.
it is with computer program, the computer machine actually works wisi.
> Therefore the algorithm is usually represented in a diagrammatic form before
being expressed into a programming language hereby it is easy for anybody to
understand clearly the flow of sequence of operations graphically, > Flow chart for
the given algorithm consist of a complete Viagram of boxes of standard shapes
( basic symbols ) by directed line segments ( arrow marks ).
The elementary steps of the alithm or the operating instructions are placed in
these boxes and t.
row mark connections to these boxes show the flow of operatione of the given
algorithm

P " Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 112 for i - l to N By drawing a flow chart,
algorithm can be better understand and can be convinced to others very easily since
it is in pictorial form.
FLOW CHARTS are normally introduced as an intermediate step to assist the
preparation of a computer program Program Flow Chart A program flowchart is a
flowchart that purely specify only the flow of operations of an algorithm,
pictorially.
It is of merely diagram matic representation of the the given algorithm.
The program flow chart illustrate graphically how the program instructions or
opera tions flow in a sequence, when the sequence of execution of instructions
changes etc.
But program flowchart never specify the computer environment in which the program
will be executed i.
e.
, it will not reveal whether the program is stored on magnetic disk, whether data
will be coming in from keyboard, also whether the results or output are printed out
on a printer.
► In other words program flowchart does not contain the basic symbols ( Standard
boxes ) to represent peripherals or I / O devices connected to the computer.
Therefore one cannot visualise pictorially the operational environment of computer
if he / she prefer to draw program flow charts.
Of course program flowchart consist only one basic symbol to represent Read /
Write instructions of an Algorithm.
The symbol is known as “ Parallelogram used to indicate standard input / output
operations, Basic Symbols Used in Drawing Flowchart > The following table shows the
standard conventions or basic symbols used to draw a program flowchart.
Each of the symbol is used to indicate a specific operations or elementary steps
of the algorithm.
Table:
Basic Symbols used in the FLOW CHARTS Symbol Name The symbol is used to indicate
input Parallelogram output operations i.
e.
, Read or Write instructions The symbol is a Processing box ' used Rectangle to
indicate arithmetic operations, as signment operations and any other computational
steps like initializations.
Diamond The symbol is a decision box or shape selection point.
It is used to indicate conditions tested.
Based on the TRUE or FALSE conditional results one path is selected for branching
the execution.
The symbol is also called a " Test box ".
The symbol is a group instruction box used to represent the repetition loops A
group of instructions to be executed, for a specified number of times, are included
within this sym bol.
The symbol indicates a predefined process.
For example sub programs like C Functions can be represented using this symbol The
symbol is a connector circle usca Small Circle to connect two parts of a flowchar
that indicates the continuity.
The syn bol is also called as " On page conner tor ".
The symbol is annotation box " os comment box.
The useful comment explaination of Flow - Chart steps can written into this symbol
The symbol arrows or directed lines Arrows indicate the flow of operations.
These Flow - Lines are used to inter - connect different boxes of Flow chart.
Used to represent Oval The symbol is used to denote either the beginning or end of
the flowchart.

113 P " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 114 Examples of Program Flowcharts The
flowcharts are drawn for the algorithms discussed in section 6.
1 ( Refer example ( 1 ) & ( 2 ) of Algorithms ) 1 ) Flow chart:
To compute the sum and average of 3 numbers START READ > System Flowcharts A
System flowchart is a flowchart which gives an over all view of computer system in
addition to the pictorial specification of the flow of operations of an algorithm.
otherwords, as the name itself indicate system flowcharts are drawn to show
diagrammatically the total environment of computer system on which the given
algorithm or program is to be solved.
System Flow - charts provide us a list of special symbols for indicating the input
- output devices on which the data transactions are read / printed.
There by one will get a clear picture of input output devices connected to a
computer system; Programmer or user if he could draw a flowchart ( for the problem
to be solved ) indicating the I - O devices with which he prefers to work with,
then it is the system flowchart that definitely assist him in this regard.
Step 1 of Algorithm NI, N2, N3 to read three numbers nl, n2, n3 Step 2 of
Algorithm SUM - NI + N2 N3 to add 3 numbers and to assign it to sum.
Step 3 of Algorithm average is computed WRITE Step 4 of Algorithm SUM, AVERAGE
output instruction prints the results sumn & average Step 5 of Algorithm STOP end
of procedure.
2 ) Flow chart:
To compute largest of given three numbers ( 6.
4.
2 ) START AVERAGE SUM READ А.
В.
с Therefore System Flowchart will further improve and assist the computer
programming.
Because system flowcharts not only specify the operations to be performed
pictorially but the computer system environment at which all these data processing
activities are handle To summarise, a system flowchart is a graphical
representation that w gives the complete view of a data processing system.
It has flowchart symbols to show the following BIGA IS YES B > BIG BIGB Step 1 of
Algorithm to read 3 numbers A, B, C Step 2 of Algorithm First number A assigned to
BIG A is initially assumed Largest number Step 3 of Algorithms 1.
elementary operation Selection is made depending upon B > BIG is true or false if
TRUE, BIG is assigned B Step 3 of Algorithm 2.
elementary operation selection is made depending on the condition C > BIG, if
TRUE, BIG gets the value of C Step 4 of Algorithms Writes the Largest number stored
in BIG Step 5 of Algorithm end of operation 11 NO IS B > BIG YES.
BIG C ► The activities ( either manual or computerised ) carried out within such a
data processing system.
NO READ A, B, C The I - O devices and storage media used to store / handle the *
aata file transactions etc.
which are involved in the data processir activities STOP

115 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 116 System Flowchart Symbols The system
Flowchart symbols are shown in the table as follow SYMBOL USED FOR SYMBOL USED FOR
Card input / output i.
e.
, 10 medium is punched cards ID Written or printed documents / sheets indicate
process or activity done manually indicate process or activity handled by a
computer Standard input -output for Read / Write operation on computer used to
indicate conditions the complexity increases and when we move down the hierarchy
the sub - division of problem increases but complexity of main problem decreases
Therefore, the strategy of dividing given problem as a whole into smaller and
simpler sub - problems and then solving individual problem - module as sub -
program / sub - problem and conquering all of them for unified and uniform results
as a whole - is termed.
Divide and Conquer Strategy Note:
Problem solving with computers in general, calls for employing DIVIDE - and
CONQUER strategy especially when a given problem is larger, with greater
complexity.
Accordingly, the High - level programming languages used for solving such problems
extend the facilities to develop and implement sub - problems interms of sub -
programs E For instance FORTRAN offer functions & sub - routines concept to develop
code for sub - programs.
The PASCAL offer procedure and C language provide the functions to implement the
sub - program modules 1 Y tested s Y M Magnetic drum -a storage medium used for
data input / output Magnetic disk -indicates that data input / output from magnetic
disk storage Magnetic tape -indicates data storage on tape memory ( decision box )
Start / stop symbol used to indicate beginning end of procedure B O L Writing
Algorithms and drawing flowcharts for simple exercises ► Swapping contents of 2
variables.
Let 2 variables are sum and diff whose contents are to le exchanged ( swapped ).
For instance say sum = 12 and diff = 8 Page connector to connect two parts of
Flowchard S 12 8 IDUAL - Data file:
Most of the data processing application handle a large quantity of data and this
data is usually stored as collection called file on a storage device.
As you can see from the figure above, the bidirectional lines connecting sub -
problem modules depict the flow of data, interaction and relationship among various
moduels with flow of results.
The figure also depict hierarchy of sub - problems under main problem - As we move
up towards main problem in the hierarchy Before Swapping After swapping → sum = 8
and diff = 12 is the required resul 8 у 12 Х After Swapping

117 P " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts Let's assume a third variable as place holder
say " temp " used in the process of swapping.
2 12 8 у х 1 3 temp ► Algorithm and Flowchart to solve given quadratic equation
Let us prepare algorithmic steps and develop equivalent flowcharts for the
following exercise.
1.
To solve a given quadratic equation ar2 + bx + c = 0 i.
e.
, to compute all possible roots.
Solution:
Given the quadratic equation:
ar?
+ bx + c = 0 if a = 0 then the single root is = - cb; 3 possible roots depending
upon the value of discriminant d are Now let's write algorithm Algorithm:
Swapping contents of 2 variables step 1:
[ Read 2 variable's contents ] step 2:
[ Assume swap variable temp & perform swapping ] let temp + sum sum diff diff temp
step 3:
[ Print the 2 variable's contents i.
e.
, swapped values ] Print sum, diff step 4:
[ End of procedure ] Exit # 1:
Real and Equal Roots:
rootl = root2 = -b 2a if d = 0 if d > 0 Flow Chart:
# 2:
Real and Distinct Roots:
root1 = -b + ſa 2a -b + ſa root2 = 2a # 3:
Imaginary and Complex Conjugate roots:
-b + ſa root1 = 2a START Read 2 variables sum, diff if d O PRO MI Exchange
contents of sum and diff variables using temp vari able as place holder of swapping
temp sum sum diff -b + ſa diff temp root2 = 2a Print swapped variable sum.
diff where in dis absolute value of d.
and d = b2 - 4ac STOP

119 Sem BCA Computer Concepts & Prog ( KUD ) Algorithms and Flowcharts 125 ► Now
let's draw flowchart for solving quadratic equation Flowchart:
To compute all possible roots of given quadratic equation START READ А, В, С Step
1 in algorithm NO IS 07 YES Step 2 in algorithm Step 3 in algorithm db 4ac TOOL с b
0 < O Step 4 in algorithm IS d?
Print root > 0 Let's write now algorithm to compute these roots Algorithm:
To compute all possible roots of given quadratic equation Step 1:
Read the values of coefficients a, b and c ] Read a, b, c Step 2:
Is a = 0 and b, c = 0 compute single root|
If a = 0 then root - e / b:
print root; exit; Step 3:
Compute the value of discriminant d ] let de bob - 4 ac Step 4:
Compute 3 possible roots of quadratic equation ] if ( d = 0 ) then print " Roots
are Real and Equal ":
let root root2 = -b / ( 2a ); print rootl, root2 stop else if ( d > 0 then print "
Roots are Real and Distinct ":
let root ( b + d ( 2 * a ); root2 ( -0 - VD ( 2 * a ):
print rootl, root2 Stop else ( ie .
.
d < 0 ) print " Roots are Imaginary and Complex Conjugate "|
let XI -b / ( 2 * a ); Y labs ( d ) / ( 2 * a ); print " root = ".
XI, " + 1 ".
Yl; print " oo2 ", XI.
" - i ", YI:
Stop Print roots real & Equal " Print roots ral & Distinct " Exit Print " roots
Imaginary & Complex Conjugate " Compute b rool 2a Compute root -b + Compute rool -b
( 2.
a ) abs root2 ( 2.
a ) r02 - 2a root2 - Jä Print root, root2 Print root, root2 Printrext = " xl ".
+1 " yl Print " ro " xl.
" - 1 " yl STOP Step 5 ir algorithm 85 Fished:
End of Procedure > Factorial of a given integer Write an algorithm to find the
factorial of a given in number.
Draw a flow chart.
Factorial of a given number N given by 1 x x x N! = 1 x 2 x 3 x --------- XN

121 1 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 122 For example:
5! = 1 x 2 X 3 X 4 X 5 = 120 4! = 1 x 2 X 3 X 4 = 24 Algorithm:
To find the factorial of a given integer number Step 1:
[ Read the given integer number ] Read N Step 2:
[ Initialize factorial to 1 ] let fact +1 Step 3:
Calculate the factorial by successive multiplications ) Repeat For i = 1, 2, 3, -
- - - N let fact fact xi Step 4:
[ Print the factorial of given integer number N ] Write " Factorial value = ",
fact.
Step 5:
[ End of procedure ) Stop Solved Problems on Algorithms & Flowcharts:
Write an algorithm to accept temperature in Fahrenheit and convert it in to
Celcius.
Draw a flow chart.
Consider centigrade temperature is stored in a memory location centmp and
Fahrenheit temperature in fahntmp.
The formula for temperature conversion is F = 1.
8C + 32 but fahntmp is input and centmp is to be computed.
F - 32 ( Fahntmp - 32 ) .
.
C = 1.
8 or centmp = 1.
8 The algorithm is written as follows Algorithm:
Temperature conversion from Fahrenheit degree to centigrada Step 1:
[ Read the temperature in Fahrenheit ] Read Fahntmp Step 2:
Compute centigrade temperature ) ( Fahntmp - 32 ) let centmp 1.
8 Step 3:
[ Print the centigrade temperature ] write " temperature in centigrade = ", centmp
Step 4:
( end of operation ] Exit.
Flow Chart:
Temperature conversion from Fahrenheit degree to ceno grade.
Flow Chart:
To find the factorial of a given integer number N.
START START Read N Read N fact 1 fact 1 for i = 1.
2, 3.
.
.
.
.
N OR next 1 START 11 NOTES MIDUAL CAMER fact fact xi fact fact xi READ Fahntmp
Iirit1 next i False Is i > N Fahrenheit degree to centigrade deg de temperature
conversion is made here using the formula C = ( F - 32 ) / 1.
8 centmp ( Fahntmp - 32 ) 1.
8 Print fact TRUE PIK Factorial, fact / HC - 6 WRITE Centmp STOP STOP STOP
flowchart ( 1 ) flowchart ( ii )

/ " Sem.
BCA Computer Concepts & C Prog.
( RUD ) Algorithms and Flowcharts 124 Write an algorithm to find the area &
circumference of a circle given radius.
Draw a flow chart.
Geometric Formula to compute the area of a circle is = str?
Geometric Formula to compute the circumference is = 2tr it is defined PIE = 3.
142 riven data:
Radius of circle ' R ' is to be read ( input ) Area of circle is denoted by ' AREA
' Circumference of circle is denoted by ' CIRCUM AREA = 3.
142 x R XR CIRCUM = 2 x 3.
142 x R Using the above two formula, the algorithm can be written as below:
Algorithm:
To calculate area & circumference of a circle Step 1:
[ Read the value of radius R of a circle ] Read R.
Step 2:
[ Calculate the area of Circle ] let AREA + 3.
142 x R XR Step 3:
[ Calculate the circumference of circle ] CIRCUM + 2 x 3.
142 x R Step 4:
[ Print the area of & circumference of circle ] Print ' Area of Circle = ', AREA,:
" CIRCUMFERENCE = " .
CIRCUM Step 5:
[ End of procedure ] Stop Write an algorithm to find whether a given number is odd
even.
Draw a flowChart.
Consider a memory location ' NUMBER ' where the number to be tested is stored.
An integer division is made to find the remainder also thus REMAINDERENUMBER MOD2
( MOD is the remainder operator ) gives the remainder.
If remainder is equal to zero then the number is even else odd.
Algorithm:
To find whether the given number is even or odd Step 1:
[ Read the number to be tested ) Read NUMBER Step 2:
[ Compute the remainder using remainder operator ] REMAINDER + NUMBER MOD 2 Step
3:
[ Test and print the number for odd or even IF Remainder = 0 Print " the given
number is Even "; else print " the given number is ODD ".
Step 4:
[ Finished ] Exit.
Flow Chart:
To find whether the given number is even or odd.
START Flow Chart:
To calculate area & circumference of a circle.
START READ NUMBER READ REMAINDER NUMBER MOD2 Here the remainder is calculated
using a mod operator also called Remainder operator AREA 3.
142 x RxR Area of Circle is calculated here using the formula A = Ter?
IS REMAINDER = 0?
YES Print " the given number is EVEN " CIRCUM - 23.
142 R Circumference of Circle is calculated using the formula C = 2tr NO
Circumference --Circum Print given number is ODD STOP STOP

124 125 Sem.


BCA Computer Concepts & C Prog.
( KUD ) odd or Algorithms and Howcharts 126 Flow Chart:
To Print sum of odd and even numbers between 1 and 100 to be er also erator ) is
even START SUMEVENO SUMODDO For example:
REMAINDER = NUMBER mod 2 let Number = 8 REMAINDER 8 mod 2 REMAINDER +0.
the given number 8 is EVEN let Number = 5 REMAINDER 5 mod 2 REMAINDER 1.
the given number 5 is ODD Write an algorithm to find the sum of odd and even
numbers between 1 and 100.
Draw a flowchart let SUMEVEN memory location holds sum of even numbers.
between 1 and 100 i.
e.
, SUMEVEN = 2 + 4 + 6 + ------ + 100 let SUMODD memory location stores the sum of
odd numbers.
between 1 and 100 i.
e.
, SUMODD = 1 + 3 + 5 + ------- + 99 As we know the range of number ( i.
e.
, 1 to 100 ) there is no need of Read statement / Step in the algorithm.
for i = 2 to 100 step 2 1 SUMEVENE SUMEVEN + Text х for j - 1 to 100 step 2
SUMODDE SUMODD + Write SUMODD, SUMEVEN STOP Dext i X ed by led a Algorithm:
To print sum of odd and even numbers between 1 and 100 Step 1:
[ Initialize the memory locations or variables ] let SUMEVEN +0 let SUMODD 0 Step
2:
[ Compute the sum of odd & even numbers separately ) Repeat for i = 02 to 100 in
steps of 2 let SUMEVEN + SUMEVEN + i Repeat for j = 1 to 100 in steps of 2 let
SUMODD + SUMODD + j Step 3:
[ Print the sum of ODD & the sum of EVEN numbers ) Write ' SUM OF ODD NUMBERS =
" .
SUMODD ' SUM OF EVEN NUMBERS = " SUMEVEN Step 4:
[ End of Operation ] Exit Write an algorithm to Print all numbers divisible by 7,
het son 1 and 100 Draw a Flowchart.
let numbers N = 1, 2, 3, ---, 100 An integer division N / 7 is made to find the
remainder i.
e.
mod operator gives the remainder R .
.
.
R = N mod 7.
If rainer R = 0 then the given number N is divisible by 7 else N is not divisible
by 7 ME

127 " ' Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts Algorithm:
To Print all numbers divisible by 7 between 1 and 100 Step 1:
Check all numbers between 1 & 100, whether divisible by 7 & Print them ) Repeat
for N = 1, 2, 3, ---, 100 REN mod 7 If ( R = 0 ) then print N Step 2:
[ Finished ) Exit 2 ) let N = 36 R 36 mod 7 ( 7 x 5 = 35 ) RE1:
N = 36 is not divisible 7:
36 will not be displayed! Write an algorithm to find the sum of digits of a given
number reducing it to a single digit.
Let us consider a number 125 stored in N.
Then sum of digits of N is S = 1 + 2 + 5 = 8 .
.
= S = 8 How to achieve this?
Flow Chart:
To print all numbers divisible by 7 between 1 and 100.
N START i ) N = 125 Make integer division to obtain integer quotient 10 for N =
1,2,3 .
.
.
100 125 = 12 10 RN mod 7 N mod 7 computes the remainder R of integer division
( N / 7 ) YES Is R = 0?
Print N:
Q = 12 Use modulus operator mod to obtain remainder .
.
R = 125 mod 10 R = 5 let S = 0 since S store the sum of digits of a number N =
125.
S = S + R = 0 + 5 = 5 ( sum of digits ) ii ) Now N = Q = 12 No ( Next N 12 N 10
PRO 1 MI = = 1 10 STOP .
.
Q = For example:
RN mod 7 1 ) Let N = 28 R28 mod 7 REO:
N = 28 is divisible 7 .
.
print N i.
e.
, 28 Now R = N mod 10 = 12 mod 10 = 2 .
.
R = 2 :
:
S = S + R = 5 + 2 = 7 - S = 7 ( sum of digits )

128 129 ' Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 130 1 iii ) Now N = Q = 1 N 10 = 0 Flow Chart:
To find the sum of digits of given number N.
START 10.
:
Q = 0 layed:
amber Read N SEO { To start with sum of digits S is equal to zero initially.
8 Now R = N mod 10 = 1 mod 10 = 1 R = 1 :
:
S = S + R = 7+ 1 = 8 :
:
S = 8 ( sum of digits ) iv ) Now N = Q = 0 As number N becomes zero.
Therefore sum of digits of given number N = 125, reduces to single digits i.
e.
S = 8 is the answer.
In other words this process must be repeated until the given number becomes zero!
at N 10 REN mod 10 Integer Division Quotient in Q.
Reduce number by one digit.
[ Separated digit in the remainder R [ Intermediate sum of digits in S.
N is assigned new number Q.
i.
e.
, reduced number will be the next number to be divided.
SES + R NO 25 No Is N - 0?
Yes Prints [ S - final sum of digits of a given numer when n reduces to 0.
S is printed STOP Algorithm:
To compute the sum of digits of a given number N.
Step 1:
[ Read the number ) Read N Step 2:
[ Initialize sum of digits S to zero ) let SEO Step 3:
[ Calculate the sum of digits of the number N ] DO WHILE ( N 0 ) Q = N / 10 REN
mod 10 let SES + R let NEO Step 4:
[ Print S - the sum of digits of the given number ] Print " sum of digits =:
S Step 5:
[ Finished ] Exit.
Write an algorithm to test whether the given number is prillic of not.
Draw the flowchart.
Given number N is a prime number if it is not divisible by any number between 2 to
For example let N = 9 9 is odd number, but it is not a prime number.
Since it is divisible by a number between 2 to integer division )

131 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 132 Flow Chart:
.
.
9 is divisible by a number between 2 to 9 4 in other words 3 = 3 START Read N For
example let N = 13 it is a prime number since it is not 13 divisible by any number
between 2 to 2 ( i.
e.
, 2 to 6 ) As usual to check the divisibility of number N, modules operator mod is
used; if R = 0 the number N is divisible else not divisible.
L 니 Interval L is taken half of the magni tude of the number N.
2 to N / 2 interval is sufficient to check the N is divisible or not for checking
it's prime property for i 2 to L REN modi Algorithm:
To test whether the given number is prime or not Step 1:
[ Read the number ] Read N Step 2:
Test the number for prime property ] Yes Is R = 0?
No Print N.
" is NOT A PRIME Text Repeat for i = 2, 3, -- .
.
N 2 Print ' N is Prime STOP REN mod i if ( R = 0 ) Print the number is not a prime
number ' stop ( the operation ) Step 3:
[ Print the number specifying its prime property ] Print the given number is prime
number ', N.
Step 4:
( Finished ) Exit Write an algorithm to compute compound interest for the given
principal amount, rate of interest and the number of years Draw a Flowchart.
Let P - Principal amount R- Rate of interest n - number of years Then compound
interest C is given by the formula 1 +

32 133 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 134 Algorithm:
To calculate the compound interest C Step 1 [ Read the values of p, r, n ] Read P,
R.
n Step 2:
Calculate compound interest i се e Step 3:
[ Print the value of C ] Write " Compound interest = ", C Step 4:
[ Finished ] Exit.
Flow Chart:
START Read P, T, Many of the ideas were adopted from the language BCPL.
Therefore to distinguish his C language from BCPL, Mr.
Thompson called it as B language, the first letter of BCPL.
This B language was written by Ken Thompson in 1970 • The B language was modified
to a greater extent such that the second letter of BCPL, C was chosen to represent
this modified version.
Thus new language the C language was developed in the same Bell laboratory of AT &
T, USA in 1972, by a system programmer Dennis Ritchie.
The language development and implementation belongs to the period late 1960's and
early 1970's.
• C was originally designed for and tested successfully on the UNIX operating
system on the DEC's PDP - 11 mini computer by Dennis Ritchie only.
C was originally written as a programming language to be worked in UNIX operating
system environment.
Later the UNIX operating system ( a system software ) itself was rewritten almost
completely in C language.
• In addition to this, the C compiler, many of the UNIX based application programs
are written in C language.
C is powerful, general - purpose structured programming language and a popular
programming language used on the present day computers.
> The historical orientations of the BCPL and B language are typeless languages i.
e.
, BCPL & B does not support various data types.
Where as C supports a variety of data types like integer numbers, floating point
numbers, characters etc.
> C is a structured language that can be used for General purpose w programming >
C programs written for one computer can be run on another computer ( with different
machine architecture ) with little or o modifications.
i.
e.
, C is famous for its portability > In C Programming, problems can be thought of as
collection of sub - problems or functions or modules.
Taxonomy of C C is considered a High level programming language as program written
in C can run on many different computer hardware platforms ( i.
e.
, machine independent ).
PRINT " COMPOUNDY INTEREST = C STOP 2.
4 Overview of C -An Introduction The history of C language starts with the language
BCPL, devel oped by Martin Richards in 1967.
BCPL stands for Basic Combined Programming Language.
At the beginning Ken Thompson, a system engineer while working at AT & T Bell
laboratories USA, wrote an earlier version of C language for the first UNIX
operating system on the DEC PDP - 7 computer system.

135 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 136 C language is derived from ALGOL, BCPL and B
with an addition of C data nypes Taxonomy of C suggest the classification as how C
downstreams from various other languages.
This is shown in figure below.
C ++ style of comments ( I / line comments ).
Extensions to int integer data ) type • Boolean data type ( bool ) · Imaginary and
complex data types ( floar imaginary, floar complex ) 1 Type ition in for statement
• Extensions to char ( character data ) type to support non english characters.
ALGOL PASCAL ALGOL - 68 BCPL 2.
5 Importance of C:
Why C?
MODULA - 2 ALGOL - W MODULA - 3 In the world of computers - it is said that " C
man is He man ".
C has come a long way from being an obscure laboratories language to the language
of choice of professional programmers, software develop ment professionals for
almost all kinds of programming needs in the areas of Artificial Intelligence,
Ubiquitous Computing ( i.
e.
, programming tiny electronic gadgets such as cell phones ), Embedded Systems,
Operating systems and computer hardware & networking, 3D Gaming softwares and so
on.
1972 Traditional C Dennis Ritchie C 1989 ANSE C ISO - ANSI C 89 -- Sundard for C
ISO C95 ISO The increasing popularity of C language is due to its accomodative
nature or adaptability both at system level and applications development level.
Therefore, it's referred to, more precisely, as Middle led language, rather than
restricting it to only as High level language.
a In particular, the salient features of C can be short listed as:
• C supports variety of data types and powerful operators.
• C has rich set of built - in functions.
• C combines capabilities of Assembly language with high lezi language features C
is much faster than BASIC programming language • C has only 32 keywords / Reserved
words • C is highly portable and well suited for structured programming • Modular
structure of C programs ( function modules ) make program debugging, testing and
maintenance quite easier.
Fig.
A Historical development of language - The following list suggests the changes or
modifications made to C language the standard C99 i.
e .
.
Updated C language features as on 1999 include

137 I " Sem.


BCA Computer Concepts & C Prog:
.
.
.
.
.
.
.
! C program to add and subtract two numbers say 45 and 5 3 ) #include < stdio.
h > void main ( ).
C has ability to extend itself with library functions and provi sions for adding
user - defined functions to C library.
.
C supports pointer data types and operations on pointers.
.
C is case sensitive.
For ex.
:
double is different from DOUBLE.
With such a set of interesting features C gains its importance in terms of:
• Fast and efficient C programs ( structured programs ) • A robust programming
language to write programs for any complex problems.
• Suitable to develop both system softwares ( such as compilers & os ) and
application softwares ( such as payroll, inventory con trol, cash - billing &
transaction processing business package development ).
int nl = 45, n2 = 5, sum, diff; / * Declarations * / sum = nl + n2; / * Addition /
diff = nl - n2; 1 printf ( " Sum = $ d In Difference = % d ", sum, diff ); 2.
6 Sample C Programs To meet the curiosity of C beginners, let's write few sample
programs in C well before exploring the intricacy of C formally! + C program to
display a message 3 main ( ) This program when executed will display:
Sum = 50 Difference = 40 / * C PROGRAM TO DISPLAY PALINDROME STRINGS * / / * A
PALINDROME STRINGS READS SAME FROM EITHER SIDE, #include < stdio.
h > main ( ) { clrscr ( ); / * built - in library function / printf ( " Sample
palindorme strings are:
\ n "; printf ( " MADAM \ n " ); printf ( " GADAG \ n " ); printf ( " MALAYALAM \
n " ); printf ( " SARAS \ n " ); getch ( ); / * library function to read a char ) /
* end of the program main ( ) * / printf ( " Keep your city clean & Green " ); This
program when executed will display a message:
Keep your city clean & green +2 ) main ( ) printf ( " Hi! Good Morning My Dear
" ); printf ( " \ n Do not use mobile phone in Class Rooms " ); printf ( " \ n
Kindly switch it off .
.
.
.
.
.
.
! " ); Sample output of this program would be Sample palindorme strings are:
MADAM GADAG MALAYALAM SARAS This program when executed will display a message:

139 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 140 > Common features observed from these sample
C programs would suggest the format of simple C programs as follows main Function
name Opening brace indicates start of program Body of the program comprises one or
more C statements > Closing brace indicates end of the program 2.
7 Basic Structure of C program While writing a program code one has to follow a
standard format or simply a layour for program statements as to, how they appear in
order and acceptable to the system for further translation This is what we refer to
it as the structure of a program.
We shall discuss structure of a C program with the help of a sample program in C
Let's consider the following sample C program / * C program to compute x * /
Sinelude < stdio.
h > #include < math.
h > main ( ) The structure of a C program comprises the following parts Pre
processor directives / statements ► Declaration statements ( Global ) ► main ( )
function > A pair of curly braces, } that encapsulate > Body of the program which
in turn comprise:
• Declaration statements ( Local ) Other statements / Language constructs •
Function calls ( user - defined ) • Library functions calls • Comments • User -
defined function definitions A few of them you'll find in the sample C program as
shown above A pre processor directives / statements These statements begin with #
symbol and appear at the beginning of a C program.
These statements serve the purpose of including header files and symbolic
constants in a C program.
By doing it so, the C preprocessor, fetches and expands the contents of built - in
library functions, macros etc.
, which are pre defined in C compiler and are used to perform common tasks that
readily assist and speed up programming in C.
For example in the C program written above #include < mch .
.
.
> is a preprocessor directive and this statement directs the prerrours C to
include the expanded contents of math library head files.
To compute x ", we have used a library function powsza ), the built - in
definition as how to compute x " is found as a suite function pow ( ) in math.
h header file.
Similarly, you'll find the definitions of built - in functions ciegos printf ( );
scanf ( ); getch ( ); etc.
, in a standard input - output header file called < stdio.
h > which is also included as # incli de stdio.
h > int x, n, Y; / Declaration statement for 3 inte ger variables / clrscr ( ); 1.
library function to clear the screen / printf ( " Enter integer values for x and n
here:
" ); scanf ( " did ", ex, en ); y = powix, n ); / * pow ( ) Built - in library
function to compute x ' .
/ printf ( " \ n y = 3d \ n ", y ); getch ( ); 1.
library function to accept a char acter input / 1 * end of main ( ) / Please note
that preprocessor statements in C programs shor be terminated by a semicolon.
Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 142 main function Every C program is a
collection of one or more user - defined functions, built - in library functions
out of which a function defini tion by name main ( ) is essential! Because
execution of a C program has to begin from main ( ).
The C compiler and Loader systems are instructed ( designed ) to do so .
.
.
.
!! In otherwords, a C program without main function definition is incomplete and
cannot be executed !!! Please note that main ( ) is written in lower case letters
and should not be followed by a semicolon.
The function main ( ) is intended to begin a C program definition and make calls
to other user - defined functions that follows main ( ).
Built - in library functions can appear both in main ( ) as well as in other user
defined functions.
Observe that function name main ( ) is always followed by a pair of parentheses
and may contain command line parameters / variables which is optional! 1.
To conclude, a C program when it begins for execution, operating system of your
computer always passes control to the main ( ) function.
Curly braces { } As C program is a collection of functions and functions are small
sub - programs written to do specific tasks.
Therefore every function code must appear separately in a pair of braces.
This allows program to be modular and divides program logic to appear in distinct
program code blocks.
Thus making programs more structured ones.
Therefore C language is termed as a structured language.
A collection of program statements can also be included in a pair of braces to
form a compound statement.
However such compound statements must be part main ( ) or other user - defined
functions.
-To conclude, { a left brace indicates the beginning of main ( ) and a right brace
concludes as end of main function.
Body of the program That is, contents of a C program as it appears between pair of
curly braces { and is referred to as body of the program main ( ) It will contain
one or more local declaration statements.
For example int x, n, y; in the C program shown above, declares 3 variables x, n
and y to be of type in integers ) datatype.
It is essential to declare variables at the beginning before any execut able
statement appears in a C program Body of the C program also comprises other
statements such as printf ( ), scanf ( ), function calls powvx.
n ) in assignment statements such as y = pow ( x, n );, independent function calls
such as clrscr ( ); getch ( ); ( as you can record your observations by referring
to the sample C program ) Comments:
You can observe comment lines appearing at all places of C program.
Comments are descriptive and explain the program logic and tasks for which
commands / statements written so.
Comments are optional! They serve the purpose of program documentation A comment
line begins with two adjacent characters / * and ends with characters * / Any
characters can be included in comment lines and comments can extend over multiple
lines.
Comments are not executable statements! Comments are in two formats.
1.
Block comments:
extend over multiple lines between an opening token / * and closing token * /
symbols > For ex:
/ * Invoke is prime ( x ) function in main program to print prime numbers between
1 and 100 * / 2.
Line comments Follow C ++ style comments i.
e.
, comme .
.
.
starts with // two successively pressed slashes and closing token is not necessary
> For ex:
// declare variables a, b and sum // Invoke function is prime ( x ) here |
|

143 " Sem.


BCA Computer Concepts & C Prog.
( RD ) Algorithms and Flowcharts 14 ►:
semicolon as statement terminator Each and every statement in a C program will be
incomplete, if it is not terminated by a; the semicolon.
It's a statement terminator as well as statement separator.
Therefore a statement in C is terminated with a semicolon.
Accordingly, there can be more than one statement on the same line as long as each
one of them is terminated with a semicolon.
For instance in the sample C program int x, n, y / is a declaration statement /
scanf ( " % d % d ", ex, en ); y = pow ( x, n ):
getch ( ):
are all valid statements irrespective of whether they are function calls,
declarations etc.
Other examples include:
i ) if ( age > = 18 ) voter_count = ( voter_count + 1 ); ii ) while ( int_rate <
0.
5 ) balance = ( credit_a_interest ); iii ) scanf ( " d ", ex ):
y = 2 * x * x +5; printf ( " y = & d ", y ); iv ) float a, b, c = 0; ® A statement
that does not endup with a semicolon is treated as erroneous line of code and
compiler signals it as an error message " missing semicolon ".
User - defined function definitions accordance with user's or application's
requirements, they are termed User defined functions.
► They may follow or precede the definition of main ( ) function ► They can be
invoked for execution from within main ( ).
Also an user - defined function can have valid identifier name followed by pair of
parentheses.
Statements block in curly braces follows the function name A user - defined
function can be invoked from within another user defined function.
To conclude, discussion on structure of a C program can be summarised into its
general format as shown below:
/ * Comment lines ( optional ) * / # preprocessor statements Declaration
statements ( Global ) Functions Prototype declarations; main ( ) Declaration
statements ( Local ); C - Statements; function calls; ( optional ) } / * User
defined function definitions * u_d_funl ( ) { Declaration statements; C -
statements; function calls; ( optional ) EDMI NOTE 6 PRO I u_d_fun2 ( ) A C
program can be written to do various data processing activities.
For each such specified activity different groups of data may have to be
processed.
Also distinct and unique operations may have to be carried out.
In such a case, addition to main ) function ( which is essential ofcourse ), one
has to write a number of other functions to carry out such specified tasks.
As user or programmer is writing those functions ( tiny sub programs ) in Ol Fig.
A The structure of a C program

145 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 2.
8 Programming Style 146 Er it could be a better practice to write as follows C is a
free form language that is, C program statements can be typed and appear from any
column number on a row ( line ).
Every C statements, braces, keywords etc.
, need not be typed from the 1st column:
int a, b, C; itself, on that line.
scanf ( " % d ", & a, Gb, & c ); Where as this flexibility does not apply while
writing programs in FORTRAN and COBOL languages!.
sum = a + b + c;:
avg = sum / 3; Thus, the freedom of typing flexibility offered by C language
compiler - should be better adopted to write a readable C source code with proper
indentation of braces ( { and } symbols ) and statements wherever necessary.
printf ( " sumed average = td \ n ", sum, avg ); Consider a tiny C program:
main ( ) A good alignment of braces and indentation of statements encour age
modular or block - structured approach to program modules.
This would further help assist in understanding program logic and flow control of
instructions in large C programs.
Consequently, program debugging will also be easier.
1 char = name; For instance:
<|
printf ( " your name please:
" ); 1.
scanf ( " % s ", name ); Recom mended Practice while writing C programs Rather
writing C program statements as ( X )|
printf ( " % s Hi! Welcome to c ", name ); ) int a, b, c, scanf ( " % d8d8d ", &
a, & b, & c ); it could be written continuously in a line or two as follows:
sum - a + b + c; avg - sum / 3; printf ( " sum - ed average = % d \ n ", sum,
avg ); ( X ) main ( ) ( char * name; printf ( " your name please:
" ); scanf ( " % s ", name ); printf ( " % s Hi! Welcome to C ", name ) NOTE 6 PRO
O MI OR V Please note that there is no readability and looks like you're taking
down / writing down the notes.
This kind of writing style is a poor programming practice and difficult to
understand program instruc tion flow.
Also, program debugging is a tedious task in case of lengthy programs 6 ) & int a,
b, c; scanf ( " % d9d % d ", & a, b, c ); sum wa + b + cavg = sum / 3; printf ( "
sum = sd average - % d \ n ", sum, avg );

147 / " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 148 if ( b > big ); big = b; A if ( b > big )
big = b; ✓ Recommended Programming Style / Practices • Write each statement on a
separate / new line Observe that C statements are terminated by a Semicolon; ) •
Comments must be used to increase the readability of program • Write / practice
writing of program statements in lower case letters only! since, uppercase letters
are used to write symbolic constants only • Braces alignment must group program
statements together to reflect program logic as compound statement or a module.
• Also, the braces should mark the beginning and end of C functions including main
• While nesting braces in a complex program logic - braces should not overlap and
number of opening braces ( ) should match ( equal to ) number of closing braces ( }
) Do's.
.
and Don'ts main ( ) main ( ) { Wrong In C every statement is terminated by a
semicolon :
) But it should not be understood as every line or row to be marked ( appended )
with semicolon :
) ( X ) while ( count! = 0 ); Right while ( count! = 0 ) { -count printf ( " % d ",
count ); wrong count; printf ( " % d ", count ); { ( 3 ) ( 2 ) ( 1 )! 2.
9 Executing a C Program We shall discuss execution of a C program on DOS and UNIX
operating system platforms separately.
As we know that a program written in C must be entered in a computer system using
an oditor program and it must be compiled for getting executable code binary O's
and 1's.
For which C compiler program is used > In particular, executing a C program
comprises the following step 1.
Creating / writing a source program using C language 2.
Compiling the program ( Translation ) 3.
Linking the program with C library 4.
Executing the object program.
We shall discuss these steps with Turbo C IDE compiler environ ment on MS - DOS /
windows OS platform.
Entering, Compiling and Executing a C program on De platform The Turbo C Compiler
Turbo C Compiler provides a powerful environment called Do not practice this way of
Alignment This kind of alignment of braces is recomm ended for clarity and ease of
understanding the program logic

149 I Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 150 Now you will be placed into Turbo C's IDE
screen as shown in figure below:
C:
\ > cd TC ( i.
e.
, Press Enter key ) C:
\ TC > TC Main Menu sia Edit Run Compile Project Options Debug Break / Watch -Edit
Line 1 Col 1 Insert Indent Tab Fill Unindent C:
NONAME.
C Editor Window Turbo C Version 2.
0 Copyright ( c ) 1987.
1988 by Borland International, Inc.
integrated development environment ( IDE ) or simply IDE screen for creating,
developing and executing C programs.
The IDE of Turbo C is menu - driven and user - friendly.
It allows the user / programmer to write new C programs, edit them, store them
compile and execute C programs using different dialogue boxes Almost all
operations, concerning editing compiling and executing C programs ( on IDE screen
of Turbo C ) can be performed by using single keystroke or easy - to - use on -
line menus ( Pull - down menus ).
> Turbo C Compiler displays diagnostic error messages in case errors ( syntax
errors ) are detected during compilation.
Once the errors are noticed, they have to be corrected ( called debugging ) and
the C program must be compiled once again.
This process of debugging ( correcting errors ) and re - compilation of a C
program must be repeated until the program becomes error free.
However during the course of C program development and execution, first one has to
write the source code C program ) by creating or opening a source code file ( a
file with.
C extension for example NONAME.
C ).
Then the C program hence written must be com piled, linked and finally run if
there are no errors.
The original C program is called source program or source code.
The compiled or translated version of C program that contain machine code ( binary
code ) is termed as object program or object code ( a file with.
obj extension ).
► It is by executing object program and entering necessary data during its
execution, one can expect useful end results what is known as Output Invoking Turbo
C Compiler At this stage, it is assumed that, Turbo C Compiler Version 2.
0 is already installed in TC sub - directory of root - directory C:
\ ( i.
e.
, in hard disk drive C :
) in your PCs.
Now let us invoke Turbo C Compiler as follows:
Step1:
go to the TC sub - directory from C:
\ Step2:
type te and press Enter keyo Message + Message box → status bar F1 - Help F5 -
Zoom 76 - Switch 97 - Trace F9 - Step F9 - Make F10 - Menu As seen from the figure
above, the IDE screen consist of four parts:
Main menu ( top line ) Editor window Message box Status bar ( bottom line ) Main
Menu Main menu consist of a number of items or options that are required for the
program development and execution.
These options inturn give rise to pull - down sub - menus for further selection of
sub - items or actions.
The main menu can be activated by pressing PRO O MI

ISI " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 152 box Thus a programmer can distinctly
visualise his program's compilation errors in message box along with the displayed
in Editor Window Status bar program function key F10 and move cursor to a
particular options like File, Compile, Run, by pressing or cursor movement arrow
keys.
Thus main menu items or options are summarised as below:
Main Menu Item Uses File permits for opening new source code file, select and load
files, save file, invoke DOS shell, quit Turbo C and return to DOS Edit allows
entering / writing a C program, to perform various editing functions like line
delete, line insert, character delete, character insert etc.
, Compile translate the current source program into machine code equivalent object
program ( obj file ) compile, link, and execute the C program cur rently available
on the IDE screen.
Project handle multiple file projects Options To set various options for compiler,
linker and IDE, directories Debug To set various debugger options Break / watch To
add / delete watch, toggle break point, to view next break point.
Editor Window You can observe the status bar at the bottom of the screen as a last
line.
It display the status of the current activity on the screen A Now, we shall
consider entering of a sample C program.
You can observe from the above IDE screen that there is a window showing Turbo C
Compiler version, copyright etc.
First we shall erase it by pressing ESC key or Enter key Entering a Sample C
program When you're in the IDE screen of Turbo C, activate main menu by pressing
F10 key.
Then select file option by pressing cursor movement keys or → Now press Enter key
on the file option to see the IDE - screen with the pull - down menu of File option
as shown in figure below Run wie Edit Run Compile Project Options Debug Edit
Break / Watch Col 1 Insert Indent Tab Fill Unindent C:
NONAME.
C It provides us a place to write the source code, to make changes to different
lines of code by inserting / deleting characters and or by inserting / deleting
lines of code.
To start with, source code file in Edit window is temporarily named as NONAME.
C.
This file name can be changed while saving the C program.
Message box ( or Watch window ) You can observe the message box watch window just
below the Editor window.
The various error messages pertaining to compila tion and linking are displayed in
the space provided for message Load F3 Pick Alt F3 New Save E2 Write to Directory
Change Dir OS Shell Quit Alt - X PRO DUAL CAME Message F1 - Help F5 - Zoom F6 -
Switch 77 - Teace F - Stop -

153 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Since you want to enter a new C program, you can move the cursor to choose
new option Pressing Enter key on new option, takes you to the Editor window and
permits you type - in your C program under source code file name NONAME.
C.
Later you can change this file name by choosing Save option or by pressing
function key F2.
> An alternative approach to program entering / feeding is to first give the file
name for the source code file in which you want to enter and store the program.
Then you start entering the program from within the editor window ► Accordingly,
press Enter key when cursor is on Load option or simply press F3 key.
Now you will have the following changes on the file option of IDE screen as shown
in figure below Algorithms and Flowcharts 154 ► Now type - in your C program in
Editor window which also displays your program source code file name as SUMAVG.
C at the top right corner of the Editor window.
This is shown in figure below:
Fa Edit Run Compile Project Options Debug Break / Watch -Edit Line 16 Col 15
Insert Indent Tab Fill Unindent C:
SUMAVG.
C / * C PROGRAM TO READ 3 INTEGERS & TO PRINT SUM AND AVERAGE / #include < stdio.
h > main ( ) { int nl, n2, n3; / * three integer number variables declared / float
sum, average; / * variables to hold sum & av erage declared / clrscr; printf ( "
PLEASE ENTER HERE 3 INTEGERS:
\ n " ); scanf ( " % d8d8d ", & n1, 6n2, & n3 ); sum - n1 + n2 + n3; printf ( "
SUM OF 3 INTEGERS IS = $ f \ n \ n ", sum ); average -sum / 3; printf ( " AVERAGE
OF THREE NUMBERS IS = $ f \ n \ n ", ' av erage ); printf ( " \ n \ n PROGRAM
EXECUTION IS OVER .
.
.
Goodbye .
.
.
\ n " ); getch ( ); pe Edit Run Compile Project Options Debug Break / Watch Edit
Load F3 Col 1 Insert Indent Tab Fill Unindent C:
NONAME.
C Load File Name SUMAVG.
C Write to Directory Change Dir OS Shell Quit Alt - X F1 - Help 5 - Zoom F6 -
Switch F7 - Trace FB - Step 29 - Make F10 - Menu Message Fl - Help F5 - Zoom F6 -
Switch F7 - Trace F - Step F9 - Make F10 - Menu We have entered here a new file
name as SUMAVG.
C - A C program that computes sum and average of three floating - point numbers )
as shown in the figure above.
Now press Enter key to go Please note that, every time when you type - in new C
program choose a source code file name such that it should not be the same of any
previously stored program files.
Otherwise Load option displays the previously stored C program and save option
asks for overwriting Compiling and executing sample C program We shall now select
compile option in the main menu of IDE screen in order to compile the source code
file SUMAVG.
C As Editor window

155 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowchats usual activate the main menu by pressing function
key F10 and move the cursor to compile option.
Press Enter Key to see the following pull - down menu on IDE screen.
File Edit Run CO Project Options Debug Break / Watch ► Now press Enter key on
Compile to OBJ option to initiate the compilation process as shown in figure below
File Edit Pun compile Project Options Debug Breakrat Line 16 col 15 Insert Indent
Tab P111 Unindent C:
SUMAVO, / * c program to Read 3 integers 5 to print sum average #include < stdio.
h > main ( ) Edit Line 16 Col Compile to CBJ C:
SUMAVG.
OBJ C:
SUMAVG.
C / * C PROGRAM TO READ Make EXE file C:
SUMAVG.
EXE GE / #include < stdio.
h > Link EXE file main Build all Primary file:
declared declared int ni, n2, 3; Get info declared / float sum, average age
declared clrscr; printf ( " PLEASE ENTER HERE 3 INTEGERS:
\ n " ); scanf ( " dedid ", enl, 62, 63 ); sumn1 + 2 + 3; printf ( " SUM OF 3
INTEGERS IS 8- \ n \ n ", sum ); average sum / 3; printf ( " AVERAGE OF THREE
NUMBERS is - sf \ n \ n ", average ); printf ( " \ n \ n PROGRAM EXECUTION IS
OVER .
.
.
Goodbye .
.
.
\ n " ); getch ( ); Compiling int ni, n2,3 Main file:
SUMAVG.
C float sum, av Compiling:
Editor SUMAVG.
C clrscr ( ); printf ( " Plea Total Pile Lines compiled:
231 231 scanf ( eded Warning:
0 0 sum - nl + 2 + Errors:
0 0 printf ( " SUM Availability memory:
269k average = sum / Success • Press anykey \ n " ); printf ( " AVER ); printf ( "
\ n \ n \ n " ); getch ( ); Watch Watch Fl - Help 15 - Zoom P6 - Switch 77 - Trace
78 - Step F9 - Make F10 - ele During compilation, if syntax or linker errors are
found, they would be displayed in the Watch box or Message Window at 2 end of
compilation process > If there are no errors or warnings, you can choose Run Option
am press Enter key twice.
There by you can observe the following interaction for data entry for the program
file SUMAVG.
C a thus the program is executed, successfully, to display the following output as
SUM and AVERAGE of three numbers:
helps - Zoom PE - Switch n - Trace 78 - step 19 - Make F10 - Menu

157 1 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharis 158 PLEASE ENTER HERE 3 INTEGERS:
10 12 10 SUM OF 3 INTEGERS IS = 32,000000 AVERAGE OF THREE NUMBERS IS = 10.
666667 PROGRAM EXECUTION IS OVER .
.
.
Goodbye .
.
.
Once after detecting these errors, Compiler gives a detailed listing of diagnostic
error message in terms of its location as line number, the missing syntactic entity
as; or reserved word etc.
, in a message box or watch window Now press Enter key to go to Editor window that
holds program being compiled.
Edit the program to eliminate the errors ( or bugs ) and then compile the program
again to see that no errors are detected further! < > Linker Errors:
There are every chances of getting linker errors during linking the object file
say SUMAVG.
obj with library function files or header files ( like stdio.
h or math.
h ) and thus to create a third file called SUMAVG.
EXE an executable file.
Linker errors are noticed when you have included say < stdio.
h >, < math.
h > < string.
h > etc.
, subject to their requirement but sometimes such headers files and library
function files are missing or corrupted in INCLUDE and / or LIB sub - directory of
C:
\ TC.
In all these situations program compilation will be completed without any errors
but compiled program will fail to link with library functions or header files
leading to Linker errors.
Thus executable.
EXE file may not be created !!! Run - time Errors:
As the name itself indicate Run - time errors are noticed during program execution
or running an executable pro > You can also run the program directly by pressing
arl key and F9 function key simultaneously.
Sometime you may not see any output on the screen.
You will see the screen flicker for a moment and you'll be placed once again in
the IDE screen with your program in Editor window.
> With Turbo C, usually the output is written to what is known as user screen.
In order to see the user screen and the output ( results ) - press Alt key and F5
function key simultaneously ► Please note that, at this point you are outside the
IDE.
To Return to IDE, press F5 key or simply Enter key.
Types of Errors It is quite natural that we can commit mistakes either while
writing a program or entering a program ( during typing ) that leads to various
errors like syntax errors, linker errors, Run - time errors or logical errors.
But all such errors are detected by the compiler or linker or by the operating
system itself.
Syntax Errors ( Compiler Errors ):
All syntax errors ( grammatical errors ) like missing semicolon, misspelling a
keyword, or typing a colon instead of comma or period etc.
, will be detected by the compiler mpilation.
Syntax errors will be noticed as a result of violating syntax rules of the
programming language.
As syntax errors are detected during compilation by the compiler, these errors can
also be referred to as Compiler Errors or simply Compilation Errors or Compile -
time errors.
gram file.
* Sometime you may observe wrong results or incomplete output due to logical
errors in your program.
Ofcourse, sometime your program can have abnormal termination during execution due
to run - time errors like null pointer assign ment, division by zero, passing
improper arguments to function etc.
> Thus the Run - time errors and logical errors together are referred to as
Semantic Errors.
Improper behaviour or Abnormal execution of a program ensures that it contains
Semantic errors i.
e.
, such program may contain either logical errors or run - time errors or both >
Logical errors in an executable program exists because of miss interpretation of
the program logic and / or incorrect translation of MI

Algorithms and Flowcharts 16 159 p " Sem.


BCA Computer Concepts & C Prog.
( KUD ) program Flowchart or Algorithm.
These errors are difficult to locate and correct To overcome these errors, the
programmer needs to re - write the program fully or partially by modifying the
program logic or by appropriate analysis and correct translation of the Algorithm
or Flowchart into a C program.
Entering, Compiling and Executing C programs on UNIX OS platform Naming Source
code file in UNIX File system environment The C program to be typed, stored and
compiled must exist in a File for which one should give a file name.
On UNIX environment, file names with uppercase and lower case letters are
different and can contain alphabets, numbers underscores and even the period.
).
The file name can start with any one of these characters.
The length of the filename ( ie.
, number of characters ) depends upon the UNIX OS implementation on your local
computer system.
For instance UNIX system V indentifies filenames to a maximum of 14 character
length ► The following list shows valid filenames for your C program under UNIX
environment:
:
fact.
c machine.
pt.
c _gear_ptr.
c 6_by_9.
c Btool.
c power_factor.
c sumavg.
c test.
c _large.
c survey_at_2.
c 404c.
c sound.
c A Ofcourse, last two characters of a C source program file ( i.
e.
, extension ) must be .
c.
Entering a C program into a file under UNIX To enter a C program into a file ( say
lathe.
c ), a text editor system program is usually required.
Most of the UNIX installations ( For example SCO UNIX OR BSD UNIX V OS
installations ) make use of two popular text editors.
They are ed ( line editor ) Vi ( screen editor ) ( just like DOS prompt C:
\ > ) as either % or $ as it appears 51 % with blinking cursor as shown here.
> Invoke either ed or vi editor with appropriate file name in order to type in a C
program.
This is shown below Bed lathe.
ca or svi lathe.
Compiling a C program under UNIX The command for program compilation under UNIX is
cc.
You can initiate the source program compilation as follows tcc lathe.
cd or $ ce lathe.
The ce command ofcourse includes many options such as compile and produce
executable output, Compile and produce semi - compiled code only, produce the
executable files under user - specified names etc.
The one shown above is a simple and direct cc command format.
The successful compilation with this command creates a file similar to DOS
environment Turbo C's.
obj file ( object code file ).
But this file will have an extension o instead of obj > In other words, the above
command execution creates a lathe.
object code file, lathe.
O is also called semi - compiled file.
However, compilation process automatically links lathe.
O file to form what is known as the executable object code file under the
defaul'ile name a.
out ( It is equivalent to lathe.
exe in Turbo C of DOC ens.
com ment ) Thus if there are no errors during compilation and thing, the compiler
creates the actual output file a out for executa Executing a C program under UNIX
After successful compilation of a C program file ( say latih program execution is
invoked by typing simply a out front of UNIX shell prompt % or $.
This is shown below:
% a.
out or $ a.
out ( indicate pressing lineer ► The a.
out execution loads the linked object code into cruters main memory and initiates
execution.
It may ask for da necessary and produces the corresponding results After logging
into your UNIX system terminal ( i.
e.
, by entering login identity word and password ) you will have the UNIX prompt
161 1 " Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms anul Flowcharts 162 To summarise, for each and every source
program file, when compiled successfully, the actual output file called a.
out is created under UNIX.
Thus one can execute the C program if and only if its corresponding executable
object code file a out exists.
+ C Character Set Like alphabet of English language, C has its own, rich character
set.
It consists of basic symbols of the language used to construct the lexical
elements ( called Tokens ) of C.
Members of C character set can be grouped into the following categories:
> Alphabets:
a, b, c, d .
.
.
.
.
.
.
.
x, y, z → Lower case letters A, B, C, D, .
.
.
.
, X, Y, Z:
Upper case letters > Digits 0.
1, 2, 3, 4, 5, 6, 7, 8, 9,:
+ All decimal digits > Special Symbols:
- "! @ # % ^ & * O - + = { } [:
; ":
< > .
.
?
/ + Special characters ► C also supports wide variety of character combinations
Viz arithmetic assignment operators, conditional operator (?
:
), incre ment ( ++ ) and decrement ( --- ) operators, Escape character sequence for
print format control, Trigraph characters for printing certain characters.
Address operators and indirection operator for pointer operations and so on .
.
The required character combinations are drawn from this special symbols set of C.
2.
10 C tokens Every language has Grammar called its Syntax.
Accordingly, the primitive elements of the language belonging to proper syntactic
classes are termed as tokens.
You will find the following categories of tokens in a given C program:
Keywords of the language C ( Also called Reserved words ) > Identifiers ( Also
termed as Variable names ) > Constants ( Also known as Literals ) Strings Operators
> Other Special symbols ( used as delimiters ) C TOKENS Special characters /
symbols ( including Arithmetic, Modulus, Bitwise, Relational & Logical operators )
with their meanings:
Plus comma Minus ( Hypen ) Period ( Dot ) Asterisk Semicolon Slash ( Forward ):
Colon Percent sign Single quote ( Apostrophe ) & Ampersand Double quote Tilde|
Pipe line character Caret! Exclamation Mark Less than sign?
Question Mark Greater than sign Underscore character Backslash Hash character
( number sign ) Left parenthesis = Equal sign Right parenthesis White spaces:
Blank space Right Brace Horizontal Tab Left Bracket Carriage return Right Bracket
- New line CONSTANTS 15.
26 257 IDENTIFIERS STRINGS -Shoot - at " closing balance OPERATORS REDMI NOTE - 6
PRO MI balance Left Brace KEYWORDS SPECIAL SYMBOLS char if 1.
1.
Form feed Fig.
A Tokens Glance

163 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 164 165 assigned meaning of the language syntax
and not to store values in it.
For examples the word int is reserved word because in C language it refiers to a
data type int.
It is used to declare variable to be of type in that refer to integer constants
only.
Therefore int is reserved by and for the language C to carry a specific meaning.
C compiler shows error -message if there would be an attempt to declare and use
reserved words of Cas variable names in a C program.
The following list specify the possible reserved words of C language.
auto double int break else long switch Keywords register typedef char extern
return union const float short unsigned continue for signed void default goto
sizeof volatile do if while struct case ** One or more of the alphanumeric
character combinations including special symbols, from C character set are used to
form valid C tokens.
These tokens are also known as Lexical elements of C language.
Appropriate combinations of one or more C tokens give rise to language constructs.
You will find various language con structs that are going to form a wide variety
of C programs in accordance with programmer's requirements.
For instance function ( definition / declaration ) header in C, a preprocessor
directive state ment, a declaration statement for variables used in a C program,
goto statement, if .
.
.
.
statement, Assignment statement likewise one can list out various language
constructs or building blocks used in a C program An example:
consider a declaration statement in a C program ----------------- int nl .
n2, sum E Here C tokens are int a keyword nl, n2, sum identifiers / variables →
special symbols used as delimiters * Consider an assignment statement in a C
program:
bal = amount - debit; enum in c static 2.
12 Identifiers 2.
* Here C tokens are → operators bal, amount, debit — identifiers / variables →
special symbol used as state ment terminator Identifiers in C are the names of
variables representing data, labels, function names, array names, user - defined
objects etc.
, An identifier in C consists of a sequence of letters ( upper case or lower
case ), digits and / or underscore symbols.
Also, the first character of an identifier must be a letter of alphabet or it can
be an underscore character too.
** There should not be any other special characters or operators in an Indentifier
except underscore symbol! Also keywords of C cannot be used as identifiers !!
Usually, the first eight characters of an identifier are guaranteed to be
significant i.
e.
, distinctly identified, although one can make use of more than eight characters to
form an identifier.
However, this is implementation dependent ( on C compiler being used at your local
installations! ) Examples of valid identifiers in C sumup2 at a rate story of 1942
tick20 check balance Q123 qity_02 PRO MI 2.
11 C Keywords Keywords or Reserved words of the language are the words whose
meaning is already defined and xplained to the C language Compiler.
Therefore reserved words cannot be used as identifiers or variable names.
They should only be used to carry the pre - defined or pre ping mesgool

165 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 166 Examples of Invalid identifiers in C:
1stnum + point rate in s flash @ min bal Rs break continue Identifiers in care
case sensitive.
Also same identifier once declared as say variable name or label cannot be used as
say function name or arrayname in a single program.
One can use identifiers of any convenient length to assign meaning ful names for
the data being used as in array names, function names, structure names and variable
names.
However number of significant characters to be recognised in an Identifier varies
from C compiler to C compiler.
( Only first 31 characters are significant ).
> C variable / identifier should not contain a blank space ( white space )! > To
conclude identifiers are variable names in C.
2.
13 Constants > Numeric constants are simply numbers, a collection of one or more
decimal digits > Non - numeric constants comprises both numerals and letters of
alphabet including special symbols.
* You'll find two distinct types in each of these categories:
+ Integer Constants Integer constants in C represent whole numbers without any
fractional part.
An integer constant is simply an integer number consisting of one or more digits
of decimal number system.
Integers as input data, there should not be any special symbols or any in between
blank spaces, commas.
At the most negative ( minus ) sign, - can precede the number to indicate that
given number is a Negative integer.
When minus sign doesn't precede the number, the integer is assumed to be a
positive one! That is prefixing a plus sign + is optional E Examples of valid
integer constants include:
1942, 144, -26, +791, 999, 0, 202, 7, 42 *** Examples of Invalid integer constants
include:
0.
0, -15 ° C, 1,25,968, 10 B 48, 23,666, 0.
0003 ( k - blank space ) Integer constants in C further classified In C, one can
use 3 types of integer constants:
viz Decimal Numbers:
Any combination of one or more digits from 0, 1, 2, 5, 6, 7, 8, 9 Octal Numbers:
Any sequence of one or more digits from 0, 1, 2, 3, 6, 7 An octal constant must
start with O It must be written without decimal point It can be a positive or
negative octal number with signs or Example for octal numbers 027, -0126, +052 A
constant can be defined as " a value or quantity which does not change during the
execution of a program ".
Constants are also termed as Literals.
In short, the meaning and value of a constant remain constant! ( doesn't change ).
In C, constants can be classified as follows:
Constants in C PRO O MLÕUAL CAMERA Numeric Constants Non - Numeric Constants
( Character cosntans ) Single Integer Floating - Point Constants ( real constants )
Constants String Cosntants Character Constants

167 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Hexa decimal Numbers:
Any combination of one or more digits from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C,
D, E, F A hexadecimal constant must start with Ox or OX It can be either positive
or negative hex number with signs + or - Example for hexadecimal numbers:
OxIAF Ox480 Ox23E • Floating - Point Constants Floating - Point constants are real
numbers! That is it may contain a fraction with decimal point embedded.
A floating point constant can be written in two forms:
1.
Decimal or Fractional Form:
E Examples:
1.
5 -0.
562 123.
0 27000.
0 95.
742 A floating - point number in fractional form should contain atleast one digit
to the right of the decimal point.
A + ve or -ve sign may precede it.
If a sign doesn't precede then the number is assumed to be positive.
2.
Exponent Form:
** Examples:
0.
481E12 + 1.
56E - 02 -23.
8E - 26 -61.
2 e9 174E08 0.
00052 e - 09 62e + 07 A floating - point number in exponent form has two parts:
mantissa and exponent.
The mantissa must contain atleast one digit and it can have a + ve or -ve sign.
Mantissa is followed by the letter e or E and the exponent ( i.
e.
, the numeric value to the power 10 ) Algorithms and Howcharts VdWp na iw The
exponent value must be an integer without any decimal point! a Mantissa can be upto
7 digits and the exponent may range from -38 to +38.
However actual number of permitted digits in both mantissa and exponent varies
from com puter to computer since it is implementation dependent! + Single Character
Constants A character constant in C represent a single character enclosed within a
pair of single quotes e Examples:
' u ', ' s ', ' $ ', ' # ', ' b ', ( -representing blank space ) ' 2 ', ' 0 ', '?
', '! ', ► Although decimal digits can be enclosed in a pair of single quotes,
they represent non numeric character constants only! Character constants are used
to give symbolic representation to data output, to represent some coding characters
such as Quality code, currency value etc.
, $ 300 0.
5 % Rs.
75 / - likewise.
String Constants A string constant in C denote a sequence of one or more
characters enclosed within a pair of double quotes, * Examples:
" Hi! Hello ”, “ 1942story ", " a ", " 5 ", “ Busy bec " " + point ", " y2k
problem ", " 12th December " Pralaya 2012 ", " What a surprise! ", " 007 ", " x 8
", " Divine Truth .
.
.
! " Character constants and string constants in C represent non numeric character
data used in string manipulation applications such as symbolic manipulations,
Natural language processing ( NLP ), etc.

169 " Sem BCA Computer Concepts & C Prog.


( KUD ) Algorithms and Flowcharts VdWivna iw od 93ION IWOS Memory Unit, where
numerical values or characters can be stored.
A variable is represented by a symbolic name.
Thus variable name refers to the location of memory in which a particular data can
be stored Variable name are also known as identifiers since they identify the
varying quantities and stores them in a particular memory location.
** For example consider the equation sum = nl 12; here nl ' and n2 are the
identifiers or variable names representing two separate quantities in two distinct
memory locations.
Similarly sum is also a variable name which holds the sum of nl and n2 quantities
after addition For example if 10 is stored in a memory location represented by nl
and 15 in n2.
Now sum = nl + n2; after execution stores the sum 25 in a memory location sum.
This is viewed pictorially as given in the figure below MEMORY Backslash Character
Constants A backslash character constant represent an escape character sequence
consisting of two characters symbol followed by a character as shown in the table
below a prefixing back slash A backslash ( 1 ) symbol when combined with certain
other charac ters give rise to special print effects, when used in format control
string of printf ( ) functions for output.
For example, when backslash followed by character nie.
, " \ n " causes subsequent printing ( displaying of cursor ) to begin on a new
line or nextline This combination of backslash with a character is known as escape
character or escape sequence.
The following table summarises various escape characters that can be used in
printf ( ) functions.
Backslash Purpose:
to issue constants Bell or beep ( For prompting or alert ) Backspace Horizontal
tab Vertical tab Newline ( line feed ) Form feed \ r Carriage return ( CR ) Double
quote 1 Single quote ( apostrophe ) \?
Question mark 10 Null character Backslash character itself 1000 Octal number ( one
to three digit ) ba .
nl 10 \ b 15 \ t Variable names Pointing to Separate memory locations that hold the
varying quantities / constants location 1 location 2 location 3 location 4 sum 25
Tv If and so on.
11 Rules and Guidelines for Naming Variables A variable name or an identifier in C
must consist of a single letter or sequence of characters, digits, or underscore
( - ) characters.
The first character of a variable name must be a letter of the alphabet or an
underscore character.
The variable name i 8 characters length aximum.
But some computer systems permit the length the variable name to be more than 8
characters.
However only the first 8 characters are significant in some Compilers.
Under such cases, if we use two variable names deposits / and deposits2 both of
them will be treated 2.
14 Variables called a variable ".
Each variable has specific memory location in " A value or quantity which may vary
during program execution is

171 Sem.
BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 172 2.
15 Declaration of Variables as same or single variable name since, the first eight
characters are same.
Therefore compiler may produce errors or computer may given wrong results In C.
upper case and lower case alphabets are recognized as separate symbols.
Therefore the variable names product, Product, & PRODUCT are treated as 3 separate
variable names.
- A variable name should not contain any other special symbols like blanks, comma,
question mark etc.
A variable name should not be a reserved word or keyword of the C language.
For example C language reserved words like if, switch, case, continue, break, long
etc.
cannot be used as variable names One can construct useful and meaningful variable
name by refer ring to the above rules Examples of VALID ( correct ) variable names
total income loss Sum of avg_temp interest rate _point marks1 test2 year_95 P123
Each variable used in a C program must be declared.
Such declarations are necessary to indicate to the C compiler, the type of
variable used and specific number of memory locations required ( size ) to hold the
different constants or values.
In other words the variable name can store constants in its memory location,
belonging to any four data types int, float, double, char.
For example if we want to use variable names marks and marks to store an integer
constants say marks 65 and 80; now we must declare that marks1 and marks2 variable
are of data type in meaning that the variables marks and marks2 hence declared,
always hold only integer values ( number without fractions ) throughout programs
execution.
This declaration is given as follows:
int marksi, marks2;.
The above specified declaration is known as Type Declaration ( Data type )
statement.
Therefore any variable to be used in the program must be declared with type
declaration statement before using it in any other C statements.
Usually the type declaration statement appears at the beginning of the C program.
* The general syntax for declaring a variables can be given as:
datatype variable - list Here datatype is a valid fundamental datatypes in C with
type modifiers if any ( like long int, unsigned char, short int etc.
, ) where as variable - list contain one or more variable names separated by comma
• Examples of INVALID ( incorrect ) variable names ( X ) 1942 story Ps - in how?
34d - cs level 2.
16 Data Types C language supports four basic ( fundmental or primary or built - in
types of constants called data types, VIZ int, float, double, char > int data type:
An integer constant or simply an integer number in C language, consist of sequence
of one or more digits of decimal PRO MI

Algorithms and Flowcharts 174 - For example:


ch Pe d e float int_rate; - computer Concepts & C Prog.
( KUD ) number system.
There should not be special symbols or any in between blanks, commas.
At best a- ( minus ) sign can precede the number to indicate it as a negative
integer.
If minus sign is not present, then the integer is considered to be positive.
Integer being a whole number, does not have either a decimal point or a fractional
number part Examples of valid integer numbers 00.
1975, -10, 123, 15000, 78, 45 Examples of Invalid integer number.
0.
0, 25.
0, 1.
1, 0.
123, 15,000, 10 b 40 ( b - blank space ) Therefore a variable that hold the integer
constant is declared to be of type int.
For example:
int nl, n2; int_rate is a variable name declared to be of data type float.
Hence it can store or refer to interest rates that are specified usually as
floating point constants viz 0.
05, 0.
08, 0.
21, 1.
2 etc.
Here float is a keyword to denote float datatypes.
double data type:
double data type is similar to float type.
It is used whenever accuracy required to represent the number is more.
In other words variable declared to be of type double can hold the floating point
numbers only but the number of significant digits stored is roughly twice or double
than that of a float variable.
Usually if a float variable can store 7 decimal digits, then a variable declared
to be of type double has an accuracy of 16 decimal digits.
Thus a floating point number with large fractions or very small floating point
number with least fractions can be represented accurately by a variable of type
double.
For example:
double air_pr, light yr; ni and n2 are two variables declared to be of data type
int hence they can store / refer only integer values.
Here int is a keyword to denote integer datatype.
> float data type:
A floating point number or simply a real number in C language consist of sequence
of one or more digits of decimal number system along with embedded decimal point
and fractional part if any.
There should not be any comma, or blanks, in between the digits except the
embedded decimal point.
It is permissible to omit either digits before decimal point or digits after
decimal point.
Thus floating point number consists both integer part and fraction part, embedded
with decimal point, also known as floating point.
A minus ( - ) sign can precede the floating point number to represent it as
negative floating point number.
Examples of valid floating point numbers.
Here double is a keyword to denote double data type.
> char data type:
In C a character constant is formed by enclosing the character within a pair of
single quotes ( ) For example ' a ', ' p ', '.
' etc.
Therefore a variable that can store the character constants or simply characters
is declared to be of type char.
A variable declared to be of type char can be used to store a single character.
Thus for example if characters ' r ' and ' $ are to be stored in the variable Si
and S2 respectively, Then the declaration is char S1, S2; 4.
, 0.
333, -0.
58, 0.
00012, 123.
56 * Therefore a variable that can store the floating point constants or frosional
RaideM is NeclaFe PRO of type float.
MIL - DUAL - CAMERA Note that Si & S2 are variables of type character which store

175 " Sem RCA Computer Concepts & C Prog ( KUD ) Algorithms and Flowcharts
Examples of Variable declaration in length, height, area; float ratio, int_rate,
balance; char code alty_sign p_indicator; double sum, grand total, avg_rate; char
name [ 20 ], ch, option; int p, q, r, bal; float total [ 20 ), min bal, percent;
char color_code [ 10 ], answer; floar p = 3.
142, r, a; int count = 0; char ch - ' Q ':
single character information at a time.
Here char is a keyword in C to denote char data type A character constant is
always represented within a pair of single quotes where as a string constant is
enclosed within a pair of double quotes and string constant can contain one or more
than one characters a character constant string constant " abed " string constant "
Wishes on 12th morning " string constant To summarise, in general > int type is for
an integer constant to be stored; int occupies 2 bytes of memory typically ► floar
type is for floating point numbers to be stored and occupies 4 bytes of memory
floar type can hold numbers with six decimal digits of precision Please note that
floating - point numbers are used to represent values, which require a decimal
point precision for fractions associated with it ► double type is for floating
point numbers to be stored in exponent and mantissa form.
double type occupies 8 bytes of memory and it can hold floating point numbers with
ten decimal digits of precision for a character constant to be stored one character
at a time occupying 1 byte of memory ** There exists void data type specifying
empty set of values or simply no datatype in return! However the size in bytes of
storage and range of data values to be represented by these data types greatly vary
with each processor type and with every newer implementation of the C compiler A
Thus while declaring variables one can initialise them in the declaration statement
itself.
* → Datatype Modifiers The storage size in bytes and range of values being
represented by basic datatypes can be modified with the help of following modifiers
as prefixes:
+ signed → unsigned + long + short Signed data type modifier can be applied to
integer variables although the default integer declaration assumes a signed integer
number When signed modifier is prefixed to char data type, small integers in the
range -128 to +127.
unsigned data type modifier can be applied to both int and chard type variables.
However char datatype is unsigned by default and holds integer values in the range
0 to 255.
char type can hold

176 177 " Sem.


BCA Computer Concepts & C Prog.
( KUD ) Algorithms and Flowcharts 1 An unsigned int datatype can hold now the
integer values in the 178 range 0 to 65,535 Data types Storage Size In bytes 1
Range of Data values being Represented Where as signed int datatype can store the
signed integer numbers in the range -32,768 to + 32,767.
This is same for in type also.
In case of signed integers, the high order bit ( also called Most Significant Bit
( MSB ) is treated as sign flag.
Accordingly, if this bit is zero ( 0 ), the integer constant is treated as
positive and negative if this most significant bit is set to one ( 1 ).
> long datatype modifier can be applied to both integer and double Prefixed with
modifiers char float double 4 8 2 2 type variables.
2 1 1 -128 to + 127 -3.
4e + 48 to + 3.
4e + 48 -1.
7e + 308 to + 1.
7e + 308 -32,768 to + 32,767 -32,768 to +32,767 -32,768 to +32, 767 0 to 255 -128
to 127 0 to 65,535 0 to 65,535 -32,768 to +32,767 -2,147,483,647 to +2,147,483,647
-2,147,483,647 to +2,147,483,647 0 to 4,294,967,295 -3.
4e - 4932 to + 1.
le +4932 int signed int short int unsigned char signed char unsigned int unsigned
short int signed short int long int signed long int unsigned long int long double 2
2 n the 2 4 4 4 ed by wing 16 A Table:
ANSI standard based Datatype Modifiers When applied to integer, a long int storage
size becomes 4 bytes long initially it is 2 bytes ) and it can represent integer
values in the range -2,147,483,647 10 +2,147, 483, 647.
* When applied to double type, a long double storage size becomes 16 bytes
( initially it is 8 bytes ) and it can represent floating point values in the range
-3.
4e -4932 to + 1.
le + 4932.
A long integer can be declared as long int or simply long.
) short data type modifier can be applied to integer type variables.
A short qualifier generally changes the size of an int to its half.
But most of the implementations of C compiler fixes the storage size of short int
exactly same as int i.
e.
, 2 bytes only! * Therefore signed int, short int and int declaration types are all
same occupying 2 bytes and representing integer values in the range - 32,768 to
+32.
767.
A short integer can be declared as short int or simply short The datatype
modifiers are also termed as qualifiers.
The following table depict different prefix combinations of data type modifiers
for four fundamental datatypes except for void type.
The table also reveals us the number of bytes of memory being occupied and various
range of values being represented by these datatypes when coupled with different
modifiers.
ables Ceger To summarise datatypes in C It is to be noted that ANSI C supports 3
classes of data types 1.
Primary or Fundamental datatypes ( Built - in ) - int integers ( white numbers ) -
char characters - float real numbers ( numbers with fractions ) - double ( double -
precision real numbers ) - void ( indicate no value; used to specify function
return value ) REDMI NO hold data and

( KUD ) Algorithm and Flowcharts 2.


Derived data types Once defined, symbolic constant's value can be used at me
places in a program.
Arrays Functions Pointers 3.
User - defined datatypes Structures Unions Enumerations We have discussed four
fundamental datatypes:
int, char, float and double.
Other datatypes we shall discuss in later chapters.
DATA TYPES E For instance we know that pi = 3.
1415927 • Also, area of a circle and circumference of a circle can be given by area
= pi r .
:
circum = 2 * pi * r;.
Here the variable pi can be defined to be a symbolic constant to denote numeric
value 3.
1415927 i.
e.
, # define pi 3.
1415927 • Now, every occurrence of symbolic constant pi in the formulae as shown
above and in the C program as well, would substitute automatically the numerical
value 3.
1415927 i.
e.
, area = 3.
1415927 * r * r; circum = 2 * 3.
1415927 r In general names of symbolic constants in C programs are formed using
capital letters only.
This is to distinguish them from variable names as they appear in lower case
letters only E For instance Detived types User - defined types Fundamental
( Primary ) types integer character.
floating point double values Arrays - structures Functions Unions Pointers
Enumerations Fig.
A Datatypes @ Glance # define # define # define COLOR CODE MINBALANCE SPEEDKMPH
220 500 67.
5 2.
17 Defining Symbolic Constants C allows defining an identifier name or variable
name as having constant value, using a preprocessor directive #define.
Such preprocessor statements are not part of a C program and are placed at the
beginning of a program.
Usually the symbol # occurs in the first column and semicolon is not required to
mark the end of this statement.
• A symbolic constant defined using # define can represent a numeric constant or
character / string constant.
2.
18 Assigning Values to Variables:
The Assignment Staterer In C the symbol = is used as an assignment operator and an
equal sign! Assignment operators are used to assign the result expression ( which
will appear on the right hand side of = ) to a variable name ( which will have to
appear on the left hand side of = ).
Her equal symbol = must be treated as " is to be replaced by rather tha equals to
"

181 " Sem.

( KUD ) Algorithms and Flowcharts 182 For instance marks = 17:


here the assignment operator = assigns or stores the integer number 17 in the
storage location named by the variable name marks which appears at its left.
Similarly, y = a * x * x + b * x + c here the assignment operator = assigns the
result of an expression a * x * x + b * x + c after its being evaluated, to a left
hand side variable name y.
Likewise we have a wide variety of arithmetic assignment operators viz + =, - =, *
=, 1 =, % =, We shall discuss the functionalities of these operators under the
heading of shorthand assignment operators, and assignment expres sions.
right handside of assignment operator = is evaluated and the resulting value say
integer number or float constant will be assigned and / or stored in a named memory
location represented by a left hand side variable name > In C variable names,
function names, array names, constants, function calls, array references, structure
references, variables coupled with operators and mathematical equations ) are all
treated as expressions.
Also, an expression enclosed within a pair of parenthesis is also an expression.
> An expression that may be assigned a value is termed as an Ivalue.
Therefore the expression on the left - hand side of an assignment operator =, must
always be an / value or simply a single variable name Therefore the following
statements are invalid assignment state ments:
x + y = x - y; basic pay.
+ hra gross pay balance + 120 int rate principal ( a * a -b ) /2.
6 = d * d - C * C:
125 = reg_no:
Assignment Expressions and Shorthand Assignment Operators C has special shorthand
assignment operators that simplifies reprc sentation of certain type of assignment
statements.
For instance sum - of_digits of number = sum_of_digits_of_number + digit; Such
assignmerft statements are much more lengthy and tedious to write.
This is due to a very long but meaningful variable name tha appears on both sides
of assignment operator.
This statement could be rewritten as an assignment expression sum of digits of
number + = digit; ► Where in the symbol + = is a shorthand assignment operator
Simple Assignment Statement An assignment statement in C has the following form
variable name = expression We know that every statement in C program will be
completed with a semicolon at the end.
For instance REDMENOTE 6 PR MI bonus_pay = ( basic pay * 12 ) / 100; test_avg = (
tlm + t2m + t3m ) / 3; d = b * b - 4 * a * c; y = num [ 8 ]; ini_rate = 5.
25; big = largest ( a, b, c ); are all examples of valid assignment statements When
an assignment statement is executed, the expression on the

I " Sem.

( KUD ) Algorithms and Flowcharts 184 Please note that variable name that appears
on both sides of an assignment operator is now Written only once on the left
handside of + = a shorthand assignment operator.
In general, the assignment expression of the form:
variable name operator = expression; Where operator can be any one of +.
*, / % and when combined with =, assignment operator as its suffix.
will be treated as variable name = variable_name operator expression; like any
other assignment statements.
Accordingly, operator combinations appearing in such assignment expressions are
termed as shorthand assignment operators.
The possible combinations of shorthand assignment operators that could appear in
an assignment expression are and can be interpreted as 1 1 add Subtract Multiply
Divide Find remainder & & & & & assign assign assign assign assign 1 > You can
observe that, when operators + =:
--:
* = = % = are used in an assignment expression, the right hand side ( part of the
expression that appears after such shorthand assignment operators ) is assumed to
be enclosed in a pair of parenthesis > Generally such shorthand assignment operator
notations are incorpo rated in professionally written C programs code.
Such assignment expressions are also known as self - referential expressions.
> To conclude an assignment expression consists of a shorthand assignment operator
short hand assignment operators are + = - =, * =.
/ =, % when we use them in an assignment expression, the right handside of the
operator is assumed to appear in a pair of parenthesis > Benefits of using
shorthand assignment operators include assignment expressions are concise and easy
to code considerable saving over length of source code.
The variable name to be used as an input operand in the expression and for
assignment on the left handside, need not be typed and / or written on the right
hand side of short hand assignment operator.
Multiple Assignment Statements C permits you to assign a single value to more than
one varuble name at a time and in a single statement.
This can be achoved using multiple assignment.
For instance x = y = z = 0.
0; > Here, variable z will be assigned first with a float value ull And now value
of z will be assigned to y; At the end, xill be assigned the value of y.
In otherwords all the 3 variables x.
and z will hold now a value 0.
0.
► In case of multiple assignments, the operator = is said to right associative as
evaluation or assignments takes place f right to left For example, let's consider
the following assignment expression Their Meaning / Evaluated as sum + = heights; →
sum = sum + heights; down count - = 1; down_count = down count -1; x_topn = a; →
x_topn = x - to - pn * a; income tax; → income = income tax; profit = ( invest 4 -
loan ); → profir = profit % ( investe 4 - loan ), let's consider a second example:
P + = a - b; → P = P + ( a - b ):
ql = 1 + r:
+ 4 = g / ( 1 + r );

184 Sem.
BCA Computer Concepts & Prog.
( KUD Algorithms and Flowcharts 186 are the tors ) Therefore in the following
multiple assignment statement:
a = b = ( x + y + 2 ) / 2; 1.
evaluation of ( x + y + z ) / 2 takes place first; 2.
Then the result is assigned to variable name b; 3.
At last a will receive now, the value of b.
consider another example of multiple assignment I = m = n * = p; тро ment 1.
Thus multiple assignment statement make use of more than one assignment operator.
Statements in C AC program comprise variety of statements that can cause different
actions when executed.
In otherwords individual C statements can directly transform into one or more
executable machine instructions for computer hard ware.
( ofcourse during compilation process ).
In all, C language define 11 ( eleven ) kinds of C statements as depicted below
ment is evaluated as 1 = m = n * = p.
1 P = ( m = ( n = = * = p ) ) ( right - to - left ) n = n * p:
1 Null:
ight of mn:
Expressions 2 return X { compound st.
) the be and conditional с Statements labelled To conclude ► 1, m and n will get
here the result of evaluation of n * p.
Thus evaluation is from right - to - left.
Multiple assignments cannot be done during declaration of variable names For
instance int p = in q = ini r = 0; is not a valid assignment! Also multiple
initializations / assignments during variable declaration is invalid and leads to
syntax errors.
For instance int x = y = z = 144; signals compiler error as y and z undefined !!!
Therefore, before doing multiple assignments, all the variables must be declared
( with appropriate data type ) a priori ole wed switch Iteractive looping PRO MI
break ky Accordingly, continue be om int x, y, z; and then * = y = 2 = 144, will
assign 144 to x, y, and z goto n.
О O

187 " Sem.


BCA Computer Concepts & Prog.
( KUD Algorithms and Flowcharts 188 Null Statements in C The null statement in C
is simply a semicolon as statement terminator without any actions.
Il null statement For " do nothing " actions in some situations of programming
contexts the null statement is useful.
• Expression statement in C Any C expression when terminated with a semicolon is
known to be expression statement For instance A compound statement can contain
optimal declarations Section and statement section.
ET Pl.
note all C functions ( sub - program ) including main are framed using compound
statements.
For example do 1 Compound digit = inum % 10; rnum = rnum * 10 + digit; sum = sum +
digit; inum = inum / 10:
statement while ( inum > 0 ); expression; // general syntax of expression
statement.
Examples y = a + b * 2.
5 - 2; b = 66:
+ + countx:
Z = y return statement in C A return statement when appears in a C functions ( Sub
- program ) terminates ( halts ) the execution of that function and returns control
& corresponding values ( if any to the calling ( main ) function.
return expression:
Il general syntax For example:
return 0; 2.
19 Input and Output Statements To meet the two important characteristics of an
Algorithm:
INPUT & OUTPUT, a precise notation called high level programming language has to
provide for input - output statements.
Thus C language consists of input - output statements in the form of input
functions to read the data to be processed by a C program and as well as an output
function to an the processed data or output results.
Such I / O functions establish:
an interactive communication between the program computer and user They can set a
dialogue session in which inputs can be fed in accordance with the dialogue that
for the required data values or operantis, Similarly with output functions of c, we
can observe the processed information or answers on a display screen or we can take
a printout of the results on a paper, using a printer.
Thus this section draw reader's attention towards input / output statement's
provisions in the C langu.
C programming language syntax do not contain any explicit in de output statements
to receive / read data from an input device and to display results on an output
device.
** However, C offers for its programmers a set of library functions or standard
builtin functions *, in order to carry out input output operations.
A function can be defined to contain a group of C statements that work
collectively, when called by function name.
return x; return ( fact ); • Compound statements in C Whenever more than one C
statement is required to be executed together in a group in response to some true
condition / false condition of the evaluation of an expression and / or repetition
of hlock of code is required for defined ( given ) number of times - then such
gruping of statements is enclosed in a pair of curly braces { and forming what is
known as " compound statement " in C.
questions

( KUD ) 189 Algorithms and Flowcharts section 190 framed to perform a specified
task.
For instance Input Function - to perform input task.
In C, the library functions employed for input and output operations can broadly
be classified as Formatted I / O Functions Unformatted I / O Functions The
following figure depicts Input / output statement's provisions in Input and Output
Statements in C Formatted I / O Functions .
scanf ( ) - For input .
printf ( ) - For output Unformatted I / O Functions For Input For Output .
getch ( ) .
getche ( ) putchar ( ) .
getchar .
gets ' ( ) putch ( ) Accordingly, the individual quantities hence read through
scanſo formatted input function, can easily be identified and stored in memory as
integer, character, floating - point number etc.
Formatted Outpur Function:
the printf ( ) To display a data value or result of type int, char, floar, string,
or double, the printf ( ) library unction is used.
The formatted output function permits the use of conversion characters or format
control characters to enable the printing of data and / or computed results
belonging to a specific data type.
Such format specifications via formar specifiers or conversion specifiers in a
printf ( ) allows the user or programmer to have an explicit control over the range
and type of data being displayed • Format Specifiers Format Specifiers give rise to
conversion characters or format characters that specify what type of value ( say
for example integer, floating - point, double - precision number or character ) is
to be read or displayed, when used in Formatted I / O functions.
The conversion characters specify the format with which the given number or
character is to be printed.
Therefore these format characters or conversion characters are also called as
formar control characters or simply format specifiers.
Following table depicts a list of conversion characters used in C and their
respective use in displaying / reading a specific data type.
Conversion Used for Reading / Printing a constant Character belonging to a
specific data type % d integer numbers % f floating - point or double precision
number ( % e ) % c Character ( Single ) % s strings ( sequence of characters ) TPUT
guage ts of ta to print h an user ance nds.
ssed it of Ter's age put 1 to puts ( ) Fig.
A Formatted and unformatted I / O Functions For example scanf ( ) and printf ( )
are formatted functions used for input and output operations respectively,
Formatted Input Function:
the scanf ( ) To read a data value of type int, char, float, string or double, the
scanf ( ) library function is used.
The formatted input function supports the use of format specifiers ( also called
as formar control characters ) to enable the reading of data belonging to a
specific data type.
Such format specifications via conversion specifiers or formar specifiers in a
scanf ( ) allows the user to control the range and type of data being read.
Table A List Conversion Characters / Specifiers 728 * and of me.
e * The percent sign % is a special character recognised by functions.
The character that immediately appears after % sigh,
( KUD ) Algorithms and Flowcharts 192 2.
20 Reading a Character These functions will read any single value ( digit or
character or special symbol ) typed in, but the value is always taken to be a
character only.
There is no provision to use format control character ( conversion character ) to
identify the values read as integer, float, char etc.
This is because whatever may be the quantity or number typed in, it will be simply
treated as a character only.
Therefore the name unformated Input functions.
Only one character will be read in at a time.
Example of unformatted input functions are:
getch ( ), getche ( getchar ( ), fgetchar getch ( ); will read a single character,
the moment it is typed on the keyboard without waiting for Enter key to be pressed
point out what type of value is to be read or displayed into from the variable name
belonging to a specific data type.
For example % d specifies an integer constant ( integer number ) is to be accessed
( read / write ).
The getchar ( ) and putchar ( ) functions The getchar ( ) and putchar are
unformatted single character input and output functions respectively.
The getchar ( ) takes the following form.
variable - name = getchar ( ); >> getchar ( ) function reads and returns the
single character input i.
e.
, the key that is being pressed on Keyboard.
Here variable - name is to be declared as char - type For example:
char p_code = getchar ( ); If you type ' A ' or say ' S ', the same will be read
and stored into char variable p_code.
where as putchar takes the following form:
putchar ( variable - name ):
purchar ( ) function will display the single character at the output i.
e.
, on VDU screen.
Here variable - name must be declared to be of type char and contains a single
character.
For example:
char option = ' y ' purchar ( option ):
will now display the single character y as output.
Also, purchar ( ' \ n ' ); P_code:
For exmaple:
char p; p = getch ( ); getche ( ); Similar to the above function but echoes the
character typed into the screen.
i.
e.
, also prints the character read, on to the screen.
getchar ( ); > Both functions will read a single character typed in fgetchar ( );
and echo the character to the screen, but require an enter key to be pressed.
In addition to the above functions for reading single character.
We have gets ( ) functions in C that will read a sequence of characters ( or a
string ) at a time.
The end of input string is indicated by pressing an Enter key.
will now cause the cursor on the VDU screen to jump to the beginning of the next
new line.
This is due back slash constant In for newline display.
We shall discuss a little more about unformatted I / O functions in the following
sections:
2.
21 Writing a Character These functions will display or print any single character
va a a time.
These functions will not permit the use of format control character ( or
conversion specifiers ) therefore called as unformatted output for tions.
Whatever information that they will print, -it will only be in the form of
characters.
Examples of unformatted output functions are:
putch ( ), putcha fputchar

( KUD ) Algorithms and Flowcharts 194 putch ( ); putchar ( ); ser or тасtет ersion
his is Il be fputchar (:
Input le of tchar All these functions print the contents of a character variable
on the display screen, i.
e.
, a single character will be displayed at a time.
For example putchar ( "?
" ); will display?
on your screen Similarly, char option; putch ( option ):
will display the contents of option a char variable.
> C also provides a standard library function puts ( ) to output a string ( a
sequence characters at a time ) to the display screen.
For example in a C program, the puts ( ) function can be used as follows:
puts ( " Good Morning * ); The execution of the same will display the following on
the screen:
Good Morning ed on be acter acter format string or control string and the second
one is a list of arguments or variable names into which the values typed in, are to
be read / stored.
As scanf is a formatted function, the format string specify the format characters.
According to the format characters ( conversion characters ) the input data is
stored into the respective variables specified arguments.
It is important to note that the number of format characters & type of format
character specifying the data type in a given control / format string, must match
the number of variables and their respective data type, that are specified as
arguments in a given scanf function.
Let us consider a few examples of scanf functions:
i ) scanf ( " % d ", & first_num ); here the variable first_num is already
declared to be of data type int, in the type declaration statement int first_num;
the scany function has two parameters; format string and argument list.
Format string is always included within double quotes.
Format string in the above example consists of a single conversion character % d
and the argument list consists of only one variable name " first_num " prefixed by
an ampersand ( & ).
This and symbol is necessary whenever a single numeric value or a character is to
be read in to a simple variable.
Ampersand ( & ) symbol merely serves as an address operator specifying the address
of mem .
.
location for the variable first_num.
Observe that the number of format characters and its conversio type ( in this case
% d for integer ) matches with the number variables ( arguments ) & its data type (
in this case first_n variable is declared to be of type int ).
Thus when this scord function is executed in a C program, it stops program
execution until an integer value ( whole number ) is typed in ( Since % d spec.
integer ) and Enter key is pressed.
After typing the necessary day the execution will be continued.
The scanf scans for integer number in accordance with the format character
specified in its format string and stores it in the respecti variable name ( memory
location specified in its argument list.
in an 2.
22 Formatted Input Statement:
the scanf ( function Now we shall discuss in detail the formatted input function:
the scanf ( ) the scanf ( In a C program when the scanf formatted input function
is used, it allows the program to be halted temporarily during program execution in
order to accept ( to read the required data value.
After typing necessary data values following pressing of an ENTER key on the
keyboard, the program execution continues to compute the results.
The function name scanf stands for " scan formatted " or " scan function ".
It is just similar to input statements of any other high level programming
language.
Thus scanfo ), a standard C library functions permit the programmer to type in
operands or input data necessary for the given program execution.
* The general form of scanf ( ) is:
scanf ( " control string ", argi, arg2, .
.
.
.
.
.
.
.
.
argn ); scanf function has to contain two parameters, the first one is a we ters
by at cter inc the -0.

( KUD ) Algorithms and Flowcharts 194 ii ) Now let us consider a second example
that reads two integer numbers scanf ( " d ", & numl, & num2 ); Two integers will
be read in by the scanf function since two format characters % d & % d are
specified in the format string and the integers will be stored in the variables num
] & num2 respectively, iii ) Consider another example that reads one floating -
point number & two integer numbers scanf ( " % d ", & int_rate, & principal, &
period ); 2.
23 Formatted Output Statement:
the printf ( function The printf formatted output function is used to display the
values or results or messages at the display screen.
The function name printf stands for " print function " or " print formatted ";
print function's work is just equivalent to an output statement of any high level
programming language.
Thus printf ( ), a standard C library function when used in a c program, display
the messages and also the results stored in variables, on to the output device -the
display screen * The general form of printf ( is:
printf ( " control string ", argi, arg2, .
.
.
.
.
.
, argn ); first value read in will be a number with decimal point & fractions and
stored in the first variable of argument list i.
e.
, in int_rate, specify interest rate on bank deposits say 00.
05 ( 5 % ).
scanf reads second & third value as integers and stores them in variables
principal and period respectively.
The variables principal and period hold the amount deposited and the number of
years of deposit respectively iv ) Consider the following example, that reads 3
characters and one integer number Usually the printf function consists of two
parameters, one the format string or control string consisting of format characters
like % d, % f, % c etc.
and the second is the argument list.
The argument list consists of one or more variables whose contents have to be
displayed on to the output unit.
In addition to the format characters, the format string can also contain any
useful message, titles specifying the name & type of result; for example.
" the largest of 3 number is = ", or " simple interest = " etc.
* It is important to note that the number of format characters and their type in a
given format string must match the number of variables and their respective data
type whose contents and shar posed to be displayed.
scanf ( " % ctctcid ", & color_1, & color_2, Ecolor_3, & code ) color_1, color_2 &
color_3 variables are declared to be of type char and can hold a single character
information.
Similarly variable code is defined to be of type in that store integer number i.
e.
, char color_1, color_2, color_3; int code; ** Now consider a few examples of
printf function i ) printf ( " The result is % d ", sum ); Now say for example
color ' r ' - for red, ' y ' for yellow, ' b'- for blue and integer number 14 are
all read & stored respectively in the variables color_1, color_2, color_3 & code
respectively.
In the above example four format characters correspond to four argument list
variables that matches both in order & type.
A Here the variable name sum has been declared earlier as an int type in a type
declaration statement:
int sum:
The format string content The result is copied to the screen as it is and the
format chatavad % d tells the computer that it should display an integer m which is
the content of argument list variable the sum.
There argument list consists of one or more variables whose contents

( KUD ) Algorithms and Flowcharts 198 ( of memory locations are to be displayed


according to conversion specification characters of format string.
In fact for the printf function itself, the format string is the first argument
and list of variables is the second argument.
i printf ( " The product of td and td is 8d \ n ", ni, n2, ped ) onl, n2 & prd
variables are all declared previously of data type int.
When the above printf function is executed, the format string ( specified within
double quotes ) is examined and the contents / characters - “ The product of " are
simply copied to the screen until the occurrence of special characters i.
e.
, format characters % d.
the moment when it comes across a a format character in this example % d, it picks
up the first variable n1 from the list of variables and prints its value in the
specified format.
Similarly the word " and " is printed as it is; next % d appears for which a
second variable n2 is picked up and its content will be displayed; next the word "
is ” is displayed as it is; next % d appears for which a third variable prd is
picked up & its content will be displayed at last.
Note that all the three conversion characters are % d only therefore values
printed are all integer numbers only.
At the end when the symbol \ n is encountered, the cursor will be placed to the
beginning of next line.
rollnum.
Next the word Sex code = appears on the screen as it is; then the encountering
character % c ask the computer to print a single character information ( m - for
male, f for female ) i.
e.
, the content of character variable scode; At last the word Percentage appears
exactly on the screen, which is followed by contents of float variable percent to
be displayed on the screen corresponding to format character % f.
Observe the two special characters backslash followed by the lower case letter n.
This combination in is known as Escape character for new line.
In other words appearance of In within the format string makes the display screen
cursor to jump to the beginning of the next line Similarly we can use the escape
character combination it for tab setting.
With the appearance \ t, in the format string of printf function, the cursor jumps
over eight columns on the same line.
* If two \ n appears adjacent to each other in a single format string of printf
function, then a blank line will be introduced in the output iv ) Considerably a
different example of printf function can appear as below:
printf ( " Roll Number = % d Sex code = $ c Percentage = f \ n ", roll_num,
s_code, percent ); --Here in this example one variable is of type int i.
e .
.
.
roll_num second variable is of type char.
i.
e, s_code and the third variable is of type float i.
e.
, percent.
All three variables have been declared previously in the type declaration viz.
roll num; char s_code; float percent; - The contents of the format string as usual
is copied to the screen T.
e.
, Roll Number =; then the appearance of format character % d makes the computer to
print the integer contents of variable printf ( " Please enter 3 integer numbers \
n " ); Please note that there is only a format string and the Et of argument
variables is absent.
This printf function display ta title or message, there by it specify what the
user hould do exact Such printf function with format string only, is called A
prompti printf function or signalling output function because it merely informs the
user that what he must do?
Just a useful meseage is displayed.
Also observe that there are no format characters exceço the message in the format
string.
Please note that if the format characters are to be present the format string then
there I be a list of argument variables that correspond to those format characters
► Such prompting printf functions are normally used with function together.
An example may reveal the importance of this combination int

BCA Computer Concepts & C Prog:


( KUD ) Algorithms and Flowcharts printf ( " please type in interest rate and
amount de posited in the bank \ n " ); scanf ( " d ".
kint_rate, & deposit_amt ); > In this example first printf prompt the user by
displaying the message as it is:
there- by programmer comes to know that he should type in first interest rate and
then bank deposit amount Therefore it would be easy enough for the programmer to
feed the specific data values as per the requirement displayed by the printf
function.
► Such a combination of prompting printf function and a following scanf function
for input sets a kind of interaction or dialogue berween user and computer during
program execution, for the specific task of data input / output to that program.
Specifying the field width:
Along with conversion specifiers ( format characters ) the following optional
specifiers can be used to specify the field width of the data value to be printed
on the screen dd - digits specifying the field width of the number to be displayed
decimal point separating field width as integer part & fraction part .
.
dd - digits after decimal point indicating the precision of the floating point
number i.
e.
, the number of decimal places ( digits ) after the decimal point.
→ The first field width specifier dd inform the printf function that how many
columns positions on screen, should be used while printing a data value - Assume,
the number stored in the variable amount is not is columns long for example amount
contains a value 1110542 Now this value is printed in a right justified manner and
is filled up with blanks at its left i.
e.
, denoted by here:
Print Columns > 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 B B B B B B B B1110542 the output
appears as above since a total of 15 column positions are reserved for printing
1110542 > If fields width specifier is not used for printing floating point number,
then a standard format of 6 decimal places ( fractions after decimal point is
followed to print that number ► But with the use of field width specifier .
dd one can have the control over the precision of the floating - point number I be
displayed.
In other words we can control the number of digits of fraction to be displayed
after the decimal point.
For example price_rate contains a floating point value 1500.
9120.
Then in a printf function given as follows; printf ( " price hike rate = % 10.
17 ", price_rate ); Here the content of price rate i.
e.
, 1500.
9120 will be printed as follows:
H Suppose, printf ( " % 15d ", amount ); is the output function to display the
integer contents of the variable, amount, then in this example % 15d tells the
print that display the contents of variable amount as a decimal integer in a field
of 15 columns width:
Print Columns > 2 3 4 5 6 7 8 9 0 price hike rate = в в в 15 оо, 9 Observe that a
precision of only one decimal place ( fraction ) after decimal point is displayed
as per % 10.
1f.
10 refers to the total field width of the floating point number.
Out of which I column occupies a decimal point another column occupies a
fractional digit after decimal point & integer part can be stored in remaining 80
columns.
But as it is, integer part is only of 4 columns width therefore 4 other columns
are padded towards its left, as blank spaces.
UMI
( KUD ) 201 Algorithms and Mowcharts 202 is not 15 0542.
Now led up with If you want to display the complete number without the lose of
fraction i.
e.
1500.
9120 then format characters with field width specifier 10.
4 has to be mentioned in the printf.
In other words printf ( " price hike rate = $ 10.
48 ", price_rate ); 3 4 5 5 4 2 sitions are cing point ions ) after have the Der to
be the output be Print Columns > 1 2 3 4 5 6 7 8 9 0 price hike rate = 1 5 0 0 9 1
2 0 with left most column padded as blank, since total field width is 10 and the
given number require only 9 columns.
Therefore all number / data values will be printed in C in a Right justified
manner.
! The First C Program Let us have a look at the simple program written in C
language.
The program consists of output function printf only.
There is no calculation and no type declaration.
Ofcourse there is no need to read input values through scanf function.
Such a simple C program merely specify the structure of a C program.
The program is written as below:
digits of 00.
9120 Usually program statements of C language program are written in lower case.
Because lower case letters are the characteristics of the C language.
At the same time C compiler knows the difference between lower case & upper case
letters.
In example program:
The first program, observe that the first line main ( ) indicate a special C
function that specify the beginning of a C program.
main ( ) is recognised by the C system under which C program runs.
Therefore every new C program must have a main ( ) function, since it points out
the beginning of a C program It is from the function name main ( ) the C program
execution begins - Immediately after the function name main the symbol { appears on
the next line.
This symbol is known as left brace or opening brace.
It is quite clear that left brace should match with the right brace } which is
placed at the end of the main function as a last line of C program.
In other words these opening and closing braces enclose the body of the function
main ( ) i.
e.
, all the statements of C that form a complete C program or main ( ) function.
Thus the example program consists of four printf output functions enclosed within
left brace & right brace, forms the body of the main ( ) function or a complete C
program Observe that all the four printf functions consist of only format string
with some message or information.
There are no variables whose contents to be displayed.
Simply the printf functions outputs the contents of format strings to the display
screen in the sequential order in which printf functions are executed.
Note that C restricts the printf function to contain only one format string.
Thus for example the following printf function.
printf ( " The first C program ", " welcomes you:
\ n " ) invalid and would not be executed since it contains two format strings.
te ); Finted as main ( ) printf ( " The first c program welcomes you:
\ n " ); printf ( " Message for the day follows:
\ n " ); printf ( " THE MOST IMPORTANT THING IN LIFE IS TO WORK .
.
.
\ n " ) printf ( " HARDWORK IS A KEY TO SUCCESS • + .
.
\ n " ); en ) after tal field MI column mal digit A First C program ining 8 width
blank * C program statements are written in a free formar i.
e.
, the Statements can appear anywhere on a line.
There is no restriction like every new statement should appear always on the first
column of the line

U A more general specification for field width would be % w.


p format character / * form 1 * % w.
p format character / * form 2 * where in All print function's format string ends
with a new line character that instructs the computer to advance to the beginning
of next new line before printing the subsequent information of next print functions
In the example program, the end of print functions is indicated by a semicolon ( ),
here semicolon acts as a statement delimiter in C Therefore in C programs, all
statements end with a semicolon.
The end of the C programs is indicated by a closing brace } that matches with the
opening brace of the function main ( ).
Thus in short every C program contains the function main ( ) and C program
statements must be enclosed within the opening brace { and closing brace of the
function main ( ).
In addition to this a C program may also contain other user defined functions that
may be called from & executed, by function main ( ).
Such C programs containing other functions addition to main function will be
discussed in detail in a chapter on User - defined Functions.
- Therefore the above example program when executed displays the output as
follows:
The first program welcomes you:
Message for the day follows:
THE MOST IMPORTANT THING IN LIFE IS TO WORK .
.
.
HARDWORK IS A KEY TO SUCCESS + + + % - Percentage symbol the first character of
specification that promotes / forces conversion denoted by format control char
acter that follows.
Hence the symbol % is compulsory.
W - Number of digits ( w = 5, w = 4 etc .
.
) specifying total field width including decimal point, if it is present.
Specifying a value for w is optional P - Number of digits of precision required
after decimal point, For example you may require precision upto 3 decimal places, a
precision upto six decimal places etc.
Specifying a value for p is optional! a period symbol specifying an optional
decimal point required for representing floating point numbers.
format character - a conversion character which is compul sory and can be one of
d, f, c, e, u, o, X, S a minus sign to force left justification for output.
Specifyingi a minus sign is optional Let us observe the effect of a minus sign in
format control in of printf ( output statement.
let an integer variable called loc is declared and initialized int loc = 5140;
then printf ( " loc = 960 \ n ", loc ); will display loc = b65140 / observe
printing in rio justified manner / -and first two columns goes blanks:
BB- / - A comment may be included in a C program as an explanatory note.
Comment must start with a pair of symbols / * and end with the pair ".
Thus in the example program a comment may be included before function main ( ).
For example First C program made simple *.
During execution of the program, comments will not appear.
Since C compiler just skips the comments.
They merely serve as an explanatory note or documen tation to the C program Format
Control Characters:
Re - visited We have already discussed a few format control characters or
conversion specifiers.
However let's consider the more details

( KUD ) Algorithms and Flowcharts 206 ed nh Where as printf ( " loc = 9-6d \ n ",
loc ) wall print loc = 5140 3 * 4 « observe printing in left justified manner * / /
* effect of minus sign / / * here the last two columns goes as blanks:
- / The following table summarises a list of format control characters that can be
used in format control string of printf ( ).
conversion To perform .
.
.
.
.
separating format characters.
Otherwise scanf expects same special character to be typed in while entering from
one data value to another data value.
scanf ( ".
ded \ n ", sp, q ); / * wrong / A common mistake is to forget the ampersand symbol
- & while typing the program, that must precede each and every variable of
parameter / variable list in scanf ( ).
The & symbol is optional in case of string variable like an array of char.
One need not specify any escape characters ( For example \ n ) leave 1 blank space
in format control string of scanf ( ).
DV The address operator ( & ):
Re - visited The symbol & ampersand ) when precedes a declared variable name,
serves as an address operator.
It specifies the address of memory location associated with that variable.
When used in a scanf ( ) function, address operator conveys the path or memory
location address ( represented by the corresponding variable name ) at which the
input data value is to be stored specifier % d % u 50 % x % X % ld print signed
decimal integer number print unsigned decimal integer number print unsigned octal
number print unsigned hexadecimal number ( using a - f ) print unsigned hexadecimal
number ( using A - F ) print a long decimal integer number print a real or floating
- point decimal value print a real or floating - point decimal value in exponent
form ( for example -1.
46e - 08 ) print a single character ( For example ' k ' one at a time ) print a
character string ( For example " Point 4590 ", at a stretch ) % f For instance Же %
c scanf ( " % d % f ", & deposit, & int_rare ) > Address operator finds its use in
pointer manipulation operations For example a pointer variable can be assigned the
address of memory location to serve the purpose of indirection ( indirecco
addressing ).
% s Common mistakes not to be committed in scanf ( ) For instance For example int
* ptl, pscore; INT t marks, total; and now prl - & r_marks pscore = & total Ó REDMI
NOTE 3 PRO MI scanf ( " 8 de def ", 61,6m, & n ); / * wrong / There should not be
any blank spaces between format characters in a format control string.
Otherwise scanf expects same number of blank spaces from one data to another data
value while reading scanf ( " od, d, & p, & q ); / * wrong / There should not be
comma or semicolon etc.
, special symbols A Thus pointers can be initialised to denote corresponding memor
locations.

( KUD ) Algorithms and Mowcharts 2.


24 Programming Examples:
Simple C Programs Write a C program to read 3 integers and to print sum and
average of these 3 integer numbers.
Soln:
Let integer variables nl.
n2 and n3 represent 3 different memory locations to hold three different integer
numbers.
Let som be another variable to store sum of three integers and average stores the
average of 3 integers.
Both sum and average are declared to be type floar, since to store any fraction
resulting from division operation.
The program in C is as follows:
program ** / " Program to compute sum and average of 3 integers / Comunicate
plaining the fune ties of program cate beginning 1 Prompting primer nl function 2 )
Sample execution of the program Please type any 3 integer numbers 08 11 07 sum of 3
integers = 26.
000000 average of 3 integers - 8.
666667 Write a program in C language to accept temperature in Fahrenheit and to
convert it in to Celsius.
Soln.
Let the variable fahntmp hold the temperature in Fahrenheit, and centmp store the
temperature in centigrade.
F = 1.
8C + 32 F - 32 or C = 1.
8 Type Declaratie int ni, n2, 13; or centmp = Eloat sum, average:
print ( " Please type any 3 integer numbers in " ); fahntmp - 32 1.
8 Fond scanf ( " ididid ", enl, 6n2, n.
3 ); Input argumcu list Variables Using this formula, the C program is written as
follows / * program to convert Fahrenheit temperature into cen tigrade
Temperature / main ( ) Assim Forsed up functie For string sum - Inl + n2 = n3 );
average - sum / 3:
Output argument variable printf ( " sum of 3 integers = \ n ", sum ) printf ( "
average of 3 integers - if \ n ", average ); Format control string float fahntmp,
centmp; printf ( " Enter the value for Fahrenheit temperaturo scanf ( " 80 ", &
fahntmp ); centmp = ( fahntmp - 32 ) 1.
1.
8; printf ( " Equivalent temperature in centigrade centmp ); A Observe that all
variables must be declared before their first use 1 ) Sample execution of the
program.
Please type any 3 integer numbers 10-12 14 sum of 3 integers - 36.
000000 average of 3 integers = 12.
000000 1 ) Sample execution of the program.
Enter the value for Fahrenheit temperature 58.
0 Equivalent temperature in centigrade - 20

BCA Computer Concepts & C Prog:


( KUD ) Algorithms and Flowcharts 210 2 ) Sample execution of the program Enter
the value for Fahrenheit temperature Equivalent temperature in centigrade - -17.
777778 Sample execution of the program for Fahrenheit temperature 0.
0 enter the value 1000 1 ) Sample execution of the program:
Type in a value for radius of a circle 2.
5 area of circle - 19.
637500 perimeter of circle = 15.
710000 2 ) Sample execution of the program Type in a value for radius of a circle
1.
25 circle = 4.
909375 perimeter of circle = 7.
855000 and of given radius.
area of Equivalent temperature in centigrade = 37.
777778 2 Write a program in C to find the area and perimeter of a circle seln:
Let T ' represent radius of circle, the variable area ' hold the area of the
circle in a separate memory location & the variable ' p ' hold the circumference or
perimeter of circle.
All variable r, p and area are declared to be of type float since geometric values
may be floating - point constants.
Area of circle is given by the formula A = TR?
Perimeter of circle is given by the formula P = 2R Let T = 3.
142.
Since it symbol is not denoted by C it is replaced by its value 3.
142 in the given formula.
Therefore using area = 3.
142 * r * r and P = 2 * 3.
142 * r; Now the program appears as follows:
Program to calculate area & perimeter of circle * / main ( ) 1 float r, P, area;
printf ( " Type in a value for radius of a circle \ n " ) scanf ( " % f ", & r );
area = 3.
142 * r * r; p = 2 + 3.
142 * r; printf ( " area of circle = f \ n ", area ); printf ( " perimeter of
circle = ' $ f \ n ", p ); Review Questions 1.
Write a brief note on the historical development of C language.
2.
In what way the language is different from other high level languages?
Explain 3.
Explain briefly the salient features of Clanguage.
4.
Define the following terms and give examples for each of them .
:
i ) Comment line, ii ) Identifier, iii ) Keyword, iv ) Constant v ) Types 5.
What are the advantages of including comments in a C progra?
Illustrate with examples.
6.
Write short notes on:
Programming style in C.
7.
Illustrate and explain with an example the basic structure! C program 8.
Explain the rules to be followed while defining an Identifier 4C 9.
What are C tokens?
Explain with examples.
10.
Distinguish between Block comments and Line comments C.
How do you specifiy?
11.
What do you mean by a keyword?
List any five keywords of C.
12.
Distinguish between a consant and variable.
13.
Explain with examples different types of numeric constants.
14.
What are Backslash constants?
Explain their use with exam

BCA Computer Concepts & Proy ( KUD ) 2 15.


Discuss briefly various rules to be followed while defining a variable name in C.
Give examples of valid and invalid variable names 16.
Explain with example declarations, the fundamental data types, in C 17.
What do you mean by data type modifiers?
How do they affect size and range of values to be represented by variables?
Explain with examples 18.
What are symbolic constants?
How do you declare them?
Give example declarations.
19.
Distinguish between character constant and string constants.
Give examples 20.
Bring out the need for declaration of variables in a C program Illustrate with
examples 21.
Bring out the importance of Input / Output statements in a program.
22.
What are C input / output functions?
23.
Explain briefly the conversion specification characters.
24.
Describe the scanf ( ) input function with examples of C program segments 25.
Distinguish between a constant and variable.
26.
Explain with examples different types of numeric constants.
27.
What are Backslash constants?
Explain their use with example.
28.
Explain with example declarations, the fundamental data types, in advantages?
Algorithms and Flowers 202 35.
Distinguish between character constant and string constants.
Gme examples 36.
Explain with the examples the assignment statement 37.
Write short notes on a ) C statements b ) Built - in Data Types in C 38.
Bring out the importance of Input / Output statements in a program 39.
What are C input / output functions?
40.
Explain briefly the conversion specification characters.
41.
Explain briefly the unformatted input functions used to read characters 42.
Explain briefly the unformatted output functions used to write prin characters on
to the screen.
43.
What do you mean by a prompting printf function?
What are is 44.
Explain briefly the significance of format string in a printf function.
45.
How do you specify field width of the number to be displayed Give examples 46.
Write short notes on i ) Formatted output function ii ) Conversion specifiers
iii ) Input / output functions of Civ ) Null statement v ) Compound statement 47.
Explain briefly the unformatted input functions used to read characters.
48.
Explain briefly the unformatted output functions used to write print characters on
to the screen.
49.
Describe Basic Programming Concepts.
50.
Define Algorithm and Flow chart 51.
What are characteristics of an Algorithm?
52.
Explain basic control structures in Algorithm 53.
Define basic symbols used in drawing Flowcharts 54.
Write an algorithm and draw a Flowchart to find sum and averas of 3 numbers 29.
What do you mean by data type modifiers?
How do they affect size and range of values to be represented by variables?
Explain with examples 30.
What are symbolic constants?
How do you declare them?
Give example declarations 31.
Explain with examples the assignment statements 32.
What do you mean by an assignment expression?
33.
Write a brief note on short hand assignment operator 14.
What are the benefits of using shorthand assignment operators?
Give examples MI

You might also like