Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ProgramminginC&DataStructureFirstModule
More NextBlog
ProgramminginC&Data
StructureFirstModule
ThisnotesisaccordingtoVTUSyllabus.Itmakeseasytolearnandunderstandableforexampointofview.
Thursday,20August2015
AboutMe
ShivaprakashRanga
Viewmycompleteprofile
MODULEI:INTRODUCTIONTOCLANGUAGE
INTRODUCTION
A computer is an electronicdevice capable of manipulating numbers and
symbolsunderthecontrolofaprogram.
Aprogramisasequenceofinstructionswrittenusingacomputerprogramming
languagetoperformaspecifiedtask.
BlogArchive
2015(1)
August(1)
MODULEI:INTRODUCTIONTOC
LANGUAGEINTRODUCTION...
APSEUDOCODESOLUTIONTOPROBLEM
Algorithm
[Whatisanalgorithm?Whataretheadvantagesofalgorithm?]
An algorithm is a step by step procedure to solve a given problem in finite
http://vtupcd.blogspot.in/
1/31
9/5/2015
ProgramminginC&DataStructureFirstModule
numberofstepsby
acceptingasetofinputsand
producingthedesiredoutputforthegivenproblem
Example:Writeanalgorithmtoadd2numbersenteredbyuser.
Step1:Start
Step2:Declarevariablesnum1,num2&sum.
Step3:Readvaluesofnum1andnum2.
Step4:Addnum1&num2andassigntheresulttosum.sumnum1+num2
Step5:Displaysum
Step6:Stop
Pseudocode
[What is pseudocode? Explain with example and how is different from
algorithm?]
Pseudocodeisamethodofdescribingthealgorithmusingacombinationof
naturallanguage(Englishlikewords)and
programminglanguage
Thisisessentiallyanintermediatesteptowardsthedevelopmentoftheactual
code.
Althoughpseudocodeisfrequentlyused,therearenosetofrulesforitsexact
writing.
Psuedocodeisusedintextbooksandscientificpublicationstodescribevarious
algorithms.
ForExample:
Problem1:Inputtwonumbersanddisplaytheirsum.
1)readnum1,num2
2)findsum=num1+num2
3)displaysum
Problem2:Inputthemarksanddisplaymessagepassedorfailedbasedon
themarks.
1)readmarks
2)ifstudent'smarksisgreaterthanorequalto35
http://vtupcd.blogspot.in/
2/31
9/5/2015
ProgramminginC&DataStructureFirstModule
print"passed"
else
print"failed"
BASICCONCEPTSOFACPROGRAM
[ExplainthestructureofaCprogramwithexample?]
ThestructureofaCprogramisshownbelow:
preprocessordirectives
voidmain()
{
declarationsection
statement1//Executablesectionstartsstatement2
statement3
statement4//Executablesectionends
}
PreprocessorDirectives
Thepreprocessoracceptsthesourceprogramandpreparethesource
programforcompilation.
Thepreprocessorstatementsstartwithsymbol#.
Thenormalpreprocessorusedinallprogramsisinclude.
The #include directive instructs the preprocessor to include the specified file
contentsinthebeginningoftheprogram.
Forex:
#include<stdio.h>
main()
EveryCprogramshouldhaveafunctioncalledasmain().
Thisthefirstfunctiontobeexecutedalways.
The statements enclosed within left and right brace is called body of the
function.Themain()functionisdividedinto2parts:
http://vtupcd.blogspot.in/
3/31
9/5/2015
ProgramminginC&DataStructureFirstModule
1)DeclarationSection
The variables that are used within the function main() should be
declaredinthedeclarationsectiononly.
Thevariablesdeclaredinsideafunctionarecalledlocalvariables.
Ex:intp,t,r
2)ExecutableSection
This contains the instructions given to the computer to perform a
specifictask.
Thetaskmaybeto
displayamessage
readdataor
add2numbersetc
Comments are portions of the code ignored by the compiler. The
commentsallowtheusertomakesimplenotesinthesourcecode.
//thisisanexampleforsinglelinecomment
/*thisisanexampleformultiplelinecomment*/
Example:Programtodisplayamessageonthescreen.
#include<stdio.h>
voidmain()
{
printf(WelcometoC)
}
Output:
WelcometoC
HOWTOLEARNCLANGUAGE?
Englishisauniversallanguageusedtocommunicatewithothers.
In the same way, C is a language used to communicate with computer. In
otherwords,Cisusedtoinstructcomputertoperformparticulartask.
Thetaskcanbe
simpletasklikeadding2numbersor
complextasklikebuildingarailwayreservationsystem
http://vtupcd.blogspot.in/
4/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Beforeyouplaythegame,youshouldlearnrulesofthegame.Sothatyoucan
play better and win easily. In the same way, to write C programs, you should
learnrulesofClanguage.
STEPSTOLEARNCLANGUAGE
Step1: Before speaking any language, we should first learn alphabets. In the
sameway,tolearnClanguage,weshouldfirstlearnalphabetsinC.
Step2:Then,weshouldlearnhowtogroupalphabetsinparticularsequenceto
form a meaningful word. In the same way, in C language, we should learn
tokens(i.e.words).
Step3:Then,youshouldlearnhowtogroupthewordsinparticularsequenceto
formameaningfulsentence.Inthesameway,inClanguage,youshouldlearn
instruction(i.e.sentence).
Step 4: Then, you should learn how to group the sentences in particular
sequencetoformameaningfulparagraph.Inthesameway,inClanguage,you
shouldlearnprogram(i.e.paragraph).
CHARACTERSET
Characterset refers to the set of alphabets, letters and some special
charactersthatarevalidinClanguage.
Forexample,thecharactersinCare:
LettersAX,az,bothupperandlower
Digits09
Symbolssuchas+*/%
Whitespaces
TOKENS
[DefinetokensinClanguageandexplain?]
AtokenisasmallestelementofaCprogram.
One or more characters are grouped in sequence to form meaningful words.
Thesemeaningfulwordsarecalledtokens.
Thetokensarebroadlyclassifiedasfollows
http://vtupcd.blogspot.in/
5/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Keywordsex:if,for,while...etc.
Identifiersex:sum,length
Constantsex:10,10.5,'a',"shivaprakash"
Operatorsex:+*/
Specialsymbolsex:[],(),{}
KEYWORDS
Keywordsaretokenswhichareusedfortheirintendedpurposeonly.
Each keyword has fixed meaning and that cannot be changed by user.
Hence,theyarealsocalledreservedwords.
Rulesforusingkeywords
Keywordscannotbeusedasavariableorfunction.
Allkeywordsshouldbewritteninlowerletters.
Somekeywordsareaslistedbelow
Break Case
Double Else
Register return
Typedef unsigned
Char
Float
Short
void
const
for
signed
while
continue
if
sizeof
Default
Int
struct
Do
long
switch
IDENTIFIER
As the name indicates, identifier is used to identify various entities of
programsuch as variables,constants,functionsetc.
Inotherwords,anidentifierisawordconsistingofsequenceof
Letters
Digitsor
"_"(underscore)
Forexarea,length,breadth
CONSTANTS
A constantis an identifierwhosevalueremainsfixed (constant) throughout
http://vtupcd.blogspot.in/
6/31
9/5/2015
ProgramminginC&DataStructureFirstModule
theexecutionoftheprogram.
Theconstantscannotbemodifiedintheprogram.
Forexample:1,3.14512,z,notesbyspr"
Differenttypesofconstantsare:
11)IntegerConstant
Anintegerisawholenumberwithoutanyfractionpart.
Thereare3typesofintegerconstants:
i)Decimalconstants(0123456789)Forex:0,9,22
ii)Octalconstants(01234567)Forex:021,077,033
iii)Hexadecimalconstants(0123456789ABCDEF)Forex:0x7f,0x2a,
0x521
2) FloatingPointConstant
Thefloatingpointconstantisarealnumber.
Thefloatingpointconstantscanberepresentedusing2forms:
i)FractionalForm
A floating point number represented using fractional form has
anintegerpartfollowedbyadotandafractionalpart.
Forex:0.5,0.99
ii)ScientificNotation(ExponentForm)
The floating point number represented using scientific notation
hasthreepartsnamely:mantissa,Eandexponent.
Forex:9.86E3imply9.86*103
3) CharacterConstant
Asymbolenclosedwithinapairofsinglequotes(')iscalledacharacter
constant.
Each character is associated with a unique value called an ASCII
(AmericanStandardCodeforInformationInterchange)code.
Forex:'9','a','\n'
4) StringConstant
Asequenceofcharactersenclosedwithinapairofdoublequotes()is
calledastringconstant.
http://vtupcd.blogspot.in/
7/31
9/5/2015
ProgramminginC&DataStructureFirstModule
ThestringalwaysendswithNULL(denotedby\0)character.
Forex:"9""a""spr""\n"
5) EscapeSequenceCharacters
Anescapesequencecharacterbeginswithabackslashandisfollowed
byonecharacter.
A backslash (\) along with some characters give rise to special
print effects by changing(escaping)themeaningofsomecharacters.
Thecompletesetofescapesequencesare:
EscapeSequencesCharacter
\b Backspace
\f Formfeed
\n Newline
\rReturn
\tHorizontaltab
\v Verticaltab
\\Backslash
\' Singlequotationmark
\"Doublequotationmark
\? Questionmark
\0 Nullcharacter
BASICDATATYPES
[Definedatatypesandexplainitstypes.
WriteanoteonthebasicdatatypesinCprogramming?]
Thedatatypedefinesthetypeofdatastoredinamemorylocation.
Csupports3classesofdatatypes:
1)Primarydatatype.Forex:int,float,char,double.
2)Deriveddatatypes.Forex:array
3)Userdefineddatatypes.Forex:structure
Csupports5primarydatatypes:
1) int
Anintisakeywordwhichisusedtodefineintegers.
http://vtupcd.blogspot.in/
8/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Usingintkeyword,theprogrammercaninformthecompilerthatthe
dataassociatedwiththiskeywordshouldbetreatedasinteger.
Csupports3differentsizesofinteger:
shortint
int
longint
2) float
Afloatisakeywordwhichisusedtodefinefloatingpointnumbers.
3) double
Adoubleisakeywordusedtodefinelongfloatingpointnumbers.
4) char
Acharisakeywordwhichisusedtodefinesinglecharacter.
5) void
void is an empty data type. Since no value is associated with this data
type, it does notoccupyanyspaceinthememory.
Thisisnormallyusedinfunctionstoindicatethat the functiondoesnot return
anyvalue.
Rangeofdatatypes
Theintegerareclassifiedinto:
unsignedinteger
signedinteger
Rangeofunsignedinteger
3bitunsignednumberrangesfrom0to7(0isminimuminbinary3bitand7is
maximum)
=0to81
http://vtupcd.blogspot.in/
9/31
9/5/2015
ProgramminginC&DataStructureFirstModule
=0to231
4bitunsignednumberrange=0to241
8bitunsignednumberrange=0to281
Ingeneral,nbitunsignedrange=0to2n1
ThereforeRangeofUnsignedNumberwillbe0to2n1inannbitmachine.
Rangeofsignedinteger
RangeofUnsignedNumberwillbe2n1to2n11inannbitmachine.
Datatype Bytes
Rangeofdatatype
Char
Int
float
double
128to127
32,768to32,767
3.4E38to3.4E38
1.7E308to1.7E308
1bytes
2bytes
4bytes
8bytes
Qualifiers(TypeModifiers/TypeSpecifier)
[ExplainbrieflydatatypesqualifiersandmodifiersinC?]
Qualifiersalterthemeaningofprimarydatatypestoyieldanewdatatype.
Builtindatatypesexceptvoiddatatypecaneasilybemodifiedbyusingdata
typemodifiers.Therearemainlyfourdatatypemodifiersnamely:
signed
unsigned
long
short
signed:indicatesthatvaluestoredinavariableiscapableofstoringnegative
values.Thevaluesinrangeof2n1 to+2n11,wherenisthesize(inbits)of
thatparticulardatatype.Example:128to+127forcharacterssincenis8bits.
Declarationexample:signedintaherevariableacanstorebothpositiveand
negativevalues.
unsigned: indicates that value stored in a variable is capable of storing
http://vtupcd.blogspot.in/
10/31
9/5/2015
ProgramminginC&DataStructureFirstModule
positivevalues.Thevaluesinrangeof0to+2n1,wherenisthesize(inbits)
ofthatparticulardatatype.Example:0to+255forcharacterssincenis8bits.
Declaration example: unsigned int a here variable a can store only positive
andvalues.
long: we can increase the storage of a variable from the storage capacity of
basicdatatypeusingkeywordlong.longdoublesthestoragecapacityofadata
typeusedtodeclarevariable.
Example: long int a here variable as size without long is 2 bytes as it is
declaredasitisint(in16bitcomputer),longintdeclarationtakes4bytesforthe
variablea.
short: we can decrease the storage capacity of a variable from the storage
capacityofbasicdatatypeusingkeywordshort.Shortreducesstoragecapacity
ofdatatypetohalf
Example:shortinta
Bydefaultintareserves2bytesforthevariablea,butshortintatakes1byte
only.
VARIABLE
[WhataretherulesforwritingvariableinCprogramming?]
Avariableisanidentifierwhosevaluecanbechangedduringexecutionofthe
program.
Inotherwords,avariableisanamegiventoamemorylocationwherethedata
canbestored.
Usingthevariablename,thedatacanbe
storedinamemorylocationand
accessedormanipulated
Rulesfordefiningavariable
1)Thefirstcharacterinthevariableshouldbealetteroranunderscore
2)Thefirstcharactercanbefollowedbylettersordigitsorunderscore
3)Noextrasymbolsareallowed(otherthanletters,digitsandunderscore)
4)Lengthofavariablecanbeuptoamaximumof31characters
5)Keywordsshouldnotbeusedasvariablenames
http://vtupcd.blogspot.in/
11/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Validvariables:a,principle_amount,sum_of_digits
Invalidvariables:
3fact//violatesrule1
sum= sumofdigits 62$//violatesrule3
forint if//violatesrule5
DeclarationofVariable
Thedeclarationtellsthecomplier
whatisthenameofthevariableused
whattypeofdateisheldbythevariable
Thesyntaxisshownbelow:
data_typev1,v2,v3wherev1,v2,v3arevariablenames
data_typecanbeint,floatorchar
Forex:inta,b,c
floatx,y,z
InitializationofVariable
The variables are not initialized when they are declared. Hence, variables
normallycontaingarbagevaluesandhencetheyhavetobeinitializedwithvalid
data.
Syntaxisshownbelow:
data_typevar_name=data
wheredata_typecanbeint,floatorchar.var_nameisanameofthevariable.
=isassignmentoperatordataisthevaluetobestoredinvariable
Forex:inta=10
floatpi=3.1416
charc='z'
DATAINPUT/OUTPUTFUNCTIONS
[ExplainstandardinputoutputfunctionsinC.
Writeanoteonprintf()andscanf()functions?]
TherearemanylibraryfunctionsforinputandoutputinClanguage.
Forex:getch(),putchar(),scanf(),printf()
For using these functions in a Cprogram there should be preprocessor
http://vtupcd.blogspot.in/
12/31
9/5/2015
ProgramminginC&DataStructureFirstModule
statement#include<stdio.h>
InputFunction
Theinputfunctionsareusedtoread the data from the keyboardand storein
memorylocation.
Forex:
scanf(),getchar(),getch(),getche(),gets()
OutputFunctions
Theoutputfunctionsareusedtoreceivethe data from memorylocationsand
displayonthemonitor.
Forex:printf(),putchar(),putch(),puts()
TypesofI/OFunctions
Thereare2typesofI/OFunctionsasshownbelow:
UNFORMATTEDI/OFUNCTIONS
getchar()andputchar()
getchar()isusedto
readacharacterfromthekeyboardand
storethischaracterintoamemorylocation
YouhavetopressENTERkeyaftertypingacharacter.
http://vtupcd.blogspot.in/
13/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Thesyntaxisshownbelow:
charvariable_name=getchar()
Forex:
charz
z=getchar()
putchar()isusedtodisplayacharacterstoredinthememorylocationonthe
screen.
#include<stdio.h>
main()
{
charx
chary=n
printf(enteroneletterterminatedbyENTERkey\n)
x=getchar()
putchar(y) //sameasprintf(%c,z)
}
Output:
enter one letter
terminated
byENTERkeym
getch()andputch()
getch() is used to read a character from the keyboard without echo(i.e.
typedcharacterwillnotbevisibleonthescreen).Thecharacterthusentered
willbestoredinthememorylocation.
putch() is used to display a character stored in memorylocation on the
screen.
#include<stdio.h>
voidmain()
{
int z
printf(enteroneletter\n)
z=getch()
putch(z) //sameasprintf(%c,z)
}
Output:
Enteroneletter
http://vtupcd.blogspot.in/
14/31
9/5/2015
ProgramminginC&DataStructureFirstModule
m//misnotvisible
m
getche()
getche()is used to read a character from the keyboard with echo(i.e. typed
characterwillbevisiblescreen).Thecharacterthusenteredwillbestoredinthe
memorylocation.
#include<stdio.h>
voidmain()
{
int z
printf(enteroneletter\n)
z=getche()
putch(z) //sameasprintf(%c,z)
}
Output:
enteroneletter
m//misvisible
m
gets()andputs()
gets()isusedto
readastringfromthekeyboardand
storethestringinmemorylocations
puts()isusedtodisplayastringstoredinmemorylocationsonthescreen.
#include<stdio.h>
voidmain()
{
charstring[20]
printf("enterastring\n")
gets(string)
puts(string) //sameasprintf("%s",string)
}
Output:
enterastring
notesbyspr
http://vtupcd.blogspot.in/
15/31
9/5/2015
ProgramminginC&DataStructureFirstModule
notesbyspr
DisadvantageofUnformattedI/O
It is not possible to read/print any other data except characters i.e. it is not
possibletoread/printintegernumbers,floatingpointnumbersetc.
FORMATTEDI/OFUNCTION
scanf()
Thescanffunctiondoesfollowingtasks:
scanaseriesofinputfieldsonecharacteratatime
Format each field according to a corresponding formatspecifier
passedinformatstring(formatmeansconvert).
Storetheformattedinputatanaddresspassedas an argumenti.e.
addresslist
Syntaxisshownbelow:
n=scanf("formatstring",addresslist)
whereformatstringcontainsoneormoreformatspecifiers
addresslistisalistofvariables.Eachvariablenamemust be
precededby&
Forex:
n=scanf("%d%f%c",&x,&y,&z)
Formatspecifiers Meaning
%d anintargumentindecimal
%ldalongintargumentindecimal
%cacharacter
%sastring
%f afloatordoubleargument
%e sameas%f,butuseexponentialnotation
%o anintargumentinoctal(base8)
%xanintargumentinhexadecimal(base16)
printf
http://vtupcd.blogspot.in/
16/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Theprintffunctiondoesfollowingtasks:
Acceptaseriesofarguments
Applyto each argumenta formatspecifier contained in the format
string
Outputtheformatteddatatothescreen
Thesyntaxisshownbelow:
n=printf("formatstring",variablelist)
where formatstring contains one or more
format specifiers and variablelist contains
namesofvariables
Forex:n=printf("%d%f%c",x,y,z)
Example:Programtoreadyourageanddisplaythesameonthescreen.
#include<stdio.h>
voidmain()
{
intage
printf(enteryourage:\n)
scanf(%d,age)
printf(yourageis=%dyears,age)
}
Output:
enteryourage:
21
yourageis=21years
VariationsInOutputFunctionForIntegerAndFloats
IntegerandfloatingpointscanbedisplayedindifferentformatsinCasshown
below:
#include<stdio.h>
voidmain()
{
http://vtupcd.blogspot.in/
17/31
9/5/2015
ProgramminginC&DataStructureFirstModule
printf("Case1:%6d\n",9876)
// Printsthenumberrightjustifiedwithin6columns
printf("Case2:%3d\n",9876)
//Printsthenumbertoberightjustifiedto3columnsbut,thereare4
// digitssonumberisnotrightjustified
printf("Case3:%.2f\n",987.6543)
//Printsthenumberroundedtotwodecimalplaces
printf("Case4:%.f\n",987.6543)
//Printsthenumberroundedto0decimalplace,i.e.,roundedtointeger
printf("Case5:%e",987.6543)
//Printsthenumberinexponentialnotation(scientificnotation)
}
Output:
Case1: 9876
Case2:9876
Case3:987.65
Case4:988
Case5:9.876543e+002
OPERATOR
Anoperatorcanbeanysymbollike+*/thatspecifieswhatoperationneedto
beperformedonthedata.
Forex:+indicatesaddoperation,*indicatesmultiplicationoperation
OPERAND
Anoperandcanbeaconstantoravariable.
EXPRESSION[DefineanexpressioninC.Explainitscategorieswithexample]
Anexpressioniscombinationofoperandsandoperatorthatreducestoasingle
value.
Forex:Considerthefollowingexpressiona+bhereaandbareoperandswhile
+isanoperator.
CLASSIFICATIONOFOPERATORS
OperatorName ForExample
http://vtupcd.blogspot.in/
18/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Arithmeticoperators +*/%
Increment/decrementoperators++
Assignmentoperators =
Relationaloperators <>==
Logicaloperators&&||~
Conditionaloperator?:
Bitwiseoperators & |^
Specialoperators[]
ARITHMETICOPERATORS
Theseoperatorsare used to performarithmeticoperationssuch as addition,
subtraction,
Thereare5arithmeticoperators:
OperatorMeaningofOperator
+addition
subtraction
* multiplication
/division
% modulos
Divisionsymbol(/)
dividesthefirstoperandbysecondoperandand
returnsthequotient.
Quotientistheresultobtainedafterdivisionoperation.
Modulussymbol(%)
dividesthefirstoperandbysecondoperandand
returnstheremainder.
Remainderistheresultobtainedaftermodulusoperation.
Toperformmodulusoperation,bothoperandsmustbeintegers.
Programtodemonstratetheworkingofarithmeticoperators.
#include<stdio.h>
voidmain()
{
inta=9,b=4,c
c=a+b
printf("a+b=%d\n",c)
http://vtupcd.blogspot.in/
19/31
9/5/2015
ProgramminginC&DataStructureFirstModule
c=ab
printf("ab=%d\n",c)
c=a*b
printf("a*b=%d\n",c)
c=a/b
printf("a/b=%d\n",c)
c=a%b
printf("Remainderwhenadividedbyb=%d",c)
}
Output:a+b=13,ab=5,a*b=36,a/b=2
Remainderwhenadividedbyb=1
INCREMENTOPERATOR
++isanincrementoperator.
Asthenameindicates,incrementmeansincrease,i.e.thisoperatorisusedto
increasethevalueofavariableby1.
Forexample:
Ifb=5
then b++ or++b //bbecomes6
Theincrementoperatorisclassifiedinto2categories:
1)PostincrementEx:b++
2)Preincrement Ex:++b
As the name indicates,postincrementmeans first use the value of variable
andthenincreasethevalueofvariableby1.
Asthenameindicates,preincrementmeansfirstincreasethevalueofvariable
by1and
thenusetheupdatedvalueofvariable.
Forex:
Ifxis10,
then z=x++setszto10
but z=++xsetszto11
Example:Programtoillustratetheuseofincrementoperators.
voidmain()
{
intx=10,y=10,z
http://vtupcd.blogspot.in/
20/31
9/5/2015
ProgramminginC&DataStructureFirstModule
z=x++
printf(z=%dx=%d\n,z,x)
z=++y
printf(z=%dy=%d,z,y)
}
Output:z=10x=11z=11y=11
DECREMENTOPERATOR
isadecrementoperator.
Asthenameindicates,decrementmeansdecrease,i.e. this operatoris used
todecreasethevalueofavariableby1.
Forexample:
Ifb=5
then b orb//bbecomes4
Similar to increment operator, the decrement operator is classified into 2
categories:
1)PostdecrementEx:b
2)Predecrement Ex:b
Forex:
Ifxis10,
then z=xsetszto10,
but z=xsetszto9.
Example:Programtoillustratetheuseofdecrementoperators.
voidmain()
{
intx=10,y=10,z
z=x
printf(z=%dx=%d\n,z,x)
z=y
printf(z=%dy=%d,z,y)
}
Output:
z=10x=9
z=9y=9
http://vtupcd.blogspot.in/
21/31
9/5/2015
ProgramminginC&DataStructureFirstModule
ASSIGNMENTOPERATOR
Themostcommonassignmentoperatoris=
Thisoperatorassignsthevalueinrightsidetotheleftside.
Thesyntaxisshownbelow:
variable=expression
Forex:
c=5 //5isassignedtoc
b=c //valueofcisassignedtob
5=c //Error!5isaconstant.
Theoperatorssuchas+=,*=arecalledshorthandassignmentoperators.
Forex,
a=a+10: canbewrittenasa+=10
Inthesameway,wehave:
Operator
=
*=
/=
%=
Example
a=b
a*=b
a/=b
a%=b
Sameas
a=ab
a=a*b
a=a/b
a=a%b
RELATIONALOPERATORS
Relationaloperatorsareusedtofindtherelationshipbetweentwooperands.
Theoutputofrelationalexpressioniseithertrue(1)orfalse(0).
Forexample
a>b //Ifaisgreaterthanb,thena>breturns1elsea>breturns0.
The2operandsmaybeconstants,variablesorexpressions.
Thereare6relationaloperators:
OperatorMeaningofOperatorExample
>Greaterthan 5>3returnstrue(1)
<Lessthan5<3returnsfalse(0)
http://vtupcd.blogspot.in/
22/31
9/5/2015
ProgramminginC&DataStructureFirstModule
>= Greaterthanorequalto5>=3returnstrue(1)
<= Lessthanorequalto 5<=3returnfalse(0)
== Equalto5==3returnsfalse(0)
!=Notequalto 5!=3returnstrue(1)
Forex:
ConditionReturnvalues
2>1 1(ortrue)
2>3 0(orfalse)
3+2<61(ortrue)
Example:Programtoillustratetheuseofallrelationaloperators.
#include<stdio.h>
voidmain()
{
printf(4>5:%d\n,4>5)
printf(4>=5:%d\n,4>=5)
printf(4<5:%d\n,4<5)
printf(4<=5:%d\n,4<=5)
printf(4==5:%d\n,4==5)
printf(4!=5:%d,4!=5)
}
Output:
4>5:0
4>=5:0
4<5:1
4<=5:1
4==5:0
4!=5:1
LOGICALOPERATORS
These operators are used to perform logical operations like negation,
conjunctionanddisjunction.
Theoutputoflogicalexpressioniseithertrue(1)orfalse(0).
Thereare3logicaloperators:
http://vtupcd.blogspot.in/
23/31
9/5/2015
ProgramminginC&DataStructureFirstModule
OperatorMeaningExample
&& LogicalANDIfc=5andd=2then((c==5)&&(d>5))returnsfalse.
|| LogicalOR Ifc=5andd=2then ((c==5)||(d>5))returnstrue.
! LogicalNOT Ifc=5then!(c==5)returnsfalse.
Allnonzerovalues(i.e.1,1,2,2)willbetreatedastrue.
Whilezerovalue(i.e.0)willbetreatedasfalse.
Truthtable
A
0
0
1
1
B
0
1
0
1
A&&B
0
0
0
1
A||B
0
1
1
1
!A
1
0
Example:Programtoillustratetheuseofalllogicaloperators.
#include<stdio.h>
voidmain()
{
clrscr()
printf(7&&0:%d\n,7&&0)
printf(7||0:%d\n,7||0)
printf(!0:%d,!0)
}
Output:
7&&0:1
7||0:1
!0:1
Example:Programtoillustratetheuseofbothrelational&Logicaloperators.
#include<stdio.h>
voidmain()
{
printf(5>3&&5<10:%d\n,5>3&&5<10)
http://vtupcd.blogspot.in/
24/31
9/5/2015
ProgramminginC&DataStructureFirstModule
printf(8<5||5==5:%d\n,8<5||5==5)
printf(!(8==8):%d,!(8==8)
}
Output:
5>3&&5<10:1
8<5||5==5:1
!(8==8):0
CONDITIONALOPERATOR
Theconditionaloperatorisalsocalledternaryoperatorittakesthreeoperands.
ConditionaloperatorsareusedfordecisionmakinginC.
Thesyntaxisshownbelow:(exp1)?exp2:exp3
whereexp1isanexpressionevaluatedtotrueorfalse
Ifexp1isevaluatedtotrue,exp2isexecuted
Ifexp1isevaluatedtofalse,exp3isexecuted.
Example:Programtofindlargestof2numbersusingconditionaloperator.
#include<stdio.h>
voidmain()
{
inta,b,max
printf(enter2distinctnumbers\n)
scanf(%d%d,&a,&b)
max=(a>b)?a:b
printf(largestnumber=%d,max)
}
Output:
enter2distinctnumbers
34
largestnumber=4
BITWISEOPERATORS
These operators are used to perform logical operation (and, or, not) on
individualbitsof a binarynumber.
http://vtupcd.blogspot.in/
25/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Thereare6bitwiseoperators:
Operators Meaningofoperators
& BitwiseAND
|BitwiseOR
^BitwiseexclusiveOR
~Bitwisecomplement
<< Shiftleft
>> Shiftright
A
0
0
1
1
TruthTable
B
A&B
0
0
1
0
0
0
1
1
A|B
0
1
1
1
A^B
0
1
1
0
~A
1
0
Exfor~(bitwisecomplement)Exfor&(bitwiseAND)
a=13 00001101a=13 00001101
~a=11110010b=6 00000110
a&b 00000100
Exfor||(bitwiseOR) Exfor^(bitwisexor)
a=13 00001101a=13 00001101
b=6 00000110b=6 00000110
a|b 00001111a^b 00001011
The operator that is used to shift the data by a specified number of bit
positionstowardsleftorrightiscalledshiftoperator.
Thesyntaxisshownbelowfor<< Thesyntaxisshownbelow
for>>
b=a<<num b=a>>num
whereaisvaluetobeshifted
numisnumberofbitstobeshifted.
Exfor<<(leftshift):Exfor>>(rightshift):
http://vtupcd.blogspot.in/
26/31
9/5/2015
ProgramminginC&DataStructureFirstModule
a=13
00001101
a=13
00001101
b=a<<1
00011010
b=a>>1
00000110
TYPECONVERSION
Typeconversionisusedtoconvertdataofonetypetodataofanothertype.
Typeconversionisof2typesasshowninbelowfigure:
IMPLICITCONVERSION
Ifacompilerconvertsonetypeofdataintoanothertypeofdataautomatically,
itisknownasimplicitconversions.
Thereisnodatalossinimplicitconversion.
Theconversionalwaystakesplacefromlowerranktohigherrank.
Forex,inttofloatasshownintheabovedatatypehierarchy.
Forex:
inta=22,b=11
floatc=a //cbecomes22.000000
floatd=b/c=11/22.000000=11.000000/22.000000=0.500000
If one operand type is same as other operand type, no conversion takes
place and type of result remains same as the operands i.e. int+int=int ,
float+float=float
http://vtupcd.blogspot.in/
27/31
9/5/2015
ProgramminginC&DataStructureFirstModule
Conversionrulesareasfollows:
Ifeitheroperandislongdouble,converttheothertolongdouble.
Otherwise,ifeitheroperandisdouble,converttheothertodouble.
Otherwise,ifeitheroperandisfloat,converttheothertofloat.
Otherwise,convertcharandshorttoint.
Then,ifeitheroperandislong,converttheothertolong.
Example:Programtoillustrateimplicitconversion.
#include<stdio.h>
voidmain()
{
inta=22,b=11
floatd
d=b/c
printf("dValueis:%f",d)
}
Output:
dValueis:0.500000
EXPLICITCONVERSION
Whenthedataofonetypeisconvertedexplicitlytoanothertypewiththe help
ofsomepredefinedfunctions,itiscalledasexplicitconversion.
Theremaybedatalossinthisprocessbecausetheconversionisforceful.
Thesyntaxisshownbelow:
data_type1v1
data_type2v2=(data_type2)v1
where v1canbeexpressionorvariable
Forex:
floatb=11.000000
intc=22
floatd=b/(float)c=11.000000/22.000000=0.500000
Example:Programtoillustrateexplicitconversion.
http://vtupcd.blogspot.in/
28/31
9/5/2015
ProgramminginC&DataStructureFirstModule
#include<stdio.h>
voidmain()
{
floatb=11.000000
intc=22
floatd
d=b/(float)c
printf("dValueis:%f",d)
}
Output:
dValueis:0.500000
THEPRECEDENCEOFOPERATORS
The order in which different operators are used to evaluate an expression
is called precedenceofoperators.
PrecedenceTable
29/31
9/5/2015
ProgramminginC&DataStructureFirstModule
language.
#include<stdio.h>
voidmain()
{
inta=20intb=10intc=15intd=5inte
e=(a+b)*c/d//(30*15)/5
printf("Valueof(a+b)*c/dis:%d\n", e)
e=((a+b)*c)/d//(30*15)/5
printf("Valueof((a+b)*c)/dis :%d\n", e)
e=(a+b)*(c/d)//(30)*(15/5)
printf("Valueof(a+b)*(c/d)is :%d\n", e)
e=a+(b*c)/d// 20+(150/5)
printf("Valueofa+(b*c)/dis :%d", e)
}
Output:
Valueof(a+b)*c/dis:90
Valueof((a+b)*c)/dis :90
Valueof(a+b)*(c/d)is :90
Valueofa+(b*c)/dis :50
..................................................EndofModuleOne....................................
PostedbyShivaprakashRangaat06:26 Nocomments:
Home
Subscribeto:Posts(Atom)
shivaprakashranga@copyrights.2015.Simpletemplate.PoweredbyBlogger.
http://vtupcd.blogspot.in/
30/31
9/5/2015
http://vtupcd.blogspot.in/
ProgramminginC&DataStructureFirstModule
31/31