0 ratings 0% found this document useful (0 votes) 45 views 55 pages Dot Net Unit 3
The document discusses operators and expressions in programming, specifically in C#. It covers various types of operators including arithmetic, relational, logical, and bitwise operators, along with their precedence and usage in expressions. Additionally, it introduces concepts like shorthand assignment operators, increment/decrement operators, and type conversions, providing examples and algorithms for better understanding.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Dot net unit 3 For Later
3.1 Introduction
3.2
Operators And €xpressions
‘An operator is a symbol or fetter used to Indicate 2 specific operation on
variables in a program. For example, the symbol '+' is an add operator that adds
two data items called operands.
e. constants, variables,
An expression is @ combination of operands (i.
bers) connected by operators and parenthesis. For instance, in the
given below, A and B are operands and '+"is an operator
num
expression
A+B
many types of operators such as arithmetic, relational, logical etc. An
volves arithmetic operators is Known as arithmetic expression.
C# supports
expression that it
The computed result of an
expression which involves relational
expression. The computed result of a boolean e)
arithmetic expression is always @ numerical value. The
and /or logical operators is called as boolean
xpression is always a logical value
i.e. either true or false.
Arithmetic Operators
Arithmetic operators are summarized in table 3.1.
[64]
3.2.1‘Arithmetic Operators
TABLE 3.1
Purpose
Example
addition
74+5 =12
- subtraction 7-5=2
or unary minus.
oe multiplication 7*5=35
iH division 75 =1
% remainder after division THh5=2
‘The unary minus (—) operator multiplies its single operand by —1. Therefore, a
number preceded by a minus sign changes its sign. When both the operands are
integers (or float) then the result produces an integer value (or float value). If one
operand is of the float type, and another is integer type, then the result is always a
float number. The modulo division operator % cannot be used on floating point data.
The operator % operates as follows :
9
-9
9
-9
% 2 = 1
% 2 = -1
% (-2) = 1
% (-2) = -1
Hence the sign of the result is always the sign of the first operand.
321 Integer Expressions
The Integer expressions are formed using Integer variables and/or Integer constants
Connected by Integer operators e.g.
[65]4°545/2-9%2
A+¢5=B°C4D%E where A, B, C, D & E are integer variables.
Fol evaluation of Integer expressions the following rules are applicable,
1. /,* and % operators have highest level of precedence and so these Operator,
will be operated first.
2. +and-~ operators have lower precedence and these operators will be operate,
later.
3. When operators have same precedence, the evaluation is carried out from let
to right.
4. . Parentheses will be used to overcome the precedence. The expressions within
parentheses will have the highest precedence and will be evaluation first.
Example 3.1
Find the value of the following integer expressions.
1. 3*5/2+6°9%3+2* 3-3
166]gt (6+2°3)+25/(2*942)
3° (542° 3) + 257 (@* 342)
3.2.2 Float Expressions
Float expressions is formed using float/Integer variable and/or float/Integer constant
connected by float operators e.g.
4.5 * 2.0 + 5.0/2.0 + 15.75
The rule for evaluating float Expressions is same as that of Integer Expressions.
Examples 3.2
Evaluate each of the following expression.
(12.5 + 2.5) * 2.0 - (11.5 - 2.5) /3.0 + 13.5
(12.542, 2.0-
(11.5-2.5)/ 3.0
+ 13.5
67}3.2.3 Mixed Mode Expression
d float quantities in an oxprossion. Such an
in this modo, Integer value ig
yiold the float value.
C# permits mixing of integer an
‘expression may be called as mixed modo expression. I
‘automatically converted into the float value and alway
Example 3.3
Assume A=45 fet
The value of the expression K/ J *(A+23* Dis
J = 2K=3 then
+ 6 + 23 5 1)
|
1.0
312
@
|
; ®
1
.0
68
Example 3.4
Write @ program that accepts as in
ito its equivalent in degrees celsi
Algorithm
AF
\put temperature in degrees Fahrenheit, converts
lus and output the temperature in degrees celsius.
Input temperature in Fahrentuit, ¢
Compute the ceisiug temperature ¢
age =(5/9\(£:32)
sep
STOP
3.33.3
using System;
class temperature
{
static void Main()
{
double £;
double c;
f = Convert..ToDouble(Console.ReadLine()) ;
c= 5.0 / 9.0 * (£ ~ 32.0);
Console.WriteLine("Equivalent celsis temperature is {0}", c);
}
Run:
c
|
1
1
!
|
|
|
|
I
i Console.WriteLine("Enter the temperature in Fahrenheit");
I
!
!
|
I
| enter th temperature in Fahrenheit
3s
| Pquivalent celsius temperature is 1.66666666666667
x
Relational Operators
Relational operators and their meanings are shown in table 3.2.
Table 3.2
> means Greater than
< means Less than
== means Equals to
ao means. Greater than or Equal to
means Less than or Equal to
l= means Not equals to
{09}33.1 Relational Expression
‘An epression sich a Siete he 6) 88 y>0) tw
s2<20letoee lee lte>x sive
Precedence of elaonl operate it 5 Heo 60}isine
[Se oe nn precedence of Bolean Operators i as shown Table 35.
‘TABLE 35
3.4 Logical Operators Opermore Precedence
Therese toe operators Lagi pears ae shown tbl 3, A + Gisheso
Tastes as 2
" 3
43.5. Shorthand Assignment Operators
tub Form of Aslgnmort operators
Truth Table ological oporators i shown in abe 34.
variable operator = expression;
TABLE 24
‘To assignment statment
variable operator = expression;
‘wendvalentto
varia
variable operator (expression)
Example 36 7
2427 Inequivalenttoa=0+7
ae3.5.1 Advantages of the Shorthand Assignment Operators
‘Advantage of the shortiand assignment operators ae
(37
1. Statements mor efient
2 What eppea on the let hand sie need not be repeated and therfore
becomes ase fo wrt,
3. Statemeats more eat to read and concise.
3.6 Increment and Decrement Operators
CC has two most useful operators namely Increment operator ++ and doce
operator These operators rentorm a variable into a statment expression ha
abbreviate a specs form o ascgnmont. Vien usod 388 standalone expression
‘+m and mes ar bot equivalent to the assignment
memets
‘ay simply increase the value of my 1. Seay, the expression statoments 2
and m--are both equivalent oth assignment
mem-%;
thoy simply decroase the value of m by 1.
ia
vrneraort psn mn Te percent ces be we
ro abot vinta erpeson ne sentences
sate lve eng por tn an mn
Soon
mele?
me
yee
eae eval clyandm ye Signs re ha above
faterent
Anon tho vale oty woud be 7 and m woud be 8
Conditional Operator
Aemary oporator pal?" avalbein G#o construc condional expression of
tee
xression 2 expression? expression:
let
roeontsevauatedtn. I ine rae). bento expres
a exp:2ssionS Is evaluated and
fan bocomes the valve of the expression hers
he value becomes tho value of he expression.
Example 3.8
x=5:
ye8
meGery2x¥ a
‘since value oy grater than the value x, s0 condone, Hence
aseignes th value oty (Le. 9).
‘The statement
me(eoy) 2%
{a equivalent to tho folowing statement a"Uy Tolevitetinet-targer member 49 40)", Bis)t
\
teen '
mi ' \
'
else i , 1
men 2. '
comple Hee 7 |
Wo arpa tan wet open unter Incas ewe veo 1
i \
'
ger number 1s 45.7
Frow charts
43.8 Bitwise Operators
: sora cn atl Usttbise operators
cpr ro urdto mitt ct to Us
Pen 097
raotea7
a a |
+ ice BID
' bance OR
* binseexuve OR
: Ones component
7 shiloh
7 shirt
/ .
foster seems |) tants brayeponion The adeapeaeeby ton cpeton agree
1 oles.
ees !
ig | as.eae
[ae wit may ! a o pase [we | ae
i
1 fost xy, bias i 0 ° ° °
Console.MriteLine("Enter the two numbers"); ! oO 1 o 7 4
Fv comctsteiopotcoucinnedionyny | : ; " ' 1
7 = convert.toSingle(console-Reedsina()),° | °
! ; 1 1 '
, Tsy eciol Operators
Sxomteas0
een Aca et alfa
f= otra os 9 FP post vee
A=toto010) chee
8-01 101100 a
then | et over
Tre sandepucer nett mm Saran
rrcana pet 1 Sl panier ed
Ae oroereeise oernney ee ter
Alaetivories Fen yo Fo camg be Pn ren
ag tea
Asa ciieotoe!
The conan eps eet: Th pnt |
‘na given expenesion
Example 3.11
Suppose Ais dee a=
Asoort0101
Its complement wl no gen by
~Axt1001010 |
‘The sit operator shits heb patams a numberof it toe X-om
‘shits m pac orig the bts operand X. The blank spaces produced at the et,
because of tho shiting are padded with 0's.
Example 3.13
‘Suppose
x 01010101
X253_ = 00001010
i
3.0.
us run re csi by arte moan
scraper
precedence in C# Operators
tra empl recoence ana of at he eparton dace 9
wen inte table 39.
avo
‘aoles9
satity
Operators
ca
irene
wn ene
eel
tem
‘arenes
tmenee
tangs
raed
. worse
ovcia
‘All assignment operators. a
0
sizeot = He == 1 = (unary mines)
vm3-11 Type Conversions
There are two metas of ype conversion n Cf,
341.1 Implicit Conversion
Ha ce corpter comers ane peo tno ects pe of at vm
comps pe pe aha
i cates inp comers Te isn dt es in impli coneson gs
3.1. stone ne tte dts conversion,
Example 3.14
short a= 15;
Inde e
Implict conversion
3.11.2 Explicit Conversion
The exp conversion is done withthe holp of cating. Let us understand tt
‘concept feast of dt,
vm
3.13 Standard Mathematical Func
“example s19p090 YOU Wall fd be a et eageenanbe man BT
ip enpestion wi ot Ne you te dosed ean
sc tot vale Son sen bo gins
vere es oft Sin would be lost ang ao woul represent @ won
A os rages evans veptan poeaaeis ane
1, pawatin a wav to tnnnant aera tee
2 Oe atest han eon ae ee
‘greason m =a may tartare be wrt as
ost a:
she general fom of casts
(Gatatyp0) expression
‘he expression may bea constant, vale oan expression
example 3.15
‘suppose tat san itagervarabe whats value 9, an ating - pit
variable whose vauo is 65. The expression
Gens
stv, because the fst operand (i ating - pit rathar than noge.
However, the expression
(on cme
{oro te fist operand ta an intager andi terete vali, esting in henge
remainder.
‘The compiler supplies several mathematical unions tht cary ost tequenty
requiedtasks, Teve functions areinown as bul-ntunctonsorstandarstctens
‘or bary funcons. Sue unetons hae pre-deined names. Each hasan sumer
‘which I always enclosed witha parentheses, Several ofthese functons are
‘summarized below, Math dass of System namespace defines folowing Methods
25 shown in Tabi 3.10.
rm1
2
3
4
5
20) Spa oto
beotto vale ool number
eof ia sane)
Cosine of en rac)
“Tangont of ein rains)
eG)
cose)
tar ()
natural og ox (00),
Logarttn of umber xt the base 10
raised tothe power y
Example 3.16
Program to find the area of a tiangle using Here's Formula,
Algorithm :
Inu tho thee edes ofthe tangle
Computes = (arbrcyi2
‘Compute the area, area = /afe—aje=Bye=e)
Print area
‘stop
to,
roe
(Gana erent
(oa
\
\
\
\
1 \
‘a \
NE ina cs oy eres \
Lo ‘console.Weitertine(“Enter the aides of tne eriangien st
1 a = Convert. ToDouble(Consol« "\
\ etait) \
1 1 convere-totouheeanste-tentint yy \
°° 2 1 convert -ttmebeeansne-tenuice ye \
1 fla@tecarn \
1 Leone mmensortia + (ee ay eee) seen |
[oo Sesion ot amc te ees we 4
Heo \
+ \
i 1
I acer the aiden of the telanste \
! 1
te \
13 1
Ve \
| Area of triangle is 290t737s0965956 |
Exercise
1
‘nats an Expression ? What aris components?
2 Whatls an Operator? Deserivo soveraiterent pes of operator avattal
cr
iControl Structure
4d Introduction
Ina program made up of only simple statements like input-output and assignment
statements, the flow of execution, also called the control flow, is strictly sequential.
When the control flow is sequential, the statements are executed in the order in
which they appear in the program as show in figure 4.1.
Csi D>
=
[statement2 |
[satemenen]
C sien >
> FIGURE 4.1
* Programming constructs used to alter the flow of control in a program from normal
Sequential execution are called Control structures.
There are three types of control structures :
_() Conditional Control Transfer or Decision statements :
This structure selects one of two alternate segments of program code depending
upon whether a given condition is true or false.
[85]Oot ee,
(iv) switch statement
OP ici sn
Th cnet coe
ne a nan Darl SHEN Ey
ose |
(0 tae Stee
aaa cemro wns pty eae 0 spr cy |
Po er tbnye bat oP eee |
cnn htt esters 3° |
© wince |
. wow
pads
9 nce
|
ya ect |
4.2 Simple if Statement
The genera fom ota singe statements:
it (conten)
i |
taterent block
)
‘te contin ist, te sttorent cc ibe exec: tonic te salon
‘lock willbe skipped. Few chart of his statement is shown in gure 4.2.
(oH
leven a val 1 #the contin is tue,
mennveraconaionevaliedin ch
an ats fle.
example 41
sone examples of hei statement are gen below.
1. (spo0d = = 100)
‘system Console Write (Speed is equal 100"
there is only one statement nthe statement back, therefore, the pair of
braces can be dropped.
2 (marks < 95)
(
‘system Console Wrtaine (ale
failures =talures + 1;
)
{tthe condition is tue (ie. marks less than 35), a message “aed” wl De
splayed on monitor and variable fallures wil be incremented by 1.
rcExample 42
Witea
OTA od he |
190 ven ener
‘Agortm me |
1: out wo mumbo a and |
2 Assign tig ea |
4 #@>b6)hendg=8 |
4 Out 9 |
5 stop |
| sing syetems
1
'
2 Larger {
{
t
f
5
| eu
hi
mercer e
bes
Jo > See ems es mates
|
{ ‘b = Convert. Tornt32 (Console. ReadLine( }); f
be tees
7 4606 > ots) ‘
ie
i sin
ee
conalnaeitanarane maar (8+
bie,
ree
4 nun f
| Eee meters :
i
as Yi
I carger number is 1 45 j
eomesetd
vente DEY SIERO ea rogram aaa e HRA econ
seein conton
RA
4000 ie
Algor
4. input basi pay BP
IF (0p <= 2000) THEN HRA « 200
2
4000) THEN HA = 350,
4
5 Output HRA
6 STOP
IF ep >2000and bp <
1 (> 4000) THEN HAA 500
PROGRAM
suring Syatens
f
1
1
1
te
1 aeatte votd mained
He ot
1
t nt bp, hea = 07 :
1 itetine(“Enter the beste p2Y"1i
i
consol
‘bp = Convert.Tofst32{Console.Resdiine())s
1
1
1
clase basicpay t
I
1
'
1
i
1
1
Hi
i 46 (bp <= 2000) new = 200;
4£ (ap > 2000 & bp & 4000) hea = 350;
4€ (op > 4000) mea = 5007
.else statement
4.3. The if
Console.keitebine("ira is {0}", hea);
The general for otis statements
| (eondtion)
t
tse
)
statement
statement 2;
‘he given condition is two then statement. Is executed ethorwiso statment?
1 <=?
‘nl be executed. Fachart ofthis statoment fs shown in gto 4.3.
[arene eeu
——
NEXT STATEMENT
example 44
sane oxapes of thet. slatement re gen blow
@ He>)
bgee
else
bia=ti
tanks > = 40)
ass = Pass +1
alse
Fal = fai 1:
@
Example 45
Wt a program to find whathor a gven numbers oc ve
‘Algorithm =
1. Input a number, N
2 (NMOD2)=0then
‘output Number is even
otherwise
‘output Number is od
im)
4 STOPPROGRAM
etme
‘Consote.kritetine( Hanber is even");
1
| tee
1
Console.Mritetine("tunber 49 odd"),
Example 46
‘Develop a program to find the largest ofthe three given numbers.
‘Steps :
1
2
Input treo numbers a,b,c
(find the larger of two numbers and siore the resi in new variablo, ig)
IF (a> b) THEN big=a ELSE bi
ie
y
1
1
1
\
1
'
i
1
i
!
reo 3
roe) THEN =
\ \
\
hee \
ee nes wo tin \
' Ceoeiectitetine tree thee eaters):
{ eee en ay
\ $l ooeemectionetemcimms
! LSnetnucnemasenoene
' 7 f \
i
Po nea \
ts \
\ \
' a \
\
1 te (e> bis) Biss \
\ ol
| ematasttan tare wet 1 Ha
Hi \
i) \
|i
\ favor three mubers \
tie 1
120 \
Ue \
I
Largest number is 30Nested if Statements
‘Tt satomert may conta oe or
‘ld te sted. An exaraio ot
rato statement shown Blow
t
conione
t
; :
:
1
fee
t
sateen 3;
,
{Rte canton i te Den he conten 2ie check condone ts
‘Ssement i exocod, tte sateen 2a exited consort saa
‘Saeent 9s exeated, Rowe tis example shown fg 44
ero ataent ne 8 hy |
mete eran o Tod elsastl oes renninte shy ect eer
proorAit
Console.Nritetine("Enter three nunbers")
1 = Convere.toines2(console-Renazine())
= Convert Botnt(eoneale-Rendiine()) +
sf (a> by
tare
big + es
\
\
|
\
\
\
\
\
\
;
\
\
{
\
\
\
:
\
\
\
/ \
\
‘big = br \
else aL \
:
console. WriteLine("Largest muaber is (0)", big):4.5. The else if ladder
‘Te le teri sou when utipath dios arelntved. The Genera,
ol tis eames.
condor)
sien (conten 2)
samen 2;
one
eau statement
‘Teconitors.ar erated tom he topto downwards. As seonasatueconiton |
|s four the stator asocoed wiht is executed. When al he nconditons |
become fale, then he deat statment willbe execved. The Flmchat ois
sxtrentis shown nique 45,
ro
cane eg
f
|
|
|
‘seat contonn) |
|
pan eration 8 su 6 G9 depending gen to mass sce yim
Ime des corresponding oh mars cana reas ude
Marks ‘Grade
eo 100
eow7
501089
401048
toga
Weta program to Spay the grade oth scent, given is mas
PROGRAM
{
| seing system
1
Vea
‘
student
static void Main)
‘
Ane marks;
char grade:
console.tiriteLine("Enter the masks"):
marks » Convert Toiat32(Console.Resdl.ine()):
if (marke > 79) grade = °X")
else if (narks > 59) grade =
S¢ (narka > 49) grade
folse if (narks > 38) grade = °D)
else grade = ‘Er
1
1
1
1
1
1
1
1
1
1
!
1
It
1
I
1
1
It‘The switch Statement
‘Tho enchant sts ha valve ofa gen expression aga to cng
als and when a msc is fund salarent eeas asscitod wth 9g
eerie. The goer! om al is satement is
sch (expression)
‘
break
caso vad
statement
tou
ésaut stoma,
break:
jon canbe an ogo, hacer sting dt ie. The expressions
Famer semis
or oxocatin Ihe vale oo expression dosnt mh wih ay ot
er pes tn oda ont A ae eth eoeta
_ i leh set iss nlp ce aca etion
enh stort tating ct be aren ening ih
pon caro ts seme sowminfgze 48
ure
. w=ste fen)
(
caso
rake
reaut = sin
break:
sul eo8 (x:
result» in);
‘
Wien=3)
result = expt
)
of caso values,
Inthe switch statement, the same statement may ba used wit two or moe veh
example 410
at ia eoger 0 vate
wach 0)
‘
oaks
case 5
case
\ aca,
|
| rea:
yes eta
|
\ Inhis example, vaio ois ether 1 or2 then awe ceased 1. vabe ot
\ ‘is either 3 0¢ 4 then a wil be decreased by 1. he value of is either 5 oF ©,
| then a wil be assigned te value ct andor al cher vaso, te value ck
wie 0.
tuNS
(109
Example 4.11
Write a, i
1903 progamta comps he naterotanye A (year vm) \
ienceca k coer = 2; ft
1
(ees | ve \
1 ri , |
| ctass sootncay y \
ie i} console station \
le Rete Reber of de aces (0), 1
[| static void mata) | eee See
ioe 1] \
at month, - \
Hip tee oy. puch eps =a | \
1 Vy {
fi ec ey 1
|
H year = Convert. ToInt32(Console.ReadLine()), ! {
1 switch (month) '§ {
1 t | \
I | ,
1 ease 1: 1} at
I case 3 te)
t I |
! 1 Ma The goto Statement
1
I
; | | his ttementanstors conc cocoate eter pact by be
1 | abel. The general torm of this statement is.
| as . 1
break: | me
case 4: | | Atabe is any vai vate rae, Ony oe start maybe pty 8
eee || parteuiar tbe. A statemont is pertued by a bela te loving manne,
case 9: . i
case 115, | Lalo : statement;
days = 30; 7 —
psa H ‘Acolon separates the label and the labeled
7
|
t
wf
ee mel2
Example 412
Tho folowing propane sktan show he ute og 2 het
Statoments
(ackvard ame) (Forward Jur)
rat outbred ee nt ia ants ssa)
Shes one rad setl ow gehts hac
tugs Sore corgi cones
teapot one |
Example 413
Wite a program fi he square rot fa nme.
Agent
1. Input tbe number,
1 (0<0) thon GOTO step 1 else Resut = sat (0)
8. Output Resut
4
sToP
w
seatie void Maint)
doutle renute
starts Concole.Neseatine| “Enter coe misbes");
fh = Convert Tots (Conese, tesétine()))
semen)
goto starts
result = math.sort(n)s
‘console, Writetine("Equare zeot is (0)", renee}:
48 Repetitive Structures (loops)
‘Alp inves repeating some poron the progam itera speed eet ot
fins, ou a priat condone bee ese. Ts one Pet
acpng) is actives in C# tough a wil cr dove fr Sateen
foreach statement vas
——Repetiv eres cont
0
Eat Point an ‘itiatization
tna:
RpeMive Srucure, below or athe pln fant th strate,
Vatabes ae haloes
whieh are conrted! di
stu.
©) Loop
(@) do staterann
as ‘9 Counter Contraeg
oo 7m
in Ct tet eed. ow at ten \
‘Acetot statements aro exeewedusingepotve ste. These sa aterent (bay Peep stoke eect nbistypecl eve nae
|
‘70 exerted many tines wile hese statements appearence in progen
| scour whos a hos dr nen, en cre
(a ext Pont it peleminns abe. peton tC rth onee
“Tere mustbe one panto ee ou cna ba eopdoemrotisig_ | Rem OCR Ge '
inteioop.
4 1.10 The while statement
nay point eee
ple | “The while oop soon vnen unter cess op aria eed
{ ~~ frat ronn nates The geal om tte set
Sam li
sepeiton 206) on ty
=y |
ak i :
Pom | seni
1 i 1
ae |The sequence epratonin tenis anon:
| 4. erate canton
4.9 Types of Repititive Structures
ie | ai connie teen ones te ane Se
Theo ar wo Wpes of opettiestuces : i
the condone en be corti arias ott Meee
(0) Condition Controlted
rowchartof wie sateen toma tgve 48 2
In i oP. ba repo iad rm fe ot hw
a G
pats remEagle 416
‘Wie ne pregame frtte sum fet 10 nti numbers ing he wha
=o
1
1
'
1" seat vote natacy |
'
\
\
\
waite (na S10
bot :
HES sai
leas
|. Coste.itetine ‘a
by 0 of first 10 natural mtr is + (0), sh:
p
i
'
'
'
1
1
1
1
i
i
i
pol
ri
cp aii msec hel ing he
we cuted ba xp bbe cand ents mi
7
ene 10. Te Wop varie num sneered ine bye eo
rent ted 10 times.
—
Se
exon 5
ire poantotasbe HCE LCA cv henna
fan
{Ging svstexs
1
[esas hee
static void Main()
Console.triteline( Enter two) numbers")
fe = Convert. tolae32 (console, Readiine()):
b= convere.Tornts2(consote.Resatine());
;
;
\
\
\
\
Ant 9, by mun, don, rea, hot, less '
\
; |
cise
den = ay
d
een = nun ¥ dea;
1
{
1
1
1
1
1
1
1
1
|
\ »
1
t
1
1
1
1
1
1
1
1
1
Ieee erent
4.11 The do Statement
het ater cnn rate at Talo ebay ep
[x be ene aa condone ated at ho ver fr ate bar
EERE sendin sere end Thorlo, body Wo opis exenn
statements);
1
le (contin;
STATEMENTS)
example 4.16
ito the program totnd ho sum of rt 10 natural nanbers using the do oop.
proGRaM
Posing. system:
static void Main)
int nun = 1, 8 = 0:
ereole ieiteLine(‘Sm of fret 10 matural nbar is + 0)", 9OE EO
Example 417
Wie program te eeckt «gen number isa pans
‘A plinrome sa sing error ihe ihe a8 ing orb
readirom ether drecton fetta rgtorsoto I). Te OACUPG. Nerang
Isto reverae he nrber and chek he eersd be eo rg
H
1
'
1
'
i
'
Integer"): i
Son = Canvert-Totnes2(coneole-RewdL.in()}7 '
i
temp = mums , '
digit = vere 8 207
i
'
i
'
tops eae 7 1
fon = mun + 10+ digit, '
1
'
1
1
1
I
,
‘hide (temp > 095
Se (enim == num)
‘conmolesteiteine( "The muber is not @ patindroe’y! |
cqste oop v5 20 1000
2 a poeon While ar. stents
wr eos
sai th coton ststedbeow execingteteycltelos.ndo
4 mrion tstod ae execuing te Boyt ep.
ty of doo eects orca, bt byt whep nay tbe
eektadat a. nwt ity conor ecaseestnoy OEP
inret get oxected even oes
3 The for Loop
ro stustons where you wanttohavea samen gu o alerts 12
‘neo
‘Meeutodruber of tne andthe runbelpettons esac depend nthe
nen butis mpaeption oa crn nares. Tabet way set
rpestn sor ep The net etrbp or Sh emeti
rh
for Gntazton; andi neroert)
i
statements
1
Te fatoing isa fr oop exam
for Got et0: 4)
a
aatement (9
,
Hr vate inas been wae. The dateentsin te ep wb exec a8
‘ong ao cueion ft) we an Iwibo ines by evry ee cei
‘meet the end of op. -‘The execton ce for eatornnt iss ftows
‘ower of tis statements hon nur 4.10
Example 418
‘Wit the rogram find he sum ol est 10 natural umber using or op
tnstentonctn crt a. 9 SD Arg,
sie "
[ta econo rex ua 106th cnon se,
eta enna) eee thon too ener
‘Now corr vari ncreentd sing an assonment tate,
sind and repeat step 2 “
4
Trilatzation
expression
Wire aprogramtotindtne oF eotntacori hetacoraolan integer nis denoted
Dyn ands dened as
1 neo
‘ad we cannot fd the valve ff nieve Soto compute the taco ofa nurbe
the umber rom 1 ton have tobe muted to ge ceed roduc.
|
i
i
sf
+‘
onsole.wrttenine "Eater 8 muster");
Reaatine());
mein
Coneole.triteLine( "Factorial = (0)", tacty,
ise
‘
ny ase)
for =
Console.tritetine( "Factorial = (0)", fact);
4.13,1Additional Features of for Loop
Tho forloopinC# has soveral capabties hat ae not foundin oar oop consines
Consider the folowing for oop
es!
or G0 0s)
f
,
elo ndesealaed100.Nhcrovetty vrs aconasto te end
“te oop and the sialeents in th oop ae repetd as og a8 | ema les
pan 10. The samo qutalento he felon for lon wn oop nex ined
custo.
0:
te 30;
c
statements;
{for oop wih ntazaton of op index and inrement outside tho fr eepit
+
for et)
sateen
he
)
um{or bop wan rtatzation flop indo, op condon& neem Udo
‘ater fe '~
we
weed
t
'
te |
NBS sats eertaiae = C0,
2s ! aoa es
! t
'
|
'
bes '
|
i pk
hf ova
the foreach Statement | ! 6
pals
The foreach opis sed oe teu he eemens ota cleconoranaz. | 1 4s
She pao tic Stee fas
foreach (ype vaiablonamein collection) |
; |
Note :
eae. Pz ot rash sce
) | ron
| examples
‘ype can be any CX datatype, Identiti and Collection is any Cf cobection oie ft [] marks;
or array, Ince, we donot eee sizeof
oe4.15 The break statement
Sonnet rene ay Wi hh
tno, spn wh tear
the ec memento Ty a
tem eaten ntore
ios
Feist cee en none
4
nh = convort.tora22 (console. Resdiine())
wate (fea)
‘
sents oy
‘
Console.writetine("Yot & prise munber"):
rune 431 os
Fonchar of broak statement i shown in figure 4.12
atten)
Ccongole.triteLine("erine susber*);
rune 412Puree ep ums oto be seo es2800
CIIRST & Bec acd conta break ot te wile epi
hes Pm contd catsice te er op ey.
4.16 The continue statement
Te contin eatoert he yop tre carlo he begin ag,
'00p. The conte stenen maybe uced when iis eed sip th,
arto De op sna ean rom te begering. A contin ~
120,22 show bow eualy associa
eatic void maint)
‘
sees 3s
for (= Leas ay
‘
for (35s $< 2; 58)
‘
uma
console.weiteLine "(0 (21°, 4, 312
Powchart of breskeatement is shown in igure 4.13,
1
sion |
- eee crane 4.17 Nested Loops b
extn win na so Teo
= | Loop constructs can be nastad nin mT
: mctboompet eben odes Tewsisbeooes
of oops: Tho following rules apaly tthe use oranges ot while,
Fount a3
© Progam,
bea‘h
(vt
de oy be fom,
comple WritacisnDstar te maker of
Stoner ota 2|ceesiefeazat
\
\
fee eo = 1) 100 & 5 roe) \
\
for We ties
oy in) Ita muciag
console ita”
tor Ge
‘console tite
‘consoles rietin
SH) iter siting
yi T/ESeg spe" ten alone sce
ies te LeeMethods
jntroduc'
‘amethod is a self-contained block of code that performs a particular task.
‘tne use of user-defined methods allows a large program to be broken down into a
number of smaller, self-contained components, each of which has some unique,
identifiable purpose. ‘Thus a C# program can be modularized through the intelligent
use of such methods.
Methods are probably the most important weapon in our battle against software
complexity. You'll want to learn when it's appropriate to break processing out into
methods (and also when it's not), and how to set up Method interfaces to best
achieve the qualities like reuseability, clarity, and maintainability.
Declaring Methods
In C#, Methods are declared inside the body of class. The general form a method
declaration is
modifiers mtype metnodname (datatype argument-1, datatype argument-2,
{
local variable declaration;
‘statement -
Statement -
return (expression);
[131]¥
1 dotining state
“
Let us have a look at its various elements :
1. The first statement of the Method must be the Mathoc
specitying the retum type, name and formal arguments of Paramotery
Method. The roturn type tolls the tw
t to the calling Method,
N
mtype specifies the retum type of the
im statemen
a value, Its return type is SPectod 5
of value to be sent back via the ret
4. If the Method is not supposed to return
void.
in
5. _ methodname indicates the name of Method. Rules for naming a Methog ay
same as for variable names.
contains valid data type and variable names separted p,
6. The argument list ;
be constants or expressions. The
commas. The argument should neither
variables used within the Methods to hol
parameters.
ld the argument values are calleg
7. If there are no format arguments, then the void may be written in the
parentheses.
8. Themodifiers are keywords that decide the nature of accessbility of the method.
A method can take one or more of the modifiers. ‘Some important method
modifiers are given below :
r
Modifier | Description
public The method is accessible from anywhere, including outside
the class.
protected | The method is accessible from within the class to which it
belongs, or a type derived from that class
private | The method is only accessible from inside the class to which
it belongs
Static
The
e method does not operate on a specific instance of the
Class i.e. object.
9.
The body of the Method is enclosed in braces.
[132]If the Method is supposed to retum a value, then here must be ate:
must east one
statement in the body of the Methods to send back the value to th
@ value to the
10.
retum
calling Method. However, if the return type is void, then the return statement
is not compulsory.
Example 5.1
Consider the following Method to display a message.
pos a
| { ;
1 Console.Writeline ("lam leaming C# methods"); 1
I !
u
sethod retum types void. Name ofthe Method is sample. Modifiers static
In this
“Lam learning C# method".
This function display a message
The return Statement
‘AMethod may or may not retum any value to the calling Method. Ifit does, itis done
through the return statement. The syntax of return statement is
retum (expression);
or
retum expression;
Where expression can be a constant, variable or expression. As soon as retum
statement is executed, the contro! will retum to the calling Method.
We can also use retum statement without expression. It does not retum any value.
It acts as the closing brace of the Method. When a return is encountered, the
control is immediately return to the calling Method.
‘The return statement need not be at the end of the Method. Itcan be used anywhere
in the Method. Also, a Method can contain any number of retum statements.
(133)FE
Example 5.2
static int even (int n)
{
W((n% 2) ==)
retum 1;
else
retum 0;
) ,
ie divisil 2 i.e. number is ever
This Method retums value 1 if the number IS divisible by n,
otherwise it retums value 0.
) a Method
ig the Method name including the actual
Calling (or Accessing,
be called by simply usin
parentheses.
5.4
A Method can
arguments, if any, enclosed within
tl using system;
| class Methoddemo
static void Main()
I
fo
i sample ()i
I Console.WriteLine("I am in main method");
|
I
}
static void Sample()
f
Console.WriteLine("I am learning c# methods");
}
}
Run:
I am learning C# methods.
I am learning in main method
ees)
‘--—-—-—-— —
I
|
|
|
1
|
|
|
!
cIn this example, we have defined two methods, namely, Main( ) and Sampte( ). The
Main() method calls the Sample( ) method. Therefore, Main( ) becomes the calling
method and Sample( ) becomes the called method.
When the name of the method is encountered, the control is transferred to the called
Method. Now execution of called method is carried out. After execution of all
statements of called method, the contro! returns to Main( ) method. Note that the
semicolon must follow the Method call if it is a solitary statement.
Formal and Actual Arguments (or Parameters)
(i) Formal Parameters are the variables which are defined within the Method.
These variables are used in expression within the body of the Method. Formal
parameters can be viewed as placeholders for the values passed to them
when the Method is called.
(ii) Actual Parameters are the variables or expressions specified in a call to the
Method. When the Method is accessed, the actual Parameters replace the
formal parameters, these creating an information exchange mechanism
between the Method and its reference point.
There are certain rules that must be observed in order to establish a correspondence
between a Method teference and the Method itself. They are :
1. The actual Parameters must of the same type as its corresponding formal
Parameter,
2 The number of actual parameters in the Method reference must be the same
as the number of formal Parameteres in the Method definition.
[135]i
i
'
!
{
'
i
1 ste We rornta2(console-ReadLiney)?
' 2 1 Gitere.totne32(Console-Readtine,))?
1 bd i naine());
! na = rendre, 211
! ay Be a 01°, am;
¥ iowa
1 sent it rtnatlat JRE 1)
t t a
| seartiy
: Too cea
eng
Hci
'
'
I
{
ines
exe fama parameters are x andy and actual parameters area |
example 55
‘ae rants ede sae a rumber by sing mathod.
sing system;
cless
sausrecal
(
etic vote ming,
float ay ages
ia
aie (Console -Readt net
i i
i \
! connote ttetinet” {
a emacs (ys ag)
{
| atic lot a \
uae \
\ fost « \
‘ een \
i Tevsta (3 1
1 y 1
1 \
Vo run: \
| Bitte « number 1
iB \
Lescbers 5
ample 6
‘wit a program to find the largest of twee numbers by sing method.
—
1
{css ate
‘i
sie void Maint)
Ant ay By cs
‘console.tiriteLine("Enter three nusbers"}:
‘a = Convert. ToInt32(Console.Readtine(});
b = Convert.tornt32(consote.Readtine()):
© Convert ToInt32(Console.Reseline());
1
'
'
t
ler = largest(ay by ©) 1
Console.WriteLino(“Largest number i (0}°, 1ar11 |
\argenttint Xe 306 Yr ANE 5)
© gyn ota
arn
eee
i
1
{
'
t
! yo
t
i
'
I
I
'
[mae
| Fette tneee memers
ii
120
130
I nacgest suber
5.6 Parameter Passing in Methods
nce, nec rope waysto pass parameters toa method. Ths, he Met
have parameters can be cle none of the folowing treo ways,
1. cay vate
2 Cabtyyreererce
S. Ascatot parameters
5.6.1 Call by Value
Tho cal by value way cole he values ofthe actual parameters int km
parameters that se Method rats sow copy of arguments vane ante
ses them. nhs meh, he changes done oh values inthe formal part
not tected back oh ealog Method,
Example 57
‘Tho program exchange the enters two vats
me
seatic oid Hain)
CroreleseiteLine( “Eater te sasbrs"):
\
\
'
'
|
|
I
'
|
cts SLE ey fe i) nh Ht
ante, bbs 1
Diesen iter wig fates ) wd 0s wh
; '
t
{
'
{
{
'
'
'
'
{
'
racic vod seeptiat x, iat yy
hoe oto ales inthe fora per
ated. Tho reason for stat he vas fe
x merary locaton of oma parameters 204 5
paneer na soe
crowing 53amps
‘The prpam Wexchange Be cnt ou aisle,
tt pares
[=] wminseetes
peanceararenob0d/ ANOS HOG
ia)
reat tees mit) Met
‘piemened poses asses of lrnces othe acta parame,
ies usted. Tbe acl ac! formal parameters share he same ne
ess Th atin yg rel word -
role eittise("Bater two mbes");
a convert fornt2{Console. Reading}
: e-ReadLino(}};
= coaeretoint32(Console.Readine())7
nse tae
serie en tc og tein wa} oad"
nile titties
Hee using fantson an(o) and be(t)
MARIE Wid ewp(cet iat x, rol iat y)
ws
nis method, he same memenylcatons ae bsng leoked upon as a ad by
eed main() an asx and y by he Meio swap) as shown in gue 52
563 The Output Parameters
“Tis way fs used when wo want he mead to ream malig aes 10 aod
rete. nis hed, wo aca parameters wih ono owe
‘Wen formal parameters decared as ut. the arson aril meas
‘he cating meted must so be dearedas out nodputrranceis a8
‘lornce paraeta. also doesnot cena anew orage oat
nei
I
i
H :
iti ee sae asi he
[27 SERRRisnileots:tesatinet 5
i
i
i
i
i
i
cot sum, ot
SEN elite Sa) nd ‘otttorence=ta)
In this example, te method sample ()ratums two vals, namely, um |
iterence of to number by using cup paramoters.
5.7 Method Overloading
Overeating retest ut the same things for diferent pups. Ct
1 owe the sane nao fr dion Mathods. AS lng as they have
rameter pe ts, the compiler wl regard tem as eiterent Methods Tt
{trated te parameters must ter coin aeent ruber preee
rere mst be tas one poston ne parameer sts whore te ye
sire. Te covet athe be vedi determined by checking ba n=
‘rd ype ol oer btraton Meo ype,
wel
pasos secon ec og ae
‘competes 1nd he ex Mach neh pa ot ci ru
esa.
it exact match nt ound, he compo ses ep conversion ote act
igronts Such 38
‘oat to double
tof amt.
inne conversion crates mute matches, then he cmp wl generate an
coor message,
‘sample 510 (Dillerent Number of Arguments)
(aia
Weise overseen
featie via mist
?
In eguaranen, cece
Sasolecteicetine(-suace aren = (0)*, svarearea)s
rectares = er0a(10, 20);
{ 1
| Seafeattite ao = (ssa |
return (x 005
featic int area(int x int)
veturn (x 4 YiS741 Advantages of Overloaded Methods
Te programs tes ese read
2. Thapar retreat EEN ny
The proyanee can cote mar tie on lop dovelopmeny
remater dterert Neto names
nop mababty of ho coo
1 Batrundetndng et eaten betwoon he program andthe,
ay
5.8 Recursion
econ tsto the proces h which Method alls aot Recursion ia
Ini ig wich sana proms canbe exszed na orn wc
coco raul satoment Ahh meted spo
"Mets rao wat priory recurve ya
of recive Maths for ober pbs stu.
Example 5.11
Program to acta number, Recurive defn fm toa
ofl tee
lovin 91 tas.
Tho eration bys afin shown blow
a sam
= arara
seore
acatest a,
arsed
=o
rm
a
very
(aim om
mo!
Mme
polo ciedinlomsctit Tslnown aan ene
1
ase factorial t
Tate vote naint 1
i '
int 0 1
Coneblatrtetinet “iter & mubee“ys '
2s Convers ota 3 cneseltos ise t
fino) :
Gonsolesehttine("tovatia i
“se ete i
"Sonsolesetteiee("{0)1 = (1 1
ON Ns me tattans
t
,
1
duatie Sat facttiae 9) 1
i '
sete 1
atuen ts |
oe '
Tetuen (1 + tact = Nhs '
, H
Fi '
'
ane t
inter « nunber t
'
S81 Advantages of Recursion
pea
Ile mere cone, eampact and arse
Inseme station, te earns thon elon Forex, Tow of
Hana.
Ince cases, may be eset we nd unten
tn data seucture the qnues, chs, irked et reir ore ay
Recursion is very usa he slaton to pclem res ts
Recursion ts a poner devs n mathematical defn. Anita st
objects can dtd by fate reason stoners i‘5.82 Disadvantages of Recursion
1. eons mae sage PACE
2 isnt more ehoertin tems of peed and exon tno,
3 Reeamsen eet cate when te PBEM cane Soh
Reason mayest a rensemintng Reatons Or rec.
. Classes and Objects
Exercise 4 Introduction
1. WattsaMeras?Whatwe teadanagestouse the Meea? | © 15g user define type which hos oh ct and ands. Tha
2 wratemsaty aha? Fam wstPaN 8 po cena tg| ms ae CBE led mene (a reba adie eee
tees? ‘arind menber metocs. The menbec mots my mare ris
Spo cepupeeedl name Silene? sofa class, The variates ca cass ae cas stances ol case obec.
4. Whatare be ences between Formal and Acta arguments 2
5 Whatizmsin 7 What atvanioge is there ins uso 2
What rete cerencs between callby-value and cat-by eters
7. Explain te concept of eall-by-value arguments and cally tens
6a. Class Declaration
doses aggeoitoncl ames ania meted acon
hase Te fost ass acon Gen son
pers yang sie apie. ‘
Hows te ct a remter deed rcs? '
8. Desoto ewer Harpe, { voriabies éeclsation
\
'
\
10. Wee apogam
weindtevabedt © “TRA
by ot class esi:
"11. What lo youean by Method overtone? Explain with examples. (1M nent nat oie a i
12. What ate the advantages of Metied overloading? tlasThis controled access is manage a
9 ido
‘hat members canal be acres
18. How do we inckoarmetod in Ce? eee Ue ee ye rae etd wine tT
ta c,h ean eye i
4. Wan ot ran? Vy ova ed tn? Fate eae tn gos be cote PAR
ed en en
| doa nomen lcs wep. vat
ws
E St aie ae cadpe accessed anys win tha
Se aonanenoe:
concen eran
lo
‘Coir fonng dcraton falas
public void sedatal)
le vit dite
esate titlisl
(RELL Wo Ls (0) and age da {2)*, rol
1
er ere ree
iso depnhersndeaerminnninshtehomsd mi esheets
megge of Pe. Te woes members eget)
} oxy neo maha can acest ta marr. Th a
iy a ant ee
p cresting Objects
marcn minnie cena cet
‘Objects re creat using he new oper. Theneweperar eas
ret spect st neu aero a ot
Tiaesiere
1
“Gti statement delve a vaabe olde bec orn
“he second satement asso the cect erence he vara
1 rats nenoned above 25
student «= new student)
Wi can combine
ables ctsclss. Taser,
1
i
1
1
1
'
1
1
1
i
1
i
1
fc on th varies ot
Netehat each objet hasis own copy to stnce
ry changes tothe vaabes cf ano objec wil have no
nator object.
ry6.4 Accessing Class Members
{coley Sten
crane saaeat
1
ale vole diate
,
exe eae RL M6. He (0 ae ge S809", sot, ay
satis void taint)
t
student ney atadet( yy
224)
1 ee ot
f
br
,
pantie vold ealeun()
i ®
,
pobtic void patent)
t
ase denoprograns
static vold maint)
eaople scoow ssmple():
Sigetaataths 2
Senisenth?
Sptanet
1
1
'
t
1
1
|
t
'
1
|
1
t
1
1
1
'
1 congotentrstensna("aaser 18 10)", et2
'
'
t
1
1
t
'
1
i
t
1
1
1
t
1
L
‘Sancos of clases an boc. ust)oo SR ee ae
Methods se wld eater
set yma Men Mae fy
ts An og
6.5. Nesting of Member
‘aime matt can bo
‘Tiss caled esog tebe
understand #5 CO
consolacweltetine("iargeat ouster ts {0}, biggectyns
eseatprogren
Example
Wea progam
ng ees fd telnet cube Kom gen tree aot
ta
static vold wain()
argest = nev largest
getdate:
xatsplay0:
private Sst a, Be er
patie vole gecdstat)
t
consctewteiteLine "Eater three minbers");
sa = convert.Tont22(Console.ReedLine());
1 = convere.toats2(Console.teadLine())
= convere.fnt22(Console,Readtine())
,
‘
66 Constructors
(Ct provides special member method called cosinor that enables an obec
Ins tee when tis erected, Thi is know as atomstiinizaton of objects
Ile a special mothod because ts nama is sme a ha clas are. Consors
not spocty atu ype, not even vol. The consrucaisinvked whenever an
ic crated Hence, wo dated a constructor 8 “8
sere)
big =
ee cae object ofits associated cass i
4 ‘member method with the same name 4s its class Is called constructor and It
In ved naize tho ebjact of tat clas pe ring eention
vs
1
i
i
1
i
1
1
'
i
1
1
1
1
1
1
fattest wise
1
1
1
1
1
!
1
1
'
i
!a
v eerie Constructors
bi vith arguments are known as parameterized constructors.
o concurs wih oa ‘helpful in a stuation where the programmer
7 Tet cone es with different values
1} pao ‘ious data elements often sbjets
He ee ee a Foren
nore
Sen
ie ss, se | 1
peace roentoe tine | 1
1 jot rose | 1
Wad 1] 1 getese ae ay bs . |
See ae :, st Xr Ant 7) paraneterteed conatre
teens Wed at a se
ee Pat '
i % els ee \
stern ree
ati wi ye
£ (ROLL Wo. is {0) and Marks is (1)-, | , t
1 cwastestsetin a Het oe aca
ti ae es ty me ot 2 3
i |
pes) '
1 1) example 68
ve |
i { 1
| ctu coz \
1 teat 1
1 tie volt mist pe \
Hee tose ot !
stadt + oe hele
1 tert ee ;
Ma on - '
es feat? tint 4, Hie $) /Meonstrucor Setined i
by eee
i t
Ue root 1
[fat to ix 100 an mck 46 09 Sep te aes
ico See et, Poe
ude] |
Ins are, decaratonnot on cat thc bea ws)
Inlze ts dte members roles snd marks wl1 pblie void arte)
leet
coeteverstezine("8 = (0) a0d B=
6.6.2 Characteristics of a Constructor
+ Acrnsoucoc name must be the same a that ots classname.
Wis dared wit no em ype (rt even vot.
| flseutatcaly invoked when an ebjoc coated,
ean nave deft arguments,
* Consivcors are wssaly pai,
\Constetrs canbe overoaded,
in sre
a bens nin tte
f
mtn onvutr moenmenonneeees
wes once Taya amen eree
serereysamiereeleshuoaplpman rad
a ceamane
ssn
exampio 69
foro ota Halse cnc ol ear
(ing tens
‘
toe a, bs
public stmple(iat 4, int 3) /Posestracter dations
‘
)
pobtle void disptan()
‘
conmole.neitetioe("a = (0) asd b= (I"s 6
1
1
1
1
t
t
1
1
i
t
1
1
1
t
'
1
1
'
1
1
1
t
1
1
1 congotectetteLine “est
1
1
1Oo ~<
class constructordemo
{
static void Main()
{
|
| i
I |
| |
|
' sample s = new sample(5, 10); |
| s.display(); |
| |
} |
|
1?
Runt |
| a= 5 andb= 10 |
| Destructor called |
—----
ee eee eee
Note that destructor method are invoked automatically when object is destroyeg,
6.7.1 Characteristics. of _a:Destructor....
A destructor has the same name as that oi class prefixed | by tilde character 2)
No arguments can be provided to a destructor.
e Ithas not return type, not even void type.
. ‘Destructors can't be overloaded.
Destructor functions are invoked automatically when the ne object is destroyed.
6.8 Operator Overloading
We have studied the concept of method overloading in the previous chapters. Method
overloading refers to the use of one function name to perform different purposes o
tasks. Similarly an operator can be redefined to perform additional tasks. For example,
consider the operation of operator (+). Operation is sum or add if operands are integer"
type and if operands are string type then operation is. string concatenation. Howevel,
using operator overloading you can extend the capability of + operator so that this
operator performs the addition of two objects of a class.
(158)
aaC# allows you to define the meaning of an operator relative to a class that you
create, This process is called operator overloading. By overloading an operator,
you expand its usage to your class.
Overloading an operator does not change the basic syntax and template of an
operator nor does it alter Its order of precedence. But, we can extend the
semantics of an operator.
Definition of Operator Overloading
Operator Overloading is a mechanism of redefining the meaning of C# operators.
Operator Overloading is done with the help of a special function. The syntax of
definition of operator method is as follows.
a
public static return_type operator op (arguments)
| 1
| 1
| 1
| _ // Method body I
! |
! |
! |
}
[Cee ee ee 7
where operator is a keyword
op is the overloading operator like +, -
arguments is the list of arguments.
return_type is the data type returned by the operation.
Although return type can be of any type you choose, the return value is often of the
Same type as the class for which the operator is being overloaded. For unary
operators, the argument must be of the same type as the class for which the operator
is being defined. For binary operators, at least one of the arguments must be of the
‘Same type as the class.
[159]6.8.2 Overloading Unary Operators
As you know, unary oparators act on only one operand. E ample Of UNATY Operaten,
are - (unaty mnus) +4 (increment), -(decrement) otc.
We will see how the overload these operator so that it will be applied to an object,
much the same way as is applied to an Int or float variable.
Example 6.10
Write a program to overload ‘the unal
the unary operator to negate an object.
ry minus (-) operator. The program will overloag
using System;
class sample
{ |
|
I
|
int a 0;
public sample()
{
} !
public sample(int a, int b)
: |
//constructor defined
n= by i
public void display)
|
{
cousole-ritetine( "a a= {0) and n= (1}", m, n);
c
|
|
|
|
1
I
!
!
I
|
!
!
!
|
|
!
I
!
|
|
|
!
!
I
I
I
}
|
160!public static sample operator -(sample x)
{
Xm * =XARy
Xan = Xen}
return (x);
?
1
|
|
l
|
|
|
|
|
|
1 class unaryoperator
|
{
; static void Main()
ss
' sample s = new sample(10, -20);
1 sample sl = new sample();
I console.WriteLine("Values of data nenber before operator overloading");
! s.display();
sl = -S;
; console.WriteLine(*Values of data menber after operator overloading”
I sl.display();
|
!
|
1
1
1
|
|
|
|
Bun:
Value of data member before operator overloading
n= 10 and n= -20
value of data menber After operator overloading
10 and n = 20
Qo ee ee ere
6.8.3 Overloading Binary Operators
Binary operators can be overloaded just as easily as unary operators. Binary
Operators need two operends. Examples of binary operators are +, —,", h
Let us overload the "+" operator.
{161}Example 6.11
lex numbers.
Overload the "4" Operator to find the sum of two comp!
Ctr
{
class complex
float real, img;
Public complex)
{
}
public complex(float r, float i) //Constructor defined
{
real = r;
img = i;
Public void display()
{
Console. WriteLine(* {9} + {1pi", real, img);
; ;
—--—-— YYclass binaryoperator
{
static void Main()
‘ complex cl = new complex(2.5f, 3.0);
complex o2 = new complex(8.2f, 6.4£);
complex c3 = new complex();
3 = cl + ¢2;
console.WriteLine("First complex number is");
cl.display();
Console.WriteLine("Second complex number is");
e2.display();
Console.WriteLine("Sum of complex numbers is");
c3.display();
}
1
1
(
{
1
1
|
l
|
|
1
!
|
|
|
1
I
|
1
red
|
|
1 nun:
| First complex number is
! 2.5 + 3i
| Second complex number is
| 8.2 + 6.4%
t Sum of complex number is
| 10.7 + 9.43
X
Exercise
1. Explain how classes are declared in C# program.
2. Distinguish between Public and Private Modifier.
3. How can you create an object? Explain by using an example.
[163]
i