Upload
maryannjunelle
View
240
Download
0
Embed Size (px)
Citation preview
8/10/2019 Manual - Turbo C Revised
1/59
C Language Programming Page
INTRODUCTIONINTRODUCTION
C is a general-purpose programming language, which features economy of expression, modern control flow and data structures and a rich set of operations Ithas !een called as "system programming language# !ecause it is useful for writingcompilers and operating systems
BB RIEFRIEF HH ISTORYISTORY OFOF CC
$ %&'O& (%lgorithmic &anguage) - $*+C.& (Com!ined .rogramming &anguage) - $*+/
/ 0C.& (0asic Com!ined .rogramming &anguage) - $*+1de2eloped !y 3artin Richards
this language in turn strongly influenced the de2elopment of the nextlanguage
04 0 - $*1
written and de2eloped !y 5en Thompson for the first UNI6 system on the D7C.D.-1 0oth 0C.& and 0 are "type less# languages
8 C - $*1an expansion of 0
a programming language designed !y Dennis Ritchie in $*1 at %T and T 0ell&a!oratoriesC was originally designed for and implemented on the UNI6 operating systemon the D7C .D. 9 II
the new C added something that 0 do not ha2e: data types+ Tur!o C 9 $*;1
a particular 2ersion of C de2eloped !y 0orland International CorporationThis 2ersion is designed to run on 2arious microcomputer systems, namelythose which use the operating system 3
8/10/2019 Manual - Turbo C Revised
2/59
C Language Programming Page
TT HEHE P P RO-R.MMIN-RO-R.MMIN- PP ROCESSROCESS( implemented using C &anguage)
CC OMPONENTSOMPONENTS OFOF T/RBOT/RBO CC
Tur!o C is more than =ust a 2ersion of the C language Rather, it includes a completeen2ironment in which to create, test, and run program This programming en2ironmentconsists of a num!er of components:
$ E#itor used to create program source codeE%ten#e# C Language this 2ersion o C is significantly extended from the "!ase !ones#
language of Ritchie>s specifications The extension includes enhancement whichma?e the Tur!o C compati!le with the new proposed and %N
8/10/2019 Manual - Turbo C Revised
3/59
C Language Programming Page
+ /ser Inter,a"e the 2arious of Tur!o C are integrated into a single program which allowsyou to smoothly from source code entry to compilation to de!ugging to runningwithout e2er lea2ing the Tur!o C en2ironment
FF E.T/RESE.T/RES .ND.ND CCH.R.CTERISTICSH.R.CTERISTICS OFOF CC
1. Middle Level Languagecom!ines elements of high-le2el language with the functionalism of assem!ly language
2. Portable Programit is possi!le to adapt software written for one type of computer for use onanother
7x .rogram written for an %pple IIA can !e easily mo2ed to an I03 .C
3. C allows almost all meaningful type conversions. 7x Char and integer types may !e freely intermixed in most expressions
. !urbo C has 3 keywords ( / as defined !y the %N
8/10/2019 Manual - Turbo C Revised
4/59
C Language Programming Page
$ &1 ))) 1& Comment
Prepro"essor Dire"ti0e Contains information needed !y the program to ensure the correct operation of
Tur!o C>s standard li!rary functions
a 2in"lu#e #ire"ti0e 3 commonly ?now as macro include) is apreprocessing directi2e that causes a copy of the file to included at thispoint in the file when compilation occurs
a Jinclude line can occur anywhere in a file, though it is typically at thehead of the file The Kuotes surrounding the name of the file arenecessary
an include file, is also called "header file#, can contain J define lines andother lines 0y con2ention, the names of header f iles end in h
E%amples(
Jinclude "stdio h# Jinclude stdio hEJinclude string hEJinclude math hE
The C system pro2ides a num!er of standard header files These filescontain the declarations of functions in the standard li!rary, macros, structuretemplates and other programming elements that are commonly used
! 2#e,ine #ire"ti0e line can occur anywhere in a program It affects onlythe lines in the file that come after it
Normally, all J define line are placed at the !eginning of the file 0ycon2ention, all identifiers that are to !e changed !y the preprocessor arewritten in capital letters
7xamples:Jdefine &I3IT $
Jdefine .I / $4$+
7xplanation:If the a!o2e lines occur in a file that is !eing compiled, the
preprocessor first changes all occurrences of the identifier &I3IT to $ alloccurrences of .I to / $4$8* The identifier &I3IT and .I are called s$m oli""onstants) The use of s$m oli" "onstants in a program ma?e it morereada!le 3ore importantly, if a constant has !een define sym!olically !ymeans of Jdefine facility and used throughout a program, it is easy to changelater, if necessary
/ De"laration Se"tionsyntax: 4#ata t$pe5 4i#enti,ier5
ex int x, y, LHfloat fM8 +1Hchar gHchar name $ Hint xM$ H
.) Data T$pesa int contain integral 2alues only, that is 2alues that do not contain
decimal places
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
4
8/10/2019 Manual - Turbo C Revised
5/59
C Language Programming Page
2aria!les of type int, can hold integer Kuantities that do not reKuire afractional component Paria!les of this type are often used for controllingloops and conditional statements
a whole num!er consisting of an optional sign (A or -) followed !y aseKuence of digit
occupies two !ytes in the address can contain no decimal point or fractional part cannot contain commas ranges from 9/ 1+; to A/ 1+1
T$pes o, int
$ s+ort int identical with intranges from 9/ 1+; to A/ 1+1
occupies two !yteslong int ta?es up more space and can store large num!er
ranges from 9 $414;/+4; to A $414;/+41 occupies 4 !ytes
/ unsigne# int cannot !e negati2e from to +88/+6) unsigne# long int
! ,loat consists of an optional sign (A or -), followed !y one or moredigits , a decimal point, and one or more further digits
occupies 4 !ytes it can include an optional exponent ranging from / 4 7 9/; to / 4 7 A/;
c #ou le is a special float which can store more significant digits andha2e longer exponent
occupies ; !ytes in the memory ranges from $ 17-/ ; to $ 17A/ ; with $8 digits accuracy
d "+ar can !e used to contain a single letter, digit, punctuation mar? orcontrol sym!ol recogniLed !y the computer Qritten enclosed within
single Kuotation mar?s, !ut literals strings are enclosed in dou!leKuotation mar?s a character may !e assigned an integer 2alue !etween 9$ ; and A$ 1
unsigned char data type may !e assigned an integer 2alue from to88
E%)( char cHchar 0 M G>Hchar a / Hchar a M "apple#H
e 0oi# 2alueless
T+ree uses o, 0oi#(
$ to declare explicitly a function as returning no 2alueHto declare explicitly a function ha2ing no parametersH
/ to create generic pointers
B) I#enti,iersThe names that are used to reference 2aria!les, functions, la!els and
2arious other user-defined o!=ects
8/10/2019 Manual - Turbo C Revised
6/59
C Language Programming Page
%n identifier in C can 2ary from one to se2eral charactersThe first character must !e a letter or an underscore with su!seKuent
characters !eing letters, num!ers or underscoreIn Tur!o C, the f irst / characters of an identifier name are significantIn C, upper and lower case are treated as different and distinct from one
another7x : studname,
8/10/2019 Manual - Turbo C Revised
7/59
C Language Programming Page
** .RI.BLES.RI.BLESare identifiers which can !e assigned a 2alue within a program/ characters are 2alid li?e letters, digits, and underscore
De"laring *aria les(
S$nta%(
Data 9 type 2aria!le listH list o, 0aria les separate# $ "ommasE%ample(
int a, !, cHchar x, yHdou!le pHfloat a2erageHchar name / H
*aria le initiali:ation the process of assigning starting 2alues to the 2aria!les
Se0eral 8a$s to Initiali:e a *aria les(
$ 'y using an assignment statement may!e used to assign to 2aria!les of any type
H
The sym!ol M C>s assignment operator
2. 'y using function( )scanf*
7xample: scanf(" d#, x)Hscanf(" lf#, y)H
3. 'y assigning value during declaration
7xample: int x M $/Hchar y M a>Hdou!le a, ! M $ H
-lo al an# Lo"al *aria les
-lo al *aria les are initialiLed only at the start of the program %ll glo!al 2aria!les areinitialiLed to Lero if no other initialiLer is specified
Lo"al *aria les are initialiLed each time the function in which they are declared is entered
CCONST.NTSONST.NTS refers to fixed 2alues that may not !e altered !y the program
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
7
8/10/2019 Manual - Turbo C Revised
8/59
C Language Programming Page
, >
integer constants are specified as num!er without fractional components7xample: * , -+
/ floating-point constant are reKuired the use of decimal point followed !y the num!ersfractional components
7xample: $ $/4
4 string constant consists of a phrase contained@enclosed within dou!le Kuotes *> int $ $ $ /float $ / /dou!le $ / / $ / ////string "7lsa#
De"lare# Constants constants which are assigned a name declared constant aredefined using a J defined declaration at the !eginning of the program Thisdeclaration is introduced !y the word J define followed !y a constant name and its2alue
7xamples: J define total amount $J define grapes *J define titi? 7> J define m $4J define salita "good day#
.""ess Mo#i,iersC has two type of modifiers that are used to control the way in which 2aria!les may !eaccessed or modified
$ ) "onst 2aria!les declared under this modifier cannot !e changed during programexecution Vowe2er, you may gi2e an initial 2alue !efore the start of theprogram
) using 2 #e,ine the J define declaration is used at the !eginning of aprogram &i?e const, Jdefine is also used in declaring constants
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
8
8/10/2019 Manual - Turbo C Revised
9/59
C Language Programming Page
8/10/2019 Manual - Turbo C Revised
10/59
C Language Programming Page
Ho9 to .ssign *alues to *aria les
$ The 2aria!le must !e on the left side of the eKual signPalues must !e on the right side of the eKual sign%ny expression can !e assigned on the 2aria!le
/ 7xpressions are not allowed on the left side of the assignment operator
O.7R%TORs 2alue If the operator follows itsoperand, C uses the operands 2alue !efore incrementing or decrementing it7xample: 6 M $ H
W M AA6H @ is A = Y is A
6 M $ HW M 6AA @ is A = Y is A>
In"rement an# De"rement Operators
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
10
8/10/2019 Manual - Turbo C Revised
11/59
C Language Programming Page
In"rement to add exactly one to the 2alue of a 2aria!leDe"rement to su!tract exactly one from the 2alue of a 2aria!le
AA increment operator 6AA post increment--6 pre increment
- - decrement operator
E%ample(
$ 6 M 6 A $ or 6AM$ is the same with 6AA 6 M 8, W M $
Q M W A 6AA Q M W A 6H $16 M 6 A $H +
Q M W A AA 6 6 M6 A $H +QM WA 6H $;
Q M W A 6-- Q M W A 6H $16 M 6 - $H 4
Q M W A -- 6 6 M6 - $H 4
QM WA 6H $+
Pre"e#en"e o, .rit+meti" Operatorshighest AA - -
- (unary)G @
lowest A -
) Relational Operators used to determine the relationship of one Kuantity to anotherrefers to the relationship 2alues can ha2e with one another
S$m ols Fun"tions E%amplesE greater than x E yEM greater than or eKual to num EM $
less than x yM less than or eKual to num M $
MM eKual x MM ySM not eKual x SM $
") Logi"al Operators refers to the ways the relationships can !e connected together using therules of formal logic
S$m ols Fun"tions and
XX orS not
#) .ssignment Operator ( M ) eKual sign
e) Com ine# Operators
AM ex aAM! aMaA!GM ex aGM! aMaG!-M ex a-M! aMa-!
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
11
8/10/2019 Manual - Turbo C Revised
12/59
C Language Programming Page
@M ex a@M! aMa@!M ex a M! aMa !
,) Ot+er Operators
1. ( Ternar$ Operator 3 uestion mar "olon !ecause it reKuires three operands and ta?esthe general form
S$nta%( 7xp$ Y exp : exp/or
condition Y statementT : statementBHresult M condition Y statementT : statementBH
E%ample(
x M $ Hy M xE* Y $ : H
xM$xE* Y printf("Wes#): printf("No#)H
max M (aE!) Y a : !H
Interpretation( 7xp$, epx and exp/ are expressionsH exp$ is e2aluated, if true thenexp is e2aluated and its 2alue !ecomes the 2alue of the expressionThe 2alue of a Y expression is determined this way: +,p1 is e2aluatedIf it is true, then +,p2 is e2aluated and !ecomes the 2alue of theentire Y expression If +,p1 is false, then +,p3 is e2aluated and its2alue !ecomes the 2alue of the expression
2 ) G t+e "omma operator is used to string together se2eral expressionsIt is used to string together se2eral expressionsThe left side of the comma operator will always !e e2aluated as 2oid Thismeans that the expression on the right side will !ecome the 2alue of thetotal comma separated expression
E%ample( W M ( 6M4, 6AA, 6 G/)H 6 M 4 6 M 8 6 M $8
Finall$ Y < A
x M (yM/, yA$)H T+e 0alue o, % is 6
y M Hx M (yMy-8, / @y)H T+e 0alue o, % is >
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
12
x M $ Hif (xE*)
W M $ Helse
W M H
8/10/2019 Manual - Turbo C Revised
13/59
C Language Programming Page
HH IER.RCHYIER.RCHY OFOF C OC O PER.TORSPER.TORS
( ) highestS AA - - (type)G @ A -
M E EMMM SM
XXYM GM @M M AM, lowest
EE @PRESSION@PRESSION
Operators, constant and 2aria!les are the constituents of e,pressions%re com!inations of operators, constants and 2aria!les
7xpression 72aluation:
$ 2 M (+ @ G /) EM ((+@ /) A + G )2 M (8 MM (/ A $)) XX (( + /) EM (8 @ )) (8 SM+)
/ % M $H 0M H CM/H6 M S((% E C) (0 EM/)) XX (C 4) ((+ M +) XX (1 0))
4 2 M S((/ G ) ($ G /)) XX S( MM )
CC .STS.STS
It is possi!le to force an expression to !e of a specific type !y using a construct called acast.
Syntax:3type expression
where:type is one of the standard C data types
Sample Program No) A
Jinclude Zstdio hZmain()
F int iHclrscr()Hfor(iM$Hi M8HAAi) printf(Z d @ is: f[nZ, i, (float)i@ )Hgetche()H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
13
8/10/2019 Manual - Turbo C Revised
14/59
C Language Programming Page
IN.UT %ND OUT.UT ,>W>,>\>)H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
14
8/10/2019 Manual - Turbo C Revised
15/59
C Language Programming Page
will print:6 W \
E%amples(
Jinclude Zstdio hZmain()
Fclrscr()Hprintf(Zprogramming is fun [nZ)Hprintf(Zprogramming in C is e2en more fun[nZ)Hgetche()H
-utputprogramming is fun
programming in C is e2en more fun
Jinclude stdio hEmain()
Fclrscr()Hprintf(ZTesting [n $[n [n /[nZ)Hgetche()H
-utput
Testing$
/
Jinclude Zstdio hZmain()
F int sumHclrscr()HsumM8 A 8Hprintf(ZThe sum of 8 and 8 is d[nZ, sum)H
getche()H
-utputThe sum of 8 and 8 is 18
Jinclude stdio hE
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
15
8/10/2019 Manual - Turbo C Revised
16/59
C Language Programming Page
main()
F int 2$, 2 M 8, sumHclrscr()H2$M8 HsumM2$A2 Hprintf(ZThe sum of d and d is d[nZ, 2$, 2 , sum)Hgetche()H
-utputThe sum of 8 and 8 is 18
>) s"an,3 CH.R&STRIN-&N/MERIC O/TP/Tis analogous to the function printf() !ut is used for input rather than outputused to read 2irtually any type of data entered at the ?ey!oardits first argument is a control string ha2ing formats that corresponds to the 2ariousways the characters in the input stream are to !e interpreted The other argumentsare argument list or addresses
Insert
8/10/2019 Manual - Turbo C Revised
17/59
C Language Programming Page
E%ample(
Jinclude stdio hEmain()
F char my charHclrscr()Hprintf(Z.lease type a character : Z)Hscanf(Z cZ, my char)Hprintf(ZThan? Wou That character was c[nZ, my char)Hgetche()H
Sample Program using print,3 an# s"an,3
Jinclude stdio hE @G this is a simple program G@
main(F char !$, ! , !/H
int aHfloat xHdou!le LH
printf("[n s [n s#, "Input three characters#, "an int, a float, and a dou!le:#)Hscanf(" c c c d f lf#, !$, ! , !/, a, x, L)Hprintf("Vere is the data that you types in:[n#)Hprintf(" /c /c /c 8d $ f $ lf#, !$,! ,!/,a,x,L)Hreturn H
// NFORM.TTEDNFORM.TTED I&O FI&O F /NCTIONS/NCTIONS ININ CC
A) get"+3 reads a character without echo Does not wait for carriage return 7NT7R ?ey
>) get"+e3 reads a character with echo Does not wait for carriage return or 7NT7R ?ey) gets3 this function ta?es the name of the string as an argument and reads characters fromthe ?ey!oard until 7NT7R ?ey is pressed 7NT7R ?ey is not stored !ut is replaces !ethe null terminator
6) get"+ar3 reads a single indi2idual character from the ?ey!oard and waits for the carriagereturn or 7NT7R ?ey
) puts3 write a string to the screen, followed !y a newline It can only output a string ofcharacters It cannot output num!ers or do format con2ersion It ta?es up less spaceand run faster
K) put"+ar3 writes a string (character) to the screen
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
17
8/10/2019 Manual - Turbo C Revised
18/59
C Language Programming Page
CONTRO& ) Sele"tion Control Stru"ture Chooses among alternati2e program statements
Uses conditions to select a course of action
Con#ition an expression that is either false ( ) or true (usually represented !y $)8 types:
$ simple if if-else
/ if-else-if 4 nested if-else8 switch
these are also called "on#itional ran"+ing "onstru"ts
) Iteration & Repetition Control Stru"ture
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
18
8/10/2019 Manual - Turbo C Revised
19/59
C Language Programming Page
Uses loops repeats a group of steps in a program repetition of action is one reason we rely on computers Qhen there are
large amount of data, it is 2ery con2enient to ha2e control mechanism thatrepeatedly execute specific statements
Loop o#$ contains the statements to !e repeated in the loop/ types:
$ forwhile/ do-while
these are also called looping "onstru"ts)
SELECTION CONTROL STR/CT/RESELECTION CONTROL STR/CT/RE
SS IMPLEIMPLE IF SIF S T.TEMENTT.TEMENT
The general form of the if statement is
Syntax : i, ( condition ) statement ! H
Example: i, (grade EM18)printf(".assed#)H
Interpretation: If condition e2aluates to true, then statement T is executedH otherwise statementis s?ipped and control passes to the next statement
Note(Usually, the condition in an i, statement is a relational, logical, eKuality expression, acondition from any domain is permissi!leQhere appropriate, compound statement should !e used to group of statements under thecontrol of a single i, "on#ition) The code !e written to !e more efficient and more
understanda!le !y using a single if statement with a compound statement for its !ody
IF ELSE SIF ELSE S T.TEMENTT.TEMENT
The general form of the if - else statement is
Syntax : i, ( condition ) statement ! (
else statement ! H
Example: i, (grade EM 18) printf(".assed#)H
else printf("Bailed#)H
Interpretation: If condition e2aluates to true, then statement T is executedH otherwise it iss?ipped and statement B is executed In !oth cases, control passes to the next statement
Note(0loc? of statements in C is surrounded !y curly !races else is optional
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
19
8/10/2019 Manual - Turbo C Revised
20/59
C Language Programming Page
IF ELSE IFIF ELSE IF SS T.TEMENTST.TEMENTS% common programming constructs is the if ] else if statement It loo? li?e this:
Syntax : i, ( condition ) /tatement 1Helse i, ( condition ) statement 2Helse i, ( condition ) statement nH
:else statement eH
Example: i, (x E printf("x is positi2e#)Helse i, (x ) printf("x is negati2e#)Helse printf("x is Lero#)H
Interpretation: The conditions here are e2aluated in seKuence until a true condition is reached If a condition is true, the statement following it is executed, and the rest is s?ippedIf a condition is false, the statement following it is s?ipped, and the next conditionis tested If all conditions are false, then the statement e following the final else isexecuted
Note(The last else is optional
NESTED IFNESTED IF E E LSELSE SS T.TEMENTST.TEMENTS% common programming constructs is the nested if ] else statement It loo? li?e this:
Syntax : i, ( condition ) i, ( condition )
statement 2Helse
statement nHelse
statement eH
Example: i, (x MM 8 i, (y EM $ ) F sum M xAyH
printf("the sum of x and y is d#, sum#)H
elseF diff M x - yHprintf("the difference of x and y is d#, diff#)H
printf("x is Lero#)Helse
printf("Next time#)H
Sample Program No) A @G .rogram to determine if a num!er is positi2e or negati2eG@Jinclude Zstdio hZmain()
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
20
8/10/2019 Manual - Turbo C Revised
21/59
C Language Programming Page
F int numH clrscr()H printf(Z7nter an integer Z)H scanf(Z dZ, num)H if (num E )
printf(Z d is a positi2e integerZ,num)H else
printf(Z d is a negati2e integerZ,num)H getch()H
Sample Program No) > @G .rogram to determine if a num!er is odd or e2enG@Jinclude Zstdio hZmain()F int num,remH clrscr()H printf(Z7nter a num!er Z)H scanf(Z dZ, num)H rem M num H if (rem MM )
printf(Z d is an e2en num!erZ,num)H else if (rem SM )
printf(Z d is an odd num!erZ,num)H getch()H
Sample Program No) @G .rogram %rithmetic Operations G@Jinclude Zstdio hZmain()F int f,s, totalM H char optrH clrscr()H printf(Z7nter $st num!er : Z)H scanf(Z iZ, f)H printf(Z7nter the operator : Z)H scanf(Z sZ, optr)H printf(Z7nter $st num!er : Z)H scanf(Z iZ, s)H if (optrMM^A^)
totalMfAsH if (optrMM^-^)
totalMf-sH if (optrMM^G^)
totalMfGsH if (optrMM^@^)
totalMf@sH if (optrMM^A^ XX optrMM^-^ XX optrMM^G^ XX optrMM^@^)
printf(Z d c d M dZ, f, optr, s, total)H else
printf(ZOperator not 2alidSSSZ)H
getch()H
S8ITCH SS8ITCH S T.TEMENTT.TEMENT
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
21
8/10/2019 Manual - Turbo C Revised
22/59
C Language Programming Page
is a multiway conditional statement generaliLing the if-else statementis a !uilt-in multiple !ranch decision statement % 2aria!le is successi2ely tested againsta list of integer or character constants Qhen a match is found, a statement or !loc? of statement is executed
Syntax: switch( variable0 e,pression )F
case constant1 : statement H !rea?H
case constant2 : statement H !rea?H
case constant3 : statement H !rea?H
:default : statement(
Example: switch(_UI\)F
case $ :case * : printf#%#)H
!rea?Hcase ; : printf#0#)H
!rea?Hcase 1 : printf#C#)H
!rea?Hcase + : printf#D#)H
!rea?Hcase 8 :case 4 :case / :case :case $ :case : printf#B#)H
!rea?Hdefault : printf("Input out of Range#)H
Interpretation:The switch expression may!e any expression which e2aluates to an intG"on#itionalG "+ar)The "ase list must consists of constants whose matches that of the switchexpression%fter the statements for a "aseG a ?eyword rea may!e used The rea ?eyword means that at that point, execution should =ump to theend of the s9it"+ statementThe s9it"+ statement is terminated !y curly !rac?et ( )This s9it"+ "onstant can !e used to specify an action to !e ta?en if the
2alue of the s9it"+ expression does not match any of the listed 2alues
Note(The "ase list cannot include 2aria!les or expressionsThe optional s9it"+ constant #e,ault)The statements following a case la!el may !e one or more C statements, soyou do not need to ma?e multiple statements into a single compoundstatement using !races
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
22
8/10/2019 Manual - Turbo C Revised
23/59
C Language Programming Page
If no case la!el 2alue matches the expression, the entire switch statement!ody is s?ipped unless it contains a default la!el If so, the statementsfollowing the default la!el are executed
T+ere are important t+ings to no9 a out s9it"+ statement($
8/10/2019 Manual - Turbo C Revised
24/59
C Language Programming Page
Fcase A> : total M f A sH !rea?Hcase -> : total M f - sH !rea?Hcase G> : total M f G sH !rea?Hcase @> : total M f @ sH !rea?Hdefault : printf("operator not 2alid#)H
ITER.TION & REPETITION CONTROL STR/CT/RESITER.TION & REPETITION CONTROL STR/CT/RES
LLOOPSOOPS%llow a set of instructions to !e repeated until a certain condition is reached
FOR LOOPFOR LOOPThe ,or loop will continue to execute as long as the condition is true Once the condition!ecomes false, program execution will resume at the statement following the ,or
Syntax: for( initiali ation e,pression( loop repetition condition( update e,pression )statement(
where: (the for statement allows many 2ariants, !ut there are three main parts)initialization e%pression is an assignment statement that is used to set theloop-control 2aria!le Loop repetition condition is a relational expression that determines when theloop will exit !y testing the loop-control 2aria!le against some 2alueUpdate expression defines how the loop-control 2aria!le will change each timethe loop is repeated
Example: for (xM $ H xSM+8Hx-M8)FLMsKrt(x)Hprintf("The sKuare root of d is f#,x,L)H
Interpretation:Birst, the initialiLation expression is executedThen, the loop repetition "on#ition is testedIf it is true, the statement is executed, and the update expression is e2aluated Theloop repetition "on#ition is re-testedIf the loop repetition "on#ition is found to !e false, the ,or loop is exited
Note & Programming st$le(These three ma=or sections must !e separated !y semicolonsWou may place all three expressions in the ,or heading in a single line, specially if all
three expressions are 2ery shortThe !ody of a ,or loop may !e a compound statement
Sample Program No) A
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
24
8/10/2019 Manual - Turbo C Revised
25/59
C Language Programming Page
@G .rogram on Bactorial G@Jinclude stdio hEmain()F int f,x,ansH clrscr()H printf(Z7nter a num!er : Z)H scanf(Z dZ, f)H ansM$H for(xMfHxEM$Hx--)
ansMxGansH printf(ZThe factorial of d is dZ,f, ans)H getche()H
Sample Program No) >
@G .rogram 7xponential G@Jinclude stdio hEmain()F int !,e,xH dou!le ansH char sagotH clrscr()H printf(Z7nter 0ase : Z)H scanf(Z dZ, !)H printf(Z7nter 7xponent: Z)H scanf(Z dZ, e)H ansM$H for(xM$Hx MeHxAA)
ansM!GansH printf(ZThe answer is fZ,ans)H getche()H
Sample Program No)
@G Displays the triangular num!er of a num!er G@Jinclude stdio hEmain()F
int n,m,t numHclrscr()Hprintf(Zwhat triangular num!er do you wantY [nZ)Hscanf(Z dZ, m)Ht numM Hfor(nM$Hn MmHnAA)
t numMt numAnHprintf(ZTriangular num!er d is d[nZ,m,t num)Hgetche()H
Sample Program No) 6
@G .rogram
8/10/2019 Manual - Turbo C Revised
26/59
C Language Programming Page
Jdefine r 1int ?, ? , x, y, LHmain()F clrscr()H ?MxM H yM H LM8H ?M$H for (H? MrH?AA)
F ? MxH xAMyH yAMLH LAM8H printf(Z d d [nZ, ?, ? )H
printf(Z d d dZ, x, y, L)H getch()H
Sample Program No)
@G.rogram
8/10/2019 Manual - Turbo C Revised
27/59
C Language Programming Page
c $ : p(Z`Z)H!rea?Hc 4 : p(ZCZ)Hc $8: p(Z5Z)Hc $+: p(ZGGZ)Hc $ : p(Z %ND Z)Hc $/: p(Z`Z)H!rea?Hdefault : p(ZIZ)Hp(Z&Z)Hp(Z&Z)Hp(Z Z)H
xAAH getch()H
8HILE L8HILE L OOPOOPcontinues to execute as long as the condition which can !e any expressions remains true
Syntax: while ( loop repetition condition )statement(
Example: while (num SM )F scanf(" d#, num)H sum AM numH
printf("the sum of all num!er is d#, sum)H
Interpretation:Birst, the loop repetition "on#ition is tested or e2aluatedIf it is true, the statement is executed and the loop repetition "on#ition is re-testedThe loop !ody, namely statement is repeated as long as the loop repetition"on#ition is trueOnce it is found to !e false, the 9+ile loop is exited and the next programstatement after the 9+ile statement is executed
Note(It is possi!le to inad2ertently specify an expression that ne2er !ecome false, andunless other means of escaping the while loop are introduced, the program isstuc? in an infinite loop Care should !e ta?en to a2oid this difficulty
Sample Program No) A
@G .rogram
8/10/2019 Manual - Turbo C Revised
28/59
C Language Programming Page
Sample Program No) >
@G This program finds the 'reatest Common Di2isor of two nonnegati2e integer 2alues G@
Jinclude stdio hEmain()
F int num$, num , tempH clrscr()H printf(Z.lease type in two nonnegati2e integers : [nZ)H
scanf(Z d dZ, num$, num )H while (num SM )
F temp M num$ num H num$ M num H num M tempH
printf(ZTheir 'reatest Common Di2isor is d [nZ,num$)H getch()H
Sample Program No)
@G .rogram to re2erse the digits of a num!er G@Jinclude stdio hEmain()F int num, rightdigitH clrscr()H printf(Z7nter a num!er [nZ)H scanf(Z dZ, num)H while (num SM )
F rightdigit M num $ H printf(Z dZ, rightdigit)H num M num @ $ H
printf(Z[nZ)H getch()H
DO 8HILE LDO 8HILE L OOPOOP
Syntax: dostatement(while ( loop repetition condition )H
Example: do Fscanf(" d#, num)Hsum AM numH
while (num E $ )Hprintf("the sum is d#, sum)H Interpretation:
The program statement is executed firstNext, the loop repetition condition inside the parenthesis is e2aluatedIf the result of the loop repetition condition is TRU7, then the loop continues and
program statements is once again executed%s long as e2aluation of expression continues to !e TRU7, program statement will
!e repetiti2ely executed Qhen e2aluation of expression pro2es B%&
8/10/2019 Manual - Turbo C Revised
29/59
C Language Programming Page
terminated and next statement in the program will !e executed in the normal seKuentialmanner
Sample Program No) A
@G .rogram to re2erse the digits of a num!er G@Jinclude stdio hEmain()F int num, rightdigitH clrscr()H printf(Z7nter a num!er [nZ)H scanf(Z dZ, num)H do
F rightdigit M num $ H printf(Z dZ, rightdigit)H num M num @ $ H
while (num SM )H printf(Z[nZ)H getch()H
Sample Program No) >
@G Bi!onacci
8/10/2019 Manual - Turbo C Revised
30/59
C Language Programming Page
stnoMgetch()H gotoxy($;4Actr,4)H printf(Z cZ,stno)H
while(S((stnoEM^ ^) (stno M^*^)))H ctrMctrA$H while (ctr M1)Hgetche()H
BB RE.7RE.7 .ND.ND CCONTIN/EONTIN/E SS T.TEMENTT.TEMENT
rea StatementThis statement is encountered inside the loop, the loop is immediately terminated andprogram control resumes at the next statement following the loop
Two Uses of Break Statement
$ To terminate a "ase in the s9it"+ statementTo force immediate termination of a loop, !ypassing the normal loop conditionaltest
Sample De"laration(
9 hile($) Fscanf(" lf#, x)Hif (x )
!rea?Hprintf(" f[n#,sKrt(x))H
E%ample(
Jinclude stdio hEmain()F int tH clrscr()H for(tM H t $ H tAA)
F printf(Z d Z,t)H if (tMM$ ) !rea?H
getch()H
"ontinue Statement
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
30
0 1 2 3 4 5 6 7 8 9 10
8/10/2019 Manual - Turbo C Revised
31/59
8/10/2019 Manual - Turbo C Revised
32/59
C Language Programming Page
E%ample(
0 oid main( ) F int counter M H
try again:if (counter $ ) goto stopHprintf(" d[n#, counter)HAAcounterHgoto try againH
stop:
FF /NCTIONS/NCTIONS
FF /NCTIONS/NCTIONS
is a su!routine that contains one or more statements and performs one or more tas?s
is a section of a program which perform a specific tas? The tas? assigned to a function isperformed whene2er C encounters the function nameIs actually a su!program that is, a function perform a tas? within a program and is
written in a form similar to C main program
Advantages of Using a !nction:A) fits naturally in top-down approach>) can !e di2ided for many programmers as su!tas?s
) can easily !e tested, each function can !e tested indi2idually
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
32
8/10/2019 Manual - Turbo C Revised
33/59
C Language Programming Page
"#y !se f!nction s!$programs%
Top'#o9n #esign ( easier an# simpler)A it can !e used to return a 2alue
Sample Program No) A
@G .rogram that uses a function without a parameter G@Jinclude stdio hE2oid star(2oid)F printf(ZGGGGGZ)H
main()F clrscr()H star()H printf(ZCZ)H star()H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
33
GGGGGCGGGGG
8/10/2019 Manual - Turbo C Revised
34/59
C Language Programming Page
getch()H
Sample Program No) >
@G .rogram that increments a num!er !y one G@Jinclude stdio hEint f(int x)F return(xA$)H
main()F clrscr()H printf(Z dZ,f( ))H getche()H
Sample Program No)
@G Display the cu!e of a num!er G@Jinclude stdio hEint cu!e(int x)F int ansH ans M x G x G xH return(ans)H
main()F int yH clrscr()H printf(Z7nter a num!er : Z)H scanf(Z dZ, y)H printf(ZThe cu!e of d is dZ,y, cu!e(y))H getche()H
Sample Program No) 6 @G .rogram that increments a num!er !y one using function with parameter G@Jinclude Zstdio hZint inc(int x)F int ansH xAAH ansMxH return(ans)H
main()F int yM8H clrscr()H printf(ZThe 2alue of y now is dZ, inc(y))H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
34
7nter a num!er : /The cu!e of / is 1
The 2alue of y now is +
8/10/2019 Manual - Turbo C Revised
35/59
C Language Programming Page
getche()H
-lo al 0aria les?nown throughout the entire program and may !e used !y any piece of code It is declaredoutside any function
Lo"al 0aria les2aria!les that are declared inside a function It can !e referenced only !y a statements thatare inside the !loc? in which the 2aria!les are declared
Formal 0aria les2aria!les that accept the 2alues of the arguments of a function
PP .SSIN-.SSIN- DD .T..T. ININ FF /NCTIONS/NCTIONS
T9o 8a$s o, Passing .rgumentsA) Call $ 0alue
this method copies the 2alue of an argument into the formal parameter of the su!routinechanges made to the parameters of the su!routine ha2e no effect on the 2aria!les used tocall it
>) Call $ re,eren"ethe address of an argument is copied into the parameter Inside the su!routine, the addressis used to access the actual argument used in the callchanges made to the parameter affect the 2aria!le used to call the routine
Sample Program No)
@G .rogram that increments a num!er !y / G@Jinclude Zstdio hZint inc(int x, int y)
F int ansH xAMyH ansMxH return(ans)H
main()F int yM8H clrscr()H printf(ZThe 2alue of y now is dZ, inc(y,/))H getche()H
Sample Program No) K
@G.rogram
8/10/2019 Manual - Turbo C Revised
36/59
C Language Programming Page
clrscr()H tric?(w,x,y,L)H tric?(x,y,w,L)H tric?(y,w,L,x)H tric?(x,x,w,L)H tric?(x,y,y,w)H tric?(x,L,L,w)H tric?(x,y,w,L)H getch()H
Sample Program No)
@G.rogram
8/10/2019 Manual - Turbo C Revised
37/59
C Language Programming Page
F int wM$ , xM$ , yM$4, LM$+H clrscr()H tric?(w, x, y, L)H tric?(x, y, w, L)H tric?(y, w, L, x)H tric?(x, x, w, L)H tric?(x, y, y, w)H tric?(x, L, L, w)H tric?(x, y, w, L)H printf(Z d d d dZ, w,x,y,L)H getch()H
Sample Program No)
@G.rogram
8/10/2019 Manual - Turbo C Revised
38/59
C Language Programming Page
main()F int xM8, yM$ , LM$8H clrscr()H swap( L, y)H printf(Z d d d[nZ, x,y,L)H swap( y, x)H printf(Z d d d[nZ, x,y,L)H swap( L, x)H printf(Z d d d[nZ, x,y,L)H swap( x, y)H printf(Z d d d[nZ, x,y,L)H swap( y, L)H printf(Z d d d[nZ, x,y,L)H getch()H
Sample Program No) AA
@G.rogram
@G.rogram
8/10/2019 Manual - Turbo C Revised
39/59
C Language Programming Page
GaMdH GcM!AdH
main()F int x, y, LH clrscr()H xMyMLM H !ali?( x,8, y)H printf(Z d d d[nZ,x,y,L)H !ali?( L,y, x)H printf(Z d d d[nZ,x,y,L)H getch()H
SS TRIN-STRIN-S
.. RR.YSRR.YS OFOF CH.R CH.R .ND.ND SS TRIN-STRIN-S
% "+ara"ter string is a seKuence of characters which is to !e considered as a single data item Thecharacters of a string are displayed enclosed within dou!le Kuotes % string may include letters, digits,sym!ols and control characters
8/10/2019 Manual - Turbo C Revised
40/59
C Language Programming Page
+,amples "Input 7rror# "$ /48+# " ;* **#
SS TRIN-TRIN- FF /NCTIONS/NCTIONS
header files : "string h#
Cop$
$ str"p$3 copy the contents of str to str$
synta, str"p$3strAGstr>
e,ample char str$ ; , str ; H
strcpy(str$,#hello#)Hstrcpy(str ,#there#)H
strcpy(str$,str )Hstrcpystr ,str$)Hprintf(" s#, str )H
outputthere
>)> strn"p$3 used to copy to "ount characters from the string sour"e;str> into thestring target;strAG target;srtA and sour"e;str> o2erlap, the !eha2ior of this isundefinedH if string pointed !y sour"e;str> has fewer "ount characters, nulls areappended
synta, strn"p$3target;strAGsour"e;str>G"ount =
e,ample strcpy(str$,#Vello)Hstrncpy(str$,str$,4)H
output:Vell
) str%,rm3 used to copy to "ount characters from the string sour"e;str> into thestring target;strA) It returns the length of the string sour"e;str>) This function isthe same with the strn"p$)
synta, strn"p$3target;strAGsour"e;str>G"ount =
Con"atenate
A) str"at3 concatenates the 2alue of str to str$returns str$contents of str is unchanged
synta, str"at3strAGstr> =
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
40
8/10/2019 Manual - Turbo C Revised
41/59
C Language Programming Page
e,amplechar str$ $8 , str ; H
strcpy(str$,#Vello#)Hstrcpy(str ,#Bol?sS#)Hstrcat(str$,#there#)Hstrcat(str$,str )Hprintf(" s s#, str ,str$)H
outputBol?sS VellothereBol?s
>) strn"at3 concatenates no more than "ount characters of str> to strA and assigns thisto strA= str> is untouched !y the operation
synta, str"at3strAGstr>G"ount =
Compares
A) str"mp3 compares the two strings until uneKual characters are found or until the endof a strings is reached It returns an integer to indicate the results of the compare!ased on the following:
*alue Meaning
str$ is less than str
str$ is eKual to str
E str$ is greater than str
synta, : str"mp3strAGstr> =e,ample
char s $ H
printf("7nter password: ")H
gets(s)Hif (((strcmp(s,#pass#)) MM ))printf("Qelcome#)H
elseprintf("IntruderSSS#)H
>) stri"mp3 & str"mpi3 compares two strings while ignoring casesH str"mpi3 is amacro that translates to a str"imp3 call
synta, str"mpi3strAGstr> = & st"ri"mp3strAG str> =
*alue Meaning
str$ is less than str
str$ is eKual to strE str$ is greater than str
) stru"mp3 & strn"mp3 & strn"mpi3 compares no more than count characters for thetwo stringsH strn"mpi3 and strni"mp3 ignore cases
synta, stru"mp3strAGstr>G"ount = & st"rn"mp3strAG str>G"ount = st"rn"mpi3strAGstr>G"ount =
Case
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
41
8/10/2019 Manual - Turbo C Revised
42/59
C Language Programming Page
A) strl9r3 con2erts the string pointed to !y str in lowercase
synta, strl9r3str =
e,amplechar s H
strcpy(s,#% T77>)H
output:77777
>) strnset3 sets the first "ount character in the str to the 2alue of "+r)synta, strnset3strG?"+r?G"ount
e,ample strcpy(str$,#V7&&O#)Hstrnset(str$,>%>,/)H
output:%%%&O
Ot+ersA) strlen3 returns the length of the string
synta, strlen(str)H
e,ample
char s Hint xHgets(s)HxMstrlen(s)Hprintf("The length is d#, x)H
>) strre03 re2erses all the characters in the string pointed to !y str
synta, strre03str =
e,ample
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
42
8/10/2019 Manual - Turbo C Revised
43/59
C Language Programming Page
char s $ H
gets(s)Hstrre2(s)Hprintf(" s#, s)H
CCH.R.CTER H.R.CTER FF /NCTIONS/NCTIONS
header files : "ctype h#
A) isalnum3 a function that returns non-Lero if its argument is either a letter of the alpha!etor a digit
synta, int isalnum3int "+ar =
>) isalp+a3 a function that returns non-Lero if char is a letter of the alpha!et otherwise Lerois returned
synta, int isalp+a3int "+ar =
) is#igit3 a function that return non-Lero if char is a digit, that is -*H otherwise Lero isreturned
synta, int is#igit3int "+ar =
6) islo9er3 a function that returns non-Lero if char is a lowercase letter (a-L)H otherwise Lerois returned
synta, int islo9er3int "+ar =
) ispun"t3 a function that returns non-Lero if char is a punctuation character, excluding thespaceH otherwise Lero is returned
synta, int ispun"t3int "+ar =
K) isspa"e3 a function that returns non-Lero if char is one of the following: a space, ta!,2ertical ta!, form feed, carriage return, newlineH otherwise Lero is returned
synta, int isspa"e3int "+ar =
) tolo9er3 returns the lowercase eKui2alent of the character pointed to !y char, if char is inlowercase it is unchanged
synta, int tolo9er3int "+ar =
e,amplechar ansHscanf(" c#, ans)Hif (tolower(ans)MM y>)
printf("!ye#)Helse
printf("againY#)H
Q) toupper3 returns the uppercase eKui2alent of the character pointed to !y char, if char is inuppercase it is unchanged
synta, touppper3"+ar =
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
43
8/10/2019 Manual - Turbo C Revised
44/59
C Language Programming Page
MM .THEM.TIC.L.THEM.TIC.L FF /NCTIONS/NCTIONS
header file : "math h#
A) a s3 a function that returns the a!solute 2alue of integer num!er synta, int a s3int num =
>) "eil3 a function smallest integer represented as dou!le not less than num synta, #ou le "eil3#ou le num =
) ,a s3 a function that return the a!solute 2alue of num synta, #ou le ,a s3#ou le num =
6) ,loor3 a function that returns the largest integer, represented as dou!le not greater than
num synta, #ou le ,loor3#ou le num =
) ,mo#3 a function that returns the remainder of x @ y synta, #ou le ,mo#3#ou le %G #ou le $ =
K) po93 a function that returns !ased to the exp power (!ase exp ) synta, #ou le po93#ou le aseG #ou le e%p =
) po9A 3 returns $ raised to the power n O2erflow and undeflow are the only possi!leerrors
synta, #ou le po9A 3int n =
Q) s rt3 returns the sKuare root of num If called with a negati2e argument domain error willoccur
synta, #ou le s rt3#ou le num =
CCON*ENTION.LON*ENTION.L FF /NCTIONS/NCTIONS
header file : "math h#
A) ato,3 a function that con2erts the string pointed to !e str into a dou!le 2alue synta, #ou le ato,3"onst "+ar 1str =
>) atoi3 a function that con2erts the string pointed to !y str into an int 2alue The string mustcontain 2alid into 2alue, if not Lero is returned
synta, int atoi3"onst "+ar 1str =
) atol3 a function that that con2erts the string pointed to !y str into a long int 2alue Thestring must contain 2alid long int 2alue
synta, int atol3 "onst "+ar 1str =
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
44
8/10/2019 Manual - Turbo C Revised
45/59
C Language Programming Page
6) itoa3 a function that con2erts the integer num!er into string eKui2alent and places theresult in the string pointed to !e str The !ase of the output string is determined !y radixwhich can !e in the range of -/+ this function returns a pointed to str There is no errorreturn 2alue 0e sure to call itoa() with string of sufficient length to hold the con2ertedresult The maximum length needed is $1 !ytes
synta, "+ar 1itoa3int numG "+ar 1strG int ra#i% =
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
45
8/10/2019 Manual - Turbo C Revised
46/59
C Language Programming Page
.. RR.YSRR.YS
.. RR.YRR.Y
collection of 2aria!les of the same type that are referenced !y a common name %specific element in an array is accessed !y an index& The lowest address corresponds tothe first element and the highest address corresponds to the last element %ll arraysha2e as the index of their first elementIs a fixed-siLe, seKuenced collection of elements of the same data type
Sample Representation(
%ssuming we ha2e a pro!lem that reKuires / integers to !e processed Qe need to read,processed and print them Qe must also ?eep these / integers in memory for the duration of theprogram Qe can declare and define / 2aria!les, each with a different name, as shown in theillustration !elow
E%planation(
This will in2ol2ed thirty 2aria!les !ut ha2ing / different names creates anotherpro!lem Vow can we read / integers from the ?ey!oard and store themY To read / integersfrom the ?ey!oard, we need thirty references, each to one 2aria!le %nother thing, once weha2e them in memory, how can we print themY To print them, we need another thirtyreferences
0ut in this situation, / integers may !e accepta!le !ut it definitely not accepta!lefor 8 or /, or / , integers To process such large amount of data, we need a powerfuldata structure, such as arra$)
// SIN-SIN- .. RR.YSRR.YS ININ CC
The ad2antages of the array would !e limited if we didn>t also ha2e programming constructs thatwould allow us to process the data more con2eniently Bortunately, there is a powerful set of programming constructs using loops that ma?es array processing easy
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
46
Num0
Num1
Num2
Num29
8/10/2019 Manual - Turbo C Revised
47/59
C Language Programming Page
Qe will first show how to declare and define arrays %fterwards, we will loo? at se2eral typicalapplications using arrays including reading 2alues into arrays, accessing and exchanging elements inarrays and printing arraysHo9 to #e"lare an# #e,ine arra$s
%n array must !e declared and defined first !efore it can !e used Through declaring and definingarrays will tell the compiler the name of the array, the type of each element, and the siLe or num!er of elements in the array The siLe of the array is a constant and must ha2e a 2alue at compilation time
Syntax:element type array name array siLe H
where:element type type of each elementsarray name name of the arrayarray siLe num!er of elements the array will hold
Example 'eclaration:int scores * H
$ / 4 8 + 1 ;
scores
char name $ H
$ / 4 8 + 1 ; *
name
float gwa 4 H
$ /1 /; /*
gwa
Sample Program(
Jinclude stdio hEJinclude conio hEint score / , x,sumM H
2oid mainF clrscr()H
printf(Z.lease enter / scores:[n Z)Hfor (xM Hx / HxAA)F
scanf(Z dZ, core x H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
47
type ofeach
element
name ofthe array
number ofelements
arraydeclaration
8/10/2019 Manual - Turbo C Revised
48/59
C Language Programming Page
sum M sum A scorex x H
getch()H
.""essing Elements in .rra$s
C uses an index (or su!script) to access indi2idual elements in an array The index must !e anintegral 2alue or an expression that e2aluates to an integral 2alue The simplest form for accessing anelement is a numeric constant
Syntax:array name index
Example:'i2en an array score / , we could access the first element as score
Storing *alues in .rra$s
Declaration and definition only reser2e for the elements in the array No 2alues will !e stored If wewant to store in the array, we must either initialiLe the elements, read 2alues from the ?ey!oard, orassign 2alues to each indi2idual element
Initiali:ation
InitialiLation of all elements in an array can !e done at the time of declaration anddefinition, =ust as with declaration of 2aria!les Bor each element in the array, pro2ide a 2alueand these should !e enclosed in curly !races, F %nd if there are more than one, separated !ycommas It is a compile error to specify more 2alues than there are elements in the array
Examples of array Initialization:
int num!ers 8 M F ,8,$ , ,44 H
8 $ 44
int num!ers M F ,8,$ , ,44 H
8 $ 44
int num!ers 8 H M F ,8 H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
8
48
this is =ust a simple array declaration of fi2eintegers It is typically the way array initialiLationis coded
when the array is completely initialiLed, it is notnecessary to specify the siLe of the array
if the num!er of 2alues pro2ided is less thanthe num!er of elements in the array, theunassigned elements are filled with Leros Qecan use this rule to easily initialiLe an array toall Leros !y supplying =ust the first Lero 2alueof the first element
the rest arefilled with
0s
8/10/2019 Manual - Turbo C Revised
49/59
8/10/2019 Manual - Turbo C Revised
50/59
C Language Programming Page
sum M x A x $ H
sum AM x Hx / AM $ Hx M x A x $ H
8/10/2019 Manual - Turbo C Revised
51/59
C Language Programming Page
Sample Program No)
@G %rrange the num!er in ascending order G@Jinclude stdio hEmain()F int num 8 , ctr$, ctr , tempH clrscr()H printf(Z7nter 8 num!ers :[nZ)H for (ctr$M Hctr$ M4Hctr$AA)
scanf(Z dZ, num ctr$ )H for (ctr$M Hctr$ M/Hctr$AA) for (ctr Mctr$A$Hctr M4Hctr AA) if (num ctr$ E num ctr )
F temp M num ctr$ H num ctr$ M num ctr H num ctr M tempH
printf(ZThe num!ers in ascending order [nZ)H for (ctr$M Hctr$ M4Hctr$AA) printf(Z d Z,num ctr$ )H getch()H
Sample Program No) 6
@G Display the num!er of times a num!er appeared G@Jinclude stdio hEmain()F int num 8 , ctr, x, yH clrscr()H printf(Z7nter 8 num!ers :[nZ)H for (ctrM Hctr M4HctrAA)
scanf(Z dZ, num ctr )H printf(ZThe num!ers are : [nZ)H for (xM Hx M4HxAA) F ctrM$H if ((xMM4) (num x EM ))
printf(Z d appears d time(s)[nZ, num x , ctr)H else if (num x EM )
F for (yMxA$Hy M4HyAA)
if (num x MM num y ) F num y M-$H ctrAM$H
printf(Z d appears d time(s)[nZ, num x , ctr)H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
51
7nter 8 num!ers :$ 4 / 8 The num!ers in ascendingorder$ / 4 8
7nter 8 num!ers :$ / / $The num!ers are :$ appears time(s)/ appears time(s)
appears $ time(s)
8/10/2019 Manual - Turbo C Revised
52/59
C Language Programming Page
getch()H
MM /LTIDIMENSION.L/LTIDIMENSION.L .. RR.YRR.Y 3T3T 8O8O DD IMENSION.LIMENSION.L .. RR.YRR.Y
Syntax:type arr name dim $dim H
Sample Program No) A
@G .rogram
@G 3ultiplication Ta!le using %RR%W G@Jinclude stdio hEint num 8 8 ,ctr, ctr , x, yHmain()F clrscr()H xMyM H for (ctrM$Hctr M8HctrAA)
F for (ctr M$Hctr M8Hctr AA) F num x y MctrGctr H yAAH xAAH yM H
for (ctrM Hctr M4HctrAA)
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
52
columnrow
;*$;*$;*$
$ /484+;$
/+*$ $84;$ $+8$ $8 8
8/10/2019 Manual - Turbo C Revised
53/59
C Language Programming Page
F for (ctr M Hctr M4Hctr AA) printf(Z dZ,num ctr ctr )H printf(Z[nZ)H
getch()H
Sample Program No)
@G
8/10/2019 Manual - Turbo C Revised
54/59
C Language Programming Page
STRE.MSTRE.M .ND.ND FILESFILES
STRE.MSTRE.Ma series of !ytes associated with a file
T$pes o, Streams(
1. Te%t Stream 9 is a seKuence of characters that does not ha2e a one-to-one relationship!etween the characters that are written or read and those on the external de2ice
2. Binar$ Stream is a seKuence of !ytes that ha2e a one-to-one correspondence to those foundon the external de2ice The num!er of !ytes written or read will !e the same as the num!erfound on the external de2ice
FILEFILEa collection of data stored in the memoryBiles reside in the secondary memory
Text file0inary file
Te%t File 9 contains characters which are encoded in %
8/10/2019 Manual - Turbo C Revised
55/59
C Language Programming Page
Operations in a File
A) Open a file>) Close a file
) Read the contents of a file6) Qrite to a file
File Han#ling Con"epts
A) 7sta!lish a stream !etweern the file and the program>) .erform the needed read @ write operation to the file
) Close the file to detach the program from the file
T+e .NSIC File S$stem
The %N
8/10/2019 Manual - Turbo C Revised
56/59
C Language Programming Page
T+e Legal *alues ,or OpenMo#e
OpenMo#e
Meaning OpenMo#e
Meaning
"r# Open a text file for reading "rA!# Open a !inary file for read @ write "w# Create a text file for writing "wA!# Create a !inary file for read @ write
"a# %ppend to a text file "aA!# Open or create a !inary file for read @ write "r!# Open a !inary file for reading "rt# Open a text file for reading "w!# Create a !inary file for reading "wt# Create a text file for writing "a!# %ppend to !inary file "at# %ppend to a text file "rA# Open a text file for read@write "rAt# Open a text file for read @ write "wA# Create a text file for read@write "wAt# Create a text file for read @ write "aA# Open or create a text file for read @
write "aAt# Open or create a text file for read @ write
If you wish to open a file for writing with the name TI._C T6T, write
fp M fopen ("TI._C T6T#,#w#)H Note(
where fp is a 2aria!le of type FILE TIP C)TE@T is not case sensiti2e and can !ewritten in uppercase or lowercase letters
Vowe2er, it is !est written in this manner
if ((fp Mfopen ("TI._C T6T#,#w#)) MM NU&&) F puts(" Cannot open file#)H exit($)H
This method detects any error in opening file, such as a write-protect or full dis?, !efore attemptingto write it NU&& is a macro defined in stdio h
"riting 'ata to Text iles
,print,3 writes formatted output to a streamthe same as the printf() command !ut instead of writing the output to the screen, the outputis written to a file
Syntax:fprintf(InternalBileName, BormatControl, fp)H
fputc( e>, fp)H
Prepare# $( Ms) Elsa *) Isip Te"+nologi"al Institute o, t+e P+ilippines
56
Qrites the text "TI._C# to the specified!y the file fp
Output(TI._C
Qrites "Vello# to the specified !y thefile fp
Output(Vello
8/10/2019 Manual - Turbo C Revised
57/59
C Language Programming Page
fputc( l>, fp)H fputc( l>, fp)H fputc( o>, fp)H
,puts3 writes a string to a stream
Syntax:fputs(Hchar 2alue+ M " C &anguage .rogramming#H
Statement Outputfprintf(outdata, " d[n, 2alue$)H $fprintf(outdata, " d d[n, 2alue$, 2alue )H $
fprintf(outdata, " f[n, 2alue/)H $8 18fprintf(outdata, " c c[n, 2alue4, 2alue8)H xyfputc(2alue4, outdata)Hfputc(2alue8, outdata)Hfputc("[n#, outdata)H
xy
fputs(2alue+, outdata)Hfputs("[n#, outdata)H
C &anguage .rogramming
fprintf(outdata,# d d f c c s[n#,2alue$, 2alu , 2alue/, 2alue4, 2alue8,2alue+)H
$ $8 18 x y C &anguage .rogramming
)eading 'ata from Text iles
,s"an,3 scans and formats input from a streamscans a series of input fields, one character at a time, reading from a stream Then each field
is formatted according to a format specification passed to fscanf()
Syntax:fscanf(InternalBileName, BormatControl
8/10/2019 Manual - Turbo C Revised
58/59
8/10/2019 Manual - Turbo C Revised
59/59
C Language Programming Page
In the example, the first program will as? the user to input a string The string will then !e sa2ed inthe file TI._C T6T the second program will retrie2e the contents of the file and display them on thescreen Note that the open mode used in the first program is "w# This means that a new file will !ecreated e2ery time the first program is executed The pre2ious contents of the file are replaced !y thenew string entered
Wou can use the open mode "a# to ena!le the file to append entries so that pre2ious contents are notlost and that new entries are added to the file
,eo,3 chec?s for end-of-file status during input
Syntax:feof(InternalBileName)H
,"lose3 to close a file or detach a file from the program
Syntax:fclose(InternalBileName)H
59
7xample:
Te%t File Sa0ing /sing Stru"tures
Jinclude stdio hEJinclude ctype hE
struct facts F char name 8 H char addr / H char !day H char age H char telno $ H
H
main()F BI&7 GpH struct facts x $ H int aM , !H char ans, ans H
clrscr()H gotoxy(//,/)H printf("B%CT< %0OUT 37#)H
gotoxy($8 8)H printf("N%37:#)H
gotoxy( , )H printf("W>)F if((fp M fopen ("B%CT< 0IO#,#a#)) MM NU&&)
F gotoxy( 1, )H printf("Cannot create file$#)H exit( )H
fprintf(p, "N%37 : s[n,x a name)H fprintf(p, "%DDR7