SlideShare a Scribd company logo
1 of 116
Download to read offline
Structure
1.0Introduction
1.1 Procedure (stepsinvolved inproblemsolving)
1.2Algorithm
1.3 Flow Chart
1.4 Symbols used in Flow Charts
1.5 Pseudo Code
Learning Objectives
• To understand the concept ofProblemsolving
• To understand steps involvedin algorithmdevelopment
•To understand the concept ofAlgorithm
• DevelopAlgorithmfor simple problem
• To understand the concept ofFlowchart development
• Draw the symbols used in Flowcharts
1
UNIT
Introduction to Problem Solving
Techniques
Computer Science and Engineering
250
1.0 Introduction
Acomputeris a verypowerfuland versatile machinecapableofperforming
a multitude ofdifferent tasks, yet it has no intelligence or thinking power. The
intelligence Quotient (I.Q) ofa computer is zero. Acomputer performs many
tasks exactlyinthe same manneras it is toldto do. Thisplaces responsibilityon
the user to instruct the computer in a correct and precise manner, so that the
machine is able to perform the required job in a proper way. A wrong or
ambiguous instructionmaysometimes prove disastrous.
In order to instruct a computer correctly, the user must have clear
understanding ofthe problemto besolved. Apart fromthis he shouldbe able to
develop amethod, inthe formofseries ofsequentialsteps, to solve it. Once the
problemiswell-definedand a methodofsolving it isdeveloped, theninstructing
he computer to solve the problembecomes relativelyeasier task.
Thus, beforeattempt to writeacomputerprogramto solveagivenproblem.
It is necessaryto formulate or definethe problemina precise manner. Once the
problemis defined, the steps required to solve it, must be stated clearly in the
required order.
1.1 Procedure (Steps Involved in Problem Solving)
A computer cannot solve a problemon its own. One has to provide step
bystep solutions ofthe problemto the computer. In fact, the task ofproblem
solving isnot that ofthecomputer. It is theprogrammer who has to write down
the solutionto the probleminterms ofsimple operations which the computer
canunderstand and execute.
Inorderto solve aproblembythecomputer, one has topassthoughcertain
stages or steps. They are
1. Understanding the problem
2. Analyzingthe problem
3. Developing thesolution
4. Coding andimplementation.
1. Understanding the problem: Herewe tryto understand the problem
to besolvedintotally. Beforewiththenext stageorstep, weshouldbeabsolutely
sure about the objectives ofthe givenproblem.
2. Analyzing the problem:After understanding thoroughlythe problem
to be solved, we look different ways ofsolving the problemand evaluate each
251
Paper - II Programming in C
of these methods. The idea here is to search an appropriate solution to the
problemunder consideration. Theend result ofthis stage isabroad overview of
the sequence ofoperations that are to be carries out to solvethe givenproblem.
3. Developing the solution: Here the overview of the sequence of
operations that was the result ofanalysis stage is expanded to forma detailed
step bystep solutionto the problemunder consideration.
4. Codingand implementation: Thelast stageofthe problemsolving is
the conversion ofthe detailed sequence ofoperations in to a language that the
computercanunderstand.Hereeachstepisconvertedto itsequivalentinstruction
orinstructionsinthecomputerlanguagethat hasbeenchosenfortheimplantation.
1.2 Algorithm
Definition
A set ofsequentialsteps usuallywritten in OrdinaryLanguage to solve a
givenproblemis called Algorithm.
It maybepossible to solve to problemin more than oneways, resulting in
more than one algorithm. The choice of various algorithms depends on the
factors likereliability, accuracyand easyto modify. Themostimportant factorin
the choice ofalgorithmis thetimerequirement to execute it, afterwritingcodein
High-levellanguage withthehelpofacomputer. The algorithmwhichwillneed
the least time when executed isconsidered the best.
Steps involved in algorithm development
Analgorithmcanbedefinedas“acomplete,unambiguous,finitenumber
of logical steps for solving a specific problem “
Step1. Identification of input: For analgorithm, there arequantities to
besupplied calledinput andthese arefed externally. The input isto be indentified
first for anyspecified problem.
Step2: Identification ofoutput: Fromanalgorithm, at least one quantity
is produced, called for anyspecified problem.
Step3 : Identification the processing operations :Allthe calculations
to be performed in order to leadto output fromthe input are to be identified in
an orderlymanner.
Step4 : Processing Definiteness : The instructions composing the
algorithmmust be clear and thereshould not be anyambiguityinthem.
Computer Science and Engineering
252
Step5 : Processing Finiteness: Ifwe go through the algorithm, then for
allcases, the algorithmshould terminate after a finite numberofsteps.
Step6 : Possessing Effectiveness : The instructions in the algorithm
must be sufficientlybasic and inpractice theycan be carries out easily.
Analgorithmmust possess the following properties
1. Finiteness:Analgorithmmust terminate in a finite number ofsteps
2. Definiteness: Each step of the algorithm must be precisely and
unambiguouslystated
3. Effectiveness: Each step must be effective, in the sense that it should
beprimitiveeasilyconvert ableintoprogramstatement)canbeperformedexactly
ina finiteamount oftime.
4. Generality: The algorithm must be complete in itselfso that it can be
used to solve problems ofa specific type for anyinput data.
5. Input/output: Eachalgorithmmust take zero, one ormorequantitiesas
input data produce one or more output values.An algorithmcanbe written in
English like sentences or inanystandard representationsometimes, algorithm
written inEnglishlike languages arecalled Pseudo Code
Example
1. Suppose wewant to find the average ofthree numbers, the algorithmis
as follows
Step 1 Read the numbers a, b, c
Step 2 Compute the sum of a, b and c
Step 3 Divide the sum by3
Step 4 Store the result in variable d
Step 5 Print the value ofd
Step 6 End ofthe program
1.2.2Algorithms forSimple Problem
Write an algorithmfor the following
1. Write analgorithmto calculate thesimple interest using the formula.
Simple interest = P*N* R/100.
253
Paper - II Programming in C
Where Pis principleAmount, Nis the number ofyears and R isthe rate
ofinterest.
Step 1: Read the three input quantities’P, N and R.
Step 2 : Calculate simple interest as
Simple interest = P* N* R/100
Step 3:Print simple interest.
Step 4: Stop.
2. Area ofTriangle: Write analgorithmto find the area ofthe triangle.
Let b, c be the sides ofthe triangleABC andAthe included angle between
the givensides.
Step 1: Input the givenelements ofthe triangle namelysides b, c and angle
between the sidesA.
Step 2: Area = (1/2) *b*C* sinA
Step 3: Output theArea
Step 4: Stop.
3. Write analgorithmto find the largest ofthree numbers X, Y,Z.
Step 1: Read the numbers X,Y,Z.
Step 2: if(X >Y)
Big = X
else BIG = Y
Step 3 : if (BIG < Z)
Step 4: Big = Z
Step 5: Print the largest numberi.e. Big
Step 6: Stop.
Computer Science and Engineering
254
4. Write down an algorithmto find the largest data value ofa set ofgiven
data values
Algorithm largest of all data values:
Step 1: LARGE  0
Step 2: read NUM
Step 3: While NUM > = 0 do
3.1 ifNUM > LARGE
3.1.1 then
3.1.1.1 LARGE  NUM
3.2. read NUM
Step 4:Write “largest data valueis”, LARGE
Step 5: end.
5. Write analgorithmwhichwilltest whether agivenintegervalue is prime
or not.
Algorithm prime testing:
Step 1: M  2
Step 2: read N
Step 3: MAX  SQRT (N)
Step 4: While M < = MAX do
4.1 if (M* (N/M) = N
4.1.1 then
4.1.1.1 go to step 7
4.2. M  M + 1
Step 5:Write “number is prime”
Step 6: go to step 8
Step 7:Write “number is not a prime”
Step 8: end.
255
Paper - II Programming in C
6. Write algorithmto find the factorialofa givennumber N
Step 1: PROD  1
Step 2: I  0
Step 3: read N
Step 4: While I < N do
4.1 I  I + 1
4.2. PROD  PROD* I
Step 5:Write “Factorialof”, N, “is”, PROD
Step 6: end.
7. Write analgorithmto findsumofgivendatavaluesuntilnegativevalueis
entered.
AlgorithmFind – Sum
Step 1: SUM  0
Step 2: I  0
Step 3: read NEWVALUE
Step 4: While NEWVALUE < = 0 do
4.1 SUM  SUM + NEW VALUE
4.2 1  I + 1
4.3 read NEWVALUE
Step 5: Write “Sumof”, I, “data value is, “SUM
Step 6: END
8. Writeanalgorithmto calculate theperimeter andareaofrectangle. Given
its lengthand width.
Step 1: Readlength ofthe rectangle.
Step 2: Readwidth ofthe rectangle.
Step 3:Calculate perimeter oftherectangle using the formulaperimeter =
2* (length+ width)
Step 4:Calculate area ofthe rectangle using the formula area = length
*width.
Computer Science and Engineering
256
Step 5: Print perimeter.
Step 6: Print area.
Step 7: Stop.
1.3 Flowchart
A flow chart is a step by step diagrammatic representation of the logic
pathsto solveagivenproblem.Or Aflowchart isvisualorgraphicalrepresentation
ofanalgorithm.
The flowcharts are pictorialrepresentation of the methods to b used
to solve a given problemand help a great dealto analyze the problemand plan
its solutionina systematic and orderlymanner. Aflowchart when translated in
to a propercomputer language, results ina complete program.
Advantages of Flowcharts
1. Theflowchart shows the logic ofa problemdisplayed inpictorialfashion
whichfelicitates easier checking ofanalgorithm.
2. The Flowchart is good means ofcommunicationto other users.It is also
a compact meansofrecording analgorithmsolutionto a problem.
3. Theflowchart allowsthe problemsolver to breaktheprobleminto parts.
These parts can be connected to make master chart.
4. The flowchart is a permanent record of the solution which can be
consulted at a later time.
Differences betweenAlgorithm and Flowchart
Algorithm
1. A method of representing the
step-by-step logicalprocedure for
solving a problem
2. It contains step-by-step English
descriptions, eachsteprepresenting
a particular operation leading to
solutionofproblem
3. These areparticularlyuseful for
smallproblems
4. For complex programs,
algorithms prove to be Inadequate
Flowchart
1. Flowchart is diagrammatic
representation of an algorithm. It is
constructed using different types ofboxes
and symbols.
2. Theflowchart employsaseriesofblocks
and arrows, each of which represents a
particular stepinanalgorithm
3. These are useful for detailed
representations ofcomplicated programs
4. For complex programs, Flowcharts
prove to be adequate
257
Paper - II Programming in C
1.4 Symbols used in Flow-Charts
The symbols that we make use while drawing flowcharts as given below
are as perconventions followed byInternationalStandard Organization(ISO).
a. Oval: Rectangle withrounded sides is used to indicate either START/
STOP ofthe program. ..
b. Input and output indicators: Parallelograms are used to represent
input and output operations. Statements like INPUT, READ and PRINT are
represented inthese Parallelograms.
c. ProcessIndicators:- Rectangleisused to indicate anyset ofprocessing
operationsuchasfor storing arithmetic operations.
d. Decision Makers: The diamond is used for indicating the step of
decision makingand therefore knownas decisionbox. Decisionboxes are used
to test the conditions or ask questions and depending upon the answers, the
appropriate actions are taken bythe computer. The decision boxsymbolis
e. Flow Lines: Flow lines indicate the direction being followed in the
flowchart. In a Flowchart, every line must have an arrow on it to indicate the
direction. Thearrows maybe inanydirection
f. On- Page connectors: Circles are used to join the different parts ofa
flowchart and these circles are called on-page connectors. The uses ofthese
connectors give a neat shape to the flowcharts. Ina complicated problems, a
flowchart mayrunin to severalpages. The parts ofthe flowchart on different
Computer Science and Engineering
258
pages are to be joined witheach other. The parts to be joined are indicated by
the circle.
g. Off-page connectors: This connectorrepresents a break inthe pathof
flowchart which is too large to fit on a single page. It is similar to on-page
connector. The connector symbolmarks where the algorithmends onthe first
page and where it continues onthe second.
1.4.1 Simple Problems using Flow Chart
Draw the Flowchart for the following
1. Draw the Flowchart to find Roots of Quadratic equation ax2
+ bx + c
= 0. The coefficients a, b, c are the input data
START
INPUT A,B,C
D = B2
- 4 * A* C
IS
D< O
YES
YES
NO
NO
x = B/2*A
Print X,Y
y = B/2*A
y = -B + D
2 x A
2 x A
x =B + D
Print X,Y
output complex roots
Stop
IS
D= O
259
Paper - II Programming in C
2. Draw a flowchart to find out the biggest ofthe three unequalpositive
numbers.
3. Draw a flowchart for adding the integers from 1 to 100 and to
print the sum.
Print Sum
Computer Science and Engineering
260
4. Draw a flowchart to find the factorial of given positive integer N.
5. Develop a flowchart to illustrate how to make a Land phone
telephone call
.
Flowchart forTelephone call
I
I
261
Paper - II Programming in C
6. 6. ABC company plans to give a 6% year-end bonus to each of its
employees earning Rs 6,000 or more per month , and a fixed Rs 250/- -
bonus to the remaining employees. Draw a flowchart for calculating the
bonus for an employee
1.5 Pseudo code
The Pseudo code is neither an algorithmnor a program. It is an abstract
form of a program. It consists of English like statements which perform the
specific operations. It is defined for analgorithm. It does not use anygraphical
representation. Inpseudo code, the programis represented in terms ofwords
and phrases, but the syntaxofprogramis not strictlyfollowed.
Advantages: * Easy to read, * Easy to understand, * Easy to modify.
Example:Writea pseudocode to performthebasicarithmetic operations.
Read n1, n2
Sum = n1 + n2
Diff= n1 – n2
Mult = n1 * n2
Quot = n1/n2
Print sum,diff, mult, quot
End.
Computer Science and Engineering
262
Activity
Practice more sample problems onalgorithmand Flowcharts
Model Questions
Short Answer Type Questions - 2 Marks
1. Define Algorithm
2. What is Flowchart
3. What is Pseudo code?
4. What are the symbols of Flowchart
5. WriteanAlgorithmfor perimeter ofTriangle
6. What are the basic steps involved In problemsolving
Long Answer Type Questions - 6 Marks
1. Differentiate betweenAlgorithmand Flowchart.
2. Write analgorithmto find greatest ofgiven three numbers.
3. Write an algorithmto check whether given integer value is PRIME or
NOT.
4. Draw the flowchart to find roots ofQuadraticequation ax2
+ bx+ c= 0
Note : Practice more relatedAlgorithms and Flowcharts.
Structure
2.0Introduction
2.1 Character Set
2.2 Structure ofa ‘C’ Program
2.3 Data Types in ‘C’
2.4 Operations
2.5 Expressions
2.6Assignment Statement
2.7 ConditionalStatements
2.8 Structurefor Looping Statements
2.9 Nested Looping Statements
2.10 MultiBranching Statement (Switch), Breakand Continue
2.11 Differences betweenBreak and Continue
2.12 UnconditionalBranching(Go to Statement)
2
UNIT
Features of ‘C’
Computer Science and Engineering
264
Learning Objectives
•
What is C Language and its importance
• To understand various data types
• To understand working functionofinput and output statements inC
• To understand workingfunctionofBranching statements inC
• To understand workingfunctionofLooping statements inC
• To Understand differences between Break and Continue
2.0 Introduction
‘C’ ishighlevellanguage andis the upgraded versionofanother language
(Basic Combined Program Language). C language was designed at Bell
laboratoriesintheearly1970’sbyDennisRitchie. Cbeingpopularinthemodern
computer world can be used in Mathematical Scientific, Engineering and
Commercialapplications
The most popular Operating systemUNIX is written inC language. This
languagealso hasthefeaturesoflowlevellanguagesand hencecalledas “System
ProgrammingLanguage”
Features of C language
• Simple, versatile, generalpurpose language
• It has richset ofOperators
• Programexecutionarefast and efficient
• Can easilymanipulates with bits, bytes and addresses
• Varieties ofdatatypes are available
• Separate compilationof functions ispossible and suchfunctionscanbe
called byanyC program
• Block- structured language
• Can be applied in Systemprogramming areas like operating systems,
compilers & Interpreters,Assembles, Text Editors, Print Spoolers, Network
Drivers, ModernPrograms, Data Bases, Language Interpreters, Utilities etc.
265
Paper - II Programming in C
2.1 Character Set
The character set is the fundamentalraw-materialfor anylanguage. Like
naturallanguages, computerlanguages willalso havewelldefinedcharacter-set,
which is usefulto build the programs.
The C language consists oftwo character sets namely– source character
set execution character set. Source character set is useful to construct the
statements inthe source program. Execution character set is employed at the
time ofexecutionofhprogram.
1. Source character set : This type ofcharacter set includes three types
ofcharacters namelyalphabets, Decimals andspecialsymbols.
i. Alphabets : Ato Z, a to z and Underscore( _ )
ii. Decimal digits : 0 to 9
iii. Special symbols: + - * / ^ % = & ! ( ) { } [ ] “ etc
2. Execution character set : This set of characters are also called as
non-graphic characters because these are invisible and cannot be printed or
displayed directly.
These characters willhave effect onlywhen the programbeing executed.
These characters are represented by a back slash () followed by a character.
Execution character Meaning Result at the time of execution
 n End ofa line Transfers the active position ofcursor
to the initial position of next line
 0 (zero) Endofstring Null
 t HorizontalTab Transfers the active positionofcursor
to the next Horizontal Tab
 v VerticalTab Transfers the activepositionofcursor
to the next Vertical Tab
 f Formfeed Transfers the active positionofcursor
to the next logical page
 r Carriage return Transfers the activepositionofcursor
to the initial position of current line
Computer Science and Engineering
266
2.2 Structure of a ‘C’ Program
The Complete structure of C program is
The basic components ofa C programare:
• main()
• pair of braces { }
• declarations and statements
• userdefined functions
PreprocessorStatements: These statements beginwith # symbol. They
are called preprocessor directives. These statements direct the C preprocessor
to include header files and also symbolic constants in to C program. Some of
the preprocessor statements are
#include<stdio.h>: for thestandard input/output functions
#include<test.h>: forfile inclusionofheaderfileTest.
#define NULL 0: for defining symbolic constant NULL = 0 etc.
GlobalDeclarations: Variables or functions whose existence isknownin
the main()function and other userdefined functions are called globalvariables
(orfunctions) andtheir declarationsis calledglobaldeclaration. This declaration
should be made before main().
main():AsthenameitselfindicatesitisthemainfunctionofeveryCprogram.
ExecutionofCprogramstarts frommain(). No C programis executedwithout
main() function. It should be written in lowercase letters and should not be
terminatedbyasemicolon. It callsotherLibraryfunctionsuserdefinedfunctions.
There must be one and onlyone main() function ineveryC program.
Braces: Every C program uses a pair of curly braces ({,}0. The left
brace indicatesbeginning ofmain() function. Onthe other hand, the right brace
indicates end ofthe main() function. The braces canalso be usedto indicate the
beginning and endof user-defined functions and compound statements.
Declarations: It is part of C program where all the variables, arrays,
functions etc., used in the C programare declared and maybe initialized with
their basic data types.
Statements: These are instructions to the specific operations. Theymay
be input-output statements, arithmetic statements, controlstatements and other
statements. Theyarealso including comments.
267
Paper - II Programming in C
User-definedfunctions:These aresubprograms. Generally, a subprogram
is a function, and they contain a set of statements to performa specific task.
These are written bythe user;hence the name is user-defined functions. They
maybe writtenbefore or after the main() function.
2.3 Data Types in ‘C’
The built-in data types and their extensions is the subject ofthis chapter.
Deriveddatatypes suchasarrays,structures, unionandpointersanduserdefined
data types such as typedefand enum.
Basic Data Types
There are four basic data types in C language. They are Integer data,
character data, floating point data and double data types.
a. Character data: Any character of the ASCII character set can be
considered as a character data types and its maximumsize can be 1 byte or 8
byte long. ‘Char’is the keyword used to represent character data type in C.
Char - a single byte size, capable of holding one character.
b. Integer data: The keyword ‘int’ stands for the integer data type in C
and its size is either 16 or 32 bits. The integer data type canagain be classified
as
1. Long int - long integerwithmore digits
2. Short int - short integer withfewer digits.
3. Unsigned int - Unsigned integer
C Data types
Built - In Derived C Data Types Void
Array Structure Union Pointer
Char Integer Float Double Type def Enum
Computer Science and Engineering
268
4. Unsigned short int – Unsigned short integer
5. Unsigned long int – Unsignedlong integer
As above, the qualifiers like short, long, signed or unsigned canbe applied
to basic data types to derive new data types.
int - an Integer with the natural size ofthe host machine.
c. Floating point data: - The numbers whichare stored infloating point
representationwithmantissaandexponent arecalledfloatingpoint(real)numbers.
These numbers can be declared as ‘float’ in C.
float – Single – precision floating point number value.
d. Double data : -Double is akeyword inC to represent double precision
floatingpoint numbers.
double - Double – precision floating point number value.
Data Kinds in C
Various data kinds that can beincluded in anyC programcanfallinto the
following.
a. Constants/Literals
b. Reserve Words Keywords
c. Delimeters
d. Variables/Identifiers
a. Constans/Literals: Constants arethose, which do not change, during
the executionofthe program. Constants maybecategorized in to:
• Numeric Constants
• Character Constants
• StringConstants
1. Numeric Constants
Numeric constants, as the name itselfindicates, are those whichconsist of
numerals, anoptionalsignand anoptionalperiod. Theyare further divided into
two types:
(a) Integer Constants (b) RealConstants
a. Integer Constants
269
Paper - II Programming in C
A whole number is an integer constant Integer constants do not have a
decimalpoint.Thesearefurtherdividedintothreetypesdependingonthenumber
systems theybelong to. Theyare:
i. Decimalintegerconstants
ii. Octalinteger constants
iii. Hexadecimalinteger constants
i. A decimal integer constant is characterized by the following
properties
• It is a sequence ofone ormore digits ([0…9], thesymbols ofdecimal
numbersystem).
• It mayhave anoptional+or –sign. Intheabsence ofsign, the constant
is assumed to be positive.
• Commas and blank spaces are not permitted.
• It should not have a period as part ofit.
Some examples ofvalid decimalinteger constants:
456
-123
Some examples ofinvalid decimalinteger constants:
4.56 - Decimalpoint is not permissible
1,23 - Commas arenot permitted
ii. An octal integer constant is characterized by the following
properties
• It is asequenceofoneormore digits ([0…7], symbolsofoctalnumber
system).
• It mayhave anoptional+or –sign. Intheabsence ofsign, the constant
is assumed to be positive.
• It should start withthe digit 0.
• Commas and blank spaces are not permitted.
• It should not have a period as part ofit.
Some examples ofvalid octalinteger constants:
Computer Science and Engineering
270
0456
-0123
+0123
Some examples ofinvalid octalinteger constants:
04.56 - Decimalpoint is not permissible
04,56 - Commas are not permitted
x34 - x is not permissible symbol
568 - 8 is not a permissible symbol
iii. An hexadecimal integer constant is characterized by the
following properties
• It isa sequence ofoneor more symbols ([0…9][A….Z], the symbols
ofHexadecimalnumber system).
• It mayhaveanoptional+or - sign. Inthe absence ofsign,the constant
is assumed to be positive.
• It should start with the symbols 0X or 0x.
• Commas and blank spaces are not permitted.
• It should not have a period as part ofit.
Some examples ofvalid hexadecimalinteger constants:
0x456
-0x123
0x56A
0XB78
Some examples ofinvalid hexadecimalinteger constants:
0x4.56 - Decimalpoint is not permissible
0x4,56 - Commas are not permitted.
b. Real Constants
The realconstants also known as floating point constants are written in
twoforms:
271
Paper - II Programming in C
(i) Fractionalform, (ii) Exponentialform.
i. Fractional Form
The real constants in Fractional form are characterized by the
following characteristics:
• Must have at least one digit.
• Must havea decimalpoint.
• Maybepositiveornegativeand intheabsenceofsigntakenaspositive.
• Must not contain blanks or commas in betweendigits.
• Maybe represented in exponentialform, ifthe value is too higher or
too low.
Some examples ofvalid realconstants:
456.78
-123.56
Some examples ofinvalid realconstants:
4.56 - Blank spaces are not permitted
4,56 - Commas arenot permitted
456 - Decimalpoint missing
ii. Exponential Form
The exponentialformoffers a convenient wayfor writing verylarge and
smallrealconstant. For example, 56000000.00, which can be writtenas 0.56
*, 108 is writtenas0.56E8or 0.56e8 inexponentialform. 0.000000234, which
canbewrittenas 0.234 * 10-6 iswrittenas0.234E-6 or 0.234e-6inexponential
form. The letterE or e stand for exponentialform.
A realconstant expressed in exponentialformhas two parts: (i) Mantissa
part, (ii)Exponent part. Mantissa is the part ofthe realconstant to theleft ofE
or e, and the Exponent ofa realconstant is to the right ofE or e. Mantissa and
Exponent ofthe above two number are shown below.
E -6
0.234
E 8
0.56
E xponent
Mantissa
E xponent
Mantissa
E -6
0.234
E 8
0.56
E xponent
Mantissa
E xponent
Mantissa
Computer Science and Engineering
272
In the above examples, 0.56 and 0.234 are the mantissa parts of the first
and second numbers, respectively, and 8 and -6 are the exponent parts ofthe
first andsecond number, respectively.
The real constants in exponential form and characterized by the
following characteristics:
• The mantissa must have at least one digit.
• The mantissa is followed bytheletter E or e and the exponent.
• The exponent must have at least one digit and must be an integer.
• Asignforthe exponent is optional.
Some examples ofvalid realconstants:
3E4
23e-6
0.34E6
Some examples ofinvalid realconstants:
23E - No digit specified for exponent
23e4.5 - Exponent should not be a fraction
23,4e5 - Commas are not allowed
256*e8- * not allowed
2. Character Constants
Anycharacterenclosed withinsinglequotes(‘)iscalledcharacter constant.
Acharacter constant:
• Maybeasingle alphabet, singledigit or single specialcharacter placed
withinsingle quotes.
• Has a maximumlength of1 character.
Here are some examples,
• ‘C’
• ‘c’
• ‘:’
• ‘*’
273
Paper - II Programming in C
3. String Constants
A string constant is a sequence of alphanumeric characters enclosed in
double quoteswhose maximumlength is255 characters.
Following arethe examples ofvalidstring constants:
• “Mynameis Krishna”
• “Bible”
• “Salaryis 18000.00”
Following arethe examples ofinvalidstring constants:
My name is Krishna - Character are not enclosed in double quotation
marks.
“Myname is Krishna - Closing double quotationmark is missing.
‘Mynameis Krishna’ - Characters are not enclosedin double quotation
marks
b. Reserve Words/Keywords
InC language , some words are reserved to do specific tasks intended for
themand are called Keywords or Reserve words. The list reserve words are
auto do goto
break double if
case else int
char extern long
continue float register
default for return
short sezeof static
struct switch typedef
union unsigned void
while const entry
violate enum noalias
Computer Science and Engineering
274
c. Delimiters
This is symbolthat has syntactic meaningand has got significance. These
willnot specifyanyoperation to result in a value. C language delimiters list is
givenbelow
Symbol Name Meaning
# Hash Pre-processor directive
, comma Variable delimiter to separate variable
: colon labeldelimiter
; Semicolon statement delimiter
( ) parenthesis used for expressions
{ } curlybraces used forblocking ofstatements
[ ] square braces used alongwitharrays
d. Variables / Identifiers
These are the names ofthe objects, whose values canbe changed during
the programexecution.Variables are named withdescriptionthat transmits the
value it holds.
[Aquantityofanitem, whichcanbe change its value during the execution
ofprogramiscalled variable. It is also known as Identifier].
Rules fornaming a variable:-
 It can be ofletters, digits and underscore( _ )
 First letter should be a letter or an underscore, but it should not be a
digit.
 Reserve words cannot be used as variable names.
Example: basic, root, rate, roll-no etc are valid names.
Declaration ofvariables:
Syntax type Variable list
int i, j i, j are declared as integers
float salary salaryis declared ad floating point variable
Char sex sex is declared as character variable
275
Paper - II Programming in C
2.4 Operators
An Operator is a symbol that operates on a certain data type. The data
items that operators act upon are called operands. Some operators require
two operands, some operators act upononlyone operand. InC, operators can
be classified into various categories based on theirutilityand action.
1.Arithmetic Operators 5. Increment & Decrement Operator
2. RelationalOperators 6. ConditionalOperator
3. LogicalOperator 7. Bitwise Operator
4.Assignment Operator 8. Comma Operator
1.Arithmetic Operators
TheArithmetic operators performs arithmetic operations. TheArithmetic
operators canoperateonanybuilt indata type.Alist ofarithmetic operators are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
2. Relational Operators
RelationalOperators areused to compare arithmetic, logicalandcharacter
expressions. The RelationalOperators compare their left hand side expression
withtheirrighthandsideexpression.Thenevaluatestoaninteger.IftheExpression
is false it evaluate to “zero”(0) ifthe expressionis true it evaluate to “one”
Operator Meaning
< Less than
> Greater than
<= Less thanor Equalto
>= Greater thanor Equalto
= = Equalto
Computer Science and Engineering
276
!= Not Equalto
The RelationalOperators are represented inthe following manner:
Expression-1 Relational Operator Expression-2
The Expression-1 willbe compared with Expression-2 and depending on
the relation theresult willbe either“TRUE” OR “FALSE”.
Examples :
Expression Evaluate to
(5 <= 10) ———————— 1
(-35 > 10) ———————— 0
(X < 10) ———————— 1 ( if value of x is less than 10)
0 Other wise
(a + b) = = ( c + d ) 1 (if sum of a and b is equal to sum of c, d)
0 Other wise
3. Logical Operators
A logicaloperator is used to evaluate logicaland relational expressions.
The logicaloperatorsact uponoperandsthat arethemselveslogicalexpressions.
There are three logicaloperators.
Operators Expression
&& LogicalAND
|| LogicalOR
! LogicalNOT
LogicalAnd (&&): AcompoundExpressionistrue whentwo expression
when two expressions are true. The&& is used inthe following manner.
Exp1 && Exp2.
The result ofa logicalAND operationwillbe true onlyifbothoperands are
true.
The results oflogicaloperators are:
Exp1 Op. Exp2 Result
True &&TrueTrue
277
Paper - II Programming in C
True && False False
False && False False
False &&True False
Example: a = 5; b = 10; c = 15;
Exp1 Exp2 Result
1. ( a< b ) && ( b < c ) => True
2. ( a> b ) && ( b < c ) => False
3. ( a< b ) && ( b > c ) => False
4. ( a> b ) && ( b > c ) => False
Logical OR: A compound expression is false when all expression are
false otherwise thecompound expressionis true. The operator “||” is used as It
evaluatesto true ifeither exp-1or exp-2 is true. The truthtable of“OR” is Exp1
|| Exp2
Exp1 Operator Exp2 Result:
True || True True
True || False True
False || True True
False || False False
Example: a = 5; b = 10; c = 15;
Exp1 Exp2 Result
1. ( a< b ) || ( b < c ) => True
2. ( a> b ) || ( b < c ) => True
3. ( a< b ) || ( b > c ) => True
4. ( a> b ) || ( b > c ) => False
Logical NOT: The NOT ( ! ) operator takes single expression and
evaluates to true(1) if the expression is false (0) or it evaluates to false (0) if
expressionis true (1). The generalformofthe expression.
! ( Relational Expression )
The truth table ofNOT :
Computer Science and Engineering
278
Operator. Exp1 Result
!True False
! False True
Example: a = 5; b = 10; c = 15
1. !( a< b ) False
2. !( a> b ) True
4.Assignment Operator
An assignment operator is used to assign a value to a variable. The most
commonlyused assignment operator is =. The generalformat for assignment
operator is :
<Identifer> = < expression >
Where identifier represent a variable and expressionrepresents a constant,
a variable or a Complex expression.
Ifthetwo operands inanassignment expressionare ofdifferent data types,
then the value ofthe expression onthe right willautomaticallybe converted to
the type ofthe identifier onthe left.
Example: Suppose that I is an Integertype Variable then
1. I = 3.3 3 ( Value of I )
2. I = 3.9 3 ( Value of I )
3. I = 5.74 5 ( Value of I )
Multiple assignment
< identifier-1 > = < identifier-2 > = - - - = < identifier-n > = <exp>;
Example: a,b,c are integers; jis float variable
1. a = b = c = 3;
2. a = j = 5.6; then a = 5 and j value will be 5.6
C containsthe following five additionalassignment operators
1. += 2.-= 3. += 4. *= 5. /=
The assignment expression is: - Exp1< Operator> Exp-2
Ex: I = 10 (assume that)
279
Paper - II Programming in C
ExpressionEquivalent to FinalValue of‘I’
1. I + = 5 I = I + 5 15
2. I - = 5 I = I - 5 10
3. I * = 5 I = I * 5 50
4. I / = 5 I = I / 5 10
5. Increment & Decrement Operator
Theincrement/decrement operatoract uponaSingleoperandand produce
a new value is also called as “unary operator”. The increment operator ++
adds 1 to the operand and the Decrement operator – subtracts 1 from the
operand.
Syntax: < operator>< variable name >;
The ++ or – operator canbe used in the two ways.
Example : ++ a; Pre-increment (or) a++ Post increment —a; Pre-
Decrement (or) a— Post decrement
1. ++ a Immediatelyincrements the value ofa by1.
2. a ++ The value ofthe a willbe increment by1 after it is utilized.
Example 1: Suppose a = 5 ;
StatementsOutput
printf ( “a value is %d”, a ); a value is 5
printf( “a value is %d”, ++ a ); a value is 6
printf( “a value is %d “, a) ; a value is 6
Example 2: Suppose : a = 5 ;
StatementsOutput
printf(“a value is %d “, a); a value is 5
printf(“a value is %d “, a++); a value is 5
printf(“a value is %d “,a); a value is 6
a anda-willbeact onoperand bydecrement valuelike increment operator.
6. Conditionaloperator(or) Ternary operator(? :)
Computer Science and Engineering
280
It is called ternarybecause it uses three expression. The ternaryoperator
acts likeIf- Else construction.
Syn :( <Exp –1 > ? <Exp-2> : <Exp-3> );
Expression-1 is evaluated first. If Exp-1 is true then Exp-2 is evaluated
other wise it evaluate Exp-3 willbe evaluated.
Flow Chart :
Exp-1
Exp-2 Exp-3
Exit
Example:
1. a = 5 ; b = 3;
( a> b ? printf(“a is larger”) : printf(“b is larger”));
Output is :a is larger
2. a = 3; b = 3;
(a> b? printf(“a islarger”) : printf(“bis larger”));
Output is :b is larger
7. Bit wise Operator
A bitwise operator operates on each bit of data. These bitwiseoperator
can be divided into three categories.
i. The logicalbitwise operators.
ii. The shift operators
iii. The one’scomplement operator.
i)The logicalBitwiseOperator:Therearethreelogicalbitwiseoperators.
Meaning Operator:
a) Bitwise AND &
b) Bitwise OR |
c) Bitwise exclusive XOR ^
281
Paper - II Programming in C
Suppose b1 and b2 represent the corresponding bits with in the first and
second operands, respectively.
B1 B2 B1 & B2 B1 | B2 B1 ^ B2
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
The operations arecarried out independentlyoneachpairofcorresponding
bits withintheoperandthus the leastsignificant bits(ietherightmost bits)within
the two operands.Willbe compared untilallthe bits have beencompared. The
results ofthese comparisons are
ABitwiseAND expression willreturn a 1 ifboth bits have a value of 1.
Other wise, it willreturn avalue of0.
A Bitwise OR expression willreturna 1 ifone or more ofthe bits have a
value of1. Otherwise, it willreturn avalue of0.
A Bitwise EXCLUSIVE OR expression willreturn a 1 ifone ofthe bits
has a value of1 and the other has a value of0. Otherwise, ifwillreturn a value
of0.
Example::Variable Value Binary Pattern
X 5 0101
Y 2 0010
X & Y 0 0000
X | Y 7 0111
X ^ Y 7 0111
ii) The Bitwise shift Operations: The two bitwise shift operators are
Shift left (<<) and Shift right (>>). Each operator requires two operands.
The first operandthat represents the bit pattern to be shifted. Thesecond is an
unsigned integerthat indicates the number ofdisplacements.
Example: c = a << 3;
The value in the integer a is shifted to the left by three bit position. The
result is assigned to the c.
Computer Science and Engineering
282
A = 13; c= A<<3;
Left shit << c= 13 * 2 3 = 104;
Binary no 0000 0000 0000 1101
After left bit shift by 3 places ie,. a<<3
0000 0000 0110 1000
The right –bit – shift operator ( >> ) is also a binaryoperator.
Example: c = a >> 2 ;
The value ofa is shifted to the right by2 position
insert 0’s Right – shift >> drop off0’s
0000 0000 0000 1101
After right shift by2 places is a>>2
0000 0000 0000 0011 c=13>>2
c= 13/4=3
iii) Bitwise complement: The complement op.~ switches allthe bits in a
binarypattern, that is all the 0’s becomes 1’s and allthe 1’s becomes 0’s.
variable value Binary patter
x 23 0001 0111
~x 132 1110 1000
8. Comma Operator
Aset ofexpressions separated byusingcommas is a validconstructioninc
language.
Example :int i, j;
i= ( j = 3, j + 2 ) ;
The first expression is j = 3 and second is j + 2. These expressions are
evaluated fromleft to right. Fromthe above example I = 5.
Size of operator: The operator size operator gives the size of the data
type or variableinterms ofbytes occupied inthe memory.This operator allows
a determinationofthe no ofbytes allocated to various Data items
Example :int i;float x; double d;char c; OUTPUT
283
Paper - II Programming in C
Printf(“integer: %dn”, sizeof(i));Integer: 2
Printf(“float : %dn”, sizeof(i));Float : 4
Printf(“double: %dn”, sizeof(i));double: 8
Printf(“char :%dn”,sizeof(i));character : 1
2.5 Expressions
An expression can be defined as collection of data object and operators
that canbe evaluatedto leadasingle newdataobject.Adataobject is a constant,
variable or another data object.
Example : a + b
x + y + 6.0
3.14 * r * r
( a + b ) * ( a – b)
The above expressions are called as arithmetic expressions because
the data objects (constants and variables) are connected using arithmetic
operators.
Evaluation Procedure: Theevaluationofarithmetic expressionsis as per
the hierarchyrules governed bythe C compiler. The precedence or hierarchy
rules forarithmetic expressions are
1. The expressionis scanned fromleft to right.
2. Whilescanningtheexpression,theevaluationpreferencefortheoperators
are
*, /, % - evaluated first
+, - - evaluated next
3. To overcome the above precedence rules, user has to make use of
parenthesis. Ifparenthesisisused, theexpression/ expressionswithinparenthesis
are evaluated first as per the above hierarchy.
Statements
Data Input & Output
Aninput/output functioncanbe accessed fromanywherewithina program
simplybywritingthe functionname followedbya list ofarguments enclosed in
parentheses. The arguments represent data itemsthat are sent to the function.
Computer Science and Engineering
284
Some input/output Functions do not require arguments though the empty
parentheses must stillappear. Theyare:
Input Statements Output Statements
Formatted scanf() printf()
Unformatted getchar()gets() putchar()puts()
getchar()
Single characters can be entered into the computer using the C library
Function getchar(). It returns a single character froma standard input device.
The functiondoesnot require anyarguments.
Syntax: <Character variable> = getchar();
Example: char c;
c = getchar();
putchar()
Single characters can be displayed using function putchar(). It returns a
singlecharacter toa standardoutput device. It must be expressedas anargument
to the function.
Syntax: putchar(<character variable>);
Example: char c;
————
putchar(c);
gets()
The function gets() receives thestring fromthe standard input device.
Syntax: gets(<string type variable or arrayofchar> );
Where s is a string.
The functiongets accepts the string as a parameter fromthe keyboard, till
anewlinecharacterisencountered.Atendthefunctionappendsa“null”terminator
and returns.
puts()
The functionputs() outputs thestring to the standardoutput device.
285
Paper - II Programming in C
Syntax: puts(s);
Where s is a string that was realwith gets();
Example:
main()
{
char line[80];
gets(line);
puts(line);
}
scanf()
Scanf()functioncanbeusedinputthedataintothememoryfromthestandard
input device. This function can be used to enter anycombination ofnumerical
Values, singlecharactersand strings. Thefunctionreturns number ofdata items.
Syntax:-scanf(“controlstrings”, &arg1,&arg2,——&argn);
Wherecontrolstringreferesto astringcontainingcertainrequiredformatting
informationandarg1,arg2——argnare arguments that represent the individual
input data items.
Example:
#include<stdio.h>
main()
{
char item[20];
intpartno;
float cost;
scanf(“%s %d %f”,&item,&partno,&cost);
}
Where s, d, fwith%are conversioncharacters. Theconversioncharacters
indicate the type of the corresponding data. Commonly used conversion
characters fromdata input.
Computer Science and Engineering
286
Conversion Characters
Characters Meaning
%c data itemis a single character.
%d data itemis a decimalinteger.
%f data itemisa floating point value.
%e data itemisa floating point value.
%g data itemisa floating point value.
%h data itemis a short integer.
%s data itemis a string.
%x data itemisa hexadecimalinteger.
%o data itemisa octalinterger.
printf()
The printf()functionis used to print the data fromthe computer’s memory
onto a standard output device. This function can be used to output any
combinationofnumericalvalues, single characterand strings.
Syntax: printf(“controlstring”, arg-1, arg-2,———arg-n );
Where controlstring is a string that contains formatted information, and
arg-1, arg-2 ——are arguments that represent theoutput data items.
Example:
#include<stdio.h>
main()
{
char item[20];
intpartno;
float cost;
———————
printf(“%s %d%f”, item, partno, cost);
} (Where %s %d %f are conversion characters.)
287
Paper - II Programming in C
2.6 Assignment Statement
Assignment statement canbe defined as the statement throughwhich the
value obtained froman expression can be stored in a variable.
The generalformofassignment statement is
< variable name> = < arithmetic expression> ;
Example: sum = a + b + c;
tot = s1 + s2 + s3;
area = ½ * b* h;
2.7 I/O Control Structure (if, If-else, for, while, do-while)
Conditional Statements
The conditional expressions are mainly used for decision making. The
following statementsare used to performthe task oftheconditionaloperations.
a. ifstatement.
b. If-else statement. Or 2 wayifstatement
c. Nested else-ifstatement.
d. Nested if–else statement.
e. Switch statement.
a. if statement
The if statement is used to express conditionalexpressions. Ifthe given
conditionistruethenit willexecute thestatementsotherwiseskipthestatements.
The simple structure of‘if’statement is
i. If(< condtional expressione>)
statement-1;
(or)
ii. If(< condtional expressione>)
{
Computer Science and Engineering
288
statement-1;
statement-2;
statement-3;
……………
……………
STATEMENT-N
}
The expressionis evaluated and ifthe expressionis truethe statements will
be executed. Ifthe expressionisfalse the statements areskipped and execution
continues withthe next statements.
Example: a=20; b=10;
if ( a > b )
printf(“big numberis %d” a);
b. if-else statements
The if-else statements is used to execute the either ofthe two statements
depending upon the value ofthe exp. The generalformis
if(<exp>)
{
Statement-1;
Statement -2;
………….. “SET-I”
……………
Statement- n;
}
else
{
Statement1;
Statement 2;
289
Paper - II Programming in C
………….. “ SET-II
……………
Statement n;
}
SET - I Statements willbe executed ifthe exp is true.
SET – II Statements willbeexecuted ifthe exp is false.
Example:
if ( a> b )
printf(“a is greater thanb”);
else
printf(“a is not greater thanb”);
c. Nested else-if statements
Ifsome situations ifmaybe desired to nest multiple if-else statements. In
this situationone ofseveraldifferent course ofaction willbe selected.
Syntax
if ( <exp1> )
Statement-1;
else if ( <exp2> )
Statement-2;
else if ( <exp3> )
Statement-3;
else
Statement-4;
When a logical expression is encountered whose value is true the
corresponding statementswillbe executed andthe remainder ofthenested else
ifstatement willbe bypassed. Thus controlwillbe transferred out ofthe entire
nest once a true conditionis encountered.
The finalelse clause willbe applyifnone ofthe exp is true.
Computer Science and Engineering
290
d. nestedif-else statement
It ispossible to nest if-elsestatements, one withinanother.There are several
different formthat nested if-else statements can take.
The most generalformoftwo-layer nesting is
if(exp1)
if(exp3)
Statement-3;
else
Statement-4;
else
if(exp2)
Statement-1;
else
Statement-2;
One complete if-else statement will be executed if expression1 is true
and another complete if-else statement willbeexecuted ifexpression1 isfalse.
e. Switch statement
Aswitchstatement isusedto choosea statement (foragroup ofstatement)
amongseveralalternatives. The switchstatementsisusefulwhenavariableis to
be comparedwithdifferent constants andincase it isequalto a constant a set of
statements are to be executed.
Syntax:
Switch (exp)
{
case
constant-1:
statements1;
case
constant-2:
291
Paper - II Programming in C
statements2;
———
———
default:
statement n;
}
Where constant1, constanat2 — — — are either integer constants or
character constants. Whenthe switchstatement is executed theexpis evaluated
and controlis transferred directly to the group ofstatement whose case label
value matches the value ofthe exp. Ifnone ofthe case labelvalues matches to
the valueofthe exp thenthe default part statements willbe executed.
If none ofthe case labels matches to the value ofthe exp and the default
group is not present then no action will be taken by the switch statement and
controlwillbe transferred out ofthe switch statement.
Asimple switchstatement is illustrated below.
Example 1:
main()
{
char choice;
printf(“EnterYourColor (Red - R/r,White –W/w)”);
choice=getchar();
switch(choice= getchar())
{
case‘r’:
case‘R’:
printf(“Red”);
break;
case‘w’:
case‘W’:
Computer Science and Engineering
292
printf(“white”);
break;
default :
printf(“no colour”);
}
Example2:
switch(day)
{
case 1:
printf(“Monday”);
break;
———
———
}
2.8 Structure for Looping Statements
Loop statements are used to execute the statements repeatedlyas long as
an expression is true. When the expression becomes false then the control
transferred out ofthe loop. There are three kinds ofloops in C.
a) while b) do-while c) for
a. while statement
while loop willbe executed as long as the exp is true.
Syntax: while (exp)
{
statements;
}
The statements willbe executed repeatedlyaslong as the exp istrue. Ifthe
exp isfalse then the controlis transferred out ofthe while loop.
Example:
293
Paper - II Programming in C
int digit = 1;
While (digit <=5) FALSE
{
printf(“%d”, digit);TRUE
Cond Exp
Statements;++digit;
}
The whileloop is top testedi.e., it evaluates theconditionbeforeexecuting
statements in the body. Then it is called entrycontrolloop.
b. do-while statement
The do-while loop evaluates theconditionafter the executionofthe statements
in the body.
Syntax: do
Statement;
While<exp>;
Here also the statements willbeexecuted as long asthe exp value istrue. If
the expressionisfalse the controlcome out ofthe loop.
Example:
-int d=1;
do
{
printf(“%d”, d); FALSE
++d;
} while (d<=5); TRUE
Cond Exp
statements
exit
Computer Science and Engineering
294
The statement withinthe do-while loop willbe executed at least once. So
the do-while loop is calleda bottomtested loop.
c. for statement
The for loop is used to executing the structure number oftimes. The for
loop includesthree expressions. First expressionspecifies aninitialvaluefor an
index (initialvalue), second expression that determines whether or not the loop
is continued(conditionalstatement) and a third expression used to modifythe
index(increment or decrement) ofeachpass.
Note: Generally for loop used when the number of passes is known in
advance.
Syntax: for (exp1;exp2;exp3)
{
Statement –1;
Statement – 2;
—————; FALSE
—————;
Statement - n;TRUE
}
exp2
Statements;
exp3
Exit loop
exp1
start
Whereexpression-1isusedto initializethecontrolvariable.Thisexpression
is executed this expressionis executed is onlyonce at the time ofbeginning of
loop.
Where expression-2 is a logical expression. If expression-2 is true, the
statementswillbeexecuted,otherwisetheloopwillbeterminated.Thisexpression
is evaluatedbefore everyexecution ofthe statement.
295
Paper - II Programming in C
Where expression-3 is an increment or decrement expression after
executing the statements, the controlis transferred back to the expression-3
and updated. There are different formats available in for loop. Some of the
expression ofloop can be omit.
Formate - I
for( ; exp2; exp3 )
Statements;
Inthis format theinitializationexpression(i.e., exp1)is omitted. The initial
value ofthe variable canbe assigned outside ofthe forloop.
Example 1
int i= 1;
for( ; i<=10; i++ )
printf(“%dn”, i);
Formate - II
for( ; exp2 ; )
Statements;
Inthis format the initializationand increment ordecrement expression (i.e
expression-1 and expression-3) are omitted. The exp-3 can be given at the
statement part.
Example 2
int i= 1;
for( ; i<=10; )
{
printf(“%d n”,i);
i++;
}
Formate - III
for( ; ; )
Statements;
Computer Science and Engineering
296
In this format the threeexpressions are omitted. The loop itselfassumes
the expression-2is true. So Statements willbe executed infinitely.
Example 3
int i= 1;
for ( ; i<=10; )
{
printf(“%d n”,i);
i++;
}
2.9 Nested Looping Statements
Manyapplications requirenesting ofthe loop statements,allowing onloop
statement to be embedded withinanother loop statement.
Definition
Nesting canbe defined as themethod ofembedding one controlstructure
withinanother controlstructure.
While making controlstructure s to be reside one within another ,the
inner and outer control structures may be of the same type or may not be of
same type. But ,it is essential for us to ensure that one control structure is
completelyembedded within another.
/*programto implement nesting*/
#include <stdio.h>
main()
{
int a,b,c,
for (a=1,a< 2, a++)
{
printf(“%d”,a)
for (b=1,b<=2,b++)
{
297
Paper - II Programming in C
print f(%d”,b)
for (c=1,c<=2,c++)
{
print f( “ MyName is Sunnyn”);
}
}
}
}
2.10 Multi Branching Statement (switch), Break, and
Continue
For effectivehandling ofthe loopstructures, C allows the following types
ofcontrolbreak statements.
a. Break Statement b. Continue Statement
a. Break Statement
The break statement is used to terminate the controlformthe loops or to
exit froma switch. It canbe used withina for, while, do-while, for.
The generalformat is :
break;
Ifbreakstatement is included ina while, do-whileor forthencontrolwill
immediately be transferred out of the loop when the break statement is
encountered.
Example
for ( ; ;) normal loop
{
break
Condition
withinloop
scanf(“%d”,&n);
if ( n < -1)
Computer Science and Engineering
298
break;
sum= sum + n;
}
b. The Continue Statement
The continuestatement is used to bypass the remainder ofthe current pass
through a loop. The loop does not terminate when a continue statement is
encountered. Rather, theremainingloopstatementsareskippedandtheproceeds
directlyto thenext pass throughtheloop. The “continue” that canbe included
with in a while ado-while and a forloop statement.
Generalform:
continue;
The continue statement is used for the inverse operation of the break
statement .
Condition
withinloop
Remaining part ofloop
continue
Example
while (x<=100)
{
if (x<= 0)
{
printf(“zero ornegative value found n”);
continue;
}
}
The above program segment will process only the positive whenever a
zero or negative value is encountered, the message will be displayed and it
continue thesame loop as long as the givenconditionis satisfied.
299
Paper - II Programming in C
2.11 Differences between Break and Continue
2.12 Unconditional Branching (Go To Statement)
goto statement
The go to statement is used to alter the programexecution sequence by
transferring the controlto some other part ofthe program.
Syntax
Where labelis an identifier used to labelthe target statement to which the
controlwould betransferred the target statement willappear as:
Syntax
goto<label>;
label:
statements;
Break
1. Break is a key word used to
terminate the loop or exit from the
block. The control jumps to next
statement after the loop or block
2. Break statements can be used with
for, while, do-while, and switch
statement. When break is used in
nested loops, thenonly the innermost
loop is terminated.
3. Syntax:{ statement1; statement2;
statement3; break;}
4. Example :Switch( choice){ Case
‘y’: printf(“yes”); break; Case ‘n’:
printf(“NO”); break;}
5. When the case matches with the
choice entered, thecorresponding case
block gets executed. When ‘break’
statement is executed, the control
jumps out ofthe switchstatement.
Continue
1. Continue is a keyword used for
containing the next iteration of the
loop
2. This statement when occurs in a
loopdoesnotterminateit ratherskips
the statements after this continue
statement and the control goes for
next iteration. ‘Continue’canbe used
withfor, while and do- while loop.
3. Syntax: { statement1;
continue; statement2;
statement3; break; }
4. Example:- I = 1, j=0;While( i<=
7){ I= I+1; If((I == 6) Continue;
j = j + 1;}
5. Inthe above loop, whenvalue of‘
i becomes 6’ continue statement is
executed. So, j= j+1 is skipped and
controlis transferred to beginning of
while loop.
Computer Science and Engineering
300
Example 1
#include <stdio.h>
main();
{
inta,b;
printf(“Enterthe two numbers”);
scanf(“%d %d”,&a,&b);
if(a>b)
gotobig;
else
gotosmall;
big :printf(“bigvalue is %d”,a);
gotostop;
small:printf(“smallvalue is %d”,b);
gotostop;
stop;
}
Simple Programs Covering Above Topics
Practice Programs
1. Write a C program to find out smallest value amongA, B,C.
Ans:
include<stdio.h>
int a,b,c;
clrscr();
scanf(%d %d %d, &a, &b, &c);
if(a<b)
{
301
Paper - II Programming in C
if(a<c)
printf(“aissmall/n”)
else
}
02. Write a‘C’ programe for5th multiplication tablewith the help of
goto statement.
Ans.
#include<stdio.h>
main()
{
int t, n = 1, P;
Printf(“Entertablenumber:”);
Scanf(“%d,&t);
A:
if(n<=10)
{
P=t * n;
Printf(“%d * %d= %d n”, t,n,p);
n++;
gotoA;
}
else
printf(“Out ofrange”);
}
03. Write a ‘C’ program to find greatest among three numbers.
Ans. #include<stdio.h>
void main( )
Computer Science and Engineering
302
{
int a,b,c;
printf(“enter thevalues ofa,b,c,”);
scanf(“%d%d%d”, &a,&b,&c);
if((a>b)&&(c>b))
{
if(a>c)
printf(“a isthe maxno”);
else
printf(“C isthe maxno”);
}
else if((b>c)&&(a>c))
{
if(b>a)
printf(“bisthe maxno”);
else
printf(“a isthe maxno”);
}
else if((b>a)&&(c>a))
{
if(b>c)
printf(“bisthe maxno”);
else
printf(“C isthe maxno”);
}
}
303
Paper - II Programming in C
Model Questions
Short Answer Type Question - 2 Marks
1. Write the structure ofC program
2. Define a variable and a constant in C.
3. What is an expression in C.
4. What are the operators used in C.
5. Mentionthe significanceofmain( ) function.
6. What are formatted and Unformatted Input-output statements.
7. Write thesyntaxofscanf() andprintf() statements.
8. Write the syntax do loop controlstructure.
9. Write short notes ongo to statement?
10. Mention difference between While loop and do…While loop.
11.What is Nested Loop?
12. Writethe syntaxof While statement.
13. Write the syntaxoffor…loop statement.
14. Writeabout ‘Switch” Statement.
15. Write the syntaxofSimpleifstatement.
16. Write the syntax of if… else statement.
17. What is Preprocessor statement in C.
18. What are different types oferrors occurred during the execution ofC
program.
19. What is Variable and Constant in C?What are types ofConstants in
C.
20. What are basic data types in C.
21. What is String Constant.
Long Answer Type Questions - 6 Marks
01. Explainthe basic structure ofC program.
02. Write about data types used in C.
Computer Science and Engineering
304
03. What is Constant? Explain various types of constants in C. (or)
04. Explainvarious types ofOperators in C.
05. Explainformattedand un-formatted input and output statements inC
06. Explainvarious conditionalcontrolstructures inC.
07. Explainvarious conditionallooping statements inC.
08. Write the differences between Break and Continue
Note: Practice some more programs relatedusing above statements.
3
UNIT
Functions
Structure
3.0Introduction
3.1 Functions
3.2 Differences betweenFunction and Procedures
3.3Advantages ofFunctions
3.4Advanced features ofFunctions
3.5 Recursion
Learning Objectives
• Define a Function
• Stress on Returnstatement
• Writeprogramsusingfunctioncalltechniques.
• Function prototype
• Differentiate Localand Globalvariables
• Recursion.
Computer Science and Engineering
306
3.0 Introduction
Experienced programmer used to divide large (lengthy) programs in to
parts, and then manage those parts to be solved one by one. This method of
programming approachis to organize thetypicalwork in asystematic manner.
Thisaspect ispracticallyachieved nC language thoroughtheconcept knownas
‘ModularProgramming”.
The entire programis divided into a series ofmodules andeachmodule is
intended to perform a particular task. The detailed work to be solved by the
module is described in the module (sub program) onlyand the main program
only contains a series of modulus that are to be executed. Division ofa main
programinto set ofmodulesandassigningvarioustaskstoeachmoduledepends
ontheprogrammer’s efficiency.
Whereas thereis a need forus repeatedlyexecute oneblock ofstatements
in one place of the program, loop statements can be used. But, a block of
statements need to be repeatedlyexecuted inmany parts ofthe program, then
repeated codingas wellas wastage ofthe vitalcomputerresource memorywill
wasted. . Ifwe adopt modular programming technique, these disadvantages
can be eliminated. The modules incorporated in C are called as the
FUNCTIONS, and each function in the program is meant for doing specific
task. C functions are easyto use and veryefficient also.
3.1 Functions
Definition
A function can be defined as a subprogram which is meant for doing a
specific task.
InaCprogram, afunctiondefinitionwillhavename,parenthesespaircontain
zero or more parameters and a body. The parameters used in the parenthesis
need to bedeclared with type and ifnot declared, theywillbeconsidered as of
integer type.
The generalformofthe functionis :
function type name <arg1,arg2,arg3, ————,argn>)
data type arg1, arg2,;
data type argn;
{
bodyoffunction;
307
Paper - II Programming in C
——————————
——————————
——————————
return(<something>);
}
Fromthe aboveformthe main componentsoffunctionare
• Returntype
• Functionname
• Functionbody
• Returnstatement
Return Type
Refers to the type of value it would return to the calling portion of the
program. It can have any of the basic data types such as int, float, char, etc.
When afunction is not supposedto returnanyvalue, it maybe declaredas type
void
Example
void function name(- - - - - - - - - -);
int function name( - - - - - - - - - - );
char function name ( — - - - - - - );
Function Name
The function name can be anyname conforming to the syntaxrules ofthe
variable.
Afunctionname is relevant to the functionoperation.
Example
output();
read data( );
Computer Science and Engineering
308
Formalarguments
The arguments are called formal arguments (or) formal parameters,
because they represent the names of data items that are transferred into the
functionfromthe calling portionoftheprogram.
Any variable declared in the bodyof a function is said to be localto that
function,othervariablewhichwerenotdeclaredeitherargumentsorinthefunction
body, are considered “globol” to the function and must be defined externally.
Example
int biggest (int a, int b)
{
————————————
————————————
————————————
return();
}
a, b are the formalarguments.
FunctionBody
Function bodyis a compound statement defines the action to be taken by
the function. It shouldincludeone or more“return”statement inorderto return
a valueto the calling portionofthe program.
Example
int biggest(int a, int b)
{
if ( a > b)
return(a);bodyoffunction.
else
return(b);
}
309
Paper - II Programming in C
EveryCprogramconsists ofoneor morefunctions. Oneofthese functions
must be called asmain.Executionofthe programwillalwaysbeginbycarrying
out the instructionsinmain.Additionalfunctionswillbesubordinateto main. Ifa
programcontains multiplefunctions, their definitions mayappearin anyorder,
thoughtheymust be independent ofone another. That is, one functiondefinition
can’t be embedded within another.
Generallya function willprocess informationthat is passed to it fromthe
calling portionofthe programand returna single value. Informationispassedto
thefunctionviaarguments(parameters)andreturnedviathe“return”statement.
Some functions accept informationbut do not returnanything(ex:printf())
whereas other functions (ex:scanf()) returnmultiple values.
3.1.1 The Return Statement
EveryfunctionsubprograminC willhave returnstatement. This statement
isusedinfunctionsubprogramsto returnavalueto thecallingprogram/function.
This statement can appear anywhere withina function bodyand we mayhave
more thanone returnstatement insidea function.
The generalformat ofreturnstatement is
return;
(or)
return (expression);
Ifno valueis returnedfromfunctionto the calling program, thenthere is no
need ofreturnstatement to be present inside the function.
Programs using function CallTechniques
Example 1: Write a programto find factorialto thegivenpositive integer
,usingfunctiontechnique.
# include <stdio.h>
main()
{
int n;
printf ( “ Enter any positive numbern”);
scanf( “%d”, &n);
Computer Science and Engineering
310
printf( “ The factorialof%d s %d n”,fact (n));
}
fact( i)
int I;
{
int j; f = 1 ;
for ( j = I; j>0; j - -)
f = f * I;
return ( f ) ;
}
Intheaboveprogramfunctionwithname‘fact’iscalledbythemainprogram.
The function fact is called with n as parameter. The value is returned through
variable fto the mainprogram.
Example 2: Write a programto find the value off(x) as f(x) = x2
+ 4, for
the givenofx. Make useoffunctiontechnique.
# include <stdio.h>
main( )
{
f ( );
}
f ( )
{ int x,y ;
printf( “Enter value ofx n”);
scanf( “ %d”, & x );
y = (x * x + 4);
printf ( “ The value off (x) id %d n”, y) ;
}
311
Paper - II Programming in C
3.2 Differences between Function and Procedures
3.3 Advantages of Function
The main advantages of using a function are:
• Easyto writea correct smallfunction
• Easyto read and debug a function.
• Easier to maintainor modifysucha function
• Smallfunctions tendto be selfdocumentingand highlyreadable
• It canbe called anynumberoftimes in anyplace withdifferent
parameters.
Storage class
Avariable’s storage class explains where the variable will be stored, its
initialvalue andlife ofthe variable.
Iteration
TheblockofstatementsisexecutedrepeatedlyusingloopsiscalledIteration
Procedure
1. Procedureis a subprogram
which is included with in
main program.
2. Procedure donot return a
value.
3. Procedure cannot be
called again and again.
4. Global variables cannot be
used in procedure.
5. Procedures can be writ-
ten only in procedural pro-
gramming such as Dbase,
Foxpro.
Function
1. Functions is sub program
which is intended for specific
task. Eg. sqrt()
2. Functions may or may not
return a value.
3. Function once defined can
be called any where n number
oftimes.
4. In functions both local and
global variables can be used.
5. Functions can be written in
modular programming such as
C,C++
Computer Science and Engineering
312
Categories of Functions
A function, depending on, whether arguments are present or not and a
value is returned or not.
Afunctionmaybe belonging to one ofthe following types.
1. Functionwithno arguments and no returnvalues.
2. Functionwitharguments and no returnvalues.
3. Functionwitharguments and returnvalues
3.4 Advanced Featured of Functions
a. Function Prototypes
b. Calling functions byvalueor byreference
c. Recursion.
a. Function Prototypes
The user defined functions maybe classified as three ways based on the
formalarguments passed andthe usage ofthe returnstatement.
a. Functions withno arguments andno return value
b. Functions witharguments no returnvalue
c. Functions witharguments and returnvalue.
a. Functions with no arguments and no return value
Afunctionisinvokedwithout passinganyformalargumentsfromthecalling
portionofa programand alsothe functiondoes not returnback anyvalueto the
called function. There is no communication between the calling portion of a
programand a called functionblock.
Example:
#include <stdio.h>
main()
{
void message( ); Function declaration
message( ); Function calling
}
313
Paper - II Programming in C
void message( )
{
printf(“GOVT JUNIOR COLLEGE n”);
printf(“t HYDERABAD”);
}
b. Function with arguments and noreturn value
This typeoffunctions passes someformalarguments to a function but the
function does not return back any value to the caller. It is any one way data
communicationbetweena callingportionoftheprogramandthefunctionblock.
Example
#include <stdio.h>
main()
{
void square(int);
printf(“Enter a value for nn”);
scanf(“%d”,&n);
square(n);
}
void square (int n)
{
int value;
value = n * n;
printf(“square of%d is %d “,n,value);
}
c. Function with arguments and return value
The thirdtypeoffunctionpassessome formalargumentsto afunctionfrom
a calling portionofthe programand the computer value is transferred back to
the caller. Data are communicated betweenthe calling portion andthe function
block.
Computer Science and Engineering
314
Example
#include <stdio.h>
main()
{
int square (int);
int value;
printf(“enter avalue for n n”);
scanf(“%d”, &n);
value = square(n);
printf(“square of%d is %d “,n, value);
}
int square(int n)
{
int p;
p = n * n;
return(p);
}
ThekeywordVOIDcanbeusedasatypespecifierwhendefiningafunction
that does not return anything or when the function definitiondoes not include
anyarguments.
Thepresenceofthiskeywordisnot mandatorybut itis goodprogramming
practice to make use ofthis feature.
Actual and FormalParameters (or)Arguments
Function parameters arethe means ofcommunicationbetweenthe calling
and the calledfunctions. The parameters mayclassifyunder two groups.
1. FormalParameters
2. ActualParameters
315
Paper - II Programming in C
1. Formal Parameters
Theformalparametersare the parameters giveninfunctiondeclarationand
function definition. When the function is invoked, the formal parameters are
replaced bythe actualparameters.
2. Actual Parameters
The parameters appearing in the function call are referred to as actual
parameters. Theactualargumentsmaybeexpressedasconstants, singlevariables
or more complex expression. Each actualparameter must be ofthe same data
type as itscorresponding formalparameters.
Example
#include <stdio.h>
int sum(int a , int b )
{
int c;
c = a + b;
return(c);
}
main()
{
intx,y,z;
printf(“enter valuefor x,yn”);
scanf(“%d %d”,&x,&y);
z = x + y;
printf(“sumis = %d”,z);
}
The variables a and b defined infunction definition are knownas formal
parameters. The variables x and y are actualparameters.
Computer Science and Engineering
316
Local and GlobalVariable:
The variables maybe classified as localor globalvariables.
Local Variable
The variables defined canbe accessed onlywithin the block in which they
are declared. These variables are called “Local” variables
Example
funct (int ,int j)
{
intk,m;
————;
————;
}
The integer variables k and m are defined within a function block ofthe
“funct()”. All the variables to be used within a function block must be either
defined at the beginning of the block or before using in the statement. Local
variables one referred onlythe particular part ofa block ofa function.
GlobalVariable
Globalvariables definedoutside the mainfunctionblock. Globalvariables
are not contained to a single function. Global variables that are recognized in
two ormore functions. Their scopeextends fromthe pointofdefinitionthrough
the remainderofthe program.
b. Calling functions by value or by reference
The arguments are sent to the functions and their values are copied in the
corresponding function. This is a sort ofinformation inter changebetweenthe
calling functionandcalled function. This isknown as Parameter passing. It is a
mechanismthroughwhich arguments are passed to the called functionfor the
required processing. There are two methods ofparameter passing.
1. CallbyValue
2. Callbyreference.
1. Callby value: When thevalues ofarguments are passed fromcalling
functionto a called function, thesevalues are copied into the calledfunction. If
317
Paper - II Programming in C
any changes are made to these values in the called function, there are
NOCHANGE theoriginalvalues withinthecalling function.
Example
#include <stdio.h>
main();
{
int n1,n2,x;
int cal_by_val();
N1 = 6;
N2 = 9;
printf( n1 = %d and n2= %dn”, n1,n2);
X = cal_by_Val(n1,n2);
Printf( n1 = %d and n2= %dn”, n1,n2);
Printf(“x=%dn”, x);
/ * end of main*/
/*functionto illustratecallbyvalue*/
Cal_by_val(p1,p2)
int p1,p2;
{
int sum;
Sum = (p1 + p2);
P1 + = 2;
P2* = p1;
printf( p1 = %d and p2= %dn”, p1,p2);
return( sum);
}
}
Computer Science and Engineering
318
When the programis executed the output willbe displayed
N1 = 6 and n2 = 9
P1 = 8 and p2 = 72
N1 = 6 and n2 = 9
X = 15
There is NO CHANGE in the values of n1 and n2 before and after the
functionis executed.
2. Cal by Reference: In this method, the actualvalues are not passed,
instead their addresses are passed. There is no copying of values since their
memory locations are referenced. Ifanymodification is made to the values in
the calledfunction, thentheoriginalvaluesgetchangedwithinthecallingfunction.
Passing ofaddresses requires the knowledge ofpointers.
Example
This programaccepts a one-dimensionalarrayofintegers and sorts them
inascendingorder. [This programinvolves passing the arrayto the function].
# include <stdio.h>
main();
{
int num[20], I,max;
void sort_nums();
printf( “enter the size ofthe array”n”);
scanf(“%d”, &max);
for( i=0;i<max;I++)
sort_nums(num,max) /* Function reference*/
printf(“sorted numbers are as followsn”);
for( i=0;i<max;I++)
printf(“%3dn”,num[i]);
/* end of the main*/
/* functionto sort list ofnumbers*/
319
Paper - II Programming in C
Void sort_nums(a,n)
Int a[],n;
{
Int I,j,dummy;
For(i=0;i<n;i++)
{
For(j=0; j<n; j++)
{
If( a[i] >a[j])
{
Dummy= a[i];
a[i] = a[j];
a[j] = dummy;
}
}
}
}
3.5 Recursion
One ofthe specialfeatures ofC language is its support to recursion. Very
few computer languageswillsupport this feature.
Recursion can be defines as the process of a function by which it can call
itself. Thefunction whichcalls itselfagainand againeither directlyor indirectly
is knownas recursive function.
The normalfunction is usuallycalled bythe main ( ) function, bymans of
its name. But, the recursive function willbe called by itselfdepending on the
conditionsatisfaction.
For Example,
main( )
{
Computer Science and Engineering
320
f1( ) ; ——— Function called by main
——————
——————
——————
}
f1( ) ; ——— Function definition
{
——————
——————
——————
f1( ) ; ——— Function called by itself
}
In the above, the main ( ) function s calling a function named f1( ) by
invoking it withits name. But, insidethefunctiondefinitionf1(), thereisanother
invoking offunctionand it is the functionf1( ) again.
Example programs on Recursion
Example 1 : Write a programto find the factorialofgiven non-negative
integerusingrecursive function.
#include<stdio.h>
main( )
{
int result, n;
printf( “Enteranynon-negative integern”);
scanf( “%d”, & n);
result = fact(n);
printf( “ The factorialof%d is %d n”, n, result);
}
321
Paper - II Programming in C
fact( n )
int n;
{
int i;
i = 1;
if( i = = 1) return ( i);
else
{
i = i * fact ( n - 1);
return( i);
}
}
Example 2: Write ‘C’programto generate Fibonacci series up to a limit
using recursionfunction. .
#include<stdio.h>
#include<conio.h>
int Fibonacci(int);
void main( )
{
int i, n;
clrscr ( );
printf(“Enterno. ofElements to be generated” n)
scanf(“%d”, &n);
for (i=1;i<n; i++)
printf(“%d”, Fibonacci(i));
getch( );
}
Computer Science and Engineering
322
int Fibonacci(int n)
{
int fno;
if(n= =1)
return1;
else
if(n= =2);
return 1;
else
fno=Fibonacci (n-1) + Fibonacci(n-2);
returnfno;
}
Model Questions
Short Answer Type Question - 2 Marks
01. What is function?Write its syntax.
02. What is I/O function?List different types of I/O functions
03. What are the advantages offunctions?
04. Write differences between Globaland Localvariables.
05. List categories offunctions
06. What is storage class?
07. What is Iteration
08. What is recursion?
Long Answer Type Question - 6 Marks
01. What is Function?Explain in detail
02. Explaindifferent types offunctions withanexample.
03. Explain about I/O functions.
04. Discuss about Globaland Localvariables.
323
Paper - II Programming in C
05. Explain about Call-by-value with an example.
06. Explain about Call-by-reference with an example.
07. Discuss about Functions and Procedures..
Computer Science and Engineering
324
4
UNIT
Arrays in ‘C’
Structure
4.0Introduction
4.1 DefinitionofArray
4.2 Types ofArrays
4.3 Two - DimensionalArray
4.4 Declare, initializearrayofchar type
Learning Objectives
• To understand theimportance ofArray
• Definitionofarray
• Declarationand InitializingofanArray
• Types ofArrays
• Examples ofanArray
4.0 Introduction
Ifwe dealwithsimilar type ofvariables inmore number at atime, we may
have to writelengthyprogramsalongwithlong list ofvariables. There shouldbe
325
Paper - II Programming in C
morenumberofassignmentstatementsinorderto manipulateonvariables. When
the number ofvariables increases, the length ofprogramalso increase.
Intheabove situationsdescribed above, where more number ofsame types
ofvariablesisused, theconceptofARRAYSis employedinC language. These
are verymuchhelpfulto store as wellas retrieve the data ofsimilar type.
AnArraydescribesa contiguouslyallocated non-emptyset ofobjects with
the same data type. The using arrays many number ofsame type of variables
can be grouped together.Allthe elements stored in the arraywillreferred bya
commonname.
4.1 Definition of Array
Array can be defined as a collection of data objects which are stored in
consecutive memorylocations witha commonvariable name.
OR
Array can be defined as a group of values referred by the same variable
name.
OR
AnArraycanbe defined as acollection ofdata objects whichare stored in
consecutive memorylocations witha commonvariable name.
The individualvalues present in thearrayare called elements ofarray. The
arrayelements can be values or variables also.
4.2 Types of Arrays
Basicallyarrays candivide in to
1. One DimensionalArray
Anarraywithonlyone subscript is called as one-dimensional array or 1-
d array. It is used to store a list ofvalues, all ofwhich share a common name
and are separable bysubscript values
2. Two DimensionalArray
An arraywith two subscripts is termed as two-dimensionalarray.
Atwo-dimensional array, it has a list of given variable -name using two
subscripts. Weknow that a one-dimensionalarraycan store a row ofelements,
so, a two-dimensionalarrayenables us to store multiple rows ofelements.
Computer Science and Engineering
326
4.2.1 Initialization of Array
Arraycanbe made initialized at the time ofdeclarationitself. The general
formofarrayinitializationis as below
type name[n]= [ element1, element2, …. element n];
The elements 1, element2… element narethe values oftheelements inthe
arrayreferenced bythe same.
Example1:- int codes[5] = [ 12,13,14,15,16];
Example2:- float a[3] = [ 1.2, 1.3, 1.4];
Example3:- char name [5] = [ ‘S’, ‘U’, ‘N’, ‘I’, ‘L’];
Inabove examples, let us consider one, it a character arraywith5 elements
and all the five elements area initialized to 5 different consecutive memory
locations.
name[0] = ‘S’
name[1] = ‘U’
name[2] = ‘N’
name[3] = ‘I’
name[4] = ‘L’
Rules forArray Initialization
1. Arrays areinitialized withconstants only.
2. Arrayscanbe initialized without specifying the number ofelements in
squarebracketsandthis number automaticallyobtainedbythecompiler.
3. The middle elements ofan arraycannot be initialized. Ifwe want to
initializeanymiddleelement thenthe initializationofpreviouselementsis
compulsory.
4. Ifthearrayelements are not assigned explicitly, initialvalueswillbe set
to zero automatically.
5. Ifalltheelements in the arrayare to be initialized withone and same
value, then repletionofdata is needed.
327
Paper - II Programming in C
4.2.2 Declaration of Array
The array must be declared as other variables, before its usage in a C
program. The arraydeclarationincludedprovidingofthe following information
to C compiler.
- The type of the array (ex. int, float or char type)
- The name of the array ( exA[ ],B[ ] , etc)
- Number ofsubscripts in the array ( i.e whether one – dimensional
orTwo-dimensional)
- Totalnumber ofmemorylocations to be allocated.
The nameofthe arraycanbe kept bytheuser (the rule similarto naming to
variable).
Thereis no limit one ondimensionsas wellas numberofmemorylocations
and it depends o the capacityofcomputer main memory..
The general formfor array declaration is
Type name[n] ; { one dimensionalarray}
Ex : int marks[20];
char name[15];
float values [ 10];
Anarray with onlyone subscript is called as one-dimensional array or
1-d array. It is used to store a list ofvalues, allofwhich sharea commonname
and are separable bysubscript values.
Declaration ofOne-dimensionalArrays:
The generalformofdeclaring aone-dimensionalarrayis
Wheredata-typerefers to anydatatypesupported byC,array-nameshould
beavalidCidentifier;thesizeindicatesthemaximumnumberofstoragelocations
(elements) that can be stored.
Each element in the array is referenced by the array name followed by a
pairofsquarebracketsenclosingasubscript value. Thesubscriptvalueisindexed
array-name [size];
data-type
Computer Science and Engineering
328
from 0 to size -1. When the subscript vale is 0, first element in the array is
selected, when the subscript value is 1, second element is selected and so on.
Example
int x [6];
Here, xis declared to beanarrayofint type and ofsize six. Sixcontiguous
memorylocations get allocated as shownbelow to store sixinteger values.
Each dataitemin the arrayx is identified bythe arrayname xfollowed by
a pair of square brackets enclosing a subscript value. The subscript value is
indexed from0to 5. i.e., x[0] denotes first data item, x[1] denotes second data
itemand x[5] denotes the last data item.
Initialization ofOne-DimensionalArrays:
Just as we initialize ordinaryvariables, we can initialize one-dimensional
arraysalso, i.e.,locationsofthearrayscanbegivenvalueswhiletheyaredeclared.
The generalformofinitializing anarrayofone-dimensionis as follows:
data - type array - name [size] = {list ofvalues};
The values in the list are separated bycommas.
Example
int x [6] = {1, 2, 3, 4, 5, 6 };
as a result ofthis, memorylocationsofx get filled up as follows:
Points to be considered during the declaration
1. Ifthenumberofvalues ininitializationvalue - isless thenthe sizeofan
array, onlythose manyfirst locations ofthe arrayare assigned the values. The
remaining locationsare assigned zero.
Example: int x [6] = {7, 8, 6 };
The size of the array x is six, initialization value - consists of only three
locations get 0 assigned to themautomatically, as follows:
1 2 3 4 5 6
x[0] x[1] x[2] x[3] x[4] x[5]
1 2 3 4 5 6
x[0] x[1] x[2] x[3] x[4] x[5]
329
Paper - II Programming in C
2. Ifthe number ofvalues listed within initialization value - list for any
arrayis greater than the sixthe array, compiler raises an error.
Example:
int x [6] = {1, 2, 3, 4, 5, 6, 7, 8 };
The size of the array x is six. But the number of values listed within the
initialization-list is eight. Thisisillegal.
3. Ifa static arrayis declared without initializationvalue - list thenthe all
locations are set to zero.
Example:
static int x[6];
4. If size is omitted in a 1-d array declaration, which is initialized, the
compilerwillsupplythisvaluebyexaminingthenumberofvaluesintheinitialization
value - list.
Example:
int x [ ] = {1, 2, 3, 4, 5, 6 };
Sincethenumberofvaluesintheinitializationvalue-list for thearrayxissix,
the size ofx is automaticallysupplied as six.
5. There is no arraybound checking mechanismbuilt into C-compiler. It
is the responsibilityofthe programmer to see to it that the subscript value does
not go beyond size-1. Ifit does, the system maycrash.
Example:
int x [6];
x [7] = 20;
7 8 6 0 0 0
x[0] x[1] x[2] x[3] x[4] x[5]
0 0 0 0 0 0
x[0] x[1] x[2] x[3] x[4] x[5]
0 0 0 0 0 0
x[0] x[1] x[2] x[3] x[4] x[5]
Computer Science and Engineering
330
Here, x [7] does not belong to the array x, it may belong to some other
program(forexample, operating system) writinginto the location maylead to
unpredictable results oreven to systemcrash.
6. Arrayelements cannot be initialized selectively.
Example:
Anattempt to initialize only2nd locationis illegal, i.e.,
int x [6] = { , 10 } is illegal.
Similar to arraysofint type, wecanevendeclare arrays ofother data types
supported byC, also.
Example
char ch [6];
chisdeclaredto beanarrayofchartypeand size 6 andit canaccommodate
6 characters.
Example:
float x[6];
xisdeclared to be anarrayoffloat typeand size 6 andit canaccommodate
6 values of float type. Following is the scheme of memory allocation for the
arrayx:
Note
Aone array is used to store a group ofvalues. Aloop (using, for loop) is
used to access each value inthe group.
Example
Programto illustrate declaration, initializationofa 1-d array
#include<stdio.h>
ch[0] ch[1] ch[2] ch[3] ch[4] ch[5]
x[0] x[1] x[2] x[3] x[4] x[5]
331
Paper - II Programming in C
#include<conio.h>
void main( )
{
int i, x [6] = {1, 2, 3, 4, 5, 6 };
clrscr( );
printf(“The elements ofarrayxn”);
for(i=0; i<6; i++)
printf(“%d”, x[i]);
getch( );
}
Input– Output:
The elements ofarrayx
1 2 3 4 5 6
4.3 Two - Dimenstional Array
An arraywithtwo subscripts is termedas two-dimensionalarray.
Atwo-dimensional array, it has a list of given variable -name using two
subscripts. Weknow that a one-dimensionalarraycan store a row ofelements,
so, a two-dimensionalarrayenables us to store multiple rows ofelements.
Example: Table ofelementsor a Matrix.
Syntaxoftwo-dimensionalarrays:
The syntaxofdeclaring a two-dimensionalarrayis:
data - type array - name [rowsize] [ colsize];
Where, data-type refers to anyvalid C data type, array-name refers to
anyvalid Cidentifier, row size indicatesthe number ofrows and columnsize
indicates thenumber ofelements ineach column.
Row sizeand column size shouldbe integer constants.
Totalnumber oflocation allocated = (row size * column size).
Computer Science and Engineering
332
Each element in a 2-d array is identified by the arrayname followed by a
pair ofsquare brackets enclosing itsrow-number, followed bya pair ofsquare
brackets enclosing its column-number.
Row-number range from0 to row size-1 and column-number range from
0 to column size-1.
Example: int y[3] [3];
y is declared to be an array of two dimensions and of data type Integer
(int), row size and column size of y are 3 and 3, respectively. Memory gets
allocated to store the array y as follows. It is important to note that y is the
common name shared byallthe elements ofthe array.
Each data itemin the arrayyis identifiable byspecifying the arrayname y
followed byapair ofsquare bracketsenclosing row number, followedbya pair
ofsquare bracketsenclosing column number.
Row-number ranges from 0 to 2. that is, first row is identified by row-
number 0, second row is identified byrow-number 1 and so on.
Similarly, column-numberranges from0 to 2. First columnisidentified by
column-number 0, second columnis identified bycolumn-number 1 andso on.
x [0] [0] refers to data itemin the first row and first column
x [0] [2] refers to data itemin the first row and third column
x [2] [3]refers to data itemin the third rowand fourthcolumn
x [3] [4] refers to data itemin the fourthrowand fifthcolumn
Initialization ofTwo-DimensionalArray
There are two forms ofinitializinga 2-d array.
First formofinitializing a 2-d arrayis as follows:
x[0] [0] x[0] [1] x[0] [2]
x[1] [0] x[1] [1] x[1] [2]
x[2] [0] x[2] [1] x[2] [2]
0 1 2
Row
num
bers
.
1
2
3
Columnnumbers
333
Paper - II Programming in C
Where, data-name refers to any data type supported by C. Array-name
refers to anyvalid C identifier. Row size indicates the number ofrows, column
size indicates the number of columns of the array. initialier-list is a comma
separated list ofvalues.
Ifthe number ofvalues in initializer-list is equalto the product ofrow size
and columnsize, the first row sizevalues inthe initializer-list willbe assigned to
the first row, the second row size values willbe assigned to the second row of
the arrayand so on
Example: int x [2] [4] = {1, 2, 3, 4, 5, 6, 7, 8 };
Since columnsizeis 4, the first 4 values ofthe initializer-list are assigned to
the first row of x and the next 4 values are assigned to the second row of x as
shownhereinafter
1 2 3 4
5 6 7 8
Note: Ifthenumber ofvalues inthe initializer-list is less thanthe product of
rowsizeand colsize, onlythe first fewmatching locations ofthearraywould get
values fromtheinitializer-list row-wise. The trailingunmatched locations would
get zeros.
Example: int x [2] [4] = {1, 2, 3, 4};
Thefirst rowofxgets filledwiththevalues intheinitializer-list. Thesecond
row getsfilled withzeros.
1 2 3 4
0 0 0 0
The second formofinitializing a 2-d arrayis as follows:
data-type array-name[rowsize] [colsize]
= {{initializer-list1},
{initializer-list2}, ………};Thevaluesininitializer-
list 1 are assigned to the locations inthe first row. The values ininitializer-list2
are assigned to the locations in the second row and so on.
Example: int x [2] [4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
data - type array- name [rowsize][colsize] = [initializer - list];
Computer Science and Engineering
334
As a result ofthis, the arrayx gets filledup as follows:
1 2 3 4
5 6 7 8
Note
1. Ifthenumberofvaluesspecifiedinanyinitializer-list islessthancolsize
ofx, onlythose may first locations in the corresponding row would get these
values. The remaininglocations inthat rowwould get 0.
Example: int x [2] [4] = { { 1, 2, 3 }, { 4, 5, 6, 7 } };
Since the first initializer-list has onlythree values, x[0][0] is set to 1, x [0]
[1] is set to 2, x [0] [2] is set to 3 and the fourth location in the first row is
automaticallyset to 0.
1 2 3 0
4 5 6 7
2. Ifthenumberofvaluesspecifiedinanyinitializer-list ismorethancolsize
ofx, compiler reports an error.
Example: int x [2] [4] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9 } };
colsize is4, but the numberofvalues listed inthe first row is 5. This results
incompilationerror.
3. Arrayelements cannot be initialized selectively.
4. It istheresponsibilityoftheprogrammerto ensurethatthearraybounds
do not exceedtherowsize andcolsizeofthe array. Iftheyexceed, unpredictable
results may be produced and even the program can result in system crash
sometimes.
5. A 2-d arrayis used to store a table ofvalues (matrix).
Similar to 2-darrays ofint type, we candeclare 2-arrays ofanyother data
type supported byC, also.
Example: float x[4] [5];
x is declared to be 2-d array of float type with 4 rows and 5 columns
double y[4] [5];
y is declared to be 2-d arrays of double type with 4 rows and 5 columns
Note
335
Paper - II Programming in C
A two-dimensional array is used to store a table of values. Two loops
(using for loops) are used to access each value inthe table, first loop acts as a
row selector and second loop acts as a column selector in the table.
4.4 Declare, Initialize Array of Char Type
DeclarationofArrayofchartype: AstringvariableisanyvalidCvariable
name and is always declared as an array. The syntax ofdeclaration of a string
variableis:
char string-name[size];
The size determines the number ofcharacter inthe string name.
Example: An arrayofchar type to store the above string isto be declared
asfollows:
char str[8];
Anarrayofchar is also called as a stringvariable, since it canstore a string
and it permits us to change its contents. In contrast, a sequence of characters
enclosed withina pair ofdoublequotes is called astring constant.
Example: “Program” isa string constant.
Initialization ofArrays of charType
The syntaxofinitializinga string variablehastwo variations:
Variation 1
char str1 [6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’};
Here, str1 is declared to be a string variable with size six. It can store
maximum six characters. The initializer – list consists of comma separated
character constants. Note that the nullcharacter ‘0’ is clearly listed. This is
required inthis variation.
Variation 2
char str2 [6] = { “Hello” };
Here, str2 is also declared to be a string variable of size six. It can store
maximumsixcharactersincluding nullcharacter. The initializer-list consists ofa
str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7]
P r o g r a m 0
Computer Science and Engineering
336
string constant. Inthis variation, nullcharacter ‘0’willbeautomaticallyadded
to the end ofstring bythe compiler.
In either ofthese variations, the sizeofthe character arraycanbe skipped,
in which case, the size and thenumber ofcharacters inthe initializer-list would
be automaticallysupplied bythe compiler.
Example
char str1 [ ] = { “Hello” };
The size ofstr1 would be six, five characters plus one forthe nullcharacter
‘0’.
char str2 [ ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’};
The size ofstr2 would be six, five characters plus one for null character
‘0’.
Example 1
Program to sort a list of numbers.
#include<stdio.h>
#include<conio.h>
void main( )
{
int x [6], n, i, j, tmp;
clrscr( );
printf(“Enter theno. ofelements n”);
scanf(“%d”, & n);
printf(“Enter %d numbers n”, n);
for (i=0;i<n; i++)
scanf(“%d”, &x [i]);
/* sortingbegins */
for (i=0;i<n; i++)
for (j=i + 1; j<n; j++)
if(x[i]>x[j])
337
Paper - II Programming in C
{
tmp = x [i];
x [i] = x [j];
x [j] = tmp;
}
/* sorting ends */
printf(“sortedlist n”);
for (i=0;i<n; i++)
printf(“%d”, x[i]);
getch( );
}
Input–Output
Enter the no. ofelements
5
Enter 5 numbers
10 30 20 50 40
Sorted list
10 20 30 40 50
Example 2 :
C program foraddition of two matrices.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main( )
{
int x [5] [5], y [5] [5], z [5] [5], m, n, p, q, i, j;
Computer Science and Engineering
338
clrscr ( );
printf(“Enter numberofrows and columns ofmatrixx n”);
scanf(“%d %d”, &m, &n);
printf(“Enter numberofrows and columns ofmatrixyn”);
scanf(“%d %d”, &p, &q);
if((m !=P) | | (n!=q))
{
printf(“Matrices not compatible for additionn”);
exit(1);
}
printf(“Enter theelements ofxn”);
for (i=0;i<m; i++)
for (j=0; j<n; j++)
scanf(“%d”, &x[i][j]);
printf(“Enter theelements ofxn”);
for (i=0;i<p; i++)
for (j=0; j<n; j++)
scanf(“%d”, &y[i] [j]);
/* Summationbegins */
for (i=0;j<m; i++)
for (j=0; j<n; j++)
z[i] [j] = x [i] [j] + y [i] [j];
/* summationends */
printf(“Summatrixzn);
for (i=0;i<m; i++)
{
for (j=0; j<n; j++)
339
Paper - II Programming in C
printf(“%d”, z[i] [j]);
printf(“n”);
}
getch( );
}
Example3
Write a programfor multiplication oftwo matrices.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main( )
{
int x [5] [5], y [5] [5], z [5] [5], m, n, p, q, I, j, k;
clrscr ( );
printf(“Enter numberofrows and columns ofmatrixx n”);
scanf(“%d %d”, &m, &n);
printf(“Enter numberofrows and columns ofmatrixyn”);
scanf (%d %d”, &p, &q);
if(n!=p)
{
printf(“Matrices not compatible formultiplicationn”);
exit (1);
}
printf(“Enter theelements ofxn”);
for (i=0;i<m; i++)
for (j=0; j<n; j++)
scanf(“%d”, &x [i] [j]);
Computer Science and Engineering
340
printf(“Enter the elements ofyn”);
for (i=0;i<p; i++)
for (j=0; j<q; j++)
scanf(“%d”, &x [i] [j]);
printf(“Enter the elements ofyn”);
for (i=0;i<p; i++)
for (j=0; j<q; j++)
scanf(“%d”, &y[i] [j]);
/* Multiplication ofmatrices ofx 7 yends */
for (i=0;i<m; i++)
for (j=0; j<q; j++)
{ z [i] [j] = 0;
for (k=0; k<n; k++)
z [i] [j] + = x [i] [k] * y [k] [j];
}
/* Multiplication ofmatrices ofx &yends */
printf(“Product Matrixzn”);
for (i=0;i<m; i++)
{
for (j=0; j<q; j++)
printf(“%d”, z[i] [j]);
printf(“n”);
}
getch( );
}
341
Paper - II Programming in C
Example 4: C program to print transpose of a matrix.
[The transpose ofa matrix isobtained byswitching therows and columns
ofmatrix].
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3] [3], b[3] [3], i, j;
clrscr ( );
printf(“Enterthe elements ofthematrix: n”);
for (i=0;i<3; i++)
for (j=0; j<3; j++)
scanf(“%d”, &a[i] [j]);
printf(“givenmatrixis :n”);
for (i=0;i<3; i++)
{
for (j=0; j<3; j++)
printf(“%d”, a[i] [j]);
printf(“n”);
}
printf(“transposeofgivenmatrixis: n”);
for (i=0;i<3; i++)
{
for (j=0; j<3; j++)
{
b [i] [j] = a [j] [i];
printf(“%d”, b[i] [j]);
Computer Science and Engineering
342
printf(“n”);
}
}
getch( );
}
Example 5
Write a ‘C’ program to find the average marks of ‘n’ students of
five subjects for each subject using arrays.
Ans.
#include <stdio.h>
void main( )
{
int Sno, S1,S2,S3;
float tot, avg;
char sname[10];
printf(“Enterstudent no;”);
scanf(“%d”, & Sname);
printf(“Enter subject - 1, sub - 2, sub - 3 marks;”);
scanf(“%d %d %d”, &s1,&s2,&s3);
tot = S1+S2+S3;
avg = tot/3;
printf(“total=%f”, tot);
printf(“Average =%f”, avg);
}
Example 6
Write a C program to check the given word is ‘Palindrome’ or not.
Ans.
#include<stdio.h>
343
Paper - II Programming in C
#include<conio.h>
void main( )
{
char str[80], rev[80];
int k, i, j, flag = 0;
clrscr ( );
printf(“Enter anystring (max. 80 chars) : n”);
gets(str);
for (i=0;str[i]!= ‘0’; i++);
for (j=i-1; k=0; j>=0; j—, k++)
rev[k] = str[j];
rev[k] = ‘0’;
for (i=0;str[i]!= ‘0’; i++)
{
if(str[i]!=rev[i])
{
flag=1;
break;
}
}
if(flag = =1);
printf(“Givenstringis not palindrome. n”);
else
printf(“Givenstringispalindrome. n”);
getch( );
}
Computer Science and Engineering
344
4.5 String Handling Functions in ‘C’
To performmanipulationsonstring data, thereare built-in-fraction(library
function) Supportedby‘c’compiler. Thestring functions are.
1. STRLEN (S1)
2. STRCMP (S1, S2)
3. STRCPY (S1, S2)
4. STRCAT (S1, S2)
1. STRLEN (S1): This function isused to returnthe lengthofthe string
name S1,
Ex: S1 = ‘MOID’
STRLEN (S1) = 4
2. STRCMP (S1, S2): This is a library function used to perform
comparisonbetweentwo strings. Thisfunctionreturnsa value<zerowhenstring
S1isless thanS2. Thefunctionreturnavalue0whenS1=S2. Finallythefunction
return a value > 0 when S1>S2.
3. STRCPY (S1, S2): This is a libraryfunctionused to copythe string
S2 to S1.
4. STRCAT (S1, S2): This is a libraryfunctionused to jointwo strings
one after the other. This functionconcatenatesstring S2 at the end ofstring S1.
Example5 : C program to concatenate the given two strings and print
newstring.
#include<stdio.h>
#include<conio.h>
main( )
{
char s1[10], s2[10], s3[10],
int i,j,k;
printf(“Enterthefirst string: n”);
scanf(“%s,S”,s1);
printf(“Enter thesecond string : n”);
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language
Problem solving techniques in c language

More Related Content

What's hot

Algorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo codeAlgorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo codehamza javed
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesFellowBuddy.com
 
Algorithm Development
Algorithm DevelopmentAlgorithm Development
Algorithm DevelopmentALI RAZA
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solvingKhan Yousafzai
 
flowchart & algorithms
flowchart & algorithmsflowchart & algorithms
flowchart & algorithmsStudent
 
Algorithm Design & Implementation
Algorithm Design & ImplementationAlgorithm Design & Implementation
Algorithm Design & ImplementationGaditek
 
Algorithms : Introduction and Analysis
Algorithms : Introduction and AnalysisAlgorithms : Introduction and Analysis
Algorithms : Introduction and AnalysisDhrumil Patel
 
Flowchart and algorithm
Flowchart and algorithmFlowchart and algorithm
Flowchart and algorithmDHANIK VIKRANT
 
2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problem2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problemFrankie Jones
 
Ds03 algorithms jyoti lakhani
Ds03 algorithms jyoti lakhaniDs03 algorithms jyoti lakhani
Ds03 algorithms jyoti lakhanijyoti_lakhani
 
Algorithms and how to write an algorithms
Algorithms and how to write an algorithmsAlgorithms and how to write an algorithms
Algorithms and how to write an algorithmsAhmed Nobi
 
Flowcharts and algorithms
Flowcharts and algorithmsFlowcharts and algorithms
Flowcharts and algorithmsStudent
 
Algorithm and Flowcharts
Algorithm and FlowchartsAlgorithm and Flowcharts
Algorithm and FlowchartsSabik T S
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchartRabin BK
 
Algorithm and pseudocode conventions
Algorithm and pseudocode conventionsAlgorithm and pseudocode conventions
Algorithm and pseudocode conventionssaranyatdr
 
MATH2088/2988 Number Theory and Cryptography Assignments
MATH2088/2988 Number Theory and Cryptography AssignmentsMATH2088/2988 Number Theory and Cryptography Assignments
MATH2088/2988 Number Theory and Cryptography AssignmentsJohnsmith5188
 
Algorithms and flowcharts ppt (seminar presentation)..
 Algorithms and flowcharts  ppt (seminar presentation).. Algorithms and flowcharts  ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..Nagendra N
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowchartsSamuel Igbanogu
 

What's hot (20)

Algorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo codeAlgorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo code
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture Notes
 
Algorithm Development
Algorithm DevelopmentAlgorithm Development
Algorithm Development
 
8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving8.1 alogorithm & prolem solving
8.1 alogorithm & prolem solving
 
flowchart & algorithms
flowchart & algorithmsflowchart & algorithms
flowchart & algorithms
 
Algorithm Design & Implementation
Algorithm Design & ImplementationAlgorithm Design & Implementation
Algorithm Design & Implementation
 
Algorithms : Introduction and Analysis
Algorithms : Introduction and AnalysisAlgorithms : Introduction and Analysis
Algorithms : Introduction and Analysis
 
Flowchart and algorithm
Flowchart and algorithmFlowchart and algorithm
Flowchart and algorithm
 
2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problem2.3 Apply the different types of algorithm to solve problem
2.3 Apply the different types of algorithm to solve problem
 
Ds03 algorithms jyoti lakhani
Ds03 algorithms jyoti lakhaniDs03 algorithms jyoti lakhani
Ds03 algorithms jyoti lakhani
 
Algorithms and how to write an algorithms
Algorithms and how to write an algorithmsAlgorithms and how to write an algorithms
Algorithms and how to write an algorithms
 
Flowcharts and algorithms
Flowcharts and algorithmsFlowcharts and algorithms
Flowcharts and algorithms
 
Algorithm and Flowcharts
Algorithm and FlowchartsAlgorithm and Flowcharts
Algorithm and Flowcharts
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Algorithm and pseudocode conventions
Algorithm and pseudocode conventionsAlgorithm and pseudocode conventions
Algorithm and pseudocode conventions
 
MATH2088/2988 Number Theory and Cryptography Assignments
MATH2088/2988 Number Theory and Cryptography AssignmentsMATH2088/2988 Number Theory and Cryptography Assignments
MATH2088/2988 Number Theory and Cryptography Assignments
 
Writing algorithms
Writing algorithmsWriting algorithms
Writing algorithms
 
Algorithms and flowcharts ppt (seminar presentation)..
 Algorithms and flowcharts  ppt (seminar presentation).. Algorithms and flowcharts  ppt (seminar presentation)..
Algorithms and flowcharts ppt (seminar presentation)..
 
Algorithms and flowcharts
Algorithms and flowchartsAlgorithms and flowcharts
Algorithms and flowcharts
 

Similar to Problem solving techniques in c language

Algorithm types performance steps working
Algorithm types performance steps workingAlgorithm types performance steps working
Algorithm types performance steps workingSaurabh846965
 
Algorithm for computational problematic sit
Algorithm for computational problematic sitAlgorithm for computational problematic sit
Algorithm for computational problematic sitSaurabh846965
 
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHESC LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHESHarshJha34
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptracha49
 
Introduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.pptIntroduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.pptBhargaviDalal4
 
Logic Development and Algorithm.
Logic Development and Algorithm.Logic Development and Algorithm.
Logic Development and Algorithm.NandiniSidana
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)praveena p
 
Lec 2 -algorithms-flowchart-and-pseudocode1.pptx
Lec 2 -algorithms-flowchart-and-pseudocode1.pptxLec 2 -algorithms-flowchart-and-pseudocode1.pptx
Lec 2 -algorithms-flowchart-and-pseudocode1.pptxAbdelrahmanRagab36
 
Algorithms notes 2 tutorials duniya
Algorithms notes 2   tutorials duniyaAlgorithms notes 2   tutorials duniya
Algorithms notes 2 tutorials duniyaTutorialsDuniya.com
 
Design and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit oneDesign and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit onessuserb7c8b8
 
01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptxssuser586772
 
GE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfGE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfAsst.prof M.Gokilavani
 
Program concep sequential statements
Program concep sequential statementsProgram concep sequential statements
Program concep sequential statementsankurkhanna
 

Similar to Problem solving techniques in c language (20)

Algorithm types performance steps working
Algorithm types performance steps workingAlgorithm types performance steps working
Algorithm types performance steps working
 
Algorithm for computational problematic sit
Algorithm for computational problematic sitAlgorithm for computational problematic sit
Algorithm for computational problematic sit
 
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHESC LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
C LANGUAGE-FLOWCHARTS,PSEUDOCODE,ALGORITHMS APPROCHES
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
 
Introduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.pptIntroduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.ppt
 
Algorithm.pdf
Algorithm.pdfAlgorithm.pdf
Algorithm.pdf
 
Logic Development and Algorithm.
Logic Development and Algorithm.Logic Development and Algorithm.
Logic Development and Algorithm.
 
UNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.pptUNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.ppt
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)
 
Lec 2 -algorithms-flowchart-and-pseudocode1.pptx
Lec 2 -algorithms-flowchart-and-pseudocode1.pptxLec 2 -algorithms-flowchart-and-pseudocode1.pptx
Lec 2 -algorithms-flowchart-and-pseudocode1.pptx
 
Algorithms notes 2 tutorials duniya
Algorithms notes 2   tutorials duniyaAlgorithms notes 2   tutorials duniya
Algorithms notes 2 tutorials duniya
 
Problem solving methodology
Problem solving methodologyProblem solving methodology
Problem solving methodology
 
Design and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit oneDesign and Analysis of Algorithm ppt for unit one
Design and Analysis of Algorithm ppt for unit one
 
Module 1 python.pptx
Module 1 python.pptxModule 1 python.pptx
Module 1 python.pptx
 
01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx
 
DATA STRUCTURE.pdf
DATA STRUCTURE.pdfDATA STRUCTURE.pdf
DATA STRUCTURE.pdf
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 
GE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdfGE3151 PSPP _Unit 1 notes and Question bank.pdf
GE3151 PSPP _Unit 1 notes and Question bank.pdf
 
Program concep sequential statements
Program concep sequential statementsProgram concep sequential statements
Program concep sequential statements
 

Recently uploaded

定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一z zzz
 
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一z xss
 
Final Completion Certificate of Marketing Management Internship
Final Completion Certificate of Marketing Management InternshipFinal Completion Certificate of Marketing Management Internship
Final Completion Certificate of Marketing Management InternshipSoham Mondal
 
定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一
定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一
定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一fjjwgk
 
Preventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptxPreventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptxGry Tina Tinde
 
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一Fs
 
Escort Service Andheri WhatsApp:+91-9833363713
Escort Service Andheri WhatsApp:+91-9833363713Escort Service Andheri WhatsApp:+91-9833363713
Escort Service Andheri WhatsApp:+91-9833363713Riya Pathan
 
Kindergarten-DLL-MELC-Q3-Week 2 asf.docx
Kindergarten-DLL-MELC-Q3-Week 2 asf.docxKindergarten-DLL-MELC-Q3-Week 2 asf.docx
Kindergarten-DLL-MELC-Q3-Week 2 asf.docxLesterJayAquino
 
办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一
办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一
办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一F La
 
MIdterm Review International Trade.pptx review
MIdterm Review International Trade.pptx reviewMIdterm Review International Trade.pptx review
MIdterm Review International Trade.pptx reviewSheldon Byron
 
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...Suhani Kapoor
 
Gray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdfGray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdfpadillaangelina0023
 
办理老道明大学毕业证成绩单|购买美国ODU文凭证书
办理老道明大学毕业证成绩单|购买美国ODU文凭证书办理老道明大学毕业证成绩单|购买美国ODU文凭证书
办理老道明大学毕业证成绩单|购买美国ODU文凭证书saphesg8
 
原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量
原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量
原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量sehgh15heh
 
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...nitagrag2
 
办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书saphesg8
 
8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR
8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR
8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCRdollysharma2066
 
定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一Fs sss
 

Recently uploaded (20)

定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一
 
Young Call~Girl in Pragati Maidan New Delhi 8448380779 Full Enjoy Escort Service
Young Call~Girl in Pragati Maidan New Delhi 8448380779 Full Enjoy Escort ServiceYoung Call~Girl in Pragati Maidan New Delhi 8448380779 Full Enjoy Escort Service
Young Call~Girl in Pragati Maidan New Delhi 8448380779 Full Enjoy Escort Service
 
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
定制(SCU毕业证书)南十字星大学毕业证成绩单原版一比一
 
Final Completion Certificate of Marketing Management Internship
Final Completion Certificate of Marketing Management InternshipFinal Completion Certificate of Marketing Management Internship
Final Completion Certificate of Marketing Management Internship
 
FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974
FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974
FULL ENJOY Call Girls In Gautam Nagar (Delhi) Call Us 9953056974
 
定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一
定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一
定制(ECU毕业证书)埃迪斯科文大学毕业证毕业证成绩单原版一比一
 
Preventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptxPreventing and ending sexual harassment in the workplace.pptx
Preventing and ending sexual harassment in the workplace.pptx
 
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
定制(Waikato毕业证书)新西兰怀卡托大学毕业证成绩单原版一比一
 
Escort Service Andheri WhatsApp:+91-9833363713
Escort Service Andheri WhatsApp:+91-9833363713Escort Service Andheri WhatsApp:+91-9833363713
Escort Service Andheri WhatsApp:+91-9833363713
 
Kindergarten-DLL-MELC-Q3-Week 2 asf.docx
Kindergarten-DLL-MELC-Q3-Week 2 asf.docxKindergarten-DLL-MELC-Q3-Week 2 asf.docx
Kindergarten-DLL-MELC-Q3-Week 2 asf.docx
 
办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一
办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一
办理(NUS毕业证书)新加坡国立大学毕业证成绩单原版一比一
 
MIdterm Review International Trade.pptx review
MIdterm Review International Trade.pptx reviewMIdterm Review International Trade.pptx review
MIdterm Review International Trade.pptx review
 
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
VIP Call Girls Firozabad Aaradhya 8250192130 Independent Escort Service Firoz...
 
Gray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdfGray Gold Clean CV Resume2024tod (1).pdf
Gray Gold Clean CV Resume2024tod (1).pdf
 
办理老道明大学毕业证成绩单|购买美国ODU文凭证书
办理老道明大学毕业证成绩单|购买美国ODU文凭证书办理老道明大学毕业证成绩单|购买美国ODU文凭证书
办理老道明大学毕业证成绩单|购买美国ODU文凭证书
 
原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量
原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量
原版定制copy澳洲查尔斯达尔文大学毕业证CDU毕业证成绩单留信学历认证保障质量
 
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
 
办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书
 
8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR
8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR
8377877756 Full Enjoy @24/7 Call Girls in Pitampura Delhi NCR
 
定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一 定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
定制(UOIT学位证)加拿大安大略理工大学毕业证成绩单原版一比一
 

Problem solving techniques in c language

  • 1. Structure 1.0Introduction 1.1 Procedure (stepsinvolved inproblemsolving) 1.2Algorithm 1.3 Flow Chart 1.4 Symbols used in Flow Charts 1.5 Pseudo Code Learning Objectives • To understand the concept ofProblemsolving • To understand steps involvedin algorithmdevelopment •To understand the concept ofAlgorithm • DevelopAlgorithmfor simple problem • To understand the concept ofFlowchart development • Draw the symbols used in Flowcharts 1 UNIT Introduction to Problem Solving Techniques
  • 2. Computer Science and Engineering 250 1.0 Introduction Acomputeris a verypowerfuland versatile machinecapableofperforming a multitude ofdifferent tasks, yet it has no intelligence or thinking power. The intelligence Quotient (I.Q) ofa computer is zero. Acomputer performs many tasks exactlyinthe same manneras it is toldto do. Thisplaces responsibilityon the user to instruct the computer in a correct and precise manner, so that the machine is able to perform the required job in a proper way. A wrong or ambiguous instructionmaysometimes prove disastrous. In order to instruct a computer correctly, the user must have clear understanding ofthe problemto besolved. Apart fromthis he shouldbe able to develop amethod, inthe formofseries ofsequentialsteps, to solve it. Once the problemiswell-definedand a methodofsolving it isdeveloped, theninstructing he computer to solve the problembecomes relativelyeasier task. Thus, beforeattempt to writeacomputerprogramto solveagivenproblem. It is necessaryto formulate or definethe problemina precise manner. Once the problemis defined, the steps required to solve it, must be stated clearly in the required order. 1.1 Procedure (Steps Involved in Problem Solving) A computer cannot solve a problemon its own. One has to provide step bystep solutions ofthe problemto the computer. In fact, the task ofproblem solving isnot that ofthecomputer. It is theprogrammer who has to write down the solutionto the probleminterms ofsimple operations which the computer canunderstand and execute. Inorderto solve aproblembythecomputer, one has topassthoughcertain stages or steps. They are 1. Understanding the problem 2. Analyzingthe problem 3. Developing thesolution 4. Coding andimplementation. 1. Understanding the problem: Herewe tryto understand the problem to besolvedintotally. Beforewiththenext stageorstep, weshouldbeabsolutely sure about the objectives ofthe givenproblem. 2. Analyzing the problem:After understanding thoroughlythe problem to be solved, we look different ways ofsolving the problemand evaluate each
  • 3. 251 Paper - II Programming in C of these methods. The idea here is to search an appropriate solution to the problemunder consideration. Theend result ofthis stage isabroad overview of the sequence ofoperations that are to be carries out to solvethe givenproblem. 3. Developing the solution: Here the overview of the sequence of operations that was the result ofanalysis stage is expanded to forma detailed step bystep solutionto the problemunder consideration. 4. Codingand implementation: Thelast stageofthe problemsolving is the conversion ofthe detailed sequence ofoperations in to a language that the computercanunderstand.Hereeachstepisconvertedto itsequivalentinstruction orinstructionsinthecomputerlanguagethat hasbeenchosenfortheimplantation. 1.2 Algorithm Definition A set ofsequentialsteps usuallywritten in OrdinaryLanguage to solve a givenproblemis called Algorithm. It maybepossible to solve to problemin more than oneways, resulting in more than one algorithm. The choice of various algorithms depends on the factors likereliability, accuracyand easyto modify. Themostimportant factorin the choice ofalgorithmis thetimerequirement to execute it, afterwritingcodein High-levellanguage withthehelpofacomputer. The algorithmwhichwillneed the least time when executed isconsidered the best. Steps involved in algorithm development Analgorithmcanbedefinedas“acomplete,unambiguous,finitenumber of logical steps for solving a specific problem “ Step1. Identification of input: For analgorithm, there arequantities to besupplied calledinput andthese arefed externally. The input isto be indentified first for anyspecified problem. Step2: Identification ofoutput: Fromanalgorithm, at least one quantity is produced, called for anyspecified problem. Step3 : Identification the processing operations :Allthe calculations to be performed in order to leadto output fromthe input are to be identified in an orderlymanner. Step4 : Processing Definiteness : The instructions composing the algorithmmust be clear and thereshould not be anyambiguityinthem.
  • 4. Computer Science and Engineering 252 Step5 : Processing Finiteness: Ifwe go through the algorithm, then for allcases, the algorithmshould terminate after a finite numberofsteps. Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficientlybasic and inpractice theycan be carries out easily. Analgorithmmust possess the following properties 1. Finiteness:Analgorithmmust terminate in a finite number ofsteps 2. Definiteness: Each step of the algorithm must be precisely and unambiguouslystated 3. Effectiveness: Each step must be effective, in the sense that it should beprimitiveeasilyconvert ableintoprogramstatement)canbeperformedexactly ina finiteamount oftime. 4. Generality: The algorithm must be complete in itselfso that it can be used to solve problems ofa specific type for anyinput data. 5. Input/output: Eachalgorithmmust take zero, one ormorequantitiesas input data produce one or more output values.An algorithmcanbe written in English like sentences or inanystandard representationsometimes, algorithm written inEnglishlike languages arecalled Pseudo Code Example 1. Suppose wewant to find the average ofthree numbers, the algorithmis as follows Step 1 Read the numbers a, b, c Step 2 Compute the sum of a, b and c Step 3 Divide the sum by3 Step 4 Store the result in variable d Step 5 Print the value ofd Step 6 End ofthe program 1.2.2Algorithms forSimple Problem Write an algorithmfor the following 1. Write analgorithmto calculate thesimple interest using the formula. Simple interest = P*N* R/100.
  • 5. 253 Paper - II Programming in C Where Pis principleAmount, Nis the number ofyears and R isthe rate ofinterest. Step 1: Read the three input quantities’P, N and R. Step 2 : Calculate simple interest as Simple interest = P* N* R/100 Step 3:Print simple interest. Step 4: Stop. 2. Area ofTriangle: Write analgorithmto find the area ofthe triangle. Let b, c be the sides ofthe triangleABC andAthe included angle between the givensides. Step 1: Input the givenelements ofthe triangle namelysides b, c and angle between the sidesA. Step 2: Area = (1/2) *b*C* sinA Step 3: Output theArea Step 4: Stop. 3. Write analgorithmto find the largest ofthree numbers X, Y,Z. Step 1: Read the numbers X,Y,Z. Step 2: if(X >Y) Big = X else BIG = Y Step 3 : if (BIG < Z) Step 4: Big = Z Step 5: Print the largest numberi.e. Big Step 6: Stop.
  • 6. Computer Science and Engineering 254 4. Write down an algorithmto find the largest data value ofa set ofgiven data values Algorithm largest of all data values: Step 1: LARGE  0 Step 2: read NUM Step 3: While NUM > = 0 do 3.1 ifNUM > LARGE 3.1.1 then 3.1.1.1 LARGE  NUM 3.2. read NUM Step 4:Write “largest data valueis”, LARGE Step 5: end. 5. Write analgorithmwhichwilltest whether agivenintegervalue is prime or not. Algorithm prime testing: Step 1: M  2 Step 2: read N Step 3: MAX  SQRT (N) Step 4: While M < = MAX do 4.1 if (M* (N/M) = N 4.1.1 then 4.1.1.1 go to step 7 4.2. M  M + 1 Step 5:Write “number is prime” Step 6: go to step 8 Step 7:Write “number is not a prime” Step 8: end.
  • 7. 255 Paper - II Programming in C 6. Write algorithmto find the factorialofa givennumber N Step 1: PROD  1 Step 2: I  0 Step 3: read N Step 4: While I < N do 4.1 I  I + 1 4.2. PROD  PROD* I Step 5:Write “Factorialof”, N, “is”, PROD Step 6: end. 7. Write analgorithmto findsumofgivendatavaluesuntilnegativevalueis entered. AlgorithmFind – Sum Step 1: SUM  0 Step 2: I  0 Step 3: read NEWVALUE Step 4: While NEWVALUE < = 0 do 4.1 SUM  SUM + NEW VALUE 4.2 1  I + 1 4.3 read NEWVALUE Step 5: Write “Sumof”, I, “data value is, “SUM Step 6: END 8. Writeanalgorithmto calculate theperimeter andareaofrectangle. Given its lengthand width. Step 1: Readlength ofthe rectangle. Step 2: Readwidth ofthe rectangle. Step 3:Calculate perimeter oftherectangle using the formulaperimeter = 2* (length+ width) Step 4:Calculate area ofthe rectangle using the formula area = length *width.
  • 8. Computer Science and Engineering 256 Step 5: Print perimeter. Step 6: Print area. Step 7: Stop. 1.3 Flowchart A flow chart is a step by step diagrammatic representation of the logic pathsto solveagivenproblem.Or Aflowchart isvisualorgraphicalrepresentation ofanalgorithm. The flowcharts are pictorialrepresentation of the methods to b used to solve a given problemand help a great dealto analyze the problemand plan its solutionina systematic and orderlymanner. Aflowchart when translated in to a propercomputer language, results ina complete program. Advantages of Flowcharts 1. Theflowchart shows the logic ofa problemdisplayed inpictorialfashion whichfelicitates easier checking ofanalgorithm. 2. The Flowchart is good means ofcommunicationto other users.It is also a compact meansofrecording analgorithmsolutionto a problem. 3. Theflowchart allowsthe problemsolver to breaktheprobleminto parts. These parts can be connected to make master chart. 4. The flowchart is a permanent record of the solution which can be consulted at a later time. Differences betweenAlgorithm and Flowchart Algorithm 1. A method of representing the step-by-step logicalprocedure for solving a problem 2. It contains step-by-step English descriptions, eachsteprepresenting a particular operation leading to solutionofproblem 3. These areparticularlyuseful for smallproblems 4. For complex programs, algorithms prove to be Inadequate Flowchart 1. Flowchart is diagrammatic representation of an algorithm. It is constructed using different types ofboxes and symbols. 2. Theflowchart employsaseriesofblocks and arrows, each of which represents a particular stepinanalgorithm 3. These are useful for detailed representations ofcomplicated programs 4. For complex programs, Flowcharts prove to be adequate
  • 9. 257 Paper - II Programming in C 1.4 Symbols used in Flow-Charts The symbols that we make use while drawing flowcharts as given below are as perconventions followed byInternationalStandard Organization(ISO). a. Oval: Rectangle withrounded sides is used to indicate either START/ STOP ofthe program. .. b. Input and output indicators: Parallelograms are used to represent input and output operations. Statements like INPUT, READ and PRINT are represented inthese Parallelograms. c. ProcessIndicators:- Rectangleisused to indicate anyset ofprocessing operationsuchasfor storing arithmetic operations. d. Decision Makers: The diamond is used for indicating the step of decision makingand therefore knownas decisionbox. Decisionboxes are used to test the conditions or ask questions and depending upon the answers, the appropriate actions are taken bythe computer. The decision boxsymbolis e. Flow Lines: Flow lines indicate the direction being followed in the flowchart. In a Flowchart, every line must have an arrow on it to indicate the direction. Thearrows maybe inanydirection f. On- Page connectors: Circles are used to join the different parts ofa flowchart and these circles are called on-page connectors. The uses ofthese connectors give a neat shape to the flowcharts. Ina complicated problems, a flowchart mayrunin to severalpages. The parts ofthe flowchart on different
  • 10. Computer Science and Engineering 258 pages are to be joined witheach other. The parts to be joined are indicated by the circle. g. Off-page connectors: This connectorrepresents a break inthe pathof flowchart which is too large to fit on a single page. It is similar to on-page connector. The connector symbolmarks where the algorithmends onthe first page and where it continues onthe second. 1.4.1 Simple Problems using Flow Chart Draw the Flowchart for the following 1. Draw the Flowchart to find Roots of Quadratic equation ax2 + bx + c = 0. The coefficients a, b, c are the input data START INPUT A,B,C D = B2 - 4 * A* C IS D< O YES YES NO NO x = B/2*A Print X,Y y = B/2*A y = -B + D 2 x A 2 x A x =B + D Print X,Y output complex roots Stop IS D= O
  • 11. 259 Paper - II Programming in C 2. Draw a flowchart to find out the biggest ofthe three unequalpositive numbers. 3. Draw a flowchart for adding the integers from 1 to 100 and to print the sum. Print Sum
  • 12. Computer Science and Engineering 260 4. Draw a flowchart to find the factorial of given positive integer N. 5. Develop a flowchart to illustrate how to make a Land phone telephone call . Flowchart forTelephone call I I
  • 13. 261 Paper - II Programming in C 6. 6. ABC company plans to give a 6% year-end bonus to each of its employees earning Rs 6,000 or more per month , and a fixed Rs 250/- - bonus to the remaining employees. Draw a flowchart for calculating the bonus for an employee 1.5 Pseudo code The Pseudo code is neither an algorithmnor a program. It is an abstract form of a program. It consists of English like statements which perform the specific operations. It is defined for analgorithm. It does not use anygraphical representation. Inpseudo code, the programis represented in terms ofwords and phrases, but the syntaxofprogramis not strictlyfollowed. Advantages: * Easy to read, * Easy to understand, * Easy to modify. Example:Writea pseudocode to performthebasicarithmetic operations. Read n1, n2 Sum = n1 + n2 Diff= n1 – n2 Mult = n1 * n2 Quot = n1/n2 Print sum,diff, mult, quot End.
  • 14. Computer Science and Engineering 262 Activity Practice more sample problems onalgorithmand Flowcharts Model Questions Short Answer Type Questions - 2 Marks 1. Define Algorithm 2. What is Flowchart 3. What is Pseudo code? 4. What are the symbols of Flowchart 5. WriteanAlgorithmfor perimeter ofTriangle 6. What are the basic steps involved In problemsolving Long Answer Type Questions - 6 Marks 1. Differentiate betweenAlgorithmand Flowchart. 2. Write analgorithmto find greatest ofgiven three numbers. 3. Write an algorithmto check whether given integer value is PRIME or NOT. 4. Draw the flowchart to find roots ofQuadraticequation ax2 + bx+ c= 0 Note : Practice more relatedAlgorithms and Flowcharts.
  • 15. Structure 2.0Introduction 2.1 Character Set 2.2 Structure ofa ‘C’ Program 2.3 Data Types in ‘C’ 2.4 Operations 2.5 Expressions 2.6Assignment Statement 2.7 ConditionalStatements 2.8 Structurefor Looping Statements 2.9 Nested Looping Statements 2.10 MultiBranching Statement (Switch), Breakand Continue 2.11 Differences betweenBreak and Continue 2.12 UnconditionalBranching(Go to Statement) 2 UNIT Features of ‘C’
  • 16. Computer Science and Engineering 264 Learning Objectives • What is C Language and its importance • To understand various data types • To understand working functionofinput and output statements inC • To understand workingfunctionofBranching statements inC • To understand workingfunctionofLooping statements inC • To Understand differences between Break and Continue 2.0 Introduction ‘C’ ishighlevellanguage andis the upgraded versionofanother language (Basic Combined Program Language). C language was designed at Bell laboratoriesintheearly1970’sbyDennisRitchie. Cbeingpopularinthemodern computer world can be used in Mathematical Scientific, Engineering and Commercialapplications The most popular Operating systemUNIX is written inC language. This languagealso hasthefeaturesoflowlevellanguagesand hencecalledas “System ProgrammingLanguage” Features of C language • Simple, versatile, generalpurpose language • It has richset ofOperators • Programexecutionarefast and efficient • Can easilymanipulates with bits, bytes and addresses • Varieties ofdatatypes are available • Separate compilationof functions ispossible and suchfunctionscanbe called byanyC program • Block- structured language • Can be applied in Systemprogramming areas like operating systems, compilers & Interpreters,Assembles, Text Editors, Print Spoolers, Network Drivers, ModernPrograms, Data Bases, Language Interpreters, Utilities etc.
  • 17. 265 Paper - II Programming in C 2.1 Character Set The character set is the fundamentalraw-materialfor anylanguage. Like naturallanguages, computerlanguages willalso havewelldefinedcharacter-set, which is usefulto build the programs. The C language consists oftwo character sets namely– source character set execution character set. Source character set is useful to construct the statements inthe source program. Execution character set is employed at the time ofexecutionofhprogram. 1. Source character set : This type ofcharacter set includes three types ofcharacters namelyalphabets, Decimals andspecialsymbols. i. Alphabets : Ato Z, a to z and Underscore( _ ) ii. Decimal digits : 0 to 9 iii. Special symbols: + - * / ^ % = & ! ( ) { } [ ] “ etc 2. Execution character set : This set of characters are also called as non-graphic characters because these are invisible and cannot be printed or displayed directly. These characters willhave effect onlywhen the programbeing executed. These characters are represented by a back slash () followed by a character. Execution character Meaning Result at the time of execution n End ofa line Transfers the active position ofcursor to the initial position of next line 0 (zero) Endofstring Null t HorizontalTab Transfers the active positionofcursor to the next Horizontal Tab v VerticalTab Transfers the activepositionofcursor to the next Vertical Tab f Formfeed Transfers the active positionofcursor to the next logical page r Carriage return Transfers the activepositionofcursor to the initial position of current line
  • 18. Computer Science and Engineering 266 2.2 Structure of a ‘C’ Program The Complete structure of C program is The basic components ofa C programare: • main() • pair of braces { } • declarations and statements • userdefined functions PreprocessorStatements: These statements beginwith # symbol. They are called preprocessor directives. These statements direct the C preprocessor to include header files and also symbolic constants in to C program. Some of the preprocessor statements are #include<stdio.h>: for thestandard input/output functions #include<test.h>: forfile inclusionofheaderfileTest. #define NULL 0: for defining symbolic constant NULL = 0 etc. GlobalDeclarations: Variables or functions whose existence isknownin the main()function and other userdefined functions are called globalvariables (orfunctions) andtheir declarationsis calledglobaldeclaration. This declaration should be made before main(). main():AsthenameitselfindicatesitisthemainfunctionofeveryCprogram. ExecutionofCprogramstarts frommain(). No C programis executedwithout main() function. It should be written in lowercase letters and should not be terminatedbyasemicolon. It callsotherLibraryfunctionsuserdefinedfunctions. There must be one and onlyone main() function ineveryC program. Braces: Every C program uses a pair of curly braces ({,}0. The left brace indicatesbeginning ofmain() function. Onthe other hand, the right brace indicates end ofthe main() function. The braces canalso be usedto indicate the beginning and endof user-defined functions and compound statements. Declarations: It is part of C program where all the variables, arrays, functions etc., used in the C programare declared and maybe initialized with their basic data types. Statements: These are instructions to the specific operations. Theymay be input-output statements, arithmetic statements, controlstatements and other statements. Theyarealso including comments.
  • 19. 267 Paper - II Programming in C User-definedfunctions:These aresubprograms. Generally, a subprogram is a function, and they contain a set of statements to performa specific task. These are written bythe user;hence the name is user-defined functions. They maybe writtenbefore or after the main() function. 2.3 Data Types in ‘C’ The built-in data types and their extensions is the subject ofthis chapter. Deriveddatatypes suchasarrays,structures, unionandpointersanduserdefined data types such as typedefand enum. Basic Data Types There are four basic data types in C language. They are Integer data, character data, floating point data and double data types. a. Character data: Any character of the ASCII character set can be considered as a character data types and its maximumsize can be 1 byte or 8 byte long. ‘Char’is the keyword used to represent character data type in C. Char - a single byte size, capable of holding one character. b. Integer data: The keyword ‘int’ stands for the integer data type in C and its size is either 16 or 32 bits. The integer data type canagain be classified as 1. Long int - long integerwithmore digits 2. Short int - short integer withfewer digits. 3. Unsigned int - Unsigned integer C Data types Built - In Derived C Data Types Void Array Structure Union Pointer Char Integer Float Double Type def Enum
  • 20. Computer Science and Engineering 268 4. Unsigned short int – Unsigned short integer 5. Unsigned long int – Unsignedlong integer As above, the qualifiers like short, long, signed or unsigned canbe applied to basic data types to derive new data types. int - an Integer with the natural size ofthe host machine. c. Floating point data: - The numbers whichare stored infloating point representationwithmantissaandexponent arecalledfloatingpoint(real)numbers. These numbers can be declared as ‘float’ in C. float – Single – precision floating point number value. d. Double data : -Double is akeyword inC to represent double precision floatingpoint numbers. double - Double – precision floating point number value. Data Kinds in C Various data kinds that can beincluded in anyC programcanfallinto the following. a. Constants/Literals b. Reserve Words Keywords c. Delimeters d. Variables/Identifiers a. Constans/Literals: Constants arethose, which do not change, during the executionofthe program. Constants maybecategorized in to: • Numeric Constants • Character Constants • StringConstants 1. Numeric Constants Numeric constants, as the name itselfindicates, are those whichconsist of numerals, anoptionalsignand anoptionalperiod. Theyare further divided into two types: (a) Integer Constants (b) RealConstants a. Integer Constants
  • 21. 269 Paper - II Programming in C A whole number is an integer constant Integer constants do not have a decimalpoint.Thesearefurtherdividedintothreetypesdependingonthenumber systems theybelong to. Theyare: i. Decimalintegerconstants ii. Octalinteger constants iii. Hexadecimalinteger constants i. A decimal integer constant is characterized by the following properties • It is a sequence ofone ormore digits ([0…9], thesymbols ofdecimal numbersystem). • It mayhave anoptional+or –sign. Intheabsence ofsign, the constant is assumed to be positive. • Commas and blank spaces are not permitted. • It should not have a period as part ofit. Some examples ofvalid decimalinteger constants: 456 -123 Some examples ofinvalid decimalinteger constants: 4.56 - Decimalpoint is not permissible 1,23 - Commas arenot permitted ii. An octal integer constant is characterized by the following properties • It is asequenceofoneormore digits ([0…7], symbolsofoctalnumber system). • It mayhave anoptional+or –sign. Intheabsence ofsign, the constant is assumed to be positive. • It should start withthe digit 0. • Commas and blank spaces are not permitted. • It should not have a period as part ofit. Some examples ofvalid octalinteger constants:
  • 22. Computer Science and Engineering 270 0456 -0123 +0123 Some examples ofinvalid octalinteger constants: 04.56 - Decimalpoint is not permissible 04,56 - Commas are not permitted x34 - x is not permissible symbol 568 - 8 is not a permissible symbol iii. An hexadecimal integer constant is characterized by the following properties • It isa sequence ofoneor more symbols ([0…9][A….Z], the symbols ofHexadecimalnumber system). • It mayhaveanoptional+or - sign. Inthe absence ofsign,the constant is assumed to be positive. • It should start with the symbols 0X or 0x. • Commas and blank spaces are not permitted. • It should not have a period as part ofit. Some examples ofvalid hexadecimalinteger constants: 0x456 -0x123 0x56A 0XB78 Some examples ofinvalid hexadecimalinteger constants: 0x4.56 - Decimalpoint is not permissible 0x4,56 - Commas are not permitted. b. Real Constants The realconstants also known as floating point constants are written in twoforms:
  • 23. 271 Paper - II Programming in C (i) Fractionalform, (ii) Exponentialform. i. Fractional Form The real constants in Fractional form are characterized by the following characteristics: • Must have at least one digit. • Must havea decimalpoint. • Maybepositiveornegativeand intheabsenceofsigntakenaspositive. • Must not contain blanks or commas in betweendigits. • Maybe represented in exponentialform, ifthe value is too higher or too low. Some examples ofvalid realconstants: 456.78 -123.56 Some examples ofinvalid realconstants: 4.56 - Blank spaces are not permitted 4,56 - Commas arenot permitted 456 - Decimalpoint missing ii. Exponential Form The exponentialformoffers a convenient wayfor writing verylarge and smallrealconstant. For example, 56000000.00, which can be writtenas 0.56 *, 108 is writtenas0.56E8or 0.56e8 inexponentialform. 0.000000234, which canbewrittenas 0.234 * 10-6 iswrittenas0.234E-6 or 0.234e-6inexponential form. The letterE or e stand for exponentialform. A realconstant expressed in exponentialformhas two parts: (i) Mantissa part, (ii)Exponent part. Mantissa is the part ofthe realconstant to theleft ofE or e, and the Exponent ofa realconstant is to the right ofE or e. Mantissa and Exponent ofthe above two number are shown below. E -6 0.234 E 8 0.56 E xponent Mantissa E xponent Mantissa E -6 0.234 E 8 0.56 E xponent Mantissa E xponent Mantissa
  • 24. Computer Science and Engineering 272 In the above examples, 0.56 and 0.234 are the mantissa parts of the first and second numbers, respectively, and 8 and -6 are the exponent parts ofthe first andsecond number, respectively. The real constants in exponential form and characterized by the following characteristics: • The mantissa must have at least one digit. • The mantissa is followed bytheletter E or e and the exponent. • The exponent must have at least one digit and must be an integer. • Asignforthe exponent is optional. Some examples ofvalid realconstants: 3E4 23e-6 0.34E6 Some examples ofinvalid realconstants: 23E - No digit specified for exponent 23e4.5 - Exponent should not be a fraction 23,4e5 - Commas are not allowed 256*e8- * not allowed 2. Character Constants Anycharacterenclosed withinsinglequotes(‘)iscalledcharacter constant. Acharacter constant: • Maybeasingle alphabet, singledigit or single specialcharacter placed withinsingle quotes. • Has a maximumlength of1 character. Here are some examples, • ‘C’ • ‘c’ • ‘:’ • ‘*’
  • 25. 273 Paper - II Programming in C 3. String Constants A string constant is a sequence of alphanumeric characters enclosed in double quoteswhose maximumlength is255 characters. Following arethe examples ofvalidstring constants: • “Mynameis Krishna” • “Bible” • “Salaryis 18000.00” Following arethe examples ofinvalidstring constants: My name is Krishna - Character are not enclosed in double quotation marks. “Myname is Krishna - Closing double quotationmark is missing. ‘Mynameis Krishna’ - Characters are not enclosedin double quotation marks b. Reserve Words/Keywords InC language , some words are reserved to do specific tasks intended for themand are called Keywords or Reserve words. The list reserve words are auto do goto break double if case else int char extern long continue float register default for return short sezeof static struct switch typedef union unsigned void while const entry violate enum noalias
  • 26. Computer Science and Engineering 274 c. Delimiters This is symbolthat has syntactic meaningand has got significance. These willnot specifyanyoperation to result in a value. C language delimiters list is givenbelow Symbol Name Meaning # Hash Pre-processor directive , comma Variable delimiter to separate variable : colon labeldelimiter ; Semicolon statement delimiter ( ) parenthesis used for expressions { } curlybraces used forblocking ofstatements [ ] square braces used alongwitharrays d. Variables / Identifiers These are the names ofthe objects, whose values canbe changed during the programexecution.Variables are named withdescriptionthat transmits the value it holds. [Aquantityofanitem, whichcanbe change its value during the execution ofprogramiscalled variable. It is also known as Identifier]. Rules fornaming a variable:-  It can be ofletters, digits and underscore( _ )  First letter should be a letter or an underscore, but it should not be a digit.  Reserve words cannot be used as variable names. Example: basic, root, rate, roll-no etc are valid names. Declaration ofvariables: Syntax type Variable list int i, j i, j are declared as integers float salary salaryis declared ad floating point variable Char sex sex is declared as character variable
  • 27. 275 Paper - II Programming in C 2.4 Operators An Operator is a symbol that operates on a certain data type. The data items that operators act upon are called operands. Some operators require two operands, some operators act upononlyone operand. InC, operators can be classified into various categories based on theirutilityand action. 1.Arithmetic Operators 5. Increment & Decrement Operator 2. RelationalOperators 6. ConditionalOperator 3. LogicalOperator 7. Bitwise Operator 4.Assignment Operator 8. Comma Operator 1.Arithmetic Operators TheArithmetic operators performs arithmetic operations. TheArithmetic operators canoperateonanybuilt indata type.Alist ofarithmetic operators are Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulo division 2. Relational Operators RelationalOperators areused to compare arithmetic, logicalandcharacter expressions. The RelationalOperators compare their left hand side expression withtheirrighthandsideexpression.Thenevaluatestoaninteger.IftheExpression is false it evaluate to “zero”(0) ifthe expressionis true it evaluate to “one” Operator Meaning < Less than > Greater than <= Less thanor Equalto >= Greater thanor Equalto = = Equalto
  • 28. Computer Science and Engineering 276 != Not Equalto The RelationalOperators are represented inthe following manner: Expression-1 Relational Operator Expression-2 The Expression-1 willbe compared with Expression-2 and depending on the relation theresult willbe either“TRUE” OR “FALSE”. Examples : Expression Evaluate to (5 <= 10) ———————— 1 (-35 > 10) ———————— 0 (X < 10) ———————— 1 ( if value of x is less than 10) 0 Other wise (a + b) = = ( c + d ) 1 (if sum of a and b is equal to sum of c, d) 0 Other wise 3. Logical Operators A logicaloperator is used to evaluate logicaland relational expressions. The logicaloperatorsact uponoperandsthat arethemselveslogicalexpressions. There are three logicaloperators. Operators Expression && LogicalAND || LogicalOR ! LogicalNOT LogicalAnd (&&): AcompoundExpressionistrue whentwo expression when two expressions are true. The&& is used inthe following manner. Exp1 && Exp2. The result ofa logicalAND operationwillbe true onlyifbothoperands are true. The results oflogicaloperators are: Exp1 Op. Exp2 Result True &&TrueTrue
  • 29. 277 Paper - II Programming in C True && False False False && False False False &&True False Example: a = 5; b = 10; c = 15; Exp1 Exp2 Result 1. ( a< b ) && ( b < c ) => True 2. ( a> b ) && ( b < c ) => False 3. ( a< b ) && ( b > c ) => False 4. ( a> b ) && ( b > c ) => False Logical OR: A compound expression is false when all expression are false otherwise thecompound expressionis true. The operator “||” is used as It evaluatesto true ifeither exp-1or exp-2 is true. The truthtable of“OR” is Exp1 || Exp2 Exp1 Operator Exp2 Result: True || True True True || False True False || True True False || False False Example: a = 5; b = 10; c = 15; Exp1 Exp2 Result 1. ( a< b ) || ( b < c ) => True 2. ( a> b ) || ( b < c ) => True 3. ( a< b ) || ( b > c ) => True 4. ( a> b ) || ( b > c ) => False Logical NOT: The NOT ( ! ) operator takes single expression and evaluates to true(1) if the expression is false (0) or it evaluates to false (0) if expressionis true (1). The generalformofthe expression. ! ( Relational Expression ) The truth table ofNOT :
  • 30. Computer Science and Engineering 278 Operator. Exp1 Result !True False ! False True Example: a = 5; b = 10; c = 15 1. !( a< b ) False 2. !( a> b ) True 4.Assignment Operator An assignment operator is used to assign a value to a variable. The most commonlyused assignment operator is =. The generalformat for assignment operator is : <Identifer> = < expression > Where identifier represent a variable and expressionrepresents a constant, a variable or a Complex expression. Ifthetwo operands inanassignment expressionare ofdifferent data types, then the value ofthe expression onthe right willautomaticallybe converted to the type ofthe identifier onthe left. Example: Suppose that I is an Integertype Variable then 1. I = 3.3 3 ( Value of I ) 2. I = 3.9 3 ( Value of I ) 3. I = 5.74 5 ( Value of I ) Multiple assignment < identifier-1 > = < identifier-2 > = - - - = < identifier-n > = <exp>; Example: a,b,c are integers; jis float variable 1. a = b = c = 3; 2. a = j = 5.6; then a = 5 and j value will be 5.6 C containsthe following five additionalassignment operators 1. += 2.-= 3. += 4. *= 5. /= The assignment expression is: - Exp1< Operator> Exp-2 Ex: I = 10 (assume that)
  • 31. 279 Paper - II Programming in C ExpressionEquivalent to FinalValue of‘I’ 1. I + = 5 I = I + 5 15 2. I - = 5 I = I - 5 10 3. I * = 5 I = I * 5 50 4. I / = 5 I = I / 5 10 5. Increment & Decrement Operator Theincrement/decrement operatoract uponaSingleoperandand produce a new value is also called as “unary operator”. The increment operator ++ adds 1 to the operand and the Decrement operator – subtracts 1 from the operand. Syntax: < operator>< variable name >; The ++ or – operator canbe used in the two ways. Example : ++ a; Pre-increment (or) a++ Post increment —a; Pre- Decrement (or) a— Post decrement 1. ++ a Immediatelyincrements the value ofa by1. 2. a ++ The value ofthe a willbe increment by1 after it is utilized. Example 1: Suppose a = 5 ; StatementsOutput printf ( “a value is %d”, a ); a value is 5 printf( “a value is %d”, ++ a ); a value is 6 printf( “a value is %d “, a) ; a value is 6 Example 2: Suppose : a = 5 ; StatementsOutput printf(“a value is %d “, a); a value is 5 printf(“a value is %d “, a++); a value is 5 printf(“a value is %d “,a); a value is 6 a anda-willbeact onoperand bydecrement valuelike increment operator. 6. Conditionaloperator(or) Ternary operator(? :)
  • 32. Computer Science and Engineering 280 It is called ternarybecause it uses three expression. The ternaryoperator acts likeIf- Else construction. Syn :( <Exp –1 > ? <Exp-2> : <Exp-3> ); Expression-1 is evaluated first. If Exp-1 is true then Exp-2 is evaluated other wise it evaluate Exp-3 willbe evaluated. Flow Chart : Exp-1 Exp-2 Exp-3 Exit Example: 1. a = 5 ; b = 3; ( a> b ? printf(“a is larger”) : printf(“b is larger”)); Output is :a is larger 2. a = 3; b = 3; (a> b? printf(“a islarger”) : printf(“bis larger”)); Output is :b is larger 7. Bit wise Operator A bitwise operator operates on each bit of data. These bitwiseoperator can be divided into three categories. i. The logicalbitwise operators. ii. The shift operators iii. The one’scomplement operator. i)The logicalBitwiseOperator:Therearethreelogicalbitwiseoperators. Meaning Operator: a) Bitwise AND & b) Bitwise OR | c) Bitwise exclusive XOR ^
  • 33. 281 Paper - II Programming in C Suppose b1 and b2 represent the corresponding bits with in the first and second operands, respectively. B1 B2 B1 & B2 B1 | B2 B1 ^ B2 1 1 1 1 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 The operations arecarried out independentlyoneachpairofcorresponding bits withintheoperandthus the leastsignificant bits(ietherightmost bits)within the two operands.Willbe compared untilallthe bits have beencompared. The results ofthese comparisons are ABitwiseAND expression willreturn a 1 ifboth bits have a value of 1. Other wise, it willreturn avalue of0. A Bitwise OR expression willreturna 1 ifone or more ofthe bits have a value of1. Otherwise, it willreturn avalue of0. A Bitwise EXCLUSIVE OR expression willreturn a 1 ifone ofthe bits has a value of1 and the other has a value of0. Otherwise, ifwillreturn a value of0. Example::Variable Value Binary Pattern X 5 0101 Y 2 0010 X & Y 0 0000 X | Y 7 0111 X ^ Y 7 0111 ii) The Bitwise shift Operations: The two bitwise shift operators are Shift left (<<) and Shift right (>>). Each operator requires two operands. The first operandthat represents the bit pattern to be shifted. Thesecond is an unsigned integerthat indicates the number ofdisplacements. Example: c = a << 3; The value in the integer a is shifted to the left by three bit position. The result is assigned to the c.
  • 34. Computer Science and Engineering 282 A = 13; c= A<<3; Left shit << c= 13 * 2 3 = 104; Binary no 0000 0000 0000 1101 After left bit shift by 3 places ie,. a<<3 0000 0000 0110 1000 The right –bit – shift operator ( >> ) is also a binaryoperator. Example: c = a >> 2 ; The value ofa is shifted to the right by2 position insert 0’s Right – shift >> drop off0’s 0000 0000 0000 1101 After right shift by2 places is a>>2 0000 0000 0000 0011 c=13>>2 c= 13/4=3 iii) Bitwise complement: The complement op.~ switches allthe bits in a binarypattern, that is all the 0’s becomes 1’s and allthe 1’s becomes 0’s. variable value Binary patter x 23 0001 0111 ~x 132 1110 1000 8. Comma Operator Aset ofexpressions separated byusingcommas is a validconstructioninc language. Example :int i, j; i= ( j = 3, j + 2 ) ; The first expression is j = 3 and second is j + 2. These expressions are evaluated fromleft to right. Fromthe above example I = 5. Size of operator: The operator size operator gives the size of the data type or variableinterms ofbytes occupied inthe memory.This operator allows a determinationofthe no ofbytes allocated to various Data items Example :int i;float x; double d;char c; OUTPUT
  • 35. 283 Paper - II Programming in C Printf(“integer: %dn”, sizeof(i));Integer: 2 Printf(“float : %dn”, sizeof(i));Float : 4 Printf(“double: %dn”, sizeof(i));double: 8 Printf(“char :%dn”,sizeof(i));character : 1 2.5 Expressions An expression can be defined as collection of data object and operators that canbe evaluatedto leadasingle newdataobject.Adataobject is a constant, variable or another data object. Example : a + b x + y + 6.0 3.14 * r * r ( a + b ) * ( a – b) The above expressions are called as arithmetic expressions because the data objects (constants and variables) are connected using arithmetic operators. Evaluation Procedure: Theevaluationofarithmetic expressionsis as per the hierarchyrules governed bythe C compiler. The precedence or hierarchy rules forarithmetic expressions are 1. The expressionis scanned fromleft to right. 2. Whilescanningtheexpression,theevaluationpreferencefortheoperators are *, /, % - evaluated first +, - - evaluated next 3. To overcome the above precedence rules, user has to make use of parenthesis. Ifparenthesisisused, theexpression/ expressionswithinparenthesis are evaluated first as per the above hierarchy. Statements Data Input & Output Aninput/output functioncanbe accessed fromanywherewithina program simplybywritingthe functionname followedbya list ofarguments enclosed in parentheses. The arguments represent data itemsthat are sent to the function.
  • 36. Computer Science and Engineering 284 Some input/output Functions do not require arguments though the empty parentheses must stillappear. Theyare: Input Statements Output Statements Formatted scanf() printf() Unformatted getchar()gets() putchar()puts() getchar() Single characters can be entered into the computer using the C library Function getchar(). It returns a single character froma standard input device. The functiondoesnot require anyarguments. Syntax: <Character variable> = getchar(); Example: char c; c = getchar(); putchar() Single characters can be displayed using function putchar(). It returns a singlecharacter toa standardoutput device. It must be expressedas anargument to the function. Syntax: putchar(<character variable>); Example: char c; ———— putchar(c); gets() The function gets() receives thestring fromthe standard input device. Syntax: gets(<string type variable or arrayofchar> ); Where s is a string. The functiongets accepts the string as a parameter fromthe keyboard, till anewlinecharacterisencountered.Atendthefunctionappendsa“null”terminator and returns. puts() The functionputs() outputs thestring to the standardoutput device.
  • 37. 285 Paper - II Programming in C Syntax: puts(s); Where s is a string that was realwith gets(); Example: main() { char line[80]; gets(line); puts(line); } scanf() Scanf()functioncanbeusedinputthedataintothememoryfromthestandard input device. This function can be used to enter anycombination ofnumerical Values, singlecharactersand strings. Thefunctionreturns number ofdata items. Syntax:-scanf(“controlstrings”, &arg1,&arg2,——&argn); Wherecontrolstringreferesto astringcontainingcertainrequiredformatting informationandarg1,arg2——argnare arguments that represent the individual input data items. Example: #include<stdio.h> main() { char item[20]; intpartno; float cost; scanf(“%s %d %f”,&item,&partno,&cost); } Where s, d, fwith%are conversioncharacters. Theconversioncharacters indicate the type of the corresponding data. Commonly used conversion characters fromdata input.
  • 38. Computer Science and Engineering 286 Conversion Characters Characters Meaning %c data itemis a single character. %d data itemis a decimalinteger. %f data itemisa floating point value. %e data itemisa floating point value. %g data itemisa floating point value. %h data itemis a short integer. %s data itemis a string. %x data itemisa hexadecimalinteger. %o data itemisa octalinterger. printf() The printf()functionis used to print the data fromthe computer’s memory onto a standard output device. This function can be used to output any combinationofnumericalvalues, single characterand strings. Syntax: printf(“controlstring”, arg-1, arg-2,———arg-n ); Where controlstring is a string that contains formatted information, and arg-1, arg-2 ——are arguments that represent theoutput data items. Example: #include<stdio.h> main() { char item[20]; intpartno; float cost; ——————— printf(“%s %d%f”, item, partno, cost); } (Where %s %d %f are conversion characters.)
  • 39. 287 Paper - II Programming in C 2.6 Assignment Statement Assignment statement canbe defined as the statement throughwhich the value obtained froman expression can be stored in a variable. The generalformofassignment statement is < variable name> = < arithmetic expression> ; Example: sum = a + b + c; tot = s1 + s2 + s3; area = ½ * b* h; 2.7 I/O Control Structure (if, If-else, for, while, do-while) Conditional Statements The conditional expressions are mainly used for decision making. The following statementsare used to performthe task oftheconditionaloperations. a. ifstatement. b. If-else statement. Or 2 wayifstatement c. Nested else-ifstatement. d. Nested if–else statement. e. Switch statement. a. if statement The if statement is used to express conditionalexpressions. Ifthe given conditionistruethenit willexecute thestatementsotherwiseskipthestatements. The simple structure of‘if’statement is i. If(< condtional expressione>) statement-1; (or) ii. If(< condtional expressione>) {
  • 40. Computer Science and Engineering 288 statement-1; statement-2; statement-3; …………… …………… STATEMENT-N } The expressionis evaluated and ifthe expressionis truethe statements will be executed. Ifthe expressionisfalse the statements areskipped and execution continues withthe next statements. Example: a=20; b=10; if ( a > b ) printf(“big numberis %d” a); b. if-else statements The if-else statements is used to execute the either ofthe two statements depending upon the value ofthe exp. The generalformis if(<exp>) { Statement-1; Statement -2; ………….. “SET-I” …………… Statement- n; } else { Statement1; Statement 2;
  • 41. 289 Paper - II Programming in C ………….. “ SET-II …………… Statement n; } SET - I Statements willbe executed ifthe exp is true. SET – II Statements willbeexecuted ifthe exp is false. Example: if ( a> b ) printf(“a is greater thanb”); else printf(“a is not greater thanb”); c. Nested else-if statements Ifsome situations ifmaybe desired to nest multiple if-else statements. In this situationone ofseveraldifferent course ofaction willbe selected. Syntax if ( <exp1> ) Statement-1; else if ( <exp2> ) Statement-2; else if ( <exp3> ) Statement-3; else Statement-4; When a logical expression is encountered whose value is true the corresponding statementswillbe executed andthe remainder ofthenested else ifstatement willbe bypassed. Thus controlwillbe transferred out ofthe entire nest once a true conditionis encountered. The finalelse clause willbe applyifnone ofthe exp is true.
  • 42. Computer Science and Engineering 290 d. nestedif-else statement It ispossible to nest if-elsestatements, one withinanother.There are several different formthat nested if-else statements can take. The most generalformoftwo-layer nesting is if(exp1) if(exp3) Statement-3; else Statement-4; else if(exp2) Statement-1; else Statement-2; One complete if-else statement will be executed if expression1 is true and another complete if-else statement willbeexecuted ifexpression1 isfalse. e. Switch statement Aswitchstatement isusedto choosea statement (foragroup ofstatement) amongseveralalternatives. The switchstatementsisusefulwhenavariableis to be comparedwithdifferent constants andincase it isequalto a constant a set of statements are to be executed. Syntax: Switch (exp) { case constant-1: statements1; case constant-2:
  • 43. 291 Paper - II Programming in C statements2; ——— ——— default: statement n; } Where constant1, constanat2 — — — are either integer constants or character constants. Whenthe switchstatement is executed theexpis evaluated and controlis transferred directly to the group ofstatement whose case label value matches the value ofthe exp. Ifnone ofthe case labelvalues matches to the valueofthe exp thenthe default part statements willbe executed. If none ofthe case labels matches to the value ofthe exp and the default group is not present then no action will be taken by the switch statement and controlwillbe transferred out ofthe switch statement. Asimple switchstatement is illustrated below. Example 1: main() { char choice; printf(“EnterYourColor (Red - R/r,White –W/w)”); choice=getchar(); switch(choice= getchar()) { case‘r’: case‘R’: printf(“Red”); break; case‘w’: case‘W’:
  • 44. Computer Science and Engineering 292 printf(“white”); break; default : printf(“no colour”); } Example2: switch(day) { case 1: printf(“Monday”); break; ——— ——— } 2.8 Structure for Looping Statements Loop statements are used to execute the statements repeatedlyas long as an expression is true. When the expression becomes false then the control transferred out ofthe loop. There are three kinds ofloops in C. a) while b) do-while c) for a. while statement while loop willbe executed as long as the exp is true. Syntax: while (exp) { statements; } The statements willbe executed repeatedlyaslong as the exp istrue. Ifthe exp isfalse then the controlis transferred out ofthe while loop. Example:
  • 45. 293 Paper - II Programming in C int digit = 1; While (digit <=5) FALSE { printf(“%d”, digit);TRUE Cond Exp Statements;++digit; } The whileloop is top testedi.e., it evaluates theconditionbeforeexecuting statements in the body. Then it is called entrycontrolloop. b. do-while statement The do-while loop evaluates theconditionafter the executionofthe statements in the body. Syntax: do Statement; While<exp>; Here also the statements willbeexecuted as long asthe exp value istrue. If the expressionisfalse the controlcome out ofthe loop. Example: -int d=1; do { printf(“%d”, d); FALSE ++d; } while (d<=5); TRUE Cond Exp statements exit
  • 46. Computer Science and Engineering 294 The statement withinthe do-while loop willbe executed at least once. So the do-while loop is calleda bottomtested loop. c. for statement The for loop is used to executing the structure number oftimes. The for loop includesthree expressions. First expressionspecifies aninitialvaluefor an index (initialvalue), second expression that determines whether or not the loop is continued(conditionalstatement) and a third expression used to modifythe index(increment or decrement) ofeachpass. Note: Generally for loop used when the number of passes is known in advance. Syntax: for (exp1;exp2;exp3) { Statement –1; Statement – 2; —————; FALSE —————; Statement - n;TRUE } exp2 Statements; exp3 Exit loop exp1 start Whereexpression-1isusedto initializethecontrolvariable.Thisexpression is executed this expressionis executed is onlyonce at the time ofbeginning of loop. Where expression-2 is a logical expression. If expression-2 is true, the statementswillbeexecuted,otherwisetheloopwillbeterminated.Thisexpression is evaluatedbefore everyexecution ofthe statement.
  • 47. 295 Paper - II Programming in C Where expression-3 is an increment or decrement expression after executing the statements, the controlis transferred back to the expression-3 and updated. There are different formats available in for loop. Some of the expression ofloop can be omit. Formate - I for( ; exp2; exp3 ) Statements; Inthis format theinitializationexpression(i.e., exp1)is omitted. The initial value ofthe variable canbe assigned outside ofthe forloop. Example 1 int i= 1; for( ; i<=10; i++ ) printf(“%dn”, i); Formate - II for( ; exp2 ; ) Statements; Inthis format the initializationand increment ordecrement expression (i.e expression-1 and expression-3) are omitted. The exp-3 can be given at the statement part. Example 2 int i= 1; for( ; i<=10; ) { printf(“%d n”,i); i++; } Formate - III for( ; ; ) Statements;
  • 48. Computer Science and Engineering 296 In this format the threeexpressions are omitted. The loop itselfassumes the expression-2is true. So Statements willbe executed infinitely. Example 3 int i= 1; for ( ; i<=10; ) { printf(“%d n”,i); i++; } 2.9 Nested Looping Statements Manyapplications requirenesting ofthe loop statements,allowing onloop statement to be embedded withinanother loop statement. Definition Nesting canbe defined as themethod ofembedding one controlstructure withinanother controlstructure. While making controlstructure s to be reside one within another ,the inner and outer control structures may be of the same type or may not be of same type. But ,it is essential for us to ensure that one control structure is completelyembedded within another. /*programto implement nesting*/ #include <stdio.h> main() { int a,b,c, for (a=1,a< 2, a++) { printf(“%d”,a) for (b=1,b<=2,b++) {
  • 49. 297 Paper - II Programming in C print f(%d”,b) for (c=1,c<=2,c++) { print f( “ MyName is Sunnyn”); } } } } 2.10 Multi Branching Statement (switch), Break, and Continue For effectivehandling ofthe loopstructures, C allows the following types ofcontrolbreak statements. a. Break Statement b. Continue Statement a. Break Statement The break statement is used to terminate the controlformthe loops or to exit froma switch. It canbe used withina for, while, do-while, for. The generalformat is : break; Ifbreakstatement is included ina while, do-whileor forthencontrolwill immediately be transferred out of the loop when the break statement is encountered. Example for ( ; ;) normal loop { break Condition withinloop scanf(“%d”,&n); if ( n < -1)
  • 50. Computer Science and Engineering 298 break; sum= sum + n; } b. The Continue Statement The continuestatement is used to bypass the remainder ofthe current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather, theremainingloopstatementsareskippedandtheproceeds directlyto thenext pass throughtheloop. The “continue” that canbe included with in a while ado-while and a forloop statement. Generalform: continue; The continue statement is used for the inverse operation of the break statement . Condition withinloop Remaining part ofloop continue Example while (x<=100) { if (x<= 0) { printf(“zero ornegative value found n”); continue; } } The above program segment will process only the positive whenever a zero or negative value is encountered, the message will be displayed and it continue thesame loop as long as the givenconditionis satisfied.
  • 51. 299 Paper - II Programming in C 2.11 Differences between Break and Continue 2.12 Unconditional Branching (Go To Statement) goto statement The go to statement is used to alter the programexecution sequence by transferring the controlto some other part ofthe program. Syntax Where labelis an identifier used to labelthe target statement to which the controlwould betransferred the target statement willappear as: Syntax goto<label>; label: statements; Break 1. Break is a key word used to terminate the loop or exit from the block. The control jumps to next statement after the loop or block 2. Break statements can be used with for, while, do-while, and switch statement. When break is used in nested loops, thenonly the innermost loop is terminated. 3. Syntax:{ statement1; statement2; statement3; break;} 4. Example :Switch( choice){ Case ‘y’: printf(“yes”); break; Case ‘n’: printf(“NO”); break;} 5. When the case matches with the choice entered, thecorresponding case block gets executed. When ‘break’ statement is executed, the control jumps out ofthe switchstatement. Continue 1. Continue is a keyword used for containing the next iteration of the loop 2. This statement when occurs in a loopdoesnotterminateit ratherskips the statements after this continue statement and the control goes for next iteration. ‘Continue’canbe used withfor, while and do- while loop. 3. Syntax: { statement1; continue; statement2; statement3; break; } 4. Example:- I = 1, j=0;While( i<= 7){ I= I+1; If((I == 6) Continue; j = j + 1;} 5. Inthe above loop, whenvalue of‘ i becomes 6’ continue statement is executed. So, j= j+1 is skipped and controlis transferred to beginning of while loop.
  • 52. Computer Science and Engineering 300 Example 1 #include <stdio.h> main(); { inta,b; printf(“Enterthe two numbers”); scanf(“%d %d”,&a,&b); if(a>b) gotobig; else gotosmall; big :printf(“bigvalue is %d”,a); gotostop; small:printf(“smallvalue is %d”,b); gotostop; stop; } Simple Programs Covering Above Topics Practice Programs 1. Write a C program to find out smallest value amongA, B,C. Ans: include<stdio.h> int a,b,c; clrscr(); scanf(%d %d %d, &a, &b, &c); if(a<b) {
  • 53. 301 Paper - II Programming in C if(a<c) printf(“aissmall/n”) else } 02. Write a‘C’ programe for5th multiplication tablewith the help of goto statement. Ans. #include<stdio.h> main() { int t, n = 1, P; Printf(“Entertablenumber:”); Scanf(“%d,&t); A: if(n<=10) { P=t * n; Printf(“%d * %d= %d n”, t,n,p); n++; gotoA; } else printf(“Out ofrange”); } 03. Write a ‘C’ program to find greatest among three numbers. Ans. #include<stdio.h> void main( )
  • 54. Computer Science and Engineering 302 { int a,b,c; printf(“enter thevalues ofa,b,c,”); scanf(“%d%d%d”, &a,&b,&c); if((a>b)&&(c>b)) { if(a>c) printf(“a isthe maxno”); else printf(“C isthe maxno”); } else if((b>c)&&(a>c)) { if(b>a) printf(“bisthe maxno”); else printf(“a isthe maxno”); } else if((b>a)&&(c>a)) { if(b>c) printf(“bisthe maxno”); else printf(“C isthe maxno”); } }
  • 55. 303 Paper - II Programming in C Model Questions Short Answer Type Question - 2 Marks 1. Write the structure ofC program 2. Define a variable and a constant in C. 3. What is an expression in C. 4. What are the operators used in C. 5. Mentionthe significanceofmain( ) function. 6. What are formatted and Unformatted Input-output statements. 7. Write thesyntaxofscanf() andprintf() statements. 8. Write the syntax do loop controlstructure. 9. Write short notes ongo to statement? 10. Mention difference between While loop and do…While loop. 11.What is Nested Loop? 12. Writethe syntaxof While statement. 13. Write the syntaxoffor…loop statement. 14. Writeabout ‘Switch” Statement. 15. Write the syntaxofSimpleifstatement. 16. Write the syntax of if… else statement. 17. What is Preprocessor statement in C. 18. What are different types oferrors occurred during the execution ofC program. 19. What is Variable and Constant in C?What are types ofConstants in C. 20. What are basic data types in C. 21. What is String Constant. Long Answer Type Questions - 6 Marks 01. Explainthe basic structure ofC program. 02. Write about data types used in C.
  • 56. Computer Science and Engineering 304 03. What is Constant? Explain various types of constants in C. (or) 04. Explainvarious types ofOperators in C. 05. Explainformattedand un-formatted input and output statements inC 06. Explainvarious conditionalcontrolstructures inC. 07. Explainvarious conditionallooping statements inC. 08. Write the differences between Break and Continue Note: Practice some more programs relatedusing above statements.
  • 57. 3 UNIT Functions Structure 3.0Introduction 3.1 Functions 3.2 Differences betweenFunction and Procedures 3.3Advantages ofFunctions 3.4Advanced features ofFunctions 3.5 Recursion Learning Objectives • Define a Function • Stress on Returnstatement • Writeprogramsusingfunctioncalltechniques. • Function prototype • Differentiate Localand Globalvariables • Recursion.
  • 58. Computer Science and Engineering 306 3.0 Introduction Experienced programmer used to divide large (lengthy) programs in to parts, and then manage those parts to be solved one by one. This method of programming approachis to organize thetypicalwork in asystematic manner. Thisaspect ispracticallyachieved nC language thoroughtheconcept knownas ‘ModularProgramming”. The entire programis divided into a series ofmodules andeachmodule is intended to perform a particular task. The detailed work to be solved by the module is described in the module (sub program) onlyand the main program only contains a series of modulus that are to be executed. Division ofa main programinto set ofmodulesandassigningvarioustaskstoeachmoduledepends ontheprogrammer’s efficiency. Whereas thereis a need forus repeatedlyexecute oneblock ofstatements in one place of the program, loop statements can be used. But, a block of statements need to be repeatedlyexecuted inmany parts ofthe program, then repeated codingas wellas wastage ofthe vitalcomputerresource memorywill wasted. . Ifwe adopt modular programming technique, these disadvantages can be eliminated. The modules incorporated in C are called as the FUNCTIONS, and each function in the program is meant for doing specific task. C functions are easyto use and veryefficient also. 3.1 Functions Definition A function can be defined as a subprogram which is meant for doing a specific task. InaCprogram, afunctiondefinitionwillhavename,parenthesespaircontain zero or more parameters and a body. The parameters used in the parenthesis need to bedeclared with type and ifnot declared, theywillbeconsidered as of integer type. The generalformofthe functionis : function type name <arg1,arg2,arg3, ————,argn>) data type arg1, arg2,; data type argn; { bodyoffunction;
  • 59. 307 Paper - II Programming in C —————————— —————————— —————————— return(<something>); } Fromthe aboveformthe main componentsoffunctionare • Returntype • Functionname • Functionbody • Returnstatement Return Type Refers to the type of value it would return to the calling portion of the program. It can have any of the basic data types such as int, float, char, etc. When afunction is not supposedto returnanyvalue, it maybe declaredas type void Example void function name(- - - - - - - - - -); int function name( - - - - - - - - - - ); char function name ( — - - - - - - ); Function Name The function name can be anyname conforming to the syntaxrules ofthe variable. Afunctionname is relevant to the functionoperation. Example output(); read data( );
  • 60. Computer Science and Engineering 308 Formalarguments The arguments are called formal arguments (or) formal parameters, because they represent the names of data items that are transferred into the functionfromthe calling portionoftheprogram. Any variable declared in the bodyof a function is said to be localto that function,othervariablewhichwerenotdeclaredeitherargumentsorinthefunction body, are considered “globol” to the function and must be defined externally. Example int biggest (int a, int b) { ———————————— ———————————— ———————————— return(); } a, b are the formalarguments. FunctionBody Function bodyis a compound statement defines the action to be taken by the function. It shouldincludeone or more“return”statement inorderto return a valueto the calling portionofthe program. Example int biggest(int a, int b) { if ( a > b) return(a);bodyoffunction. else return(b); }
  • 61. 309 Paper - II Programming in C EveryCprogramconsists ofoneor morefunctions. Oneofthese functions must be called asmain.Executionofthe programwillalwaysbeginbycarrying out the instructionsinmain.Additionalfunctionswillbesubordinateto main. Ifa programcontains multiplefunctions, their definitions mayappearin anyorder, thoughtheymust be independent ofone another. That is, one functiondefinition can’t be embedded within another. Generallya function willprocess informationthat is passed to it fromthe calling portionofthe programand returna single value. Informationispassedto thefunctionviaarguments(parameters)andreturnedviathe“return”statement. Some functions accept informationbut do not returnanything(ex:printf()) whereas other functions (ex:scanf()) returnmultiple values. 3.1.1 The Return Statement EveryfunctionsubprograminC willhave returnstatement. This statement isusedinfunctionsubprogramsto returnavalueto thecallingprogram/function. This statement can appear anywhere withina function bodyand we mayhave more thanone returnstatement insidea function. The generalformat ofreturnstatement is return; (or) return (expression); Ifno valueis returnedfromfunctionto the calling program, thenthere is no need ofreturnstatement to be present inside the function. Programs using function CallTechniques Example 1: Write a programto find factorialto thegivenpositive integer ,usingfunctiontechnique. # include <stdio.h> main() { int n; printf ( “ Enter any positive numbern”); scanf( “%d”, &n);
  • 62. Computer Science and Engineering 310 printf( “ The factorialof%d s %d n”,fact (n)); } fact( i) int I; { int j; f = 1 ; for ( j = I; j>0; j - -) f = f * I; return ( f ) ; } Intheaboveprogramfunctionwithname‘fact’iscalledbythemainprogram. The function fact is called with n as parameter. The value is returned through variable fto the mainprogram. Example 2: Write a programto find the value off(x) as f(x) = x2 + 4, for the givenofx. Make useoffunctiontechnique. # include <stdio.h> main( ) { f ( ); } f ( ) { int x,y ; printf( “Enter value ofx n”); scanf( “ %d”, & x ); y = (x * x + 4); printf ( “ The value off (x) id %d n”, y) ; }
  • 63. 311 Paper - II Programming in C 3.2 Differences between Function and Procedures 3.3 Advantages of Function The main advantages of using a function are: • Easyto writea correct smallfunction • Easyto read and debug a function. • Easier to maintainor modifysucha function • Smallfunctions tendto be selfdocumentingand highlyreadable • It canbe called anynumberoftimes in anyplace withdifferent parameters. Storage class Avariable’s storage class explains where the variable will be stored, its initialvalue andlife ofthe variable. Iteration TheblockofstatementsisexecutedrepeatedlyusingloopsiscalledIteration Procedure 1. Procedureis a subprogram which is included with in main program. 2. Procedure donot return a value. 3. Procedure cannot be called again and again. 4. Global variables cannot be used in procedure. 5. Procedures can be writ- ten only in procedural pro- gramming such as Dbase, Foxpro. Function 1. Functions is sub program which is intended for specific task. Eg. sqrt() 2. Functions may or may not return a value. 3. Function once defined can be called any where n number oftimes. 4. In functions both local and global variables can be used. 5. Functions can be written in modular programming such as C,C++
  • 64. Computer Science and Engineering 312 Categories of Functions A function, depending on, whether arguments are present or not and a value is returned or not. Afunctionmaybe belonging to one ofthe following types. 1. Functionwithno arguments and no returnvalues. 2. Functionwitharguments and no returnvalues. 3. Functionwitharguments and returnvalues 3.4 Advanced Featured of Functions a. Function Prototypes b. Calling functions byvalueor byreference c. Recursion. a. Function Prototypes The user defined functions maybe classified as three ways based on the formalarguments passed andthe usage ofthe returnstatement. a. Functions withno arguments andno return value b. Functions witharguments no returnvalue c. Functions witharguments and returnvalue. a. Functions with no arguments and no return value Afunctionisinvokedwithout passinganyformalargumentsfromthecalling portionofa programand alsothe functiondoes not returnback anyvalueto the called function. There is no communication between the calling portion of a programand a called functionblock. Example: #include <stdio.h> main() { void message( ); Function declaration message( ); Function calling }
  • 65. 313 Paper - II Programming in C void message( ) { printf(“GOVT JUNIOR COLLEGE n”); printf(“t HYDERABAD”); } b. Function with arguments and noreturn value This typeoffunctions passes someformalarguments to a function but the function does not return back any value to the caller. It is any one way data communicationbetweena callingportionoftheprogramandthefunctionblock. Example #include <stdio.h> main() { void square(int); printf(“Enter a value for nn”); scanf(“%d”,&n); square(n); } void square (int n) { int value; value = n * n; printf(“square of%d is %d “,n,value); } c. Function with arguments and return value The thirdtypeoffunctionpassessome formalargumentsto afunctionfrom a calling portionofthe programand the computer value is transferred back to the caller. Data are communicated betweenthe calling portion andthe function block.
  • 66. Computer Science and Engineering 314 Example #include <stdio.h> main() { int square (int); int value; printf(“enter avalue for n n”); scanf(“%d”, &n); value = square(n); printf(“square of%d is %d “,n, value); } int square(int n) { int p; p = n * n; return(p); } ThekeywordVOIDcanbeusedasatypespecifierwhendefiningafunction that does not return anything or when the function definitiondoes not include anyarguments. Thepresenceofthiskeywordisnot mandatorybut itis goodprogramming practice to make use ofthis feature. Actual and FormalParameters (or)Arguments Function parameters arethe means ofcommunicationbetweenthe calling and the calledfunctions. The parameters mayclassifyunder two groups. 1. FormalParameters 2. ActualParameters
  • 67. 315 Paper - II Programming in C 1. Formal Parameters Theformalparametersare the parameters giveninfunctiondeclarationand function definition. When the function is invoked, the formal parameters are replaced bythe actualparameters. 2. Actual Parameters The parameters appearing in the function call are referred to as actual parameters. Theactualargumentsmaybeexpressedasconstants, singlevariables or more complex expression. Each actualparameter must be ofthe same data type as itscorresponding formalparameters. Example #include <stdio.h> int sum(int a , int b ) { int c; c = a + b; return(c); } main() { intx,y,z; printf(“enter valuefor x,yn”); scanf(“%d %d”,&x,&y); z = x + y; printf(“sumis = %d”,z); } The variables a and b defined infunction definition are knownas formal parameters. The variables x and y are actualparameters.
  • 68. Computer Science and Engineering 316 Local and GlobalVariable: The variables maybe classified as localor globalvariables. Local Variable The variables defined canbe accessed onlywithin the block in which they are declared. These variables are called “Local” variables Example funct (int ,int j) { intk,m; ————; ————; } The integer variables k and m are defined within a function block ofthe “funct()”. All the variables to be used within a function block must be either defined at the beginning of the block or before using in the statement. Local variables one referred onlythe particular part ofa block ofa function. GlobalVariable Globalvariables definedoutside the mainfunctionblock. Globalvariables are not contained to a single function. Global variables that are recognized in two ormore functions. Their scopeextends fromthe pointofdefinitionthrough the remainderofthe program. b. Calling functions by value or by reference The arguments are sent to the functions and their values are copied in the corresponding function. This is a sort ofinformation inter changebetweenthe calling functionandcalled function. This isknown as Parameter passing. It is a mechanismthroughwhich arguments are passed to the called functionfor the required processing. There are two methods ofparameter passing. 1. CallbyValue 2. Callbyreference. 1. Callby value: When thevalues ofarguments are passed fromcalling functionto a called function, thesevalues are copied into the calledfunction. If
  • 69. 317 Paper - II Programming in C any changes are made to these values in the called function, there are NOCHANGE theoriginalvalues withinthecalling function. Example #include <stdio.h> main(); { int n1,n2,x; int cal_by_val(); N1 = 6; N2 = 9; printf( n1 = %d and n2= %dn”, n1,n2); X = cal_by_Val(n1,n2); Printf( n1 = %d and n2= %dn”, n1,n2); Printf(“x=%dn”, x); / * end of main*/ /*functionto illustratecallbyvalue*/ Cal_by_val(p1,p2) int p1,p2; { int sum; Sum = (p1 + p2); P1 + = 2; P2* = p1; printf( p1 = %d and p2= %dn”, p1,p2); return( sum); } }
  • 70. Computer Science and Engineering 318 When the programis executed the output willbe displayed N1 = 6 and n2 = 9 P1 = 8 and p2 = 72 N1 = 6 and n2 = 9 X = 15 There is NO CHANGE in the values of n1 and n2 before and after the functionis executed. 2. Cal by Reference: In this method, the actualvalues are not passed, instead their addresses are passed. There is no copying of values since their memory locations are referenced. Ifanymodification is made to the values in the calledfunction, thentheoriginalvaluesgetchangedwithinthecallingfunction. Passing ofaddresses requires the knowledge ofpointers. Example This programaccepts a one-dimensionalarrayofintegers and sorts them inascendingorder. [This programinvolves passing the arrayto the function]. # include <stdio.h> main(); { int num[20], I,max; void sort_nums(); printf( “enter the size ofthe array”n”); scanf(“%d”, &max); for( i=0;i<max;I++) sort_nums(num,max) /* Function reference*/ printf(“sorted numbers are as followsn”); for( i=0;i<max;I++) printf(“%3dn”,num[i]); /* end of the main*/ /* functionto sort list ofnumbers*/
  • 71. 319 Paper - II Programming in C Void sort_nums(a,n) Int a[],n; { Int I,j,dummy; For(i=0;i<n;i++) { For(j=0; j<n; j++) { If( a[i] >a[j]) { Dummy= a[i]; a[i] = a[j]; a[j] = dummy; } } } } 3.5 Recursion One ofthe specialfeatures ofC language is its support to recursion. Very few computer languageswillsupport this feature. Recursion can be defines as the process of a function by which it can call itself. Thefunction whichcalls itselfagainand againeither directlyor indirectly is knownas recursive function. The normalfunction is usuallycalled bythe main ( ) function, bymans of its name. But, the recursive function willbe called by itselfdepending on the conditionsatisfaction. For Example, main( ) {
  • 72. Computer Science and Engineering 320 f1( ) ; ——— Function called by main —————— —————— —————— } f1( ) ; ——— Function definition { —————— —————— —————— f1( ) ; ——— Function called by itself } In the above, the main ( ) function s calling a function named f1( ) by invoking it withits name. But, insidethefunctiondefinitionf1(), thereisanother invoking offunctionand it is the functionf1( ) again. Example programs on Recursion Example 1 : Write a programto find the factorialofgiven non-negative integerusingrecursive function. #include<stdio.h> main( ) { int result, n; printf( “Enteranynon-negative integern”); scanf( “%d”, & n); result = fact(n); printf( “ The factorialof%d is %d n”, n, result); }
  • 73. 321 Paper - II Programming in C fact( n ) int n; { int i; i = 1; if( i = = 1) return ( i); else { i = i * fact ( n - 1); return( i); } } Example 2: Write ‘C’programto generate Fibonacci series up to a limit using recursionfunction. . #include<stdio.h> #include<conio.h> int Fibonacci(int); void main( ) { int i, n; clrscr ( ); printf(“Enterno. ofElements to be generated” n) scanf(“%d”, &n); for (i=1;i<n; i++) printf(“%d”, Fibonacci(i)); getch( ); }
  • 74. Computer Science and Engineering 322 int Fibonacci(int n) { int fno; if(n= =1) return1; else if(n= =2); return 1; else fno=Fibonacci (n-1) + Fibonacci(n-2); returnfno; } Model Questions Short Answer Type Question - 2 Marks 01. What is function?Write its syntax. 02. What is I/O function?List different types of I/O functions 03. What are the advantages offunctions? 04. Write differences between Globaland Localvariables. 05. List categories offunctions 06. What is storage class? 07. What is Iteration 08. What is recursion? Long Answer Type Question - 6 Marks 01. What is Function?Explain in detail 02. Explaindifferent types offunctions withanexample. 03. Explain about I/O functions. 04. Discuss about Globaland Localvariables.
  • 75. 323 Paper - II Programming in C 05. Explain about Call-by-value with an example. 06. Explain about Call-by-reference with an example. 07. Discuss about Functions and Procedures..
  • 76. Computer Science and Engineering 324 4 UNIT Arrays in ‘C’ Structure 4.0Introduction 4.1 DefinitionofArray 4.2 Types ofArrays 4.3 Two - DimensionalArray 4.4 Declare, initializearrayofchar type Learning Objectives • To understand theimportance ofArray • Definitionofarray • Declarationand InitializingofanArray • Types ofArrays • Examples ofanArray 4.0 Introduction Ifwe dealwithsimilar type ofvariables inmore number at atime, we may have to writelengthyprogramsalongwithlong list ofvariables. There shouldbe
  • 77. 325 Paper - II Programming in C morenumberofassignmentstatementsinorderto manipulateonvariables. When the number ofvariables increases, the length ofprogramalso increase. Intheabove situationsdescribed above, where more number ofsame types ofvariablesisused, theconceptofARRAYSis employedinC language. These are verymuchhelpfulto store as wellas retrieve the data ofsimilar type. AnArraydescribesa contiguouslyallocated non-emptyset ofobjects with the same data type. The using arrays many number ofsame type of variables can be grouped together.Allthe elements stored in the arraywillreferred bya commonname. 4.1 Definition of Array Array can be defined as a collection of data objects which are stored in consecutive memorylocations witha commonvariable name. OR Array can be defined as a group of values referred by the same variable name. OR AnArraycanbe defined as acollection ofdata objects whichare stored in consecutive memorylocations witha commonvariable name. The individualvalues present in thearrayare called elements ofarray. The arrayelements can be values or variables also. 4.2 Types of Arrays Basicallyarrays candivide in to 1. One DimensionalArray Anarraywithonlyone subscript is called as one-dimensional array or 1- d array. It is used to store a list ofvalues, all ofwhich share a common name and are separable bysubscript values 2. Two DimensionalArray An arraywith two subscripts is termed as two-dimensionalarray. Atwo-dimensional array, it has a list of given variable -name using two subscripts. Weknow that a one-dimensionalarraycan store a row ofelements, so, a two-dimensionalarrayenables us to store multiple rows ofelements.
  • 78. Computer Science and Engineering 326 4.2.1 Initialization of Array Arraycanbe made initialized at the time ofdeclarationitself. The general formofarrayinitializationis as below type name[n]= [ element1, element2, …. element n]; The elements 1, element2… element narethe values oftheelements inthe arrayreferenced bythe same. Example1:- int codes[5] = [ 12,13,14,15,16]; Example2:- float a[3] = [ 1.2, 1.3, 1.4]; Example3:- char name [5] = [ ‘S’, ‘U’, ‘N’, ‘I’, ‘L’]; Inabove examples, let us consider one, it a character arraywith5 elements and all the five elements area initialized to 5 different consecutive memory locations. name[0] = ‘S’ name[1] = ‘U’ name[2] = ‘N’ name[3] = ‘I’ name[4] = ‘L’ Rules forArray Initialization 1. Arrays areinitialized withconstants only. 2. Arrayscanbe initialized without specifying the number ofelements in squarebracketsandthis number automaticallyobtainedbythecompiler. 3. The middle elements ofan arraycannot be initialized. Ifwe want to initializeanymiddleelement thenthe initializationofpreviouselementsis compulsory. 4. Ifthearrayelements are not assigned explicitly, initialvalueswillbe set to zero automatically. 5. Ifalltheelements in the arrayare to be initialized withone and same value, then repletionofdata is needed.
  • 79. 327 Paper - II Programming in C 4.2.2 Declaration of Array The array must be declared as other variables, before its usage in a C program. The arraydeclarationincludedprovidingofthe following information to C compiler. - The type of the array (ex. int, float or char type) - The name of the array ( exA[ ],B[ ] , etc) - Number ofsubscripts in the array ( i.e whether one – dimensional orTwo-dimensional) - Totalnumber ofmemorylocations to be allocated. The nameofthe arraycanbe kept bytheuser (the rule similarto naming to variable). Thereis no limit one ondimensionsas wellas numberofmemorylocations and it depends o the capacityofcomputer main memory.. The general formfor array declaration is Type name[n] ; { one dimensionalarray} Ex : int marks[20]; char name[15]; float values [ 10]; Anarray with onlyone subscript is called as one-dimensional array or 1-d array. It is used to store a list ofvalues, allofwhich sharea commonname and are separable bysubscript values. Declaration ofOne-dimensionalArrays: The generalformofdeclaring aone-dimensionalarrayis Wheredata-typerefers to anydatatypesupported byC,array-nameshould beavalidCidentifier;thesizeindicatesthemaximumnumberofstoragelocations (elements) that can be stored. Each element in the array is referenced by the array name followed by a pairofsquarebracketsenclosingasubscript value. Thesubscriptvalueisindexed array-name [size]; data-type
  • 80. Computer Science and Engineering 328 from 0 to size -1. When the subscript vale is 0, first element in the array is selected, when the subscript value is 1, second element is selected and so on. Example int x [6]; Here, xis declared to beanarrayofint type and ofsize six. Sixcontiguous memorylocations get allocated as shownbelow to store sixinteger values. Each dataitemin the arrayx is identified bythe arrayname xfollowed by a pair of square brackets enclosing a subscript value. The subscript value is indexed from0to 5. i.e., x[0] denotes first data item, x[1] denotes second data itemand x[5] denotes the last data item. Initialization ofOne-DimensionalArrays: Just as we initialize ordinaryvariables, we can initialize one-dimensional arraysalso, i.e.,locationsofthearrayscanbegivenvalueswhiletheyaredeclared. The generalformofinitializing anarrayofone-dimensionis as follows: data - type array - name [size] = {list ofvalues}; The values in the list are separated bycommas. Example int x [6] = {1, 2, 3, 4, 5, 6 }; as a result ofthis, memorylocationsofx get filled up as follows: Points to be considered during the declaration 1. Ifthenumberofvalues ininitializationvalue - isless thenthe sizeofan array, onlythose manyfirst locations ofthe arrayare assigned the values. The remaining locationsare assigned zero. Example: int x [6] = {7, 8, 6 }; The size of the array x is six, initialization value - consists of only three locations get 0 assigned to themautomatically, as follows: 1 2 3 4 5 6 x[0] x[1] x[2] x[3] x[4] x[5] 1 2 3 4 5 6 x[0] x[1] x[2] x[3] x[4] x[5]
  • 81. 329 Paper - II Programming in C 2. Ifthe number ofvalues listed within initialization value - list for any arrayis greater than the sixthe array, compiler raises an error. Example: int x [6] = {1, 2, 3, 4, 5, 6, 7, 8 }; The size of the array x is six. But the number of values listed within the initialization-list is eight. Thisisillegal. 3. Ifa static arrayis declared without initializationvalue - list thenthe all locations are set to zero. Example: static int x[6]; 4. If size is omitted in a 1-d array declaration, which is initialized, the compilerwillsupplythisvaluebyexaminingthenumberofvaluesintheinitialization value - list. Example: int x [ ] = {1, 2, 3, 4, 5, 6 }; Sincethenumberofvaluesintheinitializationvalue-list for thearrayxissix, the size ofx is automaticallysupplied as six. 5. There is no arraybound checking mechanismbuilt into C-compiler. It is the responsibilityofthe programmer to see to it that the subscript value does not go beyond size-1. Ifit does, the system maycrash. Example: int x [6]; x [7] = 20; 7 8 6 0 0 0 x[0] x[1] x[2] x[3] x[4] x[5] 0 0 0 0 0 0 x[0] x[1] x[2] x[3] x[4] x[5] 0 0 0 0 0 0 x[0] x[1] x[2] x[3] x[4] x[5]
  • 82. Computer Science and Engineering 330 Here, x [7] does not belong to the array x, it may belong to some other program(forexample, operating system) writinginto the location maylead to unpredictable results oreven to systemcrash. 6. Arrayelements cannot be initialized selectively. Example: Anattempt to initialize only2nd locationis illegal, i.e., int x [6] = { , 10 } is illegal. Similar to arraysofint type, wecanevendeclare arrays ofother data types supported byC, also. Example char ch [6]; chisdeclaredto beanarrayofchartypeand size 6 andit canaccommodate 6 characters. Example: float x[6]; xisdeclared to be anarrayoffloat typeand size 6 andit canaccommodate 6 values of float type. Following is the scheme of memory allocation for the arrayx: Note Aone array is used to store a group ofvalues. Aloop (using, for loop) is used to access each value inthe group. Example Programto illustrate declaration, initializationofa 1-d array #include<stdio.h> ch[0] ch[1] ch[2] ch[3] ch[4] ch[5] x[0] x[1] x[2] x[3] x[4] x[5]
  • 83. 331 Paper - II Programming in C #include<conio.h> void main( ) { int i, x [6] = {1, 2, 3, 4, 5, 6 }; clrscr( ); printf(“The elements ofarrayxn”); for(i=0; i<6; i++) printf(“%d”, x[i]); getch( ); } Input– Output: The elements ofarrayx 1 2 3 4 5 6 4.3 Two - Dimenstional Array An arraywithtwo subscripts is termedas two-dimensionalarray. Atwo-dimensional array, it has a list of given variable -name using two subscripts. Weknow that a one-dimensionalarraycan store a row ofelements, so, a two-dimensionalarrayenables us to store multiple rows ofelements. Example: Table ofelementsor a Matrix. Syntaxoftwo-dimensionalarrays: The syntaxofdeclaring a two-dimensionalarrayis: data - type array - name [rowsize] [ colsize]; Where, data-type refers to anyvalid C data type, array-name refers to anyvalid Cidentifier, row size indicatesthe number ofrows and columnsize indicates thenumber ofelements ineach column. Row sizeand column size shouldbe integer constants. Totalnumber oflocation allocated = (row size * column size).
  • 84. Computer Science and Engineering 332 Each element in a 2-d array is identified by the arrayname followed by a pair ofsquare brackets enclosing itsrow-number, followed bya pair ofsquare brackets enclosing its column-number. Row-number range from0 to row size-1 and column-number range from 0 to column size-1. Example: int y[3] [3]; y is declared to be an array of two dimensions and of data type Integer (int), row size and column size of y are 3 and 3, respectively. Memory gets allocated to store the array y as follows. It is important to note that y is the common name shared byallthe elements ofthe array. Each data itemin the arrayyis identifiable byspecifying the arrayname y followed byapair ofsquare bracketsenclosing row number, followedbya pair ofsquare bracketsenclosing column number. Row-number ranges from 0 to 2. that is, first row is identified by row- number 0, second row is identified byrow-number 1 and so on. Similarly, column-numberranges from0 to 2. First columnisidentified by column-number 0, second columnis identified bycolumn-number 1 andso on. x [0] [0] refers to data itemin the first row and first column x [0] [2] refers to data itemin the first row and third column x [2] [3]refers to data itemin the third rowand fourthcolumn x [3] [4] refers to data itemin the fourthrowand fifthcolumn Initialization ofTwo-DimensionalArray There are two forms ofinitializinga 2-d array. First formofinitializing a 2-d arrayis as follows: x[0] [0] x[0] [1] x[0] [2] x[1] [0] x[1] [1] x[1] [2] x[2] [0] x[2] [1] x[2] [2] 0 1 2 Row num bers . 1 2 3 Columnnumbers
  • 85. 333 Paper - II Programming in C Where, data-name refers to any data type supported by C. Array-name refers to anyvalid C identifier. Row size indicates the number ofrows, column size indicates the number of columns of the array. initialier-list is a comma separated list ofvalues. Ifthe number ofvalues in initializer-list is equalto the product ofrow size and columnsize, the first row sizevalues inthe initializer-list willbe assigned to the first row, the second row size values willbe assigned to the second row of the arrayand so on Example: int x [2] [4] = {1, 2, 3, 4, 5, 6, 7, 8 }; Since columnsizeis 4, the first 4 values ofthe initializer-list are assigned to the first row of x and the next 4 values are assigned to the second row of x as shownhereinafter 1 2 3 4 5 6 7 8 Note: Ifthenumber ofvalues inthe initializer-list is less thanthe product of rowsizeand colsize, onlythe first fewmatching locations ofthearraywould get values fromtheinitializer-list row-wise. The trailingunmatched locations would get zeros. Example: int x [2] [4] = {1, 2, 3, 4}; Thefirst rowofxgets filledwiththevalues intheinitializer-list. Thesecond row getsfilled withzeros. 1 2 3 4 0 0 0 0 The second formofinitializing a 2-d arrayis as follows: data-type array-name[rowsize] [colsize] = {{initializer-list1}, {initializer-list2}, ………};Thevaluesininitializer- list 1 are assigned to the locations inthe first row. The values ininitializer-list2 are assigned to the locations in the second row and so on. Example: int x [2] [4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; data - type array- name [rowsize][colsize] = [initializer - list];
  • 86. Computer Science and Engineering 334 As a result ofthis, the arrayx gets filledup as follows: 1 2 3 4 5 6 7 8 Note 1. Ifthenumberofvaluesspecifiedinanyinitializer-list islessthancolsize ofx, onlythose may first locations in the corresponding row would get these values. The remaininglocations inthat rowwould get 0. Example: int x [2] [4] = { { 1, 2, 3 }, { 4, 5, 6, 7 } }; Since the first initializer-list has onlythree values, x[0][0] is set to 1, x [0] [1] is set to 2, x [0] [2] is set to 3 and the fourth location in the first row is automaticallyset to 0. 1 2 3 0 4 5 6 7 2. Ifthenumberofvaluesspecifiedinanyinitializer-list ismorethancolsize ofx, compiler reports an error. Example: int x [2] [4] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9 } }; colsize is4, but the numberofvalues listed inthe first row is 5. This results incompilationerror. 3. Arrayelements cannot be initialized selectively. 4. It istheresponsibilityoftheprogrammerto ensurethatthearraybounds do not exceedtherowsize andcolsizeofthe array. Iftheyexceed, unpredictable results may be produced and even the program can result in system crash sometimes. 5. A 2-d arrayis used to store a table ofvalues (matrix). Similar to 2-darrays ofint type, we candeclare 2-arrays ofanyother data type supported byC, also. Example: float x[4] [5]; x is declared to be 2-d array of float type with 4 rows and 5 columns double y[4] [5]; y is declared to be 2-d arrays of double type with 4 rows and 5 columns Note
  • 87. 335 Paper - II Programming in C A two-dimensional array is used to store a table of values. Two loops (using for loops) are used to access each value inthe table, first loop acts as a row selector and second loop acts as a column selector in the table. 4.4 Declare, Initialize Array of Char Type DeclarationofArrayofchartype: AstringvariableisanyvalidCvariable name and is always declared as an array. The syntax ofdeclaration of a string variableis: char string-name[size]; The size determines the number ofcharacter inthe string name. Example: An arrayofchar type to store the above string isto be declared asfollows: char str[8]; Anarrayofchar is also called as a stringvariable, since it canstore a string and it permits us to change its contents. In contrast, a sequence of characters enclosed withina pair ofdoublequotes is called astring constant. Example: “Program” isa string constant. Initialization ofArrays of charType The syntaxofinitializinga string variablehastwo variations: Variation 1 char str1 [6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’}; Here, str1 is declared to be a string variable with size six. It can store maximum six characters. The initializer – list consists of comma separated character constants. Note that the nullcharacter ‘0’ is clearly listed. This is required inthis variation. Variation 2 char str2 [6] = { “Hello” }; Here, str2 is also declared to be a string variable of size six. It can store maximumsixcharactersincluding nullcharacter. The initializer-list consists ofa str[0] str[1] str[2] str[3] str[4] str[5] str[6] str[7] P r o g r a m 0
  • 88. Computer Science and Engineering 336 string constant. Inthis variation, nullcharacter ‘0’willbeautomaticallyadded to the end ofstring bythe compiler. In either ofthese variations, the sizeofthe character arraycanbe skipped, in which case, the size and thenumber ofcharacters inthe initializer-list would be automaticallysupplied bythe compiler. Example char str1 [ ] = { “Hello” }; The size ofstr1 would be six, five characters plus one forthe nullcharacter ‘0’. char str2 [ ] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘0’}; The size ofstr2 would be six, five characters plus one for null character ‘0’. Example 1 Program to sort a list of numbers. #include<stdio.h> #include<conio.h> void main( ) { int x [6], n, i, j, tmp; clrscr( ); printf(“Enter theno. ofelements n”); scanf(“%d”, & n); printf(“Enter %d numbers n”, n); for (i=0;i<n; i++) scanf(“%d”, &x [i]); /* sortingbegins */ for (i=0;i<n; i++) for (j=i + 1; j<n; j++) if(x[i]>x[j])
  • 89. 337 Paper - II Programming in C { tmp = x [i]; x [i] = x [j]; x [j] = tmp; } /* sorting ends */ printf(“sortedlist n”); for (i=0;i<n; i++) printf(“%d”, x[i]); getch( ); } Input–Output Enter the no. ofelements 5 Enter 5 numbers 10 30 20 50 40 Sorted list 10 20 30 40 50 Example 2 : C program foraddition of two matrices. #include<stdio.h> #include<conio.h> #include<process.h> void main( ) { int x [5] [5], y [5] [5], z [5] [5], m, n, p, q, i, j;
  • 90. Computer Science and Engineering 338 clrscr ( ); printf(“Enter numberofrows and columns ofmatrixx n”); scanf(“%d %d”, &m, &n); printf(“Enter numberofrows and columns ofmatrixyn”); scanf(“%d %d”, &p, &q); if((m !=P) | | (n!=q)) { printf(“Matrices not compatible for additionn”); exit(1); } printf(“Enter theelements ofxn”); for (i=0;i<m; i++) for (j=0; j<n; j++) scanf(“%d”, &x[i][j]); printf(“Enter theelements ofxn”); for (i=0;i<p; i++) for (j=0; j<n; j++) scanf(“%d”, &y[i] [j]); /* Summationbegins */ for (i=0;j<m; i++) for (j=0; j<n; j++) z[i] [j] = x [i] [j] + y [i] [j]; /* summationends */ printf(“Summatrixzn); for (i=0;i<m; i++) { for (j=0; j<n; j++)
  • 91. 339 Paper - II Programming in C printf(“%d”, z[i] [j]); printf(“n”); } getch( ); } Example3 Write a programfor multiplication oftwo matrices. #include<stdio.h> #include<conio.h> #include<process.h> void main( ) { int x [5] [5], y [5] [5], z [5] [5], m, n, p, q, I, j, k; clrscr ( ); printf(“Enter numberofrows and columns ofmatrixx n”); scanf(“%d %d”, &m, &n); printf(“Enter numberofrows and columns ofmatrixyn”); scanf (%d %d”, &p, &q); if(n!=p) { printf(“Matrices not compatible formultiplicationn”); exit (1); } printf(“Enter theelements ofxn”); for (i=0;i<m; i++) for (j=0; j<n; j++) scanf(“%d”, &x [i] [j]);
  • 92. Computer Science and Engineering 340 printf(“Enter the elements ofyn”); for (i=0;i<p; i++) for (j=0; j<q; j++) scanf(“%d”, &x [i] [j]); printf(“Enter the elements ofyn”); for (i=0;i<p; i++) for (j=0; j<q; j++) scanf(“%d”, &y[i] [j]); /* Multiplication ofmatrices ofx 7 yends */ for (i=0;i<m; i++) for (j=0; j<q; j++) { z [i] [j] = 0; for (k=0; k<n; k++) z [i] [j] + = x [i] [k] * y [k] [j]; } /* Multiplication ofmatrices ofx &yends */ printf(“Product Matrixzn”); for (i=0;i<m; i++) { for (j=0; j<q; j++) printf(“%d”, z[i] [j]); printf(“n”); } getch( ); }
  • 93. 341 Paper - II Programming in C Example 4: C program to print transpose of a matrix. [The transpose ofa matrix isobtained byswitching therows and columns ofmatrix]. #include<stdio.h> #include<conio.h> void main( ) { int a[3] [3], b[3] [3], i, j; clrscr ( ); printf(“Enterthe elements ofthematrix: n”); for (i=0;i<3; i++) for (j=0; j<3; j++) scanf(“%d”, &a[i] [j]); printf(“givenmatrixis :n”); for (i=0;i<3; i++) { for (j=0; j<3; j++) printf(“%d”, a[i] [j]); printf(“n”); } printf(“transposeofgivenmatrixis: n”); for (i=0;i<3; i++) { for (j=0; j<3; j++) { b [i] [j] = a [j] [i]; printf(“%d”, b[i] [j]);
  • 94. Computer Science and Engineering 342 printf(“n”); } } getch( ); } Example 5 Write a ‘C’ program to find the average marks of ‘n’ students of five subjects for each subject using arrays. Ans. #include <stdio.h> void main( ) { int Sno, S1,S2,S3; float tot, avg; char sname[10]; printf(“Enterstudent no;”); scanf(“%d”, & Sname); printf(“Enter subject - 1, sub - 2, sub - 3 marks;”); scanf(“%d %d %d”, &s1,&s2,&s3); tot = S1+S2+S3; avg = tot/3; printf(“total=%f”, tot); printf(“Average =%f”, avg); } Example 6 Write a C program to check the given word is ‘Palindrome’ or not. Ans. #include<stdio.h>
  • 95. 343 Paper - II Programming in C #include<conio.h> void main( ) { char str[80], rev[80]; int k, i, j, flag = 0; clrscr ( ); printf(“Enter anystring (max. 80 chars) : n”); gets(str); for (i=0;str[i]!= ‘0’; i++); for (j=i-1; k=0; j>=0; j—, k++) rev[k] = str[j]; rev[k] = ‘0’; for (i=0;str[i]!= ‘0’; i++) { if(str[i]!=rev[i]) { flag=1; break; } } if(flag = =1); printf(“Givenstringis not palindrome. n”); else printf(“Givenstringispalindrome. n”); getch( ); }
  • 96. Computer Science and Engineering 344 4.5 String Handling Functions in ‘C’ To performmanipulationsonstring data, thereare built-in-fraction(library function) Supportedby‘c’compiler. Thestring functions are. 1. STRLEN (S1) 2. STRCMP (S1, S2) 3. STRCPY (S1, S2) 4. STRCAT (S1, S2) 1. STRLEN (S1): This function isused to returnthe lengthofthe string name S1, Ex: S1 = ‘MOID’ STRLEN (S1) = 4 2. STRCMP (S1, S2): This is a library function used to perform comparisonbetweentwo strings. Thisfunctionreturnsa value<zerowhenstring S1isless thanS2. Thefunctionreturnavalue0whenS1=S2. Finallythefunction return a value > 0 when S1>S2. 3. STRCPY (S1, S2): This is a libraryfunctionused to copythe string S2 to S1. 4. STRCAT (S1, S2): This is a libraryfunctionused to jointwo strings one after the other. This functionconcatenatesstring S2 at the end ofstring S1. Example5 : C program to concatenate the given two strings and print newstring. #include<stdio.h> #include<conio.h> main( ) { char s1[10], s2[10], s3[10], int i,j,k; printf(“Enterthefirst string: n”); scanf(“%s,S”,s1); printf(“Enter thesecond string : n”);