0% found this document useful (0 votes)
5 views

C 1

The document outlines a C program that generates Fibonacci numbers, calculates factorials, checks for palindromes, and determines leap years. It includes code snippets and explanations for various programming constructs such as loops and conditional statements. Additionally, it discusses the structure of a C program, including documentation, preprocessor directives, and function definitions.

Uploaded by

darshan0406jrc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C 1

The document outlines a C program that generates Fibonacci numbers, calculates factorials, checks for palindromes, and determines leap years. It includes code snippets and explanations for various programming constructs such as loops and conditional statements. Additionally, it discusses the structure of a C program, including documentation, preprocessor directives, and function definitions.

Uploaded by

darshan0406jrc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

551GVMENT

PROGRAMMLWG
Done By
NAME:P.DHARSHAN
REG No 2109 24 20Soll
DEPT.' 1T (yeav)
Write a Cprogram to genevate he fivst n umbers
in a Fibonaci Series Fod
Find he Fac toral of a
9iven umbey, check 1F palindrome
and check whether a iven tnteger
yea is a leap year ox
not
PRDonRAM
#include/$tdio h
lFunc Ron to generate e Fvst n unbes in Whe iborac
bomsd
Sevies void qeneate Fibonacci (int n)
int a=D,b=|.next
pint F(Rbonacct 8evi es")
For (Sotiso,ien ;it+ ){
fF CT==o)
pirtFtd ",a);
else tf (i==)
printf ("hd", b);
else
next a+b,
a=b,
b next

pinltd",next);

ptntf("n)

/funcfon to cal cualate He factovial of a ruunber


g long factorial (?nt
(îrt rum)
longlong fact =1;
For (nt i=;l=um;i++)
fact* =i;

Yetxn Fact,

NFunclfon to check 1f an ntee 6 a pal+n dvome int


is Palfndome(tnt um)
int
whfleoiginal
num, veveY8ed =0 \emndey:
Chum =o)
Yemaindey = num'/. 10,
tever sed =Yevexsed* Io +Yemander
num/= 0;
Yetn ovginal ==Ye versed ;
I|Funcon to check wheher a yea ls aa leap yea
yea)f
Ov not fnt isleap year (Tnt year
ie (CHear'=0 qear
oo! =)ll(yeas .4o9*=
tenl3/l Leap year
Yetun o;/ No a leap
year
Snt main){
Bnt n,num yea;
/Abonacc?
print
Series
FCEnter he numbex of Fbonacci ters")
SeanFC d", An)
generate Fbonacct n);
)Gbonacci Cal cula ion
pÉnt F(^Enter he humber to find 1ts fac
toial"):
Scanf(/,& num),
prí ntfC factortal of d is /d
lld\n, num,factorial Crum).
I|Pal?nd ome check
pyfntF ("EnteY an
integer to check if #s a
Scanf lu paltndrome")
/d,enum);
if CisPalindome (nun){
PAntf C i8 not a pal indro me in' um):
j else
prfntfhd is a palindro men",num):
3
I| Leap year check
print fC Enter a year to che k PE
leap yeay:); Pf ?t'3 a
SconfC" /d", yeav )
if Cis leap year Cyear )7
pfntfc" d 18 a leap year \n"
else geor)
pvint fC/d 7s not a
lep yeorn"ye),
setun 0;
OUTAUr
Enter he number of Fibonacci tems
Fbonaccî Series 0W23
Enter a humbet to find 48 fac to ial s
Factorial of s 78 120
Enter an intege to chec k î it3 a palindone 12
palindt ome
Enter a year
uear to check ?f r's a leap year 024
98 a
leap yaat
Enumevate
and uwiteh
he dif ference
be kween the else-iF ladde
Case 3tatement wiHh a CC
progiam
FE ATURE ELSE IF LADDER SNITCH-CASE 3TATEMENT

VSA GE Used For checkirg malfple Used for selecng a case

Cond?hons whexe cor?ong ba Bed on a


a single
învolve rela Honal or logTca! expse ssion (ypcali;
operators ehavac ter ) Pnteyer
EXECUTIDN Evaates each Cond?on Drectly janps to he
Seauenialy wntl mate hing case ma kfng it
match i8 found. more eYricie nt ?n cehair
Seenaro8
DATA
yrEs `upport & all daBa L9mited to nteqe
sePORTE D ahd Complex CordíHon8. and character expre siort
FREORMh Slause Hece are faste in
PerORMAN iary Cond?Hons since as ît
8ome Case S

jump
H check8 each One tables

Seqpenally
No explle ft beak Reqates break to
SHEMENI heeded,a cond fion8 Ptevert Fall
Re QUEENe Tndependen to
Subsequent (ae
DEFOULT
(Ase
USe3 elae for
uses de faul! for
hardlng
AANDAINO CAses Unmatched handling Unmatched
Cases

Example C Pogram De nstvafno Poth if-else


Ladder ard
Demo
mo nstrang
Sutteh Case B\atement
Rnclude zstdio-hs
votd ug?ng IF Else Cînt num ){
pint r("ustng 9F-else ladder:\n"):
pf nt f ( One \n"),
telseif Cnuma)!
påntr (" Two\n");
Selte 1f Cnum=3){
pfntfl"Thyee n),
felse f
print f (other number \n);

vid vaßng8uiteh Case (rt num)$


pfintf "usíng buitch-cage\n");
Suitch enum)
PtntE ("one \n):
heat:

pnt F(Tuo\n).
beak ;
Case 3
Pinf(vee \n"):
deFault :
pintt(oikex number\n')
3
Snt maint)¬
Tnt num';
pitF bEnter a
ScanF ( d", &numhumber:):
):
usnaf eke (rum );
usng SuitchCase (nun)
vetm O,

OUTPUT
Enter
anumber:2
sinq 1f - else adder: Two
Sutch- Case Two
-plain e vaoua looplng 3otemen aydloble
PPoriote arnle
looping o Mecative iotereert Caytes
Lalements Cor Cormpourd 8ale rmente) o be eoslod
peatetly ntl le Specitrod CondT ltr berormot

lypee of looßng sla terente


1here ae
huo ypet of laplng Slalemed
(a)tntny Contolled oop
The tet,t ond?Iforn fz, checkod frat
befoe he loop 8 exe aulod

(b) Exit Controlled loop


he loop ?8 exeCuted cst ored hen
CondY?on i8 checkat
he (oop is exeut od at least Dnee,
CVen when he Cond?Hon 8 fa lae

do hile bop

an
entg (ond oMod oping 3tatomeht
* Aalement: oxented
while con ditton % due epeatedy
yntax
whfle Ccondi Pon)

Statemen ts
Sncement ldeCrement;
FLOWCHART

CoNDITION False

True
Inctement /
Decxement Tiue statement

Example:#ncudestdio h
int mainc ){

pYint F CNumber From I to 10:\n


while Chu m=1o )
Pint f C"% d". nurm):
hum ++

pint f("\n"),
e uno:

UruT
Numbe 8 From | to j0:
I23 45 6 78 9 10

2do-while loop
is an exît ontrolled
loop?ng statement
Lt ?8 used to exeoute a 8et oF statement S
epe atedly wntl he logeal test tesults become
false . This is ealed we post -test lbop.
Because, he test FoT Yepe PHon î6 made at
Hae end of each pas
* The do-while loop Chekg its eond? fon at
Hhe botom of he loop Whereaj Fox and
wh?le loo p8, he loop cond? Pon ?s chec ked
at he top of he loop.

do

8tateme nts:
Ynccement /dete ment)
while Ceondifon):
Flowchavt

ncrement/
Deciement True 3 tatement

True
CondHon

False
Ex:
#ncude stdio.h>
nt main (){
Éint num = ,
do
pint f (u "/ d",num ):
numtt
while (num<=s):
pint f(\n");
re turn 0:,

OUT PUT:
I23 45
3 FoR looP
+ Tt Ts an
entry Contro le d bopi ng Statement
Execut es a Seque nce o¬
of Statements muple
Hme and abbreviates he eode at
he loop variable manage
For lo op S+ructure ,more
Varfable Can be
han one
?nial ze d
more
hat Conc?se and lexible han
wh?le and do- while loops.
*For 5tate ment
3hould not end wî B temicolon
SynTAN
fo
(in?talizafon ,test - Condîfon ; încsenert/
decce ment
Statemnerts ,

Advantaqes
* More ConcTse and
and Easy to uge
Flexible
More Wran one varíable be
TnfRalized
More han Ohe ncre ment lan be
applfed
More Ran one CondiHons Can b Se.
FowcHART

Tnitializa fon
Expye ss Pon

TEsT False
CoNDMON ExT FoY lbop

TYue

Body oF he loop

nerement /
Decxe ment
Exnmple
#+încude 2stio-h>
9nt mainC)
prfntF CNumbers From I to lo:\n);
Fov Cintf=l;i=10,i++)

pf nt FC ", i):
pr? nt f( n");
Ye turn 0;

OUTPUT
Numbets From to 10:
I 2 3 45 6 78 9 I0

hote Hhe Structre of a Cpera ard epla? n


each part în detaîl.
The bafc &tructe of a e
?3 divided 6 part8 which makes
Pnogram
it easy
Tnto
to (ead, rod? fy dbcument and understand
a pacHcular fosmat
SgeTIONS OF C RoGRAM
IDoumentaon
2 re-poce s$ov Sec Ron
3. DeFfniton
4. Global Declaxa on
5. Maint) fne fon
6 Sub Rogiams
|: DocUMENTAT ION

he CCproqam beginS ui a document


Secfon.ft includes a 3et of Comment lines q
?nfomaHon Such as name of he proyYa.n Hipo se
OF he piogiam and other de laiks he documentais:
howevex t s Yecommend
paxt 9s not
|*
compulsory
tadius oF Cîxcle*/
2 Pe-pvoce ssor SecTION:
Be header Fles of

be decl aved în he pre poce ssov 3ec Hon oF


Pgam
poqiam
* The Pre
'he Proce ssoy iee Fves ave i
Speial mstruc ons 4iven to he pre proce sst
hat tell t how to pre paye our For

(onipilaion.
of he
ipevtant
dnee Ave3 Snclude
+ The 9ncude d?recHve
?rer Hve s usod to tell be
pre proce ss fnq What we rneed nfotrna on
fom Be ge lecied hbay f7le known a3
hea der (le
* The # delfne ?s also he
pre poces30r d?vec Pve T Commonly
agsigns
uged
Constant vaue to he gym bo lic Constant
SyNTex#?ncde stondard header ffle >
ExAMAE #Pncude Lstdioh>
+incude math
SyNTAX #de fine Name Vaue
ExAMP2E # de Fne MAX 100
3DEF (NITION
* Pre
PoceesoSStarts wi th he
*#defirne preprocessor fs used toSymbo)
a Constant Cteate
* Whenever hroughout he pogms.
name 13
Re achual piece of replaces by
defined Code
Exomple:
de Fine Max 100
4 GnloBAL DECLARATION
dec lafing he variables outside oF all
* By made accesgfble to all funta
func ffons, Jhey can be
în Me progvams. Sach vatlable &
are known

variakbl es
gloal
* The gobal declara fon Jec Hons Cortain
vaia bles. funcfo declaxalPon and stae varables.
* Varfables and fure ons which are delaed
n scope Can be
used angnahee me pogarn
Exampleint nm 18;

5. MAIN FUNCT ION:


Func fon
*Every C progam must have a mon
Opera ons ike declasa fon and exe alfon aYe
* maih
peroymed Bnde he cuvly baces OF he
pogess
The poqam exeufon beqins at he opering
urly bvaces and ends at he closing aliy
braces Whe main kuncon
* Vo main C) tells
he Compiley Bat Wehe
pogram will not 3e turn any vawue
* The int naint) tells
he Compiley iat
he Progiam wll ve kn an înteger va lié
6 SUB PRoGRAMS
User de fined funcons ave called n kis
SecRon oF Whe
* The program
Contro| of he
shif ted to Hhe ?s deffned
Ca Med from he Called func Pon whenevey hey ae
tunefon. man or out? de e mal
maß n )
* here aye
Speci Fiecl as per he
OF he
programmer. equ'rement
ExAM PLE:
#
4ncwude Lstd?o.h>
def?ne x = 20
int Jum (înt
vofd mainc)

pfntf( Sum =
`umly)):
Snt sum Cint y
tetusn

OUTPUT;
Sum =7o
he Various dta ypes yporte d by ha
5 Explain
are
oF d?Efevent
deelarha Variables oN fune on8
much
of a Vayîable deter mineS how Space
Hhe bit
and ow patten
upies în stoage
is intepreted

DATA TyPES

Ranay 1fundamen tal Data Types Secondary Data ypes


nt Flogt double
chax User
de Fned
Derive
SHing
typedef num

Amay Stiuctue Urfion


PeMARy DATA TyreS
Tntegex DATA TyPE:
nteger Data allows a Var?able to store
uemec Vaue.
* int koyuond 16 sed to veer
he torage Size of nt nteger da
* chuncéer Data upe allos
allos a Variale totb stae
ChartcteY
Size of chavacter data ype
Stang to yefer ChaYac ter
TupE $tora ge size
chay
Tbyte
sianed char
1hyte

cha a,
Char azC:
Toint Data
oatirg point data type onsíss of

2. do uble
* float data ype
byre allous a vaiabl to stove
desimal yaues
3tocage
Hhe
Storage size
(har
nsigned chay
Tbyte
ned char
byte
flsat a
Cloat a=3,4
oueLE
+Dauble data type s
also 8ame Float data type
as
allous upto 15 digi ts after
+1he Yange For double decimal.
îE +37 datahye îs From 1E -37 to
Otcuptes
Range
8 bytes 9n
memony
:7e-38 to 7e+ 3 o8

Stoxage size
Fioat 4 byte
19ble

ira double
1o byte
double
SECONDARr DATA TyPE
aUser de fned data ype
în addiHon to Hhe stmple data hyes Such
as nteaer, Float : Char.etc, c' allous he Wse r
to declare new data hypes Called user- defined dat
4ypes These data types Can be deelared withhe
kelp of keywords called ypedef and enumeroted
Cenum)
Type def :
în c, keywor d Called ype def ?s used
data tpe a new name to g've a
SyTAK.
bype def < type >datanames,
Ex:

tyedef unsigred char byte.


where, ypedef 9s e keyuor d
unsiqned char fs He data type
byte s he wses de fined tyre
Heve he ?dentife byte' data type hame
Can be Used
abbreviafon Foy he Fype unsi ned
an

byte bl b2; char


.EnuME RATED Cerum)
enume ated da ta ype is a user
defined data type whîch takes he fn teqer
vaus fiom list
used to deîne
e num
enum
data kype
SyN TAx
enum typenamelvalue l, vauea,
valuen
OF ENUMERATED VARABL£
DECLARATION
enum Boolean

False:,
tue;
enun Boolean check
Heve a Vayiable check s oF enum boolean

3. Void
The void ture 8pecities hat no value îs availak
t is used în Rvee kinds OF
Situa on
() Func Pon re tuns as
Vod
A func Hon w) h ho
veuin Vaue has he
rehun type Ex
void.

Void exitC?nt stoa tus)


ü) Fun Ron
aiguments
A funcon wh hono
as vol
Passed as Void pavameter Con be
Ex:

int sand (yoid):


Pointer to Voi d
pointer o
te present Hoe
Addiess obËet , but not s
Ex

H menory allbca on FuncHon Void alloc


alr
(size-1 ze) ; Retun a pointer to Voîd which
Can te Casted to
any data type

You might also like