Coding Challenges for Beginners
Coding Challenges for Beginners
1
ThereisaJARfullofcandi
esf orsaleatamallcount
er.JARhast hecapacityN,t
hatisJARcan
contai
nmaximum Ncandi eswhenJARi sf
ull
.Atanypoi ntofti
me.JARcanhav eM numberof
CandieswhereM<=N.Candiesar eservedt
othecustomer s.JARi sneverr
emainempt yaswhenl ast
kcandiesar
eleft
.JARi fr
efi
ll
edwi thnewcandiesinsuchawayt hatJARgetful
l.Writ
eacodet o
i
mplementabovescenar i
o.DisplayJARatcounterwithavail
abl
enumberofcandi es.I
nputshouldbe
thenumberofcandiesonecust omercanorderatpointoftime.UpdatetheJARaf t
ereachpurchase
anddispl
ayJARatCount er.
Outputshoul
dgi
venumberofCandi
essoldandupdat
ednumberofCandi
esi
nJAR.
I
fInputismoret
hancandi
esinJAR,r
etur
n:“I
NVALIDI
NPUT”
Gi
ven,
N=10,
whereNi
sNUMBEROFCANDIESAVAI LABLE
K=<5,wher
eki
snumberofmi
nimum candi
esthatmustbei
nsi
deJARev
er.
Exampl
e1:
(N=10,
k=<5)
I
nputVal
ue
o 3
Out
putValue
o NUMBEROFCANDI
ESSOLD:3
o NUMBEROFCANDI
ESAVAI
LABLE:
7
Exampl
e:(
N=10,
k<=5)
I
nputVal
ue
o 0
Out
putValue
o INVALIDI
NPUT
o NUMBEROFCANDI
ESLEFT:
10
I
nC
#i
ncl
ude<stdi
o.h>
i
ntmain(
)
{
intn=10,k=5;
intnum;
scanf("
%d",&num)
;
i
f(num>=1&&num<=5)
{
pri
ntf
("NUMBEROFCANDIESSOLD:%d\
n",num)
;
pri
ntf
("NUMBEROFCANDIESLEFT:
%d",
n-num);
}
else
{
pri
ntf
("I
NVALI
DINPUT\
n")
;
pri
ntf
("NUMBEROFCANDIESLEFT:
%d",
n);
}
retur
n0;
}
i
nC++
#incl
ude<iostream.h>
usingnamespacest d;
i
ntmai n(
)
{
intn=10,k=5;
intnum;
cin>>num;
if(
num>=1&&num<=5)
{
cout<<"NUMBEROFCANDIESSOLD:"<<num<<"
\n"
;
cout<<"NUMBEROFCANDIESLEFT:
"<<n-num;
}
else
{
cout<<"I
NVALIDI
NPUT\
n";
cout<<"NUMBEROFCANDIESLEFT:
"<<n;
}
retur
n0;
}
i
nJav
a
i
mpor tjav
a.util
.Scanner;
cl
assMai n{
publi
cstaticvoidmai n(St
ri
ng[]ar
gs){
i
ntn=10, k=5;
i
ntnum;
Scannersc=newScanner (
System.
in);
num =sc. nextI
nt(
);
i
f(num >=1&&num <=5){
System.out
.pri
ntl
n("
NUMBEROFCANDI ESSOLD:"+num);
System.out
.pri
nt(
"NUMBEROFCANDI ESLEFT:
"+(n-num));
}else{
System.out
.pri
ntl
n("
INVALIDINPUT"
);
System.out
.pri
nt(
"NUMBEROFCANDI ESLEFT:
"+n);
}
}
}
i
nPy
thon
total_
candies=10
no_ of
_candies=i nt
(input
())
i
fno_ of_candi
esi nrange(1,6):
pri
nt(
'No.ofCandi esSol
d:'
,
no_of_candi
es)
pri
nt(
'No.ofCandi esLef
t:
',
tot
al_
candies-
no_of
_candi
es)
else:
pri
nt(
"Inval
idInput")
pri
nt(
'No.ofCandi esLef
t:
',
tot
al_
candies)
Sel
ectionofMPCSexamsi ncl
udeaf i
tnesstestwhichi sconductedongr ound.Therewi l
lbeabat ch
of3trainees, appeari
ngforrunni
ngtestintrackfor3r ounds.Youneedt orecordtheiroxygenl ev
el
aft
erev eryround.Af t
ert
raineearefi
nishedwithallr
ounds, cal
culateforeachtrai
neehi sav er
age
oxygenl eveloverthe3roundsandsel ectonewithhighestoxy genlev
el asthemostf ittr
ainee.If
morethanonet r
aineeat
tainsthesamehi ghestaveragelevel,
theyallneedtobesel ected.
Di
spl
ayt
hemostf
itt
rai
nee(
ort
rai
nees)andt
hehi
ghestav
erageoxy
genl
evel
.
Not
e:
Theox ygenv al
ueenter
edshouldnotbeacceptedifi
tisnotintherangebetween1and
100.
I
fthecal cul
atedmaximum av
erageoxygenval
ueoft r
aineesi
sbelow70t hendecl
aret
he
tr
aineesasunf i
twit
hmeaningfulmessageas“All
trai
neesareunfi
t.
AverageOxy genVal
uesshouldberounded.
Exampl
e1:
I
NPUTVALUES
95
92
95
92
90
92
90
92
90
OUTPUTVALUES
o Tr
aineeNumber:
1
o Tr
aineeNumber:
3
Not
e:
I
nputshoul
dbe9i
ntegerv
aluesr
epr
esent
ingoxy
genl
evel
sent
eredi
nor
deras
Round1
Oxy
genv
alueoft
rai
nee1
Oxy
genv
alueoft
rai
nee2
Oxy
genv
alueoft
rai
nee3
Round2
Oxy
genv
alueoft
rai
nee1
Oxy
genv
alueoft
rai
nee2
Oxy
genv
alueoft
rai
nee3
Round3
Oxy
genv
alueoft
rai
nee1
Oxy
genv
alueoft
rai
nee2
Oxy
genv
alueoft
rai
nee3
Outputmustbeingi
venfor
matasi
nabov
eexampl
e.Foranywr
ongi
nputf
inalout
putshoul
d
di
splay“I
NVALIDINPUT”
i
nC
#i
ncl
ude<stdio.h>
i
ntmain(
)
{
inttr
ainee[3][3];
intaverage[3]={ 0} ;
inti,
j,max=0;
for(i
=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf ("%d" ,
&t r
ainee[i
][j
])
;
if
(trainee[i][
j]<1||tr
ainee[i]
[j]
>100)
{
trainee[i]
[j]=0;
}
}
}
for(i
=0;i<3;i++)
{
for(j=0;j<3;j++)
{
average[i]=av erage[
i]+trai
nee[
j]
[i
];
}
av erage[i]=av erage[i]/3;
}
for(i
=0;i<3;i++){i f(average[i
]>max)
{
max=av erage[ i
];
}
}
for(i
=0;i<3;i++)
{
if
(av erage[ i
]==max)
{
print
f("Tr
aineeNumber: %d\n"
,i
+1);
}
if
(av erage[ i
]<70)
{
print
f("Tr
aineei sUnfit"
);
}
}
retur
n0;
}
i
nC++
#incl
ude<i
ostream. h>
usingnamespacest d;
i
ntmai n(
)
{
inttr
ainee[3][
3];
intaverage[3]={0}
;
i
nti,j,max=0;
for(
i=0;i<3; i
++)
{
for(
j=0;j<3; j
++){ci n>>t rainee[i
][
j]
;
i
f(tr
ainee[ i
][
j]<1|| t
rainee[ i
][
j]
>100)
{
t
rai nee[i
][
j]=0;
}
}
}
for(
i=0;i<3; i
++)
{
for(
j=0;j<3; j
++)
{
average[i]=av erage[i]+t r
ainee[j
][
i]
;
}
average[i]=av erage[i]/3;
}
for(
i=0;i<3; i
++){i f(av erage[i
]>max)
{
max=av erage[ i
];
}
}
for(
i=0;i<3; i
++)
{
i
f(average[i]==max )
{
cout<<"TraineeNumber: "<<i
+1<<"\n"
;
}
i
f(average[i]<70)
{
cout<<"Traineei sUnf it"
;
}
}
ret
urn0;
}
i
nJav
a
i
mpor tjav
a.util
.Scanner;
cl
assMai n{
publi
cstati
cv oidmai n(St
ring[]args){
i
nt[][
]trainee=newi nt[3][
3];
i
nt[]average=newi nt[3];
i
ntmax=0;
Scannersc=newScanner (System.i
n);
for
(inti =0;i<3;i++){
f
or(
intj=0; j<3; j
++){
tr
ainee[i
][
j]=sc.next
Int()
;
i
f(trai
nee[i
][
j]<1||tr
ainee[i
][
j]>100){
tr
ainee[
i]
[j
]=0;
}
}
}
f
or(
inti
=0; i<3; i
++){
for(
intj=0; j<3; j
++){
average[i
]=av er
age[i
]+trainee[
j]
[i
];
}
average[i
]=av erage[
i]/3;
}
f
or(
inti
=0; i<3; i
++){
i
f(average[i
]>max){
max=av erage[i
];
}
}
f
or(
inti
=0; i<3; i
++){
i
f(average[i
]==max){
System.out.pr
intl
n("
Trai
neeNumber: "+(
i+1)
);
}
i
f(average[i
]<70){
System.out.pr
int(
"Tr
aineeisUnfit
");
}
}
}
i
nPy
thon
t
rai
nee=[[]
,[]
,[]
,
[]]
f
oriinr
ange( 3):
forj i
nr ange(3):
tr
ainee[i
].
append( i
nt(
input()
))
i
f(trai
nee[i][
-1])notinrange(1,101):
pri
nt( "
inval
idinput"
)
f
oriinr
ange( 3):
trainee[3]
.append((trai
nee[ 2]
[i]
+tr
ainee[1][
i]
+trai
nee[
0][
i]
)//
3)
maxi
mum =max( tr
ainee[3])
f
oriinr
ange( 3):
i
ft rainee[
3][i
]<70:
pri
nt("Tr
ainee{ 0}isunfit"
.f
ormat (i
+1))
eliftrai
nee[3][
i]==maxi mum:
pri
nt("Tr
aineeNumber :"
,i
+1)
3
Awashingmachi
neworksonthepr
incipl
eofFuzzySystem,theweightofcl
othesputi
nsideitf
or
washi
ngisuncer
tai
nButbasedonweightmeasuredbysensors,
itdecidest
imeandwat erl
evel
whi
chcanbechangedbymenusgivenont hemachinecont
rolar
ea.
Forlowlevelwater,
thetimeesti
mateis25minutes, whereappr
oximatelywei
ghtisbet
ween
2000gramsoranynonzer oposi
ti
venumberbelowt hat.
Formedium levelwater,
theti
meesti
mat ei
s35mi nutes,
whereapproximatel
yweighti
s
between2001gr amsand4000gr ams.
Forhighlevelwater
,theti
meestimat
eis45mi nutes,whereapproxi
mat el
yweighti
sabove
4000grams.
Assumethecapaci
tyofmachi
nei
smaxi
mum 7000gr
amsWher
eappr
oxi
mat
elywei
ghti
szer
o,t
ime
est
imat
eis0mi nut
es.
Wri
teaf
uncti
onwhicht
akesanumeri
cweighti
ntherange[0,
7000]asi
nputandproducesesti
mated
t
imeasout
putis:
“OVERLOADED”
,andforal
lot
heri
nputs,t
heoutputst
atementi
s“INVALIDINPUT”.
I
nputshouldbei
nthef
orm ofi
ntegerval
ue–
Out
putmusthavethef
oll
owingformat–
Ti
meEst i
mated:
Minut
es
Exampl
e:
I
nputv
alue
2000
Out
putv
alue
Ti
meEst
imat
ed:
25mi
nut
es
i
nC
#include<st dio.
h>
voidcal culateTi
me( i
ntn)
{
if(
n==0)
printf("TimeEsti
mat ed:0Mi nutes")
;
elsei f(
n>0&&n<=2000)
printf("TimeEsti
mat ed:25Mi nutes")
;
elsei f(
n>2000&&n<=4000)
printf("TimeEsti
mat ed:35Mi nutes")
;
elsei f(
n>4000&&n<=7000)
printf("TimeEsti
mat ed:45Mi nutes")
;
else
printf("I
NVALI DINPUT");
}
i
ntmai n()
{
intmachi neWeight;
scanf ("
%d" ,&machineWeight)
;
calculateTime( machineWeight)
;
return0;
}
i
nPy
thon
n=int(i
nput(
))
i
fn==0:
pr
int
("Ti
meEst imated:0Minutes")
el
ifninrange(1,
2001):
pr
int
("Ti
meEst imated:25Minutes")
el
ifninrange(2001,
4001)
:
pr
int
("Ti
meEst imated:35Minutes")
el
ifninrange(4001,
7001)
:
pr
int
("Ti
meEst imated:45Minutes")
el
se:
pr
int
("I
NVALI DINPUT")
Pr
obl
em St
atement
:
TheCaesarci
pherisat
ypeofsubst
it
uti
oncipheri
nwhi
cheachal
phabeti
nthepl
aint
extor
messagesisshi
ft
edbyanumberofplacesdowntheal
phabet
.
Forexampl e,
withashi ftof1,Pwoul dbereplacedbyQ, Qwoul dbecomeR, andsoon.Topassan
encryptedmessagef rom oneper sontoanother,i
tisfi
rstnecessarythatbothparti
eshavethe‘Key’
forthecipher
,sot hatthesendermayencr yptandthereceivermaydecr yptit.Keyi
sthenumberof
OFFSETt oshiftthecipheralphabet.Keycanhav ebasi
cshiftsfrom 1to25posi ti
onsasthereare26
totalal
phabets.Aswear edesigningcust
om CaesarCipher,inadditi
ontoalphabets,weare
consideri
ngnumer icdigit
sfrom 0t o9.Di
gitscanalsobeshi f
tedbykeypl aces.
ForExample,
ifagivenplai
ntextcont
ainsanydi
gitwit
hv al
ues5andkeyy=2,t
hen5will
berepl
aced
by7,“-
”(
minussign)wil
lremainasiti
s.Keyval
uelessthan0shoul
dresul
tint
o“INVALI
DINPUT”
Example1:
Entery
ourPl
ainText
:Al
lthebest
Entert
heKey:
1
Theencr
ypt
edTexti
s:Bmm ui
fCf
tu
Wri
teafuncti
onCustomCaesarCi
pher(i
ntkey,Str
ingmessage)whi
chwi
l
lacceptpl
aint
extandkey
asi
nputparamet
ersandret
urnsit
sciphertextasoutput
.
i
nC
#i
ncl
ude<st
dio.
h>
i
ntmain(
)
{
charst r
[100] ;
i
ntkey ,i=0, l
eft;
pri
ntf(
"Ent ery ourplaintext:");
scanf("%[^ \
n]s",
str);
pri
ntf(
"Ent erthekey: ");
scanf("%d" ,
&key );
i
f(key==0)
{
pri
ntf("INVALI DI NPUT" )
;
}
el
se
{
while(str[i
]!
='\0'
)
{
//printf("
%d\ n",str
[i
]);
i
f(str[i]
>=48&&st r
[i
]<=57)
{
if(str[
i]
+key <=57)
{
str[i
]=st r
[i]+key;
}
else
{
left=(str[i
]+key )-57;
str[i
]=47+l eft
;
}
}
elsei f(
str[i
]>=65&&st r
[i
]<=90)
{
if(str[
i]
+key <=90)
{
str[i
]=st r
[i]+key;
}
else
{
left=(str[i
]+key )-90;
str[i
]=64+l eft
;
}
}
elsei f(
str[i
]>=97&&st r
[i
]<=122)
{
if(str[
i]
+key <=122)
{
str[i
]=st r
[i]+key;
}
else
{
left=(str[i
]+key )-122;
str[i
]=96+l eft
;
}
}
i
++;
}
pr
int
f("
Theencr
ypt
edt
exti
s:%s"
,st
r);
}
ret
urn0;
}
i
nPy
thon
defceaser (
text ,
key ):
resul t=""
#t ransverset hepl aint ext
fori inrange( l
en( text )):
char=t ext [
i]
#Encr yptupper casechar actersinplai
ntext
i
f( char.
isupper ())
:
result+=chr ((or d(char)+key-65)%26+65)
#Encr yptlower casechar actersi
nplaintext
eli
f(char .
islower (
)) :
result+=chr ((or d(char)+key-97)%26+97)
eli
f(char.i
sdi gi
t() )
:
result+=st r
( i
nt( char)+key )
eli
f(char==' -')
:
result+=' -'
eli
f(char .
isspace( )):
result+=""
retur nresult
#checkt heabov ef unct i
on
text=i nput("Entery ourpl aintext:
")
key=i nt(i
nput("Ent ert hekey :
"))
print(ceaser(text,key ))
Pr
obl
em St
atement
:
Wewanttoesti
matet
hecostofpai
nti
ngaproper
ty.I
nter
iorwal
lpai
nti
ngcosti
sRs.
18persq.
ft
.and
ext
eri
orwal
lpai
nti
ngcosti
sRs.
12persq.
ft
.
Takei
nputas
NumberofI
nter
iorwal
ls
NumberofExt
eri
orwall
s
Sur
faceAr
eaofeachInter
ior4.Wal
linunit
sofsquarefeet
Sur
faceAr
eaofeachExteri
orWalli
nunitsofsquar
efeet
I
fauserent
erszero ast
henumberofwal
lst
henski
pSur
facear
eav
aluesasUsermaydon’
twant
t
opaintt
hatwall
.
Calcul
ateanddi
spl
ayt
het
otal
costofpai
nti
ngt
hepr
oper
ty
Example1:
6
3
12.
3
15.
2
12.
3
15.
2
12.
3
15.
2
10.
10
10.
10
10.
00
Tot
alest
imat
edCost:
1847.
4INR
Not
e:Fol
l
owi
ninputandout
putf
ormatasgi
veni
nabov
eexampl
e
i
nC
#i
ncl ude<st di
o. h>
i
ntmai n()
{
i
ntni ,ne,i
=0;
fl
oati nt_p=18, ext _p=12,
cost=0,
temp;
scanf ("%d%d" ,&ni,&ne);
i
f(ni<0| |ne<0)
{
printf("
INVALI DINPUT" )
;
}
elsei f(
ni==0&&ne==0)
{
printf("
Tot al estimatedCost: 0.
0");
}
else
{
for (
i=0;i
<ni;i++)
{
scanf (
"%f ",&temp);
cost+=i nt_ p*temp;
}
for (
i=0;i
<ne; i++)
{
scanf (
"%f ",&temp);
cost+=ext _ p*temp;
}
printf("
Tot al estimatedCost: %.1f
",
cost
);
}
return0;
}
i
nC++
#include<i ost r
eam>
usingnamespacest d;
i
ntmai n()
{
intni ,ne,i=0;
floati nt_ p=18,ext _
p=12,cost
=0,
temp;
scanf ("%d%d" ,&ni,
&ne);
if(ni<0| |ne<0)
{
cout <<" I
NVALI DI NPUT";
}
elsei f(
ni==0&&ne==0)
{
cout <<" Total esti
matedCost: 0.0";
}
else
{
for (
i=0; i
<ni;i
++)
{
cin>>t emp;
cost +=i nt_p*temp;
}
for (
i=0; i
<ne;i++)
{
cin>>t emp;
cost +=ext _ p*
temp;
}
cout <<" Total estimat
edCost: "<<cost
;
}
ret urn0;
}
i
nJav
a
i
mpor tj av a.util
.Scanner;
cl
assMai n{
publicst ati
cv oidmai n(Stri
ng[]args){
intni , ne,i =0;
floati nt P=18, extP=12, cost=0, t
emp;
Scannersc=newScanner (System.in);
ni =sc. next I
nt()
;
ne=sc. nextInt(
);
if(ni <0| |ne<0){
Sy st em. out.
pri
nt("I
NVALI DI NPUT" )
;
}el sei f(
ni ==0&&ne==0){
Sy st em. out.
pri
nt("Totalesti
mat edCost:
0.0"
);
}el se{
for( i=0; i<ni;
i++){
temp=sc. nextFloat(
);
cost+=intP*temp;
}
for
( i
=0; i
<ne; i
++){
temp=sc. next
Float
();
cost+=extP*t emp;
}
System.out.
pri
ntf
("Tot
alest
imat
edCost:
%.1f
",cost
);
}
}
}
i
nPy
thon
i
nterior_walls=int(i
nput())
exteri
or _
wal l
s=i nt(
input()
)
i
finterior_wall
s:
i
nt_ wall
s=[ ]
f
ori i
nr ange(i
nteri
or_walls)
:
int_walls.
append( f
loat(
input
())
)
i
fext er
ior_walls:
ext_walls=[ ]
foriinrange( exteri
or_walls)
:
ext_wal l
s.append(float(
input()
))
i
fext er
ior_walls<0ori nteri
or_wall
s<0:
print
(“I
nv al
idInput ”
)
exit(
)
i
fext er
ior_wallsandi nterior
_wall
s:
print
("Totalest i
matedCost: ",
(sum(int_wall
s)*18+sum(ext
_wal
l
s)*
12)
,"
INR"
)
el
se:
i
fext eri
or_wal l
s:
print(
"Total esti
mat edCost: ",
sum( ext_
walls)*12,
"I
NR")
eli
finteri
or_wal l
s:
pri
nt("
Tot alesti
mat edCost: "
,sum(int_
walls)*18,
"I
NR")
else:
print(
"Total esti
mat edCost: 0.0INR")
Pr
obl
em St
atement
:
ACit
yBusi saRi
ngRouteBuswhichrunsi
nci
rcul
arfashi
on.
Thatis,Busoncestar
tsatt
heSour
ce
BusStop,
halt
sateachBusStopi
nitsRout
eandattheenditreachestheSour
ceBusStopagai
n.
I
fther
earen numberofStopsandift
hebusst ar
tsatBusStop1,t
henafternthBusSt
op,
t
henextstopintheRoutewi
ll
beBusSt opnumber1al ways.
I
fther
earenst ops,
ther
ewil
lbenpaths.Onepathconnect
stwostops.Di
stances(i
nmeter
s)
f
orallpat
hsinRingRoutei
sgiveni
narrayPath[
]asgivenbel
ow:
Path=[800, 600, 750, 900,1400,1200, 1100,1500]
Fareisdetermi nedbasedont hedist
ancecov eredfrom sourcetodestinat
ionstopas
Dist
ancebet weenI nputSour ceandDest inati
onStopscanbemeasur edbyl ooki
ngatval
ues
i
nar r
ayPat h[]andf arecanbecal cul
atedasperf oll
owingcriter
ia:
Ifd=1000met res,thenf are=5INR
(Whencalculatingf areforot her
s,thecalculatedf
arecontaininganyfracti
onv al
ueshoul
dbe
ceil
ed.Forexampl e,fordistance900nwhenf areini
tial
l
ycalculatedi
s4. 5whichmustbe
ceil
edto5)
Pathiscircularinfunct
ion.Val
ueateachi
ndexindicatesdist
ancet
il
lcurr
entstopfr
om theprevi
ous
one.Andeachi ndexpositi
oncanbemappedwi t
hv aluesatsameindexinBusStops[]ar
ray,whi
chis
astri
ngar rayholdingabbrevi
ati
onofnamesforall
st opsas-
“THANERAI LWAYSTN”=” TH”,“
GAONDEVI”=“GA” ,“ICEFACTROY”=“IC”,
“HARINIWASCI RCLE”=
“HA”,“TEENHATHNAKA”=“ TE”
,“LUI
SWADI”=“LU” ,“NITI
NCOMPANYJUNCTI ON”=“ NI
”,
“CADBURRYJUNCTI ON”=“ CA”
Giv
en,n=8,
wher
eni snumberoft
otalBusStops.
BusSt
ops=[“TH”,
”GA”,”I
C”,
”HA”,”
TE”,”LU”,”NI
”,
”CA”]
Writ
eacodewi t
hfuncti
ongetFare(
Str
ingSour
ce,St
ri
ngDesti
nat
ion)whi
cht
akeInputassourceand
dest
inat
ionst
ops(i
nthef or
matcontai
ningf
ir
sttwochar
act
ersoftheNameoft
heBusSt op)and
cal
culat
eandretur
ntravelf
are.
Exampl
e1:
I
nputVal
ues
ca
Ca
Out
putVal
ues
I
NVALI
DOUTPUT
Exampl
e2:
I
nputVal
ues
NI
HA
Out
putVal
ues
23.
0INR
Not
e:InputandOutputshoul
dbeinfor
matgi
veninexampl
e.
I
nputshouldnotbecasesensi
ti
veandout
putshoul
dbeint
hefor
mat<FLOAT>I
NR
i
nC++
#incl
ude<bi
ts/st
dc++.
h>
usingnamespacestd;
i
ntmai n(){
stri
ngs, d;
cin>>s>>d;
transfor m(s.begi
n()
,s.end(),s.begi
n(),
::
toupper )
;
transfor m(d.begi
n()
,d.end(),d.begin()
,:
:toupper);
stringar rs[
8]={ "
TH", "GA","
IC", "
HA", "TE","
LU","NI
",
"CA"
};
floatar r[
8]={800,
600,750,900,1400,1200,1100,1500}
;
floatres=0;
intst,ed;
for (
inti=0;i
<8;i
++)
{
i
f(s==ar r
s[i]
)
st=i
;
i
f (d==ar rs[i
])
ed=i ;
}
i
f(
st ==ed)
{
cout <<"I NVALIDI NPUT"
;
return0;
}
el
se
{
i
nti =st +1;
cout <<i;
whi le(i!
=ed+1)
{
r
es+=( ar
r[
i]
) ;
i
=( i
+1) %8;
}
cout <<( cei
l)
(res*0.
005)
;
retur n0;
}
}
i
nPy
thon
i
mpor tmat h
defget Far e(sour ce,dest ination):
route=[[" TH" ,"
GA" ,"IC","HA" ,
"TE" ,"LU" ,"
NI "
,"CA"],
[800,600, 750, 900, 1400, 1200,1100, 1500]
]
fare=0. 0
i
fnot( sour cei nr out e[0]anddest inationi nroute[0]
):
pr i
nt (
"InvalidI nput ")
exi t
( )
i
fr out e[
0] .
index( sour ce)<r oute[0].index(destinati
on):
fori i
nr ange( rout e[0].i
ndex( sour ce),
r oute[
0].i
ndex(desti
nat
ion)
+1)
:
fare+=r out e[1][
i]
eli
fr oute[0].index( dest ination)<r out e[0].
index(source):
fori i
nr ange( rout e[0].i
ndex( sour ce)+1,len(r
oute[0])
):
fare+=rout
e[1][
i]
f
ori i
nrange(0,
route[
0].
index(
desti
nat
ion)
+1)
:
f
are+=rout
e[1][
i]
r
eturnfl
oat(math.cei
l(
far
e* 0.
005))
source=input()
desti
nati
on=i nput()
fare=getFare(source,
dest
inat
ion)
i
ff ar
e==0:
pri
nt(
"I
nv al
idInput")
else:
pri
nt(
fare)
Pr
obl
em St
atement
:
TherearetotalnnumberofMonkey ssitt
ingont hebranchesofahugeTr ee.Ast r
avel
ersoff
er
BananasandPeanut s,theMonkey sjumpdownt heTree.I fever
yMonkeycaneatkBananasandj
Peanuts.I
ftotalm numberofBananasandpnumberofPeanut sareoff
eredbyt r
avel
ers,
cal
culat
e
howmanyMonkey sr emainont heTr eeaf t
ersomeoft hem jumpeddownt oeat.Atatimeone
Monkey sgetsdownandf i
nisheseat i
ngandgot otheot hersideoft
heroad.TheMonkeywho
cli
mbeddowndoesnotcl i
mbupagai naf t
ereat i
nguntiltheotherMonkeysfi
nisheati
ng.Monkey
caneit
hereatkBananasorj Peanuts.Iff
orl astMonkeyt herearel
essthankBananasl ef
tonthe
groundorlessthanj Peanutsleftont heground,onlythatMonkeycaneatBananas( <k)al
ongwith
thePeanuts(<j
).
Wr
it
ecodet
otakei
nput
sasn,
m,p,
k,jandr
etur
nthenumberofMonkey
slef
tont
heTr
ee.
Wher
e,
n=TotalnoofMonkey s
k=Numberofeat abl
eBananasbySingl
eMonkey(Monkeythatj
umpeddownlastmayget
l
essthankBananas)
j=Numberofeat abl
ePeanutsbysi
ngleMonkey
(Monkeythatj
umpeddownlastmayget
l
essthanj Peanut
s)
m =TotalnumberofBananas
p =TotalnumberofPeanuts
Remembert
hattheMonkey
sal
way
seatBananasandPeanut
s,sot
her
eisnopossi
bil
i
tyofkandj
hav
ingaval
uezero
Exampl
e1:
I
nputVal
ues
20
2
3
12
12
Out
putVal
ues
NumberofMonkey
slef
tont
het
ree:
10
Note:Ki
ndlyf
oll
ow theor derofi
nputsasn,
k,
j,
m,pasgi
venint
heaboveexampl
e.Andoutputmust
i
nclude t
hesamef ormatasi naboveexampl
e(NumberofMonkey
slef
tontheTr
ee:<I
nteger
>)
Foranywronginputdispl
ayINVALIDINPUT
i
nC
#i
ncl ude<st dio.
h>
i
ntmai n(
)
{
i
ntn, k,
j,
m, p;
fl
oatat ebanana=0.0,atepeanut=0.0;
scanf (
"%d%d%d%d%d" ,
&n,&k,&j
,&m,&p)
;
i
f(n<0| |k<0| |
j<0|
|m<0| |p<0)
{
printf
("INVALIDINPUT" );
}
else
{
if(
k>0)
atebanana=( fl
oat)m/ k;
if(
j>0)
atepeanut=( f
loat)p/j;
n=n-at ebanana-
atepeanut ;
printf
("NumberofMonkey sleftontheTree:
%d"
,n)
;
}
return0;
}
i
nJav
a
i
mpor tjava.util
.*
;
classMonkey s
{
publi
cst aticvoidmai n(St
ri
ng[ ]
args)
{
Scannersc=newScanner( System.in)
;
i
ntn=sc. nextInt();
i
ntk=sc. nextInt();
i
ntj=sc. next I
nt();
i
ntm =sc. nextInt()
;
i
ntp=sc. nextInt();
i
ntatebanana=0, atepeanut=0;
i
f(n<0&&k<0| | j
<0| |m<0||p<0)
{
System. out.
pr i
ntln("I
nval
idInput")
;
}
el
se
{
i
f(
k>0)
atebanana=m/ k;
i
f(
j>0)
atepeanut=p/ j
;
n=n-atebanana-at
epeanut
;
System.out.pr
intl
n("
NumberofMonkey
slef
tont
heTr
ee:
"+n)
;
}
}
}
Pr
obl
em St
atement
:
ChainMar ket
ingOr ganizat
ionhashasaschemef orincomegener ati
on,throughwhichit
smember s
generat
eincomef orthemselves.Theschemei ssucht hatsupposeAj oi
nst heschemeandmakesR
andVt ojointhisscheme t henAisParentMemberofRandVwhoar echi l
dMember s.Whenany
memberj oinstheschemet hentheparentgetstot
alcommi ssi
onof10%f rom eachofi
tschi
ld
member s.Childmember srecei
vecommi ssi
onof5%r espectiv
ely
.IfaPar entmemberdoesnothave
anymemberj oi
nedunderhi m, t
henheget scommi ssionof5%.
Takenameofthemember
sjoi
ningtheschemeasi
nput
.
Displ
ayhowmanymembersj
oinedtheschemei
ncl
udi
ngparentmember
.
Calcul
atet
heTot
alcommi
ssi
ongainedbyeachmembersi
nthescheme.
Thefi
xedamountf
orjoi
ningt
heschemei
sRs.
5000onwhi
chcommi
ssi
onwi
l
lbegener
ated
SchemeAmount=5000
Exampl
e1:Whentherear
emorethanonechil
dmembers
I
nput:(
Donotgi
veinputpr
ompts.
Acceptv
aluesasf
oll
ows.)
Amit /
/Ent
erpar
entMemberast
his
Y /
/Ent
erYifPar
entmemberhaschi
l
dmembersot
her
wiseent
erN
Raj
esh,
Vir
at /
/Ent
ernamesofchi
l
dmembersofAmi
tincommasepar
ated
Out
put
:(
Final
Out
putmustbei
nfor
matgi
venbel
ow.
)
TOTALMEMBERS:3
COMISSIONDETAI
LS
Amit
:1000INR
Raj
esh:250I
NR
Vi
rat
:250INR
Exampl
e2:Whent
her
eisonl
yonechi
l
dmemberi
nthehi
erar
chy
I
nput:
Ami
t
Y
Raj
esh
Out
put
:
Tot
alMembers:2
Comissi
onDetai
l
s
Amit
:500INR
Raj
esh:250I
NR
i
nC++
usingnamespacest d;
i
ntmai n()
{
stri
ngpar ;
cin>>par ;
stri
ngx;
cin>>x;
i
f( x==" N"){
cout<<" TOTALMEMBERS: 1\n"
;
cout<<" COMI SSIONDETAI LS\n"
;
cout<<par<<" :250INR\ n";
}else{
stringchi l
d;
cin>>chi l
d;
vect or<str
ing>v ;
stringt emp=" "
;
for( inti=0; i<chi ld.
length();i
++){
if( chil
d[i]==','
){
v .
push_ back( t
emp) ;
temp=" "
;
}
el se if(chil
d[i]!=''
)
temp+=chi ld[
i];
}
v.push_ back( temp) ;
cout<<" TOTALMEMBERS: "<<v.si
ze(
)+1<<"\n"
;
cout<<" COMI SSIONDETAI LS\n"
;
cout<<par<<" :"<<v .
size()*500<<"I NR\
n";
for( autoa: v){
cout<<a<<" :"<<"250I NR\ n";
}
}
}
i
nPy
thon
par
ent=i
nput
()
Yes_No=i nput()
i
fYes_ No==" N":
pri
nt("
TOTALMEMBERS: 1\nCOMMI SSIONDETAI LS\n{
0}:
250I NR".
format(
par
ent
))
el
ifYes_No==" Y"
:
chil
d=li
st(map(st
r,
input(
).
split
("
,"
)))
pri
nt("
TOTALMEMBERS: {}
".f
ormat(l
en(chi
l
d)+1))
pri
nt("
COMMI SSI
ONDETAI LS\n{0}
:{1}I
NR".f
ormat(par
ent,
len(
chil
d)*500)
)
forii
nchi l
d:
pri
nt("
{0}:
250INR".f
ormat (
i)
)
Pr
obl
em St
atement
FULLYAUTOMATICVENDINGMACHI NE–dispensesy
ourcuppaonj
ustpr
essofbut
ton.Av
endi
ng
machi
necanser
verangeofpr
oduct
sasfol
l
ows:
Cof
fee
1. EspressoCoffee
2. CappuccinoCoffee
3. Latt
eCof fee
Tea
1. Plai
nTea
2. Assam Tea
3. GingerTea
4. Cardamom Tea
5. MasalaTea
6. LemonTea
7. GreenTea
8. OrganicDar
jeel
i
ngTea
Soups
1. HotandSourSoup
2. VegCornSoup
3. TomatoSoup
4. Spi
cyTomatoSoup
Bev
erages
1. HotChocolat
eDri
nk
2. Badam Dr
ink
3. Badam-Pi
staDri
nk
Wr
it
eapr
ogr
am t
otakei
nputf
ormai
nmenu&submenuanddi
spl
ayt
henameofsubmenu
sel
ect
edi
nthef
oll
owi
ngf
ormat(
ent
ert
hef
ir
stl
ett
ert
osel
ectmai
nmenu)
:
Wel
comet
oCCD
Enj
oyy
our
Exampl
e1:
I
nput:
o c
o 1
Out
put
o WelcometoCCD!
o Enj
oyyourEspr
essoCof
fee!
Exampl
e2:
I
nput
o t
o 9
Out
put
o I
NVALI
DOUTPUT!
i
nC
#include<st dio.h>
i
ntmai n(
)
{
charc[ 3][
20]={ "
Espr essoCoffee",
"CappuccinoCof f
ee","
Latt
eCoffee"
};
chart [
8][30]={"PlainTea","
Assam Tea" ,
"GingerTea",
"Cardamom Tea",
"Masal
aTea",
"LemonTea"
,"
G
reenTea" ,
"Organi cDar jeel
i
ngTea" }
;
chars[ 4][
20]={ "
HotandSourSoup" ,
"VegCor nSoup","
Tomat oSoup",
"Spi
cyTomatoSoup"}
;
charb[ 3][
20] ={"HotChocol at
eDr i
nk",
"Badam Dr i
nk",
"Badam-Pi
staDrink"
};
charst r[
]="Wel comet oCCD!\nEnjoyyour" ;
charch;
intitem, i;
scanf (
"%c" ,
&ch) ;
scanf (
"%d" ,
&i t
em) ;
if(
ch=='c')
{
for(i
=0; i
<3; i++)
{
if(
item==i +1)
{
pri
ntf("Wel comet oCCD! \
nEnjoyy our%s!",
c[
i]
);
break;
}
}
if(
i==3)
{
pr
int
f("
INVALI
DOPTI
ON!
")
;
}
}
elseif(ch=='t'
)
{
for(i
=0; i
<8; i
++)
{
if(
item==i +1)
{
pri
ntf("
Wel cometoCCD!\nEnj
oyy
our%s!
",
t[
i]
);
break;
}
}
if(
i==8)
{
printf("
INVALI DOPTION!"
);
}
elseif(ch=='s'
)
{
for(i
=0; i
<4; i
++)
{
if(
item==i +1)
{
pri
ntf("
Wel cometoCCD!\nEnj
oyy
our%s!
",
s[
i]
);
break;
}
}
if(
i==4)
{
printf("
INVALI DOPTION!"
);
}
elseif(ch=='b'
)
{
for(i
=0; i
<3; i
++)
{
if(
item==i +1)
{
pri
ntf("
Wel cometoCCD!\nEnj
oyy
our%s!
",
b[i
])
;
break;
}
}
if(
i==3)
{
printf("
INVALI DOPTION!"
);
}
else
{
printf(
"INVALI DINPUT!
");
}
return0;
}
i
nPy
thon
menu=[ [
'EspressoCof f
ee',
'CappuucinoCof fee',
'Latt
eCoffee']
,[
'Pl
ainTea'
,
'
Assam Tea' ,'
GingerTea' ,
'Cardamom Tea' ,'
Masal aTea'
,'
LemonTea' ,
'
GreenTea'
,
'
OrganicDar jeelingTea'],[
'HotandSourSoup' ,
'
VegCor nSoup',
'
Tomat oSoup'
,
'
SpicyTomat oSoup' ],[
'HotChocol ateDrink','
Badam Drink'
,
'
Badam- PistaDr ink'
]]
m =input()
i
fm==' c'orm==' t'orm==' s'orm==' b'
:
i
fm==' c':
submenu=i nt (
input())
i
fsubmenui nrange(3):
pri
nt('
Wel comet oCCD! \nEnjoyy our{
}!'
.format(menu[0][
submenu-1])
)
el
se:
pri
nt("I
NVALI DI NPUT" )
i
fm==' t'
:
submenu=i nt (
input())
i
fsubmenui nrange(8):
pri
nt('
Wel comet oCCD! \nEnjoyy our{
}!'
.format(menu[1][
submenu-1])
)
el
se:
pri
nt("I
NVALI DI NPUT" )
i
fm==' s':
submenu=i nt (
input())
i
fsubmenui nrange(4):
pri
nt('
Wel comet oCCD! \nEnjoyy our{
}!'
.format(menu[2][
submenu-1])
)
el
se:
pri
nt("I
NVALI DI NPUT" )
i
fm==' b':
submenu=i nt (
input())
i
fsubmenui nrange(3):
pri
nt('
Wel comet oCCD! \nEnjoyy our{
}!'
.format(menu[3][
submenu-1])
)
el
se:
pri
nt("I
NVALI DI NPUT" )
el
se:
pr
int("
INVALI DI NPUT! "
)
10
Pr
obl
em St
atement
Adoctorhasacl i
nicwhereheserveshispat i
ents.Thedoct or
’sconsult
ati
onf eesaredi f
fer
entfor
di
ffer
entgroupsofpatient
sdependingont heirage.Ifthepati
ent’sageisbelow17, feesis200INR.
I
fthepati
ent’sageisbetween17and40, feesi s400I NR.Ifpati
ent’
sageisabov e40, feesis300
I
NR.Wr i
teacodet ocalcul
ateearni
ngsinadayf orwhi chonearray/Li
stofvaluesrepresenti
ngage
ofpati
ent
sv i
sit
edont hatdayispassedasi nput.
Not
e:
Ageshoul
dnotbezeroorlesst
hanzeroorabov
e120
Doct
orconsult
samaximum of20pati
entsaday
Ent
eragevalue(pr
essEnt
erwit
houtaval
uetostop)
:
Exampl
e1:
I
nput
20
30
40
50
2
3
14
Output
Tot
al I
ncome2000I
NR
Note:I
nputandOutputFor
matshouldbesameasgi
veni
ntheabov
eexampl
e.
Foranywronginputdi
spl
ayINVALI
DI NPUT
Out
putFor
mat
Tot
alI
ncome<I
nteger
>INR
i
nPy
thon
age=[ ]
foriinr ange(20):
m =i nput (
)
ifm ==" "
:
break
eli
fint (
m)i nrange(0,
120):
age. append(int
(m))
else:
print("I
NVALI DINPUT")
exit()
fees=0
foriinage:
ifi<17:
fees+=200
eli
fi <40:
fees+=400
else:
fees+=300
pri
nt("Tot alI
ncome{ }INR".
for
mat
(fees)
)
11
Pr
obl
em St
atement
:
Checki
ngi
fagi
veny
eari
sleapy
earornot
Expl
anat
ion:
Tocheckwhet
heray
eari
sleapornot
St
ep1:
Wefir
stdivi
detheyearby4.
I
fiti
snotdivi
sibl
eby4t heniti
snotaleapy
ear
.
I
fiti
sdivi
sibl
eby4leavingremainder0
St
ep2:
Wedivi
dethey earby100
I
fiti
snotdi v
isi
bleby100theniti
saleapyear
.
I
fiti
sdivi
sibl
eby100l eav
ingr
emainder0
St
ep3:
Wedivi
dethey earby400
I
fiti
snotdivi
sibleby400theniti
sal eapy
ear
.
I
fiti
sdivi
sibl
eby400l eav
ingremainder0
Theni
tisal
eapy
ear
i
nC
#i
nclude<st di
o.h>
i
ntleappr og( i
ntyear)
{
//
checki ngdi vi
sibi
li
tyby4
i
f(year%4==0)
{
//
checki ngdi vi
sibi
li
tyby100
i
f(y ear%100==0)
{
//
checki ngdi vi
sibi
li
tyby400
if(y ear%400==0)
pri
ntf("
%d, t
hey earenter
edhappenst obealeapyear"
,year
);
else
pri
ntf("
%di ssurelynotaleapyear"
,year
);
}
else
printf("
%d, t
hey earenter
edhappenst obealeapyear"
,year);
}
el
se
printf(
"%di ssurel
ynotal eapy ear
",y
ear);
return0;
}
i
ntmai n()
{
i
nti nput_year,val;
pri
nt f(
"Enterthey earthatyouwantt
ocheck"
);/
/ent
ert
hey
eart
ocheck
scanf (
"%d" ,
&input_year)
;
val=l eapprog(input_year)
;
r
eturn0;
}
i
nC++
//C++Pr ogr am
//Leapy earornot
#include<stdi o.h>
usingnamespacest d;
//mai nprogr am
i
ntmai n(
)
{
//initiali
singvariables
inty ear ;
cout <<"Enteryeartocheck: "
;
//useri nput
cin>>y ear;
//checki ngforleapy ear
if(((y ear%4==0) &&(year%100! =0))||(
year%400==0))
{
//i
nputisal eapyear
cout<<year<<"isaleapy ear
";
}
else
{
//i
nputisnotal eapy ear
cout<<year<<"isnotal eapyear"
;
}
retur n0;
}
i
nJav
a
/*Jav
aprogram t
ocheckwhetheray earent
eredbyuseri
saleapy
earornotandal eapyearisa
year
whichiscomplet
elydi
vi
sibl
eby4,buttheyearshoul
dnotbeacent
uryyearexcepti
tisdi
visi
bleby
400*/
i
mportj
ava.ut
il
.Scanner
;
publ
i
cclassMai n
{
publ
icstati
cvoidmai
n(St
ri
ng[
]ar
gs)
{
//
scannerclassdecl arat
ion
Scannersc=newScanner (Syst
em. i
n);
//
inputyearf r
om user
System.out.
printl
n("
EnteraYear ");
i
ntyear=sc. nextI
nt();
//
conditi
onf orcheckingy earenteredbyuserisal
eapyearornot
i
f((
year%4==0&&y ear%100! =0)||year%400==0)
Syst
em.out .
pri
ntl
n( y
ear+"i saleapy ear.")
;
el
se
Sy stem.out.
pri
ntln(y
ear+"i snotaleapy
ear.
")
;
}
}
i
nPy
thon
#py thonpr ogram tochecki fay earnumbert akenf rom t heuseri saleapy earornot
,usi
ngnest
edi
f-
el
se.
num =i nt(input(
"Enterthey eary ouwantt ochecki fisleapy earornot :"
))
#takei nputy earfr
om t heusert ochecki fi
tisal eapy ear
i
f(num%4==0) :
#checki fthenumberi sdiv isibleby4andi ftruemov etonextl oop
if(num%100==0) :
#checki ftheinputy eari sdi visibl
eby100andi ftruemov et onextloop
if(
num%400==0) :
pr i
nt ("
They ear{}isal eapy ear".
format (
num) )
#t hei nputyearisdi visibleby4, 100and400, hencel eapy ear.
else:
pr i
nt ("
They ear{}isNotal eapy ear".
format (
num) )
else:
print("They ear{}isal eapy ear ".
format (
num) )
#ifthenumberi sdivisiblebybot h4and100i tisal eapy ear
el
se:
pr i
nt("They ear{}isNotal eapy ear"
.format(num) )
#i fthei nputnum i snotdi v isibleby4t henitcannotbeal eapy earal
together.
i
nPer
l
#per lScr i
pt
#leapy ear
pr
int"Ent erYear
:";
$year=;
#condi tiontocheckforl
eapyear
i
f((0==$y ear%4)&&( 0!=$year%100)|
|(0==$y
ear%400))
{
print"Leapyear
";
}
el
se
{
print"Notaleapyear
";
}
12
Writeacodetocheckwhet hernoi
spri
meornot.Condit
ionusef
uncti
oncheck(
)tof
indwhether
enterednoisposit
iveornegati
ve,
i
fnegat
ivet
henentert
heno,Andifyespasnoasaparametert
o
pri
me( )andcheckwhethernoispr
imeornot?
Whet
hert
henumberisposi
ti
veornot
,ifi
tisnegat
ivet
henpr
intt
hemessage“
pleaseent
er
t
heposi
ti
venumber
”
I
tisposi
ti
vethencal
lthef
unct
ionpr
imeandcheckwhet
hert
het
akeposi
ti
venumberi
s
pr
imeornot.
i
nC
#include<st di
o.h>
voidpr i
me( intn)
{
i
ntc=0;
for(i
nti =2;i
<n;
i++)
{
if(
n%i ==0)
c=c+1;
}
if(
c>=1)
printf("
%di snotapr imenumber "
,n)
;
else
printf("
%di sapr imenumber",
n);
}
voidmai n( )
{
i
ntn;
print
f("Enterno: ");
/ /
entert
henumber
scanf (
"%d" ,
&n);
i
f(n<0)
{
printf(
"Pleaseent eraposit
ivei
nteger"
);
}
else
prime( n);
}
i
nC++
//
C++Progr
am
//
Pri
meNumber
#i
ncl
ude
usingnamespacest d;
//f
unctiondecl
arat
ion
voidenter(
);
voidcheck(i
nt)
;
voidpri
me( i
nt)
;
//mainprogram
i
ntmai n()
{
enter(
);
ret
urn0;
}
//functi
ont oentervalue
voident er()
{
i
ntnum;
cout<<"Ent ernumber :"
;
cin>>num;
check(num) ;
}
//functi
ont ocheckwhet hert
heinputisposi
ti
veornegat
ive
voidcheck( i
ntnum)
{
i
f(num<0)
{
cout<<"invalidinputenterval
ueagain"
<<endl
;
enter()
;
}
else
{
prime(num) ;
}
}
//functi
ont ocheckf orpri
menumber
voidprime( intnum)
{
i
nti ,
div=0;
for(i
=1;i<=num; i
++)
{
i
f(num%i ==0)
{
div++;
}
}
//pri
menumberonl yhavetwodivi
sors
i
f(div==2)
{
cout<<num<<"i sapr imenumber";
}
//notapr i
menumber
else
{
cout
<<num<<"i
snotapr
imenumber
";
}
Out
put
:
Ent
ernumber
:29
29i
sapr
imenumber
.
i
nJav
a
/*Javapr
ogram t
ocheckwhetheranumberent
eredbyuseri
spr
imeornotf
oronl
yposi
ti
ve
numbers,
ifthenumberisnegat
ivet
henasktheusert
ore-
entert
henumber*
/
/
/Pr
imenumberi
sanumberwhi
chi
sdi
vi
sibl
eby1andanot
herbyi
tsel
fonl
y.
i
mpor tjav a.uti
l.Scanner ;
classMai n
{
publ icst aticv oidmai n(
Stri
ng[]args)
{
Scannersc=newScanner (Sy
st em.i
n);
//inputanumberf rom user
Sy stem. out.printl
n("Enterthenumbert obechecked: ")
;
i
ntn=sc. next Int(
);
//cr eateobj ectofcl assCheckPr i
me
Mai nob=newMai n();
//cal l
ingf unct ionwi thv al
uen, asparameter
ob. check( n) ;
}
//funct ionf orchecki ngnumberi sposi
ti
veornegati
ve
voidcheck( i
ntn)
{
i
f(n<0)
Sy stem. out .
printl
n("Pleaseenteraposi t
iveint
eger
");
else
prime( n);
}
//funct ionf orchecki ngnumberi spri
meornot
voidpr ime( intn)
{
i
ntc=0;
for(inti =2;i<n;i
++)
{
i
f(n%i ==0)
++c;
}
i
f(c>=1)
Sy stem. out.printl
n("Enterednumberi snotapr i
menumber "
);
else
Sy stem. out.printl
n("Enterednumberi sapr i
menumber "
);
}
}
i
nPy
thon
defpr i
me( n):
ifn>1:
foriinrange( 2,n):
if(n%i )==0:
print(n,"
isnotapr i
menumber")
break
else:
print(
n, "i
sapr imenumber"
)
num =i nt(i
nput (
"enteranumber
:")
)
i
f(num >0) :
prime(num)
el
se:
print
("pleaseent eraposi
ti
venumber"
)
i
nPer
l
#PerlScr
ipt
#PrimeNumberorNot
pri
nt"Ent
eranumber ";
$n=<STDIN>;
$d=0;
i
f($n<0)
{
print"I
vali
dInput!!
!EnterValueAgain"
;
}
el
se
{
#Loopt ofi
ndnumberofdi visors
for($c=1;
$c<=$n;$c++)
{
i
f($n%$c==0)
{
$d=$d+1;
}
}
#checkingf orpri
menumber s
if
($d==2)
{
print"
Pri
meNumber ";
}
else
{
print"
NotaPr imenumber ";
}
}
13
Pr
obl
em St
atement
:
Fi
ndt
he15t
hter
m oft
heser
ies?
0,
0,
7,
6,
14,
12,
21,
18,
28
Expl
anat
ion:I
nthi
sser
iest
heoddt
ermi
sincr
ementof7{
0,7,
14,
21,
28,
35––––––}
Andev
ent
ermi
sai
ncr
ementof6{
0,6,
12,
18,
24,
30––––––}
i
nC
Ent
erposi
ti
on:
15
49.
i
nC++
#include<i
ost ream>
usingnamespacest d;
i
ntmai n(
)
{
//ini
tial
isingv ariabl
es
intn,d;
cout <<"Entert heposit
ion:"
;
//userinput
cin>>n;
//logictof indnt hel
ementoft heser
ies
if(
n==1| |n==2)
{
cout<<0;
ret
urn0;
}
elsei f
(n%2==0)
{
n=n/ 2;
d=6;
}
else
{
n=n/ 2+1;
d=7;
}
//logicendsher e
//printi
ngout put
cout <<(n-1)*d;
return0;
}
Out put
Ent
erposi
ti
on:
15
49.
i
nJav
a
cl
assMai
n
{
publ
i
cst
aticvoidmai
n(Str
ing[]ar
gs)
{
inta=7, b=0,c;
Sy st
em.out
.pr
int
ln("Ser
ies:
")
;
for(i
nti=1;i<8; i++)
{
c=a*b;
Syst
em.
out
.pr
int
(c+" "
+(c-
b)+""
);
b++;
}
c=a*b;
Sy
stem.
out
.pr
int
ln(c)
;
Sy
stem.
out
.pr
int
("15t
hel
ementoft
heser
iesi
s="
+c)
;
}
}
Out
put
Ent
erposi
ti
on:
15
49.
i
nPy
thon
num =i nt(input('
ent
erthenumber:'
))
a=0
b=0
fori i
nrange( 1,num+1):
if(i
%2!=0) :
a=a+7
else:
b=b+6
i
f(num%2! =0):
pr i
nt(
'{}t er
m ofseri
esis{}
'.
for
mat(num,
a-7))
else:
pr i
nt(
'{
}t erm ofseri
esis{
}'
.f
ormat(num,
b-6)
)
Out put
Ent
erposi
ti
on:
15
49.
i
nPer
l
#perlScri
pt
pri
nt"Ent
erposit
ion:"
;
$n=;
$term=0;
$d=0;
i
f($n==0||
$n==1)
{
$term=0;
}
el
se
{
if
(0==$n%2)
{
$n=($n/2)
;
$d=6;
}
el
se
{
$n=($n/
2)+0.
5;
$d=7;
}
$t
erm=(
$n-
1)*$d;
}
pr
int"
$ter
m."
;
Output
Ent
erposi
ti
on:
15
49.
14
Pr
obl
em St
atement
:
Consi
dert
hef
oll
owi
ngser
ies:
1,1,
2,3,
4,9,
8,27,
16,
81,
32,
243,
64,
729,
128,
2187…
Thisser
iesi
samixt
ureof2seri
es–allt
heoddtermsi
nthi
sseri
esf
orm ageomet
ricser
iesandall
theeventer
msf
ormy etanot
hergeomet
ri
cser
ies.Wr
it
eaprogr
am t
ofi
ndtheNthtermintheser
ies.
ThevalueNinaposit
ivei
ntegerthatshoul
dbereadf
rom STDI
N.TheNthter
mt hatiscal
cul
atedby
thepr
ogram shoul
dbewr i
tt
entoSTDOUT.Ot hert
hanval
ueofnthter
m,noothercharact
er/str
ing
ormessageshouldbewrit
tentoSTDOUT.Forexample,i
fN=16,t
he16thter
mi ntheseri
esis2187,
soonlyval
ue2187shouldbeprintedtoSTDOUT.
Youcanassumet
hatNwi
l
lnotexceed30.
i
nC
#i
nclude<st di
o.h>
i
ntmai n()
{
i
nti, n,a=1,b=1;
pri
ntf (
"enternumber:
");
scanf (
"%d" ,
&n);
for
(i=1;i<=n;
i++)
{
i
f(i%2! =0)
{
a=a*2;
}
else
{
b=b*3;
}
}
i
f(n%2!
=0)
{
pri
ntf
("\
n%dt
erm ofser
iesi
s%d\
t",
n,
a/2)
;
}
else
{
pri
ntf
("\
n%dt
erm ofser
iesi
s%d\
t",
n,
b/3)
;
}
r
eturn0;
}
Output:
Ent
ert
heposi
ti
on:
17
256
i
nC++
#include<i ostream>
#include<st dio.h>
usingnamespacest d;
i
ntmai n()
{
//ini
tial
isingv ariabl
es
i
ntn, r,
ter m;
cout <<"Entert hepositi
on:"
;
//useri nput
cin>>n;
//logict ofindnt helementoft
heser
ies
i
f(n==1| |n==2)
{
cout <<1;
return0;
}
elsei f
(n%2==0)
{
n=n/ 2-1;
r=3;
}
else
{
n=n/ 2;
r=2;
}
//logicendsher e
//printi
ngout put
cout <<(int)
(pow( r,
n));
return0;
}
Out put:
Ent
ert
heposi
ti
on:
17
256
i
nJav
a
i
mpor tj
ava.ut
il
.Scanner;
cl
assMai n
{
publ
icstaticvoidmai n(Str
ing[]ar gs)
{
Scannersc=newScanner (
Sy stem.in)
;
//inputvalueofn
Sy stem.out.
print(
"Entert hev alueofn: ")
;
intn=sc. nextInt(
);
inta=1, b=1;
//statementf orevenv alueofn
if(n%2==0)
{
for(i
nti =1; i <=(n-2); i=i+2)
{
a=a*2;
b=b*3;
}
Sy stem.out.pr i
nt(
n+"el ementoftheser
iesi
s="
+b)
;
}
//statementf oroddv al ueofn
else
{
for(i
nti =1; i <(n-2); i=i+2)
{
a=a*2;
b=b*3;
}
a=a*2;
Sy stem.out.pr i
nt(
n+"el ementoftheser
iesi
s="
+a)
;
}
}
}
Output:
Ent
ertheval
ueofn:14
14elementoft
heser
iesi
s=729
i
nPy
thon
n=i nt(
input('
entert
henumber
:')
)
a=1
b=1
foriinrange(1,n+1):
if
(i%2!=0):
a=a* 2
el
se:
b=b* 3
i
f(
n%2!=0):
pr
int
('
\n{
}ter
m ofser
iesi
s{}
\t'
.
for
mat
(n,
a/2)
)
el
se:
pr
int
('
\n{
}ter
m ofser
iesi
s{}
\t'
.
for
mat
(n,
a/2)
)
i
nPer
l
#Per lScr i
pt
$a=1;
$b=1;
print("enternumber: "
);
$n=<STDI N>;
for($i=1;$i<=$n;
$i++)
{
if($i%2!=0)
{
$a=$a*2;
}
else
{
$b=$b*3;
}
}
i
f($n%2! =0)
{
pr i
nt (
"$nt er
m ofseri
esi
s",
$a/
2);
}
else
{
pr i
nt (
"$nt er
m ofseri
esi
s",
$b/
3);
}
Out put
ent
ernumber:17
17ter
m ofser
iesi
s256
15
Pr
obl
em St
atement:
Consi
dert
hebel
owser
ies:
0,
0,2,
1,4,
2,6,
3,8,
4,10,
5,12,
6,14,
7,16,
8
Thisseri
esi
samixtur
eof2ser
iesal
ltheoddter
msi nthi
sseriesfor
m evennumbersi
nascendi
ng
orderandev
eryev
entermsi
sderi
vedfrom t
heprev
iousterm usi
ngtheformul
a(x/
2)
Wr
it
eapr
ogr
am t
ofi
ndt
hent
hter
mint
hisser
ies.
Theval
ueninaposi t
ivei
ntegerthatshoul
dbereadfrom STDI
Nthent
hter
mt hati
scalcul
atedby
thepr
ogram shoul
dbewrittentoSTDOUT.Otherthantheval
ueoft
hentht
erm noothercharact
ers
/st
ri
ngsormessageshouldbewr i
tt
entoSTDOUT.
Forexampl
eifn=10,
the10tht
ermintheser
iesist
obederi
vedfrom t
he9thter
mintheser
ies.The
9thter
mis8sot he10tht
ermis(
8/2)
=4.Onlythev
alue4shoul
dbepr i
ntedt
oSTDOUT.
Youcanassumet
hatt
henwi
l
lnotexceed20,
000.
i
nC
#i
ncl ude<st dio.h>
i
ntmai n()
{
i
nti ,n,a=0, b=0;
printf(
"ent ernumber:
");
scanf (
"%d" ,
&n);
for(i
=1;i<=n;i++)
{
if(
i%2! =0)
{
if(i
>1)
a=a+2;
}
else
{
b=a/ 2;
}
}
i
f(n%2! =0)
{
printf("%d",a)
;
}
else
{
printf("%d",b)
;
}
return0;
}
i
nC++
#incl
ude<i
ostr
eam>
usingnamespacest
d;
i
ntmai n(
)
{
i
nti ,n,
a=0, b=0;
cout<<" enternumber:
";
cin>>n;
for(i
=1;i
<=n;i++)
{
if(
i%2!=0)
{
if(
i>1)
a=a+2;
}
else
{
b=a/ 2;
}
}
i
f(n%2!=0)
{
cout<<a;
}
else
{
cout<<b;
}
return0;
}
i
nJav
a
i
mpor tjava.
ut i
l
.Scanner ;
cl
assMai n
{
publicstat
icv oi
dmai n(Str
ing[]args)
{
Scannersc=newScanner (
Sy st
em.in)
;
i
ntn=sc. nextI
nt(
);
i
nta=0, b=0;
i
f(n%2==0)
{
for(i
nti=1; i
<=( n-2);i
=i +2)
{
a=a+2;
b=a/2;
}
System.out.pri
nt(
b) ;
}
else
{
for(i
nti=1; i<(n-2);i=i+2)
{
a=a+2;
b=a/2;
}
a=a+2;
Sy
stem.
out
.pr
int
(a)
;
}
}
}
i
nPy
thon
n=i nt(
input(
'enterthenumber
:'
))
a=0
b=0
foriinrange(1,n+1):
if(
i%2!=0):
a=a+2
else:
b=b+1
i
f(n%2!=0):
print
('
{}'
.f
ormat (
a-2))
else:
print
('
{}'
.f
ormat (
b-1))
16
Pr
obl
em St
atement
:
Thepr
ogr
am wi
l
lreci
eve3Engl
i
shwor
dsi
nput
sfr
om STDI
N
1. Thesethr
eewordswil
lbereadoneatat i
me, inthreesepar
atel i
ne
2. Thefi
rstwor
dshouldbechangedli
keallvowel sshouldbereplacedby%
3. Thesecondwordshoul
dbechangedl i
keallconsonantsshouldber epl
acedby#
4. Thethi
rdwordshoul
dbechangedlikeall
charshoul dbeconv ert
edtouppercase
5. Thenconcat
enatet
hethreewordsandprintthem
Ot
herthant
heseconcat
enat
edwor
d,noot
herchar
act
ers/
str
ingshoul
dormessageshoul
dbe
wr
it
tentoSTDOUT
Forexampl
eify
oupr
inthowar
eyout
henout
putshoul
dbeh%wa#eYOU.
Youcanassumet
hati
nputofeachwor
dwi
l
lnotexceedmor
ethan5char
s
i
nC
#incl
ude<stdi
o.h>
#incl
ude<stri
ng.h>
i
ntmai n()
{
chara[10]
,b[
10],c[
10]
;
i
nti,
j;
i
ntx,y,z;
scanf("
%s" ,a);
scanf("
%s" ,b);
scanf("
%s" ,c);
x=st rl
en(a) ;
y=st rl
en(b) ;
for(
i=0;
i<x;i
++)
{
i
f(
a[i]
=='a'||
a[i
]=='e'|
|
a[i
]=='i
'||
a[i
]=='o'
|
|a[i
]=='u'
)
{
a[i
]=' %';
}
}
for(
j=0;
j<y;j
++)
{
i
f(b[j
]=='
b' |
|b[
j]=='c'
||
b[j
]=='d'
||
b[j]
=='f
'|
|b[j
]=='g'
||
b[j
]=='
h'
||
b[j
]=='
j
'|
|b[
j]
=='k'
|
|b[
j]
=='l
'
||
b[
j]
=='m' |
|b[
j]=='n'
||
b[j
]=='p'|
|b[j
]=='
q'|
|b[j
]=='r
'|
|
b[j
]=='
s'|
|
b[j
]=='
t'
||
b[j
]=='
v'
||
b[j
]=='
w'|
|
b[
j]
=='x'||
b[j
]=='y'|
|
b[j]
=='z')
{
b[j
]=' #';
}
i
f(
b[j
]=='
B'|
|
b[j
]=='
C'|
|
b[j
]=='D'||
b[j
]=='
F'
||
b[j
]=='
G'|
|
b[j
]=='
H'|
|
b[j
]=='
J'
||
b[j
]=='
K'
||
b[j
]=='
L'
||
b[j
]=='
M'|
|b[
j]
=='
N'|
|b[
j]=='P'
||
b[j
]=='
Q'|
|
b[j
]=='
R'|
|b[
j]
=='
S'|
|b[
j]
=='
T'|
|
b[j
]=='
V'|
|
b[j
]=='
W'|
|
b[j
]=='
X'
||
b[j
]=='
Y'
||
b[j
]=='Z')
{
b[
j]='
#';
}
}
z=0;
while(c[z]!
='\0'
){
i
f( c[z]>='a'&&c[z]<='
z'
)
{
c[z]=c[z]-32;
}
z++;
}
pr
intf("%s%s%s",a,
b,c)
;
}
i
nC++
#i
ncl
ude<i
ostr
eam>
#i
ncl
ude<st
ri
ng.h>
usi
ngnamespacest
d;
i
ntmai n()
{
chara[10]
,b[
10]
,c[
10]
;
i
nti,
j;
i
ntx,y,z;
ci
n>>a;
ci
n>>b;
ci
n>>c;
x=st r
len(a);
y=st r
len(b);
f
or(i
=0;i<x;i
++)
{
i
f(
a[i]=='
a'|
|a[
i]
=='e'
||
a[i
]=='i'|
|
a[i]
=='o'
||
a[i]
=='u')
{
a[
i]='%';
}
}
f
or(j
=0;j<y;
j++)
{
i
f(
b[j]=='
b'|
|b[
j]
=='c'
||b[
j]=='d'
||
b[j
]=='f
'|
|b[j
]=='g'
||
b[j
]=='
h'
||
b[j
]=='
j
'|
|b[
j]
=='k'
|
|b[
j]
=='l
'
||
b[j
]=='m'||
b[j
]=='
n'|
|b[
j]=='p'|
|b[
j]
=='q'
||b[
j]=='r
'|
|
b[j
]=='
s'|
|
b[j
]=='
t'
||
b[j
]=='
v'
||
b[j
]=='
w'|
|
b[j
]=='x'
||
b[j
]=='y'
|
|b[j
]=='z')
{
b[
j]='#';
}
i
f(
b[j
]=='
B'|
|
b[j
]=='
C'|
|
b[j
]=='D'||
b[j
]=='
F'
||
b[j
]=='
G'|
|
b[j
]=='
H'|
|
b[j
]=='
J'
||
b[j
]=='
K'
||
b[j
]=='
L'
||
b[j
]=='
M'|
|b[
j]
=='
N'|
|b[
j]=='P'
||
b[j
]=='
Q'|
|
b[j
]=='
R'|
|b[
j]
=='
S'|
|b[
j]
=='
T'|
|
b[j
]=='
V'|
|
b[j
]=='
W'|
|
b[j
]=='
X'
||
b[j
]=='
Y'
||
b[j
]=='Z')
{
b[
j]='
#';
}
}
z=0;
while(c[z]!
='\0'
){
if(c[z]>='a'&&c[
z]<='
z'
)
{
c[z]=c[z]-32;
}
z++;
}
cout<<a<<b<<c;
r
etur
n0;
}
i
nJav
a
i
mportj
ava.ut
il
.*
;
publ
i
cclassMain
{
publ
icstat
icvoidmain(Str
ing[
]ar
gs)
{
Scannersc=newScanner(Syst
em.
in)
;
Syst
em. out
.pr
int
ln("
Ent
ert
hreewor
ds:")
;
St
ri
ngs1=sc.
next
();
St
ri
ngs2=sc.
next
();
St
ri
ngs3=sc.
next
();
i
ntl
1=s1.
lengt
h()
;
i
ntl
2=s2.
lengt
h()
;
Str
ingstr1=" "
;
Str
ingstr2=" "
;
Str
ingstr3=" "
;
charc;
for
(inti
=0; i<l1; i
++)
{
c=s1. char At(i
);
if(
c==' A'||c==' a'|
| c=='E' |
|
c=='e'
||c=='I'|
|c==' i'
||c==' O'||c==' o'|
|c=='U'|
|c=='u'
)
str1=st r1+" %";
else
str1=st r1+c;
}
for
(inti
=0; i<l2; i
++)
{
c=s2. char At(i
);
if(
(c>=' A'&&c<=' Z')|
|(c>='a'&&c<='z'
))
{
i
f(c=='A' |
|c==' a'||c=='
E'|
|c=='e'
||
c=='I'
||c=='i'|
|c==' O' |
|c==' o'||c==' U'|
|c=='u'
)
str2=st r
2+c;
el
se
str2=st r
2+" #"
;
}
else
str2=str2+c;
}
str
3=s3. toUpperCase( );
System.out.
print
ln(str1+str
2+st r3);
}
}
17
Pr
obl
em St
atement
:
Usi
ngamet
hod,
passt
wov
ari
abl
esandf
indt
hesum oft
wonumber
s.
Testcase:
Number1–20
Number2–20.
38
Sum =40.
38
Ther
ewereat ot
alof4testcases.Onceyoucompi
le3ofthem wi
llbeshownt
oyouand1wi
l
lbea
hi
ddenone.Youhavetodisplayerr
ormessagei
fnumbersarenotnumeri
c.
i
nC
#include<st dio.h>
addition(intx,floaty)
{
fl
oatans;
ans=( float)x+y ;
pri
nt f(
"Answer: %.
2f"
,ans)
;
}
i
ntmai n()
{
inta;
floatb;
pr i
nt f
("enterfirstnumber:");
scanf ("%d" ,
&a) ;
pr i
nt f
("entersecondnumber: ")
;
scanf ("%f "
,&b);
addi ti
on( a,b);
}
i
nC++
#include<st dio.h>
usingnamespacest d;
//functiont oaddt wonumber s
fl
oatsum( inta, fl
oatb)
{
return(f l
oat)(a+b);
}
//mai nprogr am
i
ntmai n()
{
//ini
tial
isingv ari
ables
i
nta;
fl
oatb;
cout <<"Entertwonumber s"
;
//useri nput
cin>>a;
cin>>b;
//callfunct i
ont ofi
ndsum
cout <<"Sum of" <<a<<"and"<<b<<"i
s"<<sum(
a,b)
;
return0;
}
i
nJav
a
i
mportj
ava.ut
il
.Scanner;
cl
assMain
{
publ
icstaticvoidmain(
Stri
ng[ ]args)
{
Scannersc=newScanner (System.i
n);
Sy st
em.out.
pri
nt("Number1: ")
;
intnum1=sc. nextInt()
;
Sy st
em.out.
pri
nt("Number2: ")
;
floatnum2=sc. nex tFl
oat(
);
floatsum =num1+num2;
Sy st
em.out.
pri
ntln("Sum ="+sum) ;
}
}
18
Pr
obl
em St
atement
:
Consi
dert
hebel
owser
ies:
0,
0,2,
1,4,
2,6,
3,8,
4,10,
5,12,
6,14,
7,16,
8
Thisseri
esi
samixtur
eof2ser
iesal
ltheoddter
msi nt
hisser
iesfor
m evennumbersi
nascendi
ng
orderandev
eryev
entermsi
sderi
vedfrom t
heprev
iouster
m usingthef
ormula(
x/2)
Wr
it
eapr
ogr
am t
ofi
ndt
hent
hter
mint
hisser
ies.
Theval
ueninaposi t
ivei
ntegerthatshoul
dbereadfrom STDI
Nthent
hter
mt hati
scalcul
atedby
thepr
ogram shoul
dbewrittentoSTDOUT.Otherthantheval
ueoft
hentht
erm noothercharact
ers
/st
ri
ngsormessageshouldbewr i
tt
entoSTDOUT.
Forexampl
eifn=10,
the10tht
ermintheser
iesist
obederi
vedfrom t
he9thter
mintheser
ies.The
9thter
mis8sot he10tht
ermis(
8/2)
=4.Onlythev
alue4shoul
dbepr i
ntedt
oSTDOUT.
Youcanassumet
hatt
henwi
l
lnotexceed20,
000.
i
nC
#i
nclude<stdi
o.h>
i
ntmai n()
{
i
ntn;
scanf (“
%d”,&n) ;
i
f( n%2==1)
{
i
nta=1;
i
ntr=2;
i
ntt erm_in_series=( n+1)/2;
i
ntr es=2*( term_ i
n_ser
ies-1)
;
printf(
“%d“, r
es) ;
}
else
{
inta=1;
intr=3;
intt erm_i
n_ser i
es=n/2;
intr es=term_ in_seri
es-1;
pr i
nt f
(“%d“,res);
}
return0;
}