8/11/2019 TurboC Notes
1/102
Computer Programming 1Turbo C
8/11/2019 TurboC Notes
2/102
What is computer Programming?
Computer programming is creating asequence of instructions to enablethe computer to do something.
8/11/2019 TurboC Notes
3/102
What is a programming language?
A programming languageis anartificial language that can be usedto control the behavior of amachine, particularly a computer.
8/11/2019 TurboC Notes
4/102
Programming Language Translation
Source Program -- program written ina high-level programming language.
Object Program -- the source
program after it has been translatedinto machine language.
Translator Program -- the programthat translates the source program
into the object program. Can beeither a compiler or an interpreter.
8/11/2019 TurboC Notes
5/102
Compilers vs. Interpreters
Compiler -- spends some time evaluating theentire program and then translates all theprogramming statements of a program into amachine language program, which is then
executed at once. Interpreter -- translates interactively each
programming statement into an immediatelyusable machine language instruction. Although aninterpreter slows down the execution speed of aprogram somewhat, it does not require extra stepsto compile and link like a compiler.
In a production environment where throughput ismore critical, a compiled language is preferred.
Any high-level language can either be interpretedor compiled.
8/11/2019 TurboC Notes
6/102
8/11/2019 TurboC Notes
7/102
Categories of Programming
Systems programminginvolves writingprograms that enable a computer to carry outits basic internal functions as well as some
other specialized functions. Examples ofsystems programs include operating systems,device drivers, and utility programs.
Applications programmingrefers to theprocess of developing programs to be used for
specific applications, such as a businessapplication (e.g., computing benefits to bepaid to different employee classifications) oran academic application (e.g., determiningwho qualifies for which scholarship, based onspecified eligibility criteria).
8/11/2019 TurboC Notes
8/102
Stages in the Applications
Programming Process
1. Problem statement: The programmingprocess begins with a clear, writtenstatement of the problem to be solved by the
computer.2. Algorithm development: Once the problem
has been clearly stated and all therequirements have been understood, thenext step is to develop the program logic
necessary for accomplishing the task.*An algorithmis defined as a logical sequence
of steps that must be performed in order toaccomplish a given task.
Sample Tool:Flowchart
8/11/2019 TurboC Notes
9/102
Stages in the Applications
Programming Process
1. Program coding: When the programmer issatisfied with the efficacy of the logicdeveloped in the preceding step, it is time
to convert that logic (in either flowchart orpseudocode form) to the specific syntax ofthe programming language that will beused.
2. Program testing: The coded program is nextchecked for errors.
3. Program documentation: The programmingprocess is complete when the program has
been fully documented.
8/11/2019 TurboC Notes
10/102
Computer Programming 1
Five steps to define a programming problem:
1.Restate the problem.
2.Analyze the problem.
3. Identify the input.
4. Identify the process.
5. Identify the output.
8/11/2019 TurboC Notes
11/102
Common Programming Errors
1.Syntax Errors
- occur when your code violates one or more
grammar rules of C and is detected by the
compiler as it attempts to translate your
program.
Note: If a statement has a syntax error, it cannotbe translated and your program will not be
executed.
8/11/2019 TurboC Notes
12/102
Common Programming Errors
2.Run-time Errors
- are detected errors and displayed by thecompiler during the execution of the program.
- occurs when the program directs thecomputer to perform illegal operation, such asdividing a number by zero.
- an attempt to perform an invalid operation,
detected during program execution.Note: When a run-time error occurs, the
computer will stop executing your programand will display a diagnostic message thatindicates the line where the error wasdetected.
8/11/2019 TurboC Notes
13/102
Common Programming Errors
3. Logic Errors
- occur when a program follows a
faulty algorithm.- do not cause a run-time error anddo not display error messages, so arevery difficult to detect.
Note: The only sign of a logic error maybe incorrect program output.
8/11/2019 TurboC Notes
14/102
Introduction to Flowcharting
8/11/2019 TurboC Notes
15/102
Flowcharting
Flowchart - a graphical representationof the solution in computing aproblem in a logical and step bystep process.
- consists of geometrical symbolthat are interconnected to provide a
pictorial representation of dataprocessing.
8/11/2019 TurboC Notes
16/102
Algorithms and Flowcharting
Flowchart Symbols:
1. Terminal Symbol- used to designate the beginningand end of a program.
1. Input Symbol- represents an instruction to aninput device
8/11/2019 TurboC Notes
17/102
Algorithms and Flowcharting
Flowchart Symbols:
3. Processing Symbol
- used to represent a group of programinstructions that perform a processingfunction or activity such as
mathematical operations or logicalcomparisons.
4. Output Symbol
- represents an instruction to an output
device
8/11/2019 TurboC Notes
18/102
Algorithms and Flowcharting
Flowchart Symbols:
5. Decision Symbol
- denotes a point in the program wheremore than one path can be taken or usedto designate a decision making process.
6. Flow lines and Arrowheads
- used to show reading order or sequencein which flowchart symbols are to belead.
- show the direction of processing of dataflows.
8/11/2019 TurboC Notes
19/102
Algorithms and Flowcharting
Flowchart Symbols:
7. On-page Connector- non processing symbol
- used to connect one part of the
flowchart to another withoutdrawing flow lines.
AA
Denotes an
entry
Denotes an
exit
8/11/2019 TurboC Notes
20/102
Algorithms and Flowcharting
Flowchart Symbols:
8. Off-page connector- designate an exit or entry to pagewhen a flowchart requires morethan one page.
9. Preparation Symbol
- commonly used for initialization ofcounters or defining constants.
8/11/2019 TurboC Notes
21/102
Algorithms and Flowcharting
Flowchart Symbols:
10. Predetermined Symbol- used as a subroutine symbol
- inner procedure needs to be
repeated several times.
8/11/2019 TurboC Notes
22/102
Introduction to the C language
8/11/2019 TurboC Notes
23/102
Turbo C History
Dennis Ritchie developed Turbo C atAT&T Bell Laboratories.
Turbo C was first developed forsystem programming.
8/11/2019 TurboC Notes
24/102
C Language Elements
The C Preprocessor- a program thatis executed before the source code is
compiled.DIRECTIVES how C preprocessorcommands are called, and begin with apound / hash symbol (#). No white
space should appear before the #, anda semi colon is NOT required at theend.
8/11/2019 TurboC Notes
25/102
C Language Elements
Two Common Directives:
1. #include gives program access to alibrary.
- causes the preprocessor to insertdefinitions from a standard header fileinto the program before compilation.
- tells the preprocessor that some
names used in the program are found inthe standard header file.
8/11/2019 TurboC Notes
26/102
C Language Elements
Two Common Directives:
2. #define allows you to make text
substitutions before compiling theprogram.
- by convention, all identifiers thatare to be changed by the
preprocessor are written in capitalletters.
8/11/2019 TurboC Notes
27/102
C Language Elements
#include
#define MIN 0/* #defines */
#define MAX 10
#define TRUE 1
#define FALSE 0
int main() {/* beginning of program */
int a;
int okay=FALSE;/*the compiler sees this as int okay=0;*/
while(!okay) {
printf("Input an integer between %d and %d: ", MIN,MAX); scanf("%d", &a);
if(a>MAX) {
printf("\nToo large.\n"); }
else if(a
8/11/2019 TurboC Notes
28/102
C Language Elements
Libraries C implementations thatcontain collections of usefulfunctions and symbols that may be
accessed by a program.
Note: A C system may expand the number ofoperation available by supplying additional
libraries. Each library has a standardheader file whose name ends with thesymbol .h.
8/11/2019 TurboC Notes
29/102
C Language Elements
Commenting Your CodeYou can add comments to your code by enclosing
your remarks within /* and */. However, nestedcomments aren't allowed.
A few properties of comments:They can be used to inform the person viewing thecode what the code does. This is helpful when yourevisit the code at a later date.
The compiler ignores all the comments. Hence,commenting does not affect the efficiency of the
program.You can use /* and */ to comment out sections of
code when it comes to finding errors, instead ofdeletion.
8/11/2019 TurboC Notes
30/102
C Language Elements
Here are examples of commented code:
/* Comments spanning several */
/* lines can be commented*/
/* out like this!*/
/* But this is a simpler way of doing it! */
// These are C++
// style comments
// and should NOT// be used with C!!
/* /* NESTED COMMENTS ARE ILLEGAL!! */ */
8/11/2019 TurboC Notes
31/102
C Language Elements
Function Main
Every C program has a main function. This iswhere program execution begins.
Body- the remaining line of the program inthe body.
Braces {} enclose the body of the function.
- indicates the beginning and end of thefunction main.
8/11/2019 TurboC Notes
32/102
C Language Elements
Two parts of the function body:
1. Declarations the part of the programthat tells the compiler the names of
memory cells in a program needed in thefunction, commonly data requirementsidentified during problem analysis.
2. Executable statements derived
statements from the algorithm intomachine language and later executed.
8/11/2019 TurboC Notes
33/102
C Language Elements
Your First Program
#include
int main()
{clrscr();
printf("Hello World!\n");
return 0;
getch();}
8/11/2019 TurboC Notes
34/102
C Language Elements
Reserved Words
In C, a reserved word is defined as
the word that has special meaning inC and cannot be used for otherpurposes.
Examples: int, void, double, return
8/11/2019 TurboC Notes
35/102
C Language Elements
Punctuation Marks/* */ -(slash asterisk) used to enclose a single line
remarks. -(double quotation) used to display series of
characters, and initializing string constant.; -(semicolon) statement separator, -(comma) used to separate one variable to
another= -(equal sign) used as assignment operator
-(single quotation) used for initializing character
expression& -(ampersand) used as address operator{} -(open/close braces) denotes the beginning and
end of the program.
8/11/2019 TurboC Notes
36/102
Variables, Data Types and Constants
Naming Conventions (Identifiers)
1. Names are made up of letters and digits.
2. The first character must be a letter.3. C is case-sensitive, example s is not
the same with S.4. The underscore symbol (_) is considered
as a letter in C. It is not recommended
to be used, however, as the firstcharacter in a name.5. At least the first 3 characters of a name
are significant.
8/11/2019 TurboC Notes
37/102
Variables, Data Types and Constants
Names... Example
CANNOT start with a number 2i
CAN contain a number elsewhere h2o
CANNOT contain any arithmetic operators... r*s+t
CANNOT contain any other punctuation marks... #@x%!!a
CAN contain or begin with an underscore _height_
CANNOT be a C keyword struct
CANNOT contain a space im stupid
CAN be of mixed cases XSquared
8/11/2019 TurboC Notes
38/102
Variables, Data Types and Constants
Variables- are like containers in yourcomputer's memory - you can store valuesin them and retrieve or modify them whennecessary.
- associated with a memory cell whosevalue can change as the program executes.
Variable declarationstatements thatcommunicate to the C compiler the names
of all variables used in the program and thekind of information stored in each variable.- also tells how that information will berepresented in memory.
8/11/2019 TurboC Notes
39/102
Variables, Data Types and Constants
Syntax for Declarations:
data type variable_list;
Ex. int x,age;
float sum,a,b;
char middle_intial;
8/11/2019 TurboC Notes
40/102
Variables, Data Types and Constants
Data Typea set of values and a setof operations that can be performedon those values.
Standard Predefined Data Type in C:
char
double
int
8/11/2019 TurboC Notes
41/102
Variables, Data Types and Constants
Seven Basic C Data Types:
1. Text (data type char) made up of single characters(example x,#,9,E) and strings (Hello), usually 8 bits, or1 byte with the range of 0 to 255.
2. Integer values those numbers you learned to count
with.3. Floating-point values numbers that have fractional
portions such as 12.345, and exponents 1.2e+22.
4. Double-floating point values have extended range of1.7e-308 to 1.7e+308.
5. Enumerated data types allow for user-defined datatypes.
6. void signifies values that occupy 0 bit and have novalue. You can also use this type to create genericpointers.
7. Pointer does not hold information as do the other datatypes. Instead, each pointer contains the address of thememory location.
8/11/2019 TurboC Notes
42/102
8/11/2019 TurboC Notes
43/102
8/11/2019 TurboC Notes
44/102
Variables, Data Types and Constants
Modifiers
The three data types above have the followingmodifiers.
short long
signed
unsigned
The modifiers define the amount of storage allocatedto the variable. The amount of storage allocatedis not cast in stone. ANSI has the following rules:
short int
8/11/2019 TurboC Notes
45/102
Variables, Data Types and Constants
Type Bytes Bits Rangeshort int 2 16 -32,768 -> +32,767 (32kb)
unsigned short int 2 16 0 -> +65,535 (64Kb)
unsigned int 4 32 0 -> +4,294,967,295 ( 4Gb)int 4 32 -2,147,483,648 -> +2,147,483,647(2Gb)
long int 4 32 -2,147,483,648 -> +2,147,483,647(2Gb)
signed char 1 8 -128 -> +127
unsigned char 1 8 0 -> +255
float 4 32
double 8 64
long double 12 96
8/11/2019 TurboC Notes
46/102
Variables, Data Types and Constants
Constantsidentifiers that are having aconstant value all throughout the programexecution.- also fixed values that may not be altered
by the program.
Examples:1. Character constantsenclosed between
single quotes. Ex. A, +2. Integer constantsspecified as numbers
without fractional components.Ex. 5 and -160
8/11/2019 TurboC Notes
47/102
Variables, Data Types and Constants
Floating constantsrequire the use ofdecimal point followed by the numbersfractional components. Ex. 16.234
String constantsset of charactersenclosed by double quotes. Ex. bagand this is good
Backslash character constantsenclosing all character constants in
single quotes that works for mostprinting characters. Ex. g = \t
8/11/2019 TurboC Notes
48/102
Variables, Data Types and Constants
SEQUENCE NAME MEANING
\a Alert Sound a beep
\b Backspace Backs up one character
\f Form feed Starts a new screen of page
\n New line Moves to the beginning of the nextline
\r CarriageReturn
Moves to the beginning of thecurrent line
\t Horizontal tab Moves to the next Tab position
\v Vertical tab Moves down a fixed amount
\\ Backslash Displays an actual backslash
\ Single quote Displays an actual single quote
\? Question mark Displays an actual question mark
\ Double quote Displays an actual double quote
8/11/2019 TurboC Notes
49/102
Variables, Data Types and Constants
Defining Constants
#define preprocessor
- allows us to define symbolic names and
constants.A quick example:
#define PI 3.14159
This statement will translate every occurrence ofPI in the program to 3.14159.
Here is a more complete example:#define PI 3.14159 main() { int r=10; float cir;
cir = PI * (r*r); }
8/11/2019 TurboC Notes
50/102
Variables, Data Types and Constants
Defining Constants
The const keyword.
- used to create a read only variable. Once
initialized, the value of the variable cannot bechanged but can be used just like any othervariable.
const syntax:
main()
{ const float pi = 3.14; }The const keyword is used as a qualifier to the
following data types - int float char double struct.
const int degrees = 360;
const float pi = 3.14;
const char quit = 'q';
8/11/2019 TurboC Notes
51/102
Operators
Assignment Operator Equal sign (=)
- the most basic operator where thevalue on the right of the equal sign
is assigned to the variable on theleft.
Example:
c = c + 1;radius = 2 * diameter;
stat = getch();
8/11/2019 TurboC Notes
52/102
Operators
Binary Operators
- take two operands and return a result.
Operator Use Result+ op1 + op2 adds op1 to op2
- op1 - op2 subtracts op2 from op1
* op1 * op2 multiplies op1 by op2
/ op1 / op2 divides op1 by op2% op1 % op2 computes the remainder
from dividing op1by op2
8/11/2019 TurboC Notes
53/102
Operators
Unary Operators
- changes the sign of a value orvariable.
- Unary minus (-) and unary plus(+)
Examples:
2 +-3
((-x) + (+y))
8/11/2019 TurboC Notes
54/102
Operators
Increment (++) and Decrement (--)Operators
++ increment adds one to a value of the
variable-- decrement subtracts one from a value
of the variable
Note: The value of the expression in which++ or -- operator is used depends on theposition of the operator.
8/11/2019 TurboC Notes
55/102
Operators
Prefix increment/decrementwhen the ++or is placed immediately in front of itsoperand. Meaning the value of theexpression is the variables value afterincrementing or decrementing.
Postfix increment/decrementwhen the++ or comes immediately after the
operand. The value of the expression isthe value of the variable before it isincremented or decremented.
8/11/2019 TurboC Notes
56/102
Predefined Mathematical Functions
Function Purpose
abs(x) returns the absolute value of integer x.
x=abs(-5); x=5
fabs(x) returns the absolute valued of type
double.x=fabs(-5.2); x=5.2
ceil(x) rounds up or returns the smallest wholenumber that is not less than x.
x=ceil(5.2); x=6
floor(x) rounds down or returns the largestwhole number that is not greater
than x.
x=floor(5.2); x=5
8/11/2019 TurboC Notes
57/102
Predefined Mathematical Functions
Function Purpose
sqrt(x) returns the non-negative square of x.
x=sqrt(25); x=5
pow(x,y) returns x to the power of y.
x=pow(4,2); x=16
sin(x) returns the sine of angle x.
cos(x) returns the cosine of angle x.
tan(x) returns the tangent of angle x.
log(x) returns the natural logarithm of x.
log10(x) returns the base 10 logarithm of x.
8/11/2019 TurboC Notes
58/102
Conversion Specifications
Date Types printf conversionspecification
scanf conversionspecifications
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long int %lu %lu
long int %ld %ld
unsigned int %u %uint %d %d
short %hd %hd
char %c %c
String - %s
8/11/2019 TurboC Notes
59/102
I/O Functions
Numeric Input Command
scanf()one of the Turbo C object stream
object that is used to accept data from thestandard input, usually the keyboard.
syntax:
scanf(format, &var_name);
Example:
printf(Input side of the square:);
scanf(%d, &s);
8/11/2019 TurboC Notes
60/102
8/11/2019 TurboC Notes
61/102
I/O Functions
Character/String Input Command
getche()allows the user to input acharacter and there is no need for the enter
key. Inputted char will be echoed but couldbe stored if location is specified.
Syntax:getche();var_name = getche();
Example: ans = getche();
8/11/2019 TurboC Notes
62/102
I/O Functions
Character/String Input Command
gets()allows the user to input a sequence
of characters (string).syntax:
gets(variable_name_of_char_type);
Example:
gets(name);
8/11/2019 TurboC Notes
63/102
I/O Functions
Output Command
printfwrites formatted output to the standardoutput device such as the monitor.
syntax:printf(format code,var_name);
Example:
printf(%d,x);
putswrites the string to the standard outputdevice such as the monitor and positions thecursor to the next line.
syntax:
puts(string expression);
Example: puts(CIT);
8/11/2019 TurboC Notes
64/102
I/O Functions
Output Command
putchar writes the single character to
the screen.syntax:
putchar(var_name);
Example:
putchar(a);
8/11/2019 TurboC Notes
65/102
Control Flow
Control Structures - specify the sequence ofexecution of a group of statements.
3 Types:
1. Sequential2. Conditional
3. Iterative
Sequential - organized such that statementsare executed in sequence, i.e., one afterthe other in the order of their appearancein the source code.
8/11/2019 TurboC Notes
66/102
Control Flow
Conditional Control Structure - organizedin such a way that there is always acondition that has to be evaluated first.The condition will either evaluate to atrue or false.
2 Types:
1. if statement (including if-else andnested if)
2. switch case statement
8/11/2019 TurboC Notes
67/102
8/11/2019 TurboC Notes
68/102
Operators
Logical Operators
- used in boolean expressions and consists oflogical and", or" and not".
0-> false and 1-> true or nonzero digit
Operator Use Result&& op1 && op2 true if op1 and op2 are both
true|| op1 || op2 true if either op1 or op2 is
true
! !op1 op1 is false if its originalvalue is true and viceversa
8/11/2019 TurboC Notes
69/102
Control Flow
if Selection Structure
- performs an indicated action onlywhen the condition is true, otherwise
the action is skipped.
Syntax: if ()
ConditionStatementT
Example:
8/11/2019 TurboC Notes
70/102
p
Write a program that will allow the user to input aninteger value. If the value is greater than or equal to
zero, print the word POSITIVE.Begin
End
num
ifnum>=0
POSITIVE
8/11/2019 TurboC Notes
71/102
Control Flow
Other Problems:
1. Write a program that will allow the userto input a double precision floating point
value. Print the word NEGATIVE if thenumber is a negative value.
2. Write a program to input two integers.Thereafter, the program should determine
if these two numbers are equivalent. Ifthey are equivalent, print the wordEQUIVALENT.
3. Write a program that will input an integer
and determine if it is an even number.
8/11/2019 TurboC Notes
72/102
Control Flow
if-else Selection Structure
- allows the programmer to specify that
different actions are to be performed when
the condition is true than when thecondition is false.
- If condition evaluates to true, then
statementTis executed and statementFisskipped; otherwise, statementTis skipped
and statementFis executed.
8/11/2019 TurboC Notes
73/102
Control Flow
Syntax:
if (condition)
statementT;
else
statementF;
Conditio
n
StatementT
Statement
F
Example:
8/11/2019 TurboC Notes
74/102
Begin
End
num
POSITIVE
NEGATIVE
T
F
Write a program that accepts an integer. If the enteredinteger is positive, it prints POSITIVE. Otherwise,it prints NEGATIVE.
ifnum>=0
8/11/2019 TurboC Notes
75/102
Control Flow
if-else (multiple alternatives)
- The conditions in a multiple-alternativedecision are evaluated in sequence until a
truecondition is reached. If a condition istrue, the statement following it isexecuted, and the rest of the multiple-alternative decision is skipped. If a
condition is false, the statement followingit is skipped, and the condition next istested. If all conditions are false, then thestatement following the final elseisexecuted.
8/11/2019 TurboC Notes
76/102
T
TCondition
Statement
Condition
Condition
Statement
Statement
Statement
T
F
F
F
Control Flow
Syntax:
if (condition)
statement;
else if (condition)statement;
else if (condition)
statement;
else
statement;
Make aBegin
8/11/2019 TurboC Notes
77/102
program thatwould input aYEAR code(between 1and 4) andoutputFRESHMAN,
SOPHOMORE, JUNIORor SENIOR.Furthermore,
if YEAR is notbetween 1and 4, outputERROR.
End
YEAR
ifYEAR==1
ifYEAR==2
ifYEAR==3
ifYEAR==4
FRESHMAN
ERROR
SOPHOMORE
SENIOR
JUNIOR
T
T
T
T
F
F
F
F
8/11/2019 TurboC Notes
78/102
Control Flow
Nested-if Statement Syntax:
if (condition)
{
if(condition)
statement;
else
statement;
}
Condition
Condition
Statement
Statement
F
T
F
T
8/11/2019 TurboC Notes
79/102
Control Flow
Switch Statement- the controlling expression, anexpression with a value of type int or typechar, is evaluated and compared to each
of the case labels in the case constantuntil a match is found. A case constant ismade of one or more labels of the formcase followed by a constant value and acolon. When a match between the value
of the controlling expression and a caselabel value is found, the statementfollowing the case label are executed untila break statement is encountered. Thenthe rest of the switch statement isskipped.
8/11/2019 TurboC Notes
80/102
8/11/2019 TurboC Notes
81/102
Control Flow
Loops and Counters
Loop a control structure that repeats agroup of steps in a program. It defines a
block of code that is repeatedly executed.Depending on the kind of loop that youare using, the block of code could beexecuted a set number of times or until a
certain condition is met.- Repetition loops can also be altered bybreak or continue statements.
8/11/2019 TurboC Notes
82/102
Control Flow
Break - Exits from the lowest-level loop inwhich it occurs.
- used for early exit from the loop, or forexiting a forever loop
Continue causes immediate loop iteration,skipping the rest of the loop statements
- jumps to the loop test when used withwhileor do
-jumps to loop increment, then test whenused with for
- does not exit the loop (unless next loopis false)
8/11/2019 TurboC Notes
83/102
Control Flow
A loop has the following components:1. Initialization of variables setting an
initial value of zero before the loopstatement is reached.
2. Condition/testing (that would evaluateto either true or false) the condition tocheck is usually made on the currentvalue of the variable initialized in (1) for itcontrols the loop repetition.
3. Body statements that are repeated inthe loop.
4. Updating a statement inside the body ofthe loop that updates the value of thevariable that is initialized during each
repetition.
8/11/2019 TurboC Notes
84/102
Control Flow
3 Types:
1. do-whilestatement
2.
whilestatement3. forstatement
8/11/2019 TurboC Notes
85/102
Control Flow
do-while statement
- This loop executes a block ofcodes as long as the specifiedcondition is true.
- It is a post checked loop becauseit checks the controlling condition
after the code is executed.
8/11/2019 TurboC Notes
86/102
Control Flow
Syntax:do{
statement;} while (loop repetition condition);
Example:c=1;
do{printf(Hello World\n);c++;
} while (c
8/11/2019 TurboC Notes
87/102
Control Flow
Initialization
Process insidethe loop
WhileCondition?
do
T
F
c=1
Whilec
8/11/2019 TurboC Notes
88/102
Control Flow
while Statement
- Like do-while, this will execute ablock of codes while the given
condition is true.
- It is a pre-checked loop because itchecks the controlling condition first
before the code is executed.
8/11/2019 TurboC Notes
89/102
Control Flow
Syntax:while (loop repetition condition){
statement;}
Example:c=1;
while (c
8/11/2019 TurboC Notes
90/102
Control Flow
Initialization
Process insidethe loop
WhileCondition?
T
F
c=1
Whilec
8/11/2019 TurboC Notes
91/102
Control Flow
for Statement
- a kind of loop command wherein theexecution of the statement does not depend on
another instruction.Syntax:
for (initialization expression; loop repetition condition;update expression)
{statement;
}
8/11/2019 TurboC Notes
92/102
8/11/2019 TurboC Notes
93/102
Functions
Function a subroutine that contains one ormore statements and performs a singlewell-defined task.
2 Types:1. Pre-defined those functions written by
for us (by some other programmers).
2. User-defined those functions that we
are going to write/implement byourselves.
Difference between the main
8/11/2019 TurboC Notes
94/102
program and the function
Main Program
Input Output
Function
Input Output
scanf() printf() parameters return
8/11/2019 TurboC Notes
95/102
Functions
Begin
Calling afunction
End
Function_name (paramaters)
Return
Function body
8/11/2019 TurboC Notes
96/102
Functions
Function Syntax and Function Definition Syntax:
return_type function_name(parameter list){
local declaration;. . .statement/s;
}
Note: No function can have the same name asthe one of TCs reserved words.
8/11/2019 TurboC Notes
97/102
Functions
Where:
return_type = any standard datatype in C
parameter list consists ofvariables that receive the value ofthe arguments used in the functioncall.
Arguments a value that is passed tothe function at the time that it iscalled.
8/11/2019 TurboC Notes
98/102
8/11/2019 TurboC Notes
99/102
Functions
Example:
int func(int one, int two)
{
int sum;
sum=one + two;
return sum;
}
8/11/2019 TurboC Notes
100/102
Functions
Functions Returning Values
The returnkeyword has two importantuses:
1. It can be used to cause an immediate exitfrom the function it is in. That is, thereturn will cause program execution toreturn to the calling as soon as it isencountered.
2. It can also be used to return a value.
Note: The returnstatement can also beused without any value associated with it.
8/11/2019 TurboC Notes
101/102
Functions
Function Definition (Without return typeand parameters)
Syntax:
void fname(void)
{
local declarations
executable statements
}Example:
void hello(void){
printf(Hello);
}
8/11/2019 TurboC Notes
102/102
Functions
Function Definition (Without return typeand with parameters)
Syntax:void fname(parameters list){
local declarationsexecutable statements
}Example:
void add(int one, int two){int sum;sum=one + two;
Top Related