You are on page 1of 217

Week 1 – Introduction

to Computer and Algorithm


(Part1)

UniMAP Sem II – 11/12 DKT121: Basic Computer Programming 1


General Information
 Contributes 3 units:
 2 hours – lectures
 2 hours – labs and tutorials
 Main Objective:
 Students can independently write, compile,
debug and execute computer programs to
solve problems, especially engineering
related problems.

2
Course Outcomes
 Ability to define and describe programming
concepts and principles.

 Ability to apply programming techniques and tools


such as flowchart and pseudo code to design
computer programs.

 Ability to apply GNU/Linux for coding, compiling,


executing and debugging computer programs.

 Ability to solve engineering related problems using


computer programming techniques.
3
Overall Evaluation
 4 main components:
 4 Assignments (20%)
 Final exam (40%),
 Test 1 (10%)
 Individual Lab Test (30%)
 Assignments are individual “take home”
+ lab
 One test is written test
4
References
 Hanly, J.R. and Koffman, E.B., “C Program Design
for Engineers”, 2nd Ed., Addison-Wesley, 2001.
ISBN : 0321204174
 Deitel & Deitel, Suhizaz Sudin, R. Badlishah and
Yasmin Yacob, “C How To Program”, Pearson-
Prentice Hall, 2006.
 Tan, H.H. and D’Orazio,T.B., “C Programming for
Engineering & Computer Science”, Mc Graw Hill,
1999.
5
Notes
 This course is NOT about the language
per se, it is about problem solving,
analytical skills and to apply C to solve
problems.
 Write C program in Linux environment
 Do early reading
 Do not hesitate to ask during lecture
sessions

6
Outline
 Computer Fundamentals
 Computer organization and hardware
 Computer software
 Programming Languages
 Machine language
 Assembly language
 High-level language
 Algorithm : pseudo code and flowchart
 Control Structures
 Simple C Program

7
Computer Fundamentals
 Computer system is divided into hardware
and software.
 Hardware refers to physical components of
computer which are:
 Main Memory
 Central Processing Unit (CPU)
 Input Device
 Output Device
 Secondary Memory Device
8
Figure 1.1
The Intel Atom processor chip contains the full circuitry of a
central processing unit in an integrated circuit whose small size and
low power requirements make it suitable for use in mobile internet
devices. (Intel Corporation Pressroom Photo Archives)
Figure 1.2

(a) Notebook Computer


(HP Pavilion dv5©, Courtesy of
Hewlett-Packard).

(b) Palmtop Computer


(iPhone 3G©, Courtesy of
Apple, Inc.)

(c) Desktop Computer


(iMac©, Courtesy of Apple,
Inc.)

1-10
Figure 1.3 Components of a Computer

1-11
Computer Hardware

CPU
Control Unit
Input Device Arithmetic and Output Device
Logic Unit
Register

Main Memory

Secondary Memory

12
Central Processing Unit (CPU)
 CPU is the computer’s administrator and is
responsible for supervising the operation of
the other sections
 Consists of two functional units; control unit
and arithmetic-logic unit (ALU)
 Control unit supervises all activities of the
computer system
 ALU performs basic arithmetic operations
and comparison operations

13
Main Memory
 keeps information from the input unit
 also keeps processed information until it
can be placed on output devices
 all programs must be loaded into main
memory before they can be executed
and all data must be brought into main
memory before it can be manipulated.

14
Main Memory
 Main memory can be further classified
into two types:
 Random Access Memory (RAM)
 information in RAM will be lost when the
computer is turned-off.
 Read Only Memory (ROM)
 It has been set during manufacturing process.
ROM usually contains instructions and
information considered to be fundamental to
the computer.

15
Figure 1.4
1000 Memory Cells in
Main Memory

1-16
Secondary Memory
 Main memory is only used during
processing following certain instructions
 Permanent information is NOT stored in
main memory but is stored in secondary
memory
 E.g. program file, data fail, etc
 E.g. hard disk, diskette, CD

17
Figure 1.5 Secondary Storage Media

1-18
Input/Output Devices
 Input devices - feed data and programs
into computers
 E.g. keyboard, mouse, touch screen,
scanners
 Output devices - display results
produced by computer
 E.g. monitor, printer, speaker

19
Software
 As a complement to hardware,
computer system needs software to
solve problems.
 Software are classified into :
 System software
 Application software

20
Software
 System software : manages the computer
and its peripheral devices (hardware)
 E.g. Operating system (OS)
 Text editor
 Pre-processor
 Language translator
 Linker
 Loader

21
Software
 Application software : performs specific tasks
 There are two types:
 Program to solve specific problems
 Program written by user to solve specified
problem
 E.g. word processor, desktop publishing
software, spreadsheets, database, graphics,
communication, programs perform specific
tasks such as accounting, scientific,
engineering, education, etc
22
Programming Languages
 Programming language is divided into
three categories:
 Machine Language
 Assembly Language
 High-Level Language

23
Machine Language
 Language understood by the computer
 Bunch of 0’s and 1’s
 Program written in machine language can be
executed without being translated
 Nevertheless, hard to learn because it is
written in 0’s and 1’s
 Program is too long to solve simple problem
 Machine-dependant and not portable
 E.g.
 0101 0001 1100 0100 1011 1000
 0101 1000 0101 1001 1100 0111

24
Figure 1.6 Relationship Between a Byte and a Bit

1-25
Assembly Language
 Strings of 0’s and 1’s are replaced into
instructions which resemble English
language to represent computer
operation element
 Easier to understand and write
 E.g. LOAD
MULT
rate
hour
STOR wages

26
Assembly Language
 Nevertheless, needs language translator
called Assembler to change Assembly
Language to Machine Code for
execution purpose
 still too long and not portable

27
High-Level Language
 Improves weaknesses in Machine Language
and Assembly Language
 Portable
 Written in one instruction to carry out several
instructions in machine level
 E.g. discount_price = price – discount;
 Must be changed to machine code before
executed, needs compiler : a system software
that translates source program to object
program

28
Algorithms
 The solution to any computing problem involves
executing series of actions in a specific order
 Pseudo code : artificial and informal language that
helps programmers develop algorithms
 E.g.
if student’s grade is greater than or equal to 50
Print “Pass”
else
Print “Fail”

29
Algorithms
 Flowchart: visual-form of an algorithm
Begin
 E.g.
Data

Process 1 Decision Process 2

End

30
Algorithm-Basic symbols in a
flowchart
Flow
Start/End
direction

Process
Connector

Input/Output

Decision

31
Flowchart-(example)
Start

read num1, num2

sum=num1+num2

print sum

End

32
TRY THIS!!!

Write a pseudo code, flowchart and program that


calculates and prints the SUM of two integers A and B.

33
Flowchart

Begin

Pseudo code Input


A,B
• Begin
• Input A and B
• Calculate A + B Calculate
• Print result of SUM A+ B
• End
Print SUM

End

34
Control Structure
 All programs could be written in terms
of three control structures:
 Sequence structure
 Selection structure
 Repetition structure

35
Sequence Structure
 Is a series of steps executed
sequentially by default
Pseudo code Flowchart

Read num1, num2


Read num1, num2
Calculate total=num1+num2
Print total total = num1+num2

print total

36
Selection Structure
 Used to choose among alternative
courses of action
 C has three types: if, if..else, and
switch

37
The if Selection Structure
 “if” structure is a single-entry/single-
exit structure
If student’s grade is greater than or equal to 60
Print “Pass”

true
grade >= 60 print “Pass”

false

38
The if..else Selection
Structure
 Specifies an action to be performed
both when the condition is true and
when it is false If student’s grade is greater than or equal
to 60
Print “Pass”
else
Print “Fail”

false true
grade >= 60

print “Fail” print “Pass”

39
Repetition Structure
 Specifies a block of one or more
statements that are repeatedly
executed until a condition is satisfied
 Three types : while, for,
do-while

40
The while Repetition
Structure
 Programmer specifies an action is to be
repeated while some conditions remain true

true
product <= 1000 product = 2 * product

false
While product is less than or equal 1000
calculate product=2 * product

41
Basics of a Typical C Program
Development Environment

UniMAP Sem I – 09/10 EKT120: Computer Programming 42


Figure 1.7 Entering,
Translating,
and Running
a High-Level Language
Program

1-43
Figure 1.8 Flow of Information During Program
Execution

1-44
Simple C Program: Program to add two numbers

#include <stdio.h>
int main(void)
{
int A, B, SUM;
printf (“input first integer \n”);
scanf (“%d”, &A)
printf (“input second integer \n”);
scanf (“%d”, &B)
OUTPUT
SUM = A + B; Input first integer
39
printf (“Sum is %d\n”, SUM); Input second integer
return 0;
27
}
Sum is 66

45
End Week 1 – Part1

Q & A!

UniMAP Sem II – 10/11 DKT121: Basic Computer Programming 46


Week 2 – Introduction
to Computer and Algorithm
(Part 2)

UniMAP Sem II-11/12 DKT121


1
Outline
 Pseudo code & flowchart
 Sample programming question
 Sample C program
 Identifiers and reserved words
 Program comments
 Pre-processor directives
 Data types and type declarations
 Operators
 Formatted input and output
 Program debugging

2
Sample Programming
Question
• Write a program that calculates area of
triangle. Your program should read the
base length and the height length from
user. Given the formula to calculate the
area of triangle: 0.5 x (base) x (height).
• Steps:
 Analyze the problem
 Use algorithm
 Convert to actual codes
3
Recall..Pseudo code and
Flowchart
Try develop the pseudo code and flowchart for the
problem given in the previous slide.

4
Sample C Program
/*Program name : program1.c Comments
Programmer : Yasmin
This program calculates the area of triangle*/
#include <stdio.h>
Preprocessor directives
begin int main(void)
{
double dBase, dHeight, dArea; The term void indicates we receive
Variables nothing from OS and return an
printf(“Enter base length : “);
declaration scanf(“%f”, &dBase);
integer to OS
printf(“Enter height length : “);
scanf(“%f”, &dHeight);
body
dArea=0.5 * dBase * dHeight;
printf(“\nArea of the triangle is : %5.2f\n”, dArea);
return 0;
}
return 0 (int) to
end OS
5
Variables & Reserved Words
 Identifiers/Variables
 labels for program elements
 case sensitive
 can consist of capital letters[A..Z], small letters[a..z],
digit[0..9], and underscore character _
 First character MUST be a letter or an underscore
 No blanks
 Reserved words cannot be variables/identifiers
 Reserved words
 already assigned to a pre-defined meaning
 e.g.: delete, int, main, include, double, for, if, etc.

6
Variables & Reserved Words
An identifier for the data in the program
Hold the data in your program
Is a location (or set of locations) in memory
where a value can be stored
A quantity that can change during program
execution

7
Constants
 A constant is a named or unnamed value,
which does not change during the program
execution.
 Example:
 const double dPi=3.141592
 Const int iDegrees=360;
 Const char cQuit=‘q’;
 Unnamed constant are often called literals
 Eg: 3.141592 and 360
8
Program Comments
 Starts with /* and terminates with */
OR
 Character // starts a line comment, if
several lines, each line must begin with
//
 Comments cannot be nested /* /* */*/

9
Preprocessor Directives
 An instruction to pre-processor
 Standard library header: <stdio.h>,<math.h>
 E.g. #include <stdio.h>
 for std input/output
 #include <stdlib.h>
 Conversion number-text vise-versa, memory
allocation, random numbers
 #include <string.h>
 string processing

10
Data Types
Data types determine the following:
Type of data stored
Number of bytes it occupies in memory
Range of data
Operations that can be performed on the data
Modifiers alter the meaning of the base type to more
precisely fit a specific need
C supports the following modifiers along with data
types:
short, long, signed, unsigned

11
Data Types & Memory
Allocation
Type Bits Bytes Range
Char or Signed Char 8 1 -128 to +127
Unsigned Char 8 1 0 to +255
Int or Signed int 32 4 -2,147,483,648 to +2,147,483,647
Unsigned int 32 4 0 to +4,294,967,295
Short int or Signed short int 16 2 -32,768 to + +32,767
Unsigned short int 16 2 0 to +65,535
Long int or signed long int 32 4 -2,147,483,648 to +2,147,483,647
Unsigned long int 32 4 0 to +4,294,967,295
Float 32 4 3.4 e-38 to 3.4 e+38
Double 64 8 1.7e-308 to 1.7e+308
Long Double 64 8 1.7e-308 to 1.7e+308
12
Variables Naming Conventions
Variable names should use Hungarian notation
Start with an appropriate prefix that indicates the
data type
After the prefix, the name of variable should have
ore or more words
The first letter of each word should be in upper
case
The rest of the letter should be in lower case.
The name of variable should clearly convey the
purpose of the variable

13
Naming Variables According to
Standards
Prefix Data Type Example
i int and unsigned int iTotalScore
f float fAverageScore
d double dHeight
l long and unsigned long lFactorial
c signed char and unsigned char cProductCode
ai Array of integer aiStudentId
af Array of float afWeight
ad Array of double adAmount
al Array of long integer alSample
ac Array of characters acMaterial
14
Data Types Declaration
 float fIncome;
float income, net_income;
float fNet_income;
 double dBase, dHeight, dArea;
Declare and initialize
 int iIndex =0, iCount =0;
 char cCh=‘a’, cCh2;
 const float fEpf = 0.1, fTax = 0.05;
Named constant declared and initialized

15
Types of Operators
 Types of operators are:
 Arithmetic operators
(+ , - , * , / , %)
 Relational operators
(> , < , == , >= , <=, !=)
 Logical operators (&& , ||)
 Compound assignment operators
(+=, -=, *=, /=, %=)
 Binary operators: needs two operands
 Unary operators: single operand
 Bitwise operators: executes on bit level

16
Arithmetic Operators
 Used to execute mathematical
equations
 The result is usually assigned to a data
storage (instance/variable) using
assignment operator ( = )
 E.g.
sum = marks1 + marks2;

17
Arithmetic Operators
C Operation Arithmetic Algebraic C Expression
Operator Expression
Addition + f+7 f+7
Subtraction - p–c p-c
Multipication * bm b*m
Division / x/y x/y
Remainder % r mod s r%s
(Modulus)
18
Exercise on Arithmetic Operators

Given x = 20, y = 3
z=x%y
= 20 % 3
= 2 (remainder)

19
Relational and Logical Operators

 Previously, relational operator:


>, < >=, <=, == , !=
 Previously, logical operator:
&&, ||
 Used to control the flow of a program
 Usually used as conditions in loops and
branches
20
More on relational operators
 Relational operators use mathematical
comparison (operation) on two data, but give
logical output
e.g.1 let say b = 8, if (b > 10)
e.g.2 while (b != 10)
e.g.3 if (mark == 60) print (“Pass”);
Reminder:
DO NOT confuse == (relational operator)
with = (assignment operator)
21
More on logical operators
 Logical operators are manipulation of
logic. For example:
i. b=8, c=10,
if ((b > 10) && (c<10))
ii. while ((b==8) || (c > 10))
iii. if ((kod == 1) && (salary > 2213))

22
Truth Table for &&
(logical AND) Operator
exp1 exp2 exp1 && exp2

false false false

false true false

true false false

true true true

23
Truth Table for ||
(logical OR) Operator
exp1 exp2 exp1 || exp2

false false false

false true true

true false true

true true true

24
Compound Assignment Operators
 To calculate value from expression and store
it in variable, we use assignment operator (=)
 Compound assignment operator combines
binary operator with assignment operator
 E.g. val +=one; is equivalent to val = val + one;
 E.g. count = count -1; is equivalent to
count -=1;
count--;
--count;

25
Unary Operators
 Obviously operating on ONE operand
 Commonly used unary operators
 Increment/decrement { ++ , -- }
 Arithmetic Negation { - }
 Logical Negation { ! }
 Usually using prefix notation
 Increment/decrement can be both a
prefix and postfix
26
Comparison of Prefix and Postfix Increments

27
Unary Operators (Example)
 Increment/decrement { ++ , -- }
 prefix:value incr/decr before used in expression
 postfix:value incr/decr after used in expression
val=5; Output: val=5; Output:
printf (“%d”, ++val); 6 printf (“%d”, --val); 4

val=5; Output: val=5; Output:


printf (“%d”, val++); 5 printf (“%d”, val--); 5

28
Operator Precedence
Operators Precedence
! + - (unary operators) first
* / % second
+ - (binary operators) third
< <= >= > fourth
== != fifth
&& sixth
|| seventh
= last

29
Formatted Output with “printf”
#include <stdio.h>
void main (void)
{ Declaring variable (iMonth) to be integer

int iMonth; Declaring variables (fExpense and


fIncome) to be real
float fExpense, fIncome;
iMonth = 12; Assignment statements store numerical values
in the memory cells for the declared variables
fExpense = 111.1;
fIncome = 1000.0; ‘,’ separates string literal from variable names
printf (“Month=%2d, Expense=$%9.2f\n”,iMonth,fExpense);
} Correspondence between variable names and
%...in string literal
30
Formatted Output with “printf”

31
Formatted Input with “scanf”

32
Formatted Input with “scanf”

33
Program Debugging
 Syntax error
 Mistakes caused by violating “grammar” of C
 C compiler can easily diagnose during compilation
 Run-time error
 Called semantic error or smart error
 Violation of rules during program execution
 C compiler cannot recognize during compilation
 Logic error
 Most difficult error to recognize and correct
 Program compiled and executed successfully but
answer wrong

34
Program Debugging-syntax
error snapshot

35
Program Debugging-run time
error snapshot

36
Program Debugging-logic
error snapshot

37
End Week 2 – Session 2

Q & A!

38
Week 4 – Selection Structures

UniMAP Sem II-11/12 DKT121 Basic Computer Programming 1


Outline
 Recall selection control structure
 Types of selection
 One-way selection
 Two-way selection
 Multi-selection
 Compound statement
 Nested if
 Conditional operator
 Switch structure

2
Recall..
Selection Structure
 Used to choose among alternative
courses of action
 C has three types: if, if..else, and
switch

3
The if selection structure
 if structure is a single-entry/single-exit
structure
If student’s grade is greater than or equal to 60
Print “Pass”

true
fGrade >= 60 print “Pass”

false

4
The if..else selection
structure
 Specifies an action to be performed
both when the condition is true and
when it is false If student’s grade is greater than
or equal to 60
print “Pass”
else
print “Fail”

false true
fGrade >= 60

print “Fail” print “Pass”

5
Selection Statements
 Used to control the flow of a program
 Also called as decision or branches
 Branches are conditions or choices used
to enable selection of program flow

6
Types of selection
 One-way selection = if
 Two-way selection = if..else
 Multi-selection
 Nested if
 Switch structure = switch

7
One-way Selection = if
 In C, a condition is represented by a logical (Boolean)
expression
 true and false are logical (Boolean) values
 The syntax of one-way selection is:

 if (expression) statement;

 If the value of the expression is true, statement is


executed;
 if false, statement is not executed and the computer
goes on to the next statement in the program.

8
One-way Selection = if
If student’s grade is greater than or equal to 60
Print “Pass”

true
fGrade >= 60 print “Pass”

false

9
One-way Selection = if
…..
if(fGrade >= 60)
printf(“Pass”);
…..
…..

10
One-way Selection = if
 Another example:
char cGrade;
……
if(fMarkah>= 90)
cGrade = 'A';
……
…...
printf(“Grade is : %c\n”, cGrade);

11
One-way Selection = if
 Another example:
 if (temperature is greater than 70 degree
and it is not raining)
 recommended activity is golfing

bool rain=false;

if((fTemp > 70) && !(rain))
printf(“recommended activity is golfing”);

12
One-way Selection = if
 Common Errors
 if fScore >= 90 //no parentheses
cGrade = 'A';
 if(fScore >= 90); //; not here
cGrade = 'A';

13
Two-way Selection =
if..else
 The syntax of two-way selection is:

 if (expression)
statement1;
else
statement2;

 If the value of the expression is true,


statement1 is executed;
 if false, statement2 is executed

14
Two-way Selection =
if..else
If student’s grade is greater than or equal
to 60
print “Pass”
else
print “Fail”

false true
fGrade >=
60
print print
“Fail” “Pass”

15
Two-way Selection =
if..else
………
if(fGrade >=60)
printf(“Pass”);
else
printf(“Fail”);
……

16
Two-way Selection =
if..else
 Another example:
if (fHour > 40.0)
//Line 1
fWages = 40.0 * fRate +1.5 * fRate * (hour - 40.0); //Line 2
else //Line 3
fWages = fHour * fRate; //Line 4
 If fHour is 50, then the statement at Line 2 is
executed
 If fHour is 30, then the statement at Line 4 is
executed
17
Multi-selection = if-else if
 The syntax is: An if-else if control structure
if(exp1) shifts program control, step by
step, through a series of
stmt1; statement blocks.
else if(exp2)
stmt2;
else if(exp3)
stmt3;

else
stmt n;

18
Multi-selection = if-else if
 E.g. true
fTemp >30 Print “hot”
temp display
false
true
>30 0c hot fTemp > 20 Print “mild”

20-30 0c mild false


true
10-20 0c cold fTemp >10 Print “cold”

<10 0c very cold false


Print “very cold”

19
Multi-selection = if-else if
if(fTemp > 30)
printf( “hot\n”);
else if((fTemp >=20) && (fTemp<=30))
printf( “mild\n”);
else if(fTemp >=10) && (fTemp < 20))
printf(“cold\n”);
else
printf( “very cold\n”);
20
Compound (Block of) Statement
 A compound statement (also called a
block of statements) takes the form of
 {
 statement 1; statement 2;
 .
 .
 .
 statement n;
 }
 It is considered a single statement

21
Compound (Block of) Statement
 Example:
if (iAge > 18)
{
printf("Eligible to vote\n“);
printf("No longer a minor\n“);
}
else
{
printf("Not eligible to vote\n“);
printf(“Still a minor\n”);
}

22
Nested if
 When one control statement is within another, it is
said to be nested
 if(exp1)
if(exp2)
statement1; OR
 if(exp1)
{
statement1;
if(exp2)
statement2;
}

23
Nested if
 Example:
if (fTemperature >= 50)
{
if (fTemperature >= 80)
printf( "Good day for swimming.\n”);
else
printf( "Good day for golfing.\n“);
}
else
printf("Good day to play tennis.\n“);

24
Nested if
#include <stdio.h> Output
void main (void)
Type the day and time of interest
{
int iDay; Keyboard input 3 10.00
float fTime; Relax

printf ("Type the day and time of interest\n\n");


scanf (" %d %f ", &iDay, &fTime);

if (iDay <= 5)
{
if (fTime <= 9.00)
printf (" Work \n\n");
else
printf (" Relax \n\n");
}
else
{
if (fTime <= 8.00)
printf (" Sleep \n\n");
else
printf (" Have Fun \n\n");
}
}
25
The Conditional Operator (? :)
 The syntax of using the conditional operator
is: expression1 ? expression2 : expression3;
 This is called a conditional expression.
 The statement:
if (a >= b)
max = a;
else
max = b;
 Is equivalent to the statement:
max = (a >= b) ? a : b;

26
switch Structures
 Similar to if-else if control structure
 The general form (syntax):
switch (expression)
{
case value1: statements1; break;
case value2: statements2; break;
.
.
.
case valuen: statementsn; break;
default: statements;
}

27
switch Structures
 The break statement has a special
meaning and may or may not appear
after each statement.
 In C, switch, case, break, and default
are reserved words.
 In a switch structure, first the
expression is evaluated. The value of
the expression is then used to perform
the corresponding action.

28
switch Structures
 The expression is usually an identifier.
 The value of the expression can be only integral.
 The expression is sometimes called the selector. Its
value determines which statement is selected for
execution.
 A particular case value should appear only once.
 One or more statements may follow a case label, so
you do not need to use braces to turn multiple
statements into a single compound statement.
 The break statement may or may not appear after
each statement.

29
switch Structures
 Example:
switch (cGrade)
{
case 'A': printf("The grade is A.“); break;
case 'B': printf("The grade is B.“); break;
case 'C': printf("The grade is C.“); break;
case 'D': printf("The grade is D.“); break;
case 'F': printf("The grade is F.“); break;
default: printf("The grade is invalid.“);
}
 where, cGrade is a variable of the type char. If the
value of cGrade is, say 'A', the output is
The grade is A.

30
switch Structures
 The switch statement executes according to the
following rules:
 When the value of the expression is matched against a case
value (also called a label), the statements execute until
either a break statement is found or the end of the switch
structure is reached.
 If the value of the expression does not match any of the
case values, the statements following the default label
execute. If the switch structure has no default label, and if
the value of the expression does not match any of the case
values, the entire switch statement is skipped.
 A break statement causes an immediate exit from the
switch structure

31
What’s wrong??

32
End Week 2

Q & A!

33
Week 4 – Repetition Structures /
Loops

UniMAP SEM II 11/12 DKT121 1


Outline
 Introduction
 While loops
 Three types of while loops
 Do-while loops
 For loops
 Nested loops

2
Why Need Loops ?
 Suppose we want to add five numbers and
find the average.
 From what you have learned so far, you could
proceed as follows
scanf(“%d %d %d %d %d”, &iNum1, &iNum2,
&iNum3, &iNum4, &iNum5);
iSum = iNum1 + iNum2 + iNum3 + iNum4 +
iNum5;
fAverage = iSum / 5;
 If 100 numbers, 1000 numbers?
3
Repetition (Loop)
 Used to control the flow of a program
 Loops are basically repetitions or iterations used to
repeat a segment of code
 Three statements can be used to implement loops in
C
 w hile statement
 do-w hile statement
 for statement
 w hile and for statements are similar in
implementation, but have different syntax
 The do-w hile statement is different - the following
code is executed at least once

4
The while loop structure
 The general form of the while statement is:
while (expression)
statement;
 To avoid an infinite loop, make sure that
the loop’s body contains statement (s) that
assure that the exit condition i.e. the
expression in the while statement will
eventually be false.
 while loop repeates until condition becomes
false

5
Flowchart of a while statement

6
The while loop structure-cont
 There are basically three types of while
loops:
 Counter-controlled while loop
 Sentinel-controlled while loop
 Flag-controlled while loop

7
Counter-Controlled while
Loops
 Definite repetition: know how many times loop will execute
 Control variable used to count repetitions

Example: Requirement:
int iCounter = 1; // declare and initialize 1. Declare and initialize
while ( iCounter <= 10 ) // test condition control variable value (or
{ loop counter)
printf( "%d\n", iCounter ); 2. A condition that tests
++iCounter; // update for the final value of the
} control variable (i.e.,
whether looping should
continue)
3. Update control variable
(incr/decr)

8
Counter-Controlled while
Loops
declare and initialize
 Another example:
int iProduct = 2; test condition

while ( iProduct <= 1000 ) increment


iProduct = 2 * iProduct;

true
iProduct <= 1000 iProduct = 2 * iProduct

false

9
Sentinel-Controlled while
Loops
 Indefinite repetition
 Used when number of repetitions not known
and loop needs to input value repeatedly for
each iteration
 Sentinel value indicates "end of data“

10
Sentinel-Controlled while
Loops-continued
Example: Requirement:
int iNumber, iCount, iSum;
1. Read control
iSum = 0;
iCount = 0; variable value
before enter loop
printf(“To stop enter -999. Enter positive numbers : " ); 2. A condition that
scanf(“%d”, &iNumber); tests control
while (iNumber != -999) Sentinel value variable’s validity
{ (i.e., whether
iSum = iSum + iNumber; //find sum of numbers entered looping should
iCount++; //count how many numbers entered
continue)
printf(“To stop enter -999. Enter positive numbers : " );
3. Read again
scanf(“%d”, &iNumber);
} control variable
before end of loop
printf(“\nThe sum of %d numbers is %d“, iCount, iSum);

11
Sentinel-Controlled while
Loops-continued
 Another example:
float fGradePt;
char cChoice;
printf(“Continue? y-yes n-no: ”); read control variable
scanf(“%c”, &cChoice);
while ( cChoice == ‘y’) test condition
{ printf(“\nEnter grade point:”);
scanf(“%f”, &fGradePt);
if(fGradePt > 2.0)
printf(“\nPass);
printf(“Continue? y-yes n-no: ”);
scanf(“%c”, &cChoice);
} read again

12
Flag-Controlled while Loops
 Uses a flag to control the loop.
 Loop exit when expression is evaluated to false.
int error; Set Flag, by default error =1
Requirement:
int iGuess; 1. Set control variable
while (error) test condition before loop
{ 2. A condition that tests
control variable. If expr
printf("Enter number between 1 and 200:"); evaluated to 1, loop
scanf("%d", &iGuess); continue
decision if ((iGuess>= 88) &&(iGuess <=128)) 3. A decision structure to
structure {error = 0; test value validity
printf("\nBINGO!");} 4. Set control variable to
0 to indicate found
} Set error to 0
UniMAP SEM I 11/12 EKT150 13
The do-while Repetition
Structure
 Similar to the while structure
 Condition for repetition is tested after the
body of the loop is performed
 All actions are performed at least once
 Expression can be written as count-controlled
or sentinel-controlled
 Format:
do {
statement;
} while ( condition );

14
Flowchart of a do-while
structure

action(s)

true
condition

false

15
The do-while Repetition
Structure
 Example : prints the integers from 1 to 10
int iCounter = 1;
do {
printf( "%d ", iCounter ); count-controlled
} while (++iCounter <= 10);
 Another example:
do {
printf(“\nEnter grade point:”);
scanf(“%f”, &fGradePt);
if(fGradePt > 2.0)
printf(“\nPass);
printf(“Continue?y-yes n-no :”);
scanf(“%c”, &cChoice);
}while ( cChoice == ‘y’) sentinel-controlled

16
The do-while Repetition
Structure
 To avoid an infinite loop, make sure that the loop body contains a
statement that ultimately makes the expression false and assures that
it exits
 Another example:
int iLoop = 0;

do
{
printf (“%d ”,iLoop);
iLoop = iLoop + 5;
} while (iLoop <= 20);

The output is:


0 5 10 15 20

17
The do-while Looping
Structure (Example)
 Example: Consider the following two loops
(a)
(b)
iLoop = 11;
iLoop = 11;
while (iLoop <= 10)
do
{
{
printf("%d",iLoop);
printf("%d",iLoop);
iLoop = iLoop + 5;
iLoop = iLoop + 5;
}
}
while (iLoop <= 10);

18
The do-while Looping
Structure (Example)
 In (a), the while loop, produces nothing
 In (b) the do...while loop, outputs the
number 11

19
The for Repetition Structure
 Format when using for loops
for (initialization ; loop continuation test ; increment statement)

 Use for loops when already know how


many times to repeat
 Example:
for(iCounter = 1;iCounter <= 10;iCounter++)
printf("%d\n",iCounter);
 Prints the integers from 1 to 10
20
The for Repetition Structure
 ‘for’ loops can usually be rewritten as while loops:
initialization;
while ( loop continuation test )
{
statement;
increment statement;
}
 Initialization and increment
 Can be comma-separated lists. Example:

int iVar1, iVar2;


for(iVar1=0,iVar2=0;iVar2+iVar1<=10;iVar2++,iVar1++)
printf(“%d\n”,iVar2+iVar1);
21
Flow of a for statement

22
Nested loop
 Loop within a loop
 Inner loop is performed first
 e.g.
for(iLoop1=1;iLoop1<4;iLoop1++) Output
{ 1234
for(iLoop2=1;iLoop2<5;iLoop2++) 1234
printf(“%d”, iLoop2); 1234
printf(“\n”);
}

23
Nested loop
 Another example:
 Program finds and prints avg of three test scores, then asks
whether user wants to continue
do
{
for(iCount=0; iCount <3;iCount++)
{ printf(“\nEnter test marks: ”);
scanf(“%d”, &iMarks);
iTotal=iTotal+iMarks;
}
fAvg=iTotal/iCount;
printf(“\nAverage:%5.2f”, fAvg);
printf(“\nContinue?”);
scanf(“%c”, &cChoice);
}while(cChoice == ‘y’);
24
End Week 4 - Loops

Q & A!

25
Week 7 – Functions (1)

UniMAP Sem II-11/12 DKT121 1


Outline
 Why use functions?
 Functions in C
 Pre-defined functions
 User-defined functions
 Function prototypes
 Function definitions
 Function calls
 What about number, order and type of parameter?
 Functions that do not return a value
 Functions that return a value
 Miscellaneous about functions
 Sample application
 Scope and mechanics of passing values to functions

2
Why use functions?
 Let say you want to print one row of number 8 and one row of number 9

#include <stdio.h>
int main()
{ int iLoop1, iLoop2;

//print one row of number 8


for(iLoop1=1; iLoop1<=10; iLoop1++)
printf(“8");
printf("\n"); //go to new line

//print one row of number 9


for(iLoop2=1; iLoop2<=10; iLoop2++)
printf(“9“);
printf("\n"); //go to new line

return 0;
}
3
Why use functions?
 It seems that you are doing the same
thing twice!!(i.e. printing two rows of
numbers)
 This is wasting time and not flexible!!
 So, need to use function

4
Why use functions?
#include <stdio.h>
void fnDisplay(int); //function prototype
int main()
{
fnDisplay(8); //function call
fnDisplay(9); //function call
return 0;
}

void fnDisplay(int value) //function definition


{ int iLoop;
for(iLoop=1; iLoop<=10; iLoop++)
printf("%d", value);
printf("\n"); //go to new line
}
5
Functions in C
 Functions can be created to execute small,
frequently-used tasks
 In C, there are predefined functions or sometimes
called standard functions, and there are user-
defined functions.
 Predefined functions are already available
functions that can be used, called library
 The usage is like stdio.h, in which the library
name must be #included at the top of the source
code (preprocessor directive)

6
Predefined Functions (Library)
 Common libraries are stdio.h, math.h,
string.h, and stdlib.h
 stdio.h related functions: printf, scanf,etc
 math.h related functions: sin, cos, exp, pow,
sqrt, etc.
 string.h related functions: strcmp, strcpy,
strlen, etc.
 stdlib.h related functions: abs, fabs

7
Predefined Functions
(Library)-example
#include <stdio.h>
#include <math.h>
#include <string.h>
void main()
{
string sName;
int iVol1, iVol2, iN,i R, iKTemp, iLength;

strcpy(sName, “Marina”);
iVol2 = iVol1 * exp(iN * iR * iKTemp);
iLength = strlen(“Mahathir”);
}
8
User-Defined Functions
 What do we need to define and make
use of user-defined functions?
 Function prototypes
 Function definitions
 Function calls

9
Function Prototypes
 Function prototype is a declaration; indicates
the function exists
 Should have function name, return type and
parameter
 Argument name is not compulsory in function
header
 Function prototype has the following form:
 <return_type> <function_name> (arg_type arg_name, ...);
 int fnSum (int iNum1,int iNum2);
 int fnSum (int,int); //is also acceptable
semicolon

10
Function Definitions
 Function definition includes the body of a function
 Function definition has the following form:
 <return_type> <function_name> (arg_type arg_name, ...)
{
… statements …
} no semicolon
 int fnSum (int iNum1,int iNum2)
{ function header
int iAdd;
iAdd = iNum1 + iNum2;
return(iAdd);
}

 Notice that argument name is used in the function body


 Unlike function prototype, argument name in function definition
must be included in function header

11
Function Calls
 Consists of a function name followed by an argument
expression list enclosed in parentheses
 Function call has the following form:
 <function_name> (exp, exp ...)

 exp is an expression – can be variable or constant

 iResult = iSum(x,y);

12
Example of function in
program
//This program sums up two numbers
#include <stdio.h>
int fnSum(int, int); //function prototype
int main()
{ int iX, iY, iResult;
printf( “Enter x and y : ”);
scanf(“%d %d”, &iX, &iY);
iResult = fnSum(x,y); //function call
printf(“Sum is : %d”, iResult);
return 0; function header
}
int fnSum(int iNum1, int iNum2)//function definition
{ int iAdd;
iAdd = iNum1+iNum2;
return(iAadd);}
} 13
What about number, order
and type of parameter?
 Number, order and type of parameters in the
argument list of a function call and function
definition MUST match.
 If function prototype and definition have three
parameters then the function call must have
three parameters.
 If the types are int, float and double in the
prototype, the types in the function call should
be int, float and double, respectively.
14
What about number, order
and type of parameter?(e.g1)
prototype void fnFunction2(int iN, double dX);

function header void fnFunction2(int iN, double dX)

function call fnFunction2 (iM, dY);

 Note that there are two arguments for function prototype,


function definition and function call; the first is int and the
second is double. With these three we have met the
number, order and type requirements.

15
What about number, order
and type of parameter?(e.g2)
int fnSum(int, int); //function prototype

int fnSum(int iNum1, int iNum2) //function definition

fnSum(iX,iY); //function call

 Refer to program in slide 13


 Number, order and type parameter are met because:
there are two parameters, the parameters are listed in
order i.e respectively and first parameter is int and
second parameter is int.
16
Functions that do not return a
value
//This program sums up two numbers
#include <stdio.h>

void fnSumPrint(int, int); //function prototype


void fnFunction1(); //function prototype

int main()
{ int iX,iY;
fnFunction1(); //function call
printf(“Enter x and y: ”);
scanf(“%d %d”, &iX, &iY);
fnSumPrint(iX,iY); //function call
return 0;
}
void fnSumPrint(int iNum1, int iNum2) //function definition
{ int iAdd;
iAdd = iNum1+iNum2;
printf(“Sum is: %d”,iAdd);
}
void fnFunction1()
{ printf(“Welcome to this program\n”); }
17
Functions that return a value
//This program sums up two numbers
#include <stdio.h>
int fnSum(int,int); //function prototype

int main()
{ int iX,iY,iResult;
printf(“Enter x and y: ”);
scanf(“%d %d”, &iX, &iY);
iResult = fnSum(iX,iY); //function call
printf(“Sum is : %d”,iResult);
return 0;
}

Int fnSum(int iNum1, int iNum2) //function definition


{ int iAdd;
iAdd = iNum1+iNum2;
return(iAdd);
}
18
Miscellaneous about functions
 Function call used as logical expression
int fnCalc(int,int); //function prototype
int main(void)
{ int iNum1, iNum2;
scanf(“%d %d”,&iNum1,&iNum2);
if(fnCalc(iNum1,iNum2)>100) //function call used as logical expression
printf(“result greater than 100”);
else
printf(“result less than 100”);
return 0;
}

int fnCalc(int iN1,int iN2)


{ int iAnswer;
iAnswer=iN1+iN2;
return(iAnswer);
}

19
Miscellaneous about functions
 Function call used in printf statement
int fnCalc(int,int); //function prototype
int main(void)
{ int iNum1,iNum2;
scanf(“%d %d”,&iNum1,&iNum2);
printf(“Sum = %d”,fnCalc(iNum1, iNum2)); //function call returns a
//value and puts in printf
return 0;
}

int fnCalc(int iN1,int iN2)


{ int iAnswer;
iAnswer=iN1+iN2;
return(iAnswer);
}

20
Miscellaneous about functions
 Rules regarding naming convention for variables
 iNum1 passes value to iN1, iNum2 passes value to iN2
 Better use different variable names for parameters in main AND
parameters in function definition

int fnCalc(int,int); //prototype function


int main(void)
{ int iNum1,iNum2,iResult; //declare like this
scanf(“%d %d”,&iNum1,&iNum2);
iResult = fnCalc(iNum1,iNum2); //function call
printf(“sum = %d“,iResult);
return 0;
}

//function definition
int fnCalc(int iN1,int iN2) //simply declare like this
{ int iAnswer;
iAnswer=iN1+iN2;
return(iAnswer);
}

21
Sample application
 Write a C program that calculates and prints
addition and subtraction of numbers.
 Your program should have functions:
 fnAdd : adds two numbers
 fnSubtract : subtracts two numbers
 fnPrintResult : prints results from calculation

22
Sample application(cont)
#include <stdio.h> int fnAdd(int iX,int iY)
int fnAdd(int,int); {
int fnSubtract(int,int); int iSum;
void fnPrintResult(int);
iSum = iX+iY;
int main() return(iSum);
{ int iNum1,iNum2,iAnswer; }
char cOp;
printf(“Enter two numbers and operator:”); int fnSubtract(int iX,int iY)
scanf(“%d %d %c”, &iNum1,&iNum2,&cOp); {
switch(cOp) int iSub;
{ case ‘+’ :iAnswer=fnAdd(iNum1,iNum2);break;
iSub=iX-iY;
case ‘-’ :iAnswer=fnSubtract(iNum1,iNum2);break;
default: printf(“Invalid operator”); return(iSub);
} }

fnPrintResult(iAnswer); void fnPrintResult(int iAns)


return 0; {
} printf(“Answer is %d”, iAns);
}

23
1/* Fig. 5.4: fig05_04.c
2 Finding the maximum of three integers */
3#include <stdio.h>
4
5int fnMaximum(int, int, int); /* function prototype */
6 1. Function prototype
7int main() (3 parameters)
8{
9 int iA, iB, iC;
10
11 printf( "Enter three integers: " );
12 scanf( "%d %d %d", &iA, &iB, &iC );
13 printf( "Maximum is: %d\n", fnMaximum( iA, iB, iC ) );
14 2. Function call
15 return 0;
16 }
17
18 /* Function maximum definition */
19 int fnMaximum(int iX, int iY, int iZ)
20 { 3. Function definition
21 int iMax = iX;
22
23 if ( iY > iMax )
24 iMax = iY;
25
26 if ( iZ > iMax )
27 iMax = iZ;
28
29 return iMax;
30 }
Enter three integers: 22 85 17 Program Output
Maximum is: 85
24
Scope and Mechanics of
Passing Values to Functions
 Scope refers to the region in which a declaration is active
 File scope is also called global variable
 declared at the top of a source file

 declarations not placed in any functions

 can be used by any statements that are being executed

in the system
 Function scope is also called local variable
 declared in a block { … }

 scope is within its block – lifetime while the block is

executed

25
Global Variable : Example
 #include <stdio.h>
int iGlobal = 3; //This is the global variable
void fnChangeGlobal( );

int main(void)
{ printf("%d\n“, iGlobal); //Reference to global
//variable in a function
fnChangeGlobal();
printf("%d\n", iGlobal);
return 0;
}
void fnChangeGlobal( )
{ iGlobal = 5; } //Reference to global
//variable in a function
26
Global Variable : Example
The output will be:
3
5

27
Local Variable : Example
 #include <stdio.h>
void fnChangeLocal();
int main(void)
{ int iLocal = 3; //This is a local variable
printf("%d\n", iLocal); //Reference to local
//variable in a function
fnChangeLocal();
printf("%d\n", iLocal);
return 0;
}
void fnChangeLocal()
{ int iLocal = 5; //This is another local variable
printf("%d\n", iLocal); }
28
Local Variable : Example
The output will be:
3
5
3

29
End Week 7 – Functions (1)

Q & A!

30
Week 8 – Functions (2)

UniMAP SemII-11/12 DKT121 1


Outline
 Recall - sample application
 functions that do not return value

 functions that return a value

 Recall – global variable vs. local variable


 Passing parameters in functions :- Pass by value
 Functions that return more than one value
 Sample application-functions that return more than one value
 Passing parameters in functions :- Pass by reference
 Sample application
 Recursive function

2
Sample application
 Write a C program that reads item code and quantity,
then calculates the payment. Use functions:
 fnMenu – print item code menu

 fnDeterminePrice – determine price based on

item code
 fnCalc - calculate payment

 fnPrintResult – print payment

What argument Think!! Which


names do I want function returns no
to feed in as value and which
parameters and function returns a
what to return?? value.
3
Sample application
#include <stdio.h>
void fnMenu();
float fnDeterminePrice(int);
float fnCalc(float,int);
void fnPrintResult(float);

int main()
{ int iCode,iQty;
float fPrice,fPay;
fnMenu();
printf("Enter item code and quantity: ");
scanf("%d %d", &iCode,&iQty);
fPrice = fnDeterminePrice(iCode);
fPay = fnCalc(fPrice,iQty);
fnPrintResult(fPay);
return 0;
}
4
void fnMenu()
{
printf("Code\tItem\tPrice\n");
printf("1\tPapaya\t1.00\n"); Code Item Price
printf("2\tMelon\t2.00\n"); 1 Papaya 1.00
printf("3\tDurian\t3.00\n"); 2 Melon 2.00
printf("\tOthers\t4.00\n"); 3 Durian 3.00
} Others 4.00
float fnDeterminePrice(int iItemCode) Enter item code and quantity: 1 3
{ float fPricing; Payment is 3.00
***************************
switch(iItemCode)
Code Item Price
{
1 Papaya 1.00
case 1:fPricing = 1.00;break; 2 Melon 2.00
case 2:fPricing = 2.00;break; 3 Durian 3.00
case 3:fPricing = 3.00;break; Others 4.00
default:fPricing = 4.00; Enter item code and quantity: 9 3
} Payment is 12.00
return(fPricing);
}
float fCalc(float fItemPrice, int iQuality)
{ float fTotal;
fTotal = fItemPrice*iQuantity;
return(fTotal);
}
void fnPrintResult(float fPayment)
{ printf("Payment is %.2f\n", fPayment);
}
5
Global Variable vs. Local Variable
#include <stdio.h> float fnDeterminePrice(int iCode) Output:
void fnMenu();
modification { Code Item Price
float fnDeterminePrice(int); iCode--; 1 Papaya 1.00
float fnCalc(float,int); switch(iCode) 2 Melon 2.00
void fnPrintResult(float); { 3 Durian 3.00
int iCode,iQty; float fPrice,fPay; case 1:fPrice=1.00;break; Others 4.00
int main() case 2:fPrice=2.00;break; Enter item code and quantity: 1 4
{ case 3:fPrice=3.00;break; Payment is 16.00
fnmenu(); default:fPrice=4.00;
printf("Enter item code and } Output:
quantity:"); return(fPrice); Code Item Price
scanf("%d %d", &iCode,&iQty); } 1 Papaya 1.00
fPrice= fnDeterminePrice(iCode); float fnCalc(float fPrice,int iQuantity) 2 Melon 2.00
fPay=fnCalc(fPrice,iQty); { 3 Durian 3.00
fnPrintResult(fPay); fPay=fPay+1; Others 4.00
return 0; fPay=fPrice*iQuantity; Enter item code and quantity: 3 1
} return(fPay); Payment is 2.00
void fnMenu( ) }
{ void fnPrintResult(float fPay)
printf("Code\tItem\tPrice\n"); { printf("Payment is %.2f\n", fPay);
printf("1\tPapaya\t1.00\n"); }
printf("2\tMelon\t2.00\n");
printf("3\tDurian\t3.00\n"); However, sometimes we need to do some modifications
printf("\tOthers\t4.00\n");
from inside a function; using global variable will make
}
things worse!!!
6
Pass by Value
 If a parameter is passed by value, then the
value of the original data is copied into the
function’s parameter (scope: local variable(s))
 In other words, it (i.e. local variable) has its
own copy of the data
 changes to copy do not change original
data
 During program execution, it (i.e. local
variable) will manipulate the data stored in its
own memory space

7
Pass by Value (Example)
Output
#include <stdio.h> Before fnFun 1
void fnFun1(int,int); //function prototype iA = 5 iB = 10
int main(void)
{
Inside fnFun 1
int iA=5, iB=10; iAA = 6 iBB = 9
printf("Before fun 1\n“);
printf(" iA = %d iB = %d\n”, iA,iB);
fnFun1(iA, iB); //function call After fnFun 1
printf("\nAfter fun 1\n“); iA = 5 iB = 10
printf(" iA = %d iB = %d\n”, iA,iB);
return 0;
}

void fnFun1(int iAA,int iBB) //function definition


{
iAA++;
iBB--;
printf("\n\nInside fun 1\n)";
printf(“iAA = %d iBB = %d\n”, iAA,iBB);
}
8
Functions that return more
than one value
 When we talk about functions that
return more than one value it also
means that we want to pass arguments
by reference
 passes addresses (references), NOT value
or data
 allows direct manipulation
 changes will affect original data

9
Functions that return more
than one value
 There are cases where you need to
manipulate the value of an external
variable from inside a function, thus we
pass the value by reference

10
Sample application
 Write a C program that calculates and
prints average of 2 test marks.
 Your program should have functions:
 fnReadMarks – read 2 test marks
 fnCalcAvg – calculate average of two test
marks
 fnPrint - print average

UniMAP SemI-11/12 EKT150 11


Function that returns
more than one value -

Sample application arguments are passed by


reference

void fnReadMarks(float *fM1,float *fM2)


#include <stdio.h> {
void fnReadMarks(float*,float*); printf("Enter marks for test1 and test2 : ");
float fnCalcAvg(float,float); scanf("%f %f", fM1,fM2); //notice no &
void fnPrint(float); }
int main(void) float fnCalcAvg(float fM1, float fM2)
{ {
float fMarks1, fMarks2, fAvg; return((fM1 + fM2)/2);
}
fnReadMarks(&fMarks1,&fMarks2);
fAvg = fnCalcAvg(fMarks1,fMarks2); void fnPrint(float fAverage)
fnPrint(fAvg); {
return 0; printf("\nAverage marks are :%.2f\n",fAverage);
} }

Output
Enter marks for test1 and test2 : 70 80
Average marks are : 75.00
12
Pass by Reference
 A function’s parameter that receives the location (memory address) of
the corresponding actual variables
 When we attach * (star) after the arg_type in the parameter list of a
function, then the variable following that arg_type is passed by
reference
 It stores the address of the actual variable, NOT the value
 During program execution to manipulate the data, the address stored
will direct control to the memory space of the actual variable
 Syntax:
 In function protoype and function definition, put the * (star) after the data
type
Example : void fnReadMarks(float *,float *);
 In function call, put the &(ampersand) before the argument name to be
passed by reference
Example : fnReadMarks(&fMarks1,&fMarks2);

13
Pass by Reference
 Pass by reference is useful in two situations:
 when you want to return more than one

value from a function


 when the value of the actual parameter

needs to be changed

14
Sample application
 Write a C program that reads character and
calculates numbers of vowel and consonant
 Your program should have function:
 fnRead – read character
 fnFindCountVC – determine and calculate
number of vowel or consonant
 fnPrint - print number of vowel or consonant

15
Enter character : f

Sample application
Do you want to continue?y
Enter character : I
Do you want to continue?y
#include <stdio.h> Enter character : k
#include <string.h> Do you want to continue?n
char fnRead(); Number of vowel : 1
void fnFindCountVC(char, int*, int*); Number of consonant : 2
void fnPrint(int,int);
void fnFindCountVC(char cCh1, int *iVowel, int
int main() *iConsonant)
{ char cCh, cChoice; int iCountV=0, iCountC=0; {
do switch(cCh1) Functions that “return”
{ cCh = fnRead(); { case 'A': more than one value i.e.
fnFindCountVC(cCh, &iCountV, &iCountC); case 'a': arguments are passed by
printf("Do you want to continue? "); case 'E': reference
scanf("%c", &cChoice); case 'e':
getchar(); case 'I':
}while((cChoice == 'y') ||(cChoice =='Y')); case 'i':
print(iCountV,iCountC); case 'O':
return 0; case 'o':
} case 'U':
case 'u': *iVowel = *iVowel +1;break;
char fnRead() default: *iConsonant = *iConsonant + 1;
{ char cCh1; }
printf("Enter character : "); }
scanf("%c", &cCh1); void fnPrint(int iVowel, int iConsonant)
getchar(); {
return(cCh1); printf("Number of vowel : %d\n", iVowel);
} printf("Number of consonant : %d\n", iConsonant);
} 16
Pass by Reference (Example)
#include <stdio.h> Output
void fnFun1(int, int*); //function prototype Before fun 1
int main(void) iA=5 iB = 10
{ Inside fun 1
int iA=5,iB=10; iAA = 6 iBB = 9
printf("Before fun 1\n”);
printf(“iA = %d iB = %d”,iA,iB); After fun 1
fnFun1(iA, &iB); //function call iA = 5 iB = 9
printf(“\n\nAfter fun 1\n”);
printf(“iA = %d iB = %d\n”,iA,iB);
return 0;
}
void fnFun1(int iAA, int * iBB)//function definition
{
iAA++;
*iBB--;
printf("\n\nInside fun 1\n”);
printf(“iAA = %d iBB = %d”,iAA,iBB);
}

17
Recursive Functions
 Recursion is a term describing functions which are called by
themselves (functions that call themselves)
 Recursive function has two parts i.e. base case and not base
case
 If not base case, the function breaks the problem into a slightly
smaller, slightly simpler, problem that resembles the original
problem and
 Launches a new copy of itself to work on the smaller
problem, slowly converging towards the base case
 Makes a call to itself inside the return statement

 Eventually the base case gets solved and then that value works
its way back up to solve the whole problem
 Recursion is very useful in mathematical calculations and in
sorting of lists

18
Recursive Functions
 Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
 Recursive relationship:
 ( n! = n * ( n – 1 )! )
 5! = 5 * 4!
 4! = 4 * 3!…

 Base case (1! = 0! = 1)

19
Recursive Functions(Example)
 Factorial
4 * 6 = 24 is returned
Factorial(4)

4* Factorial(3) 3 * 2 = 6 is returned

3* Factorial(2)
2 * 1 = 2 is returned

2* Factorial(1)

Value 1 is returned
1

20
Recursive Functions(Example)
#include <stdio.h>
int fnFactorial(int);

void main()
{
int iN=4;
printf(“Factorial %d is %d“,n, fnFactorial(n));
}

int fnFactorial(int iN)


{ Call function
if(iN <= 1) //base case name itself
return 1;
else
return ( iN * fnFactorial(iN-1));
}
21
Recursive Functions (Example)
 Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
 Each number is the sum of two previous numbers
 Example of a recursive formula:
fib(n) = fib(n-1) + fib(n-2)

22
Recursive Functions (Example)
 Diagram of Fibonacci function:
f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0

23
Recursive Functions (Example)
 Sample code for fibonacci function
long fnFibonacci( long lN )
{
if ( lN == 0 || lN == 1 ) //base case
return lN;
else
return fnFibonacci( lN - 1 ) +
fnFibonacci( lN – 2 );
}

24
End Week 8 – Functions (2)

Q & A!

25
Lecture 9 - Pointers

1
Outline
 Introduction
 Pointer Variable Definitions and Initialization
 Pointer Operators
 Calling Functions by Reference
 Pointer Expressions and Pointer Arithmetic
 Relationship between Pointers and Arrays
 Arrays of Pointers

2
Introduction
 Pointer is the address (i.e. a specific memory
location) of an object.
 It can refer to different objects at different times.
 Pointers are used in C programs for a variety of
purposes:
 To return more than one value from a function (using pass
by reference)
 To create and process strings
 To manipulate the contents of arrays and structures
 To construct data structures whose size can grow or shrink
dynamically

3
Pointer Variable Definitions and
Initialization
 Pointer variables
 Contain memory addresses as their values
 Normal variables contain a specific value (direct
reference) num
7

 Pointer contains an address of a variable that has


a specific value (indirect reference)
 Indirection – referencing a pointer value
numPtr num
7

4
Pointer Variable Definitions and
Initialization
 Pointer definitions
 * is used with pointer variables
int *numPtr;
 Defines a pointer to an int (pointer of type int *)
 Multiple pointers require using a * before each variable
definition
int *numPtr1, *numPtr2;
 Can define pointers to any data type
 Initialize pointers to 0, NULL, or an address
 0 or NULL – points to nothing (NULL preferred)
 int *numPtr = NULL; or int *numPtr = 0;
5
Pointer Operators
 Symbol & is called address operator
 Returns address of operand

int num = 7;
int *numPtr;
numPtr = &num; /* numPtr gets address of num */

numPtr “points to” num


num numPtr num

numPtr
7 500000 600000 600000 7

Address of
num is value
of numPtr 6
Pointer Operators
 Symbol * is called indirection/dereferencing
operator
 Returns a synonym/alias of what its operand points to
 *numPtr returns num (because numPtr points to num)
 * can also be used for assignment
 Returns alias to an object

*numPtr = 10; /* changes num to 10 */ show pictures!!


 Dereferenced pointer (operand of *) must be an lvalue (no
constants)
 * and & are inverses
 They cancel each other out

7
Sample program
number = 7
numPtr points to num whereby the value is = 7
#include <stdio.h> Address of numPtr : 1245060 Contents of numPtr : 1245064
int main() Address of num : 1245064
{ int num;
int *numPtr; Dereferencing pointer, *numPtr = 15
int num1=5; num = 20
*numPtr = 20
num = 7; *numPtr + num1 = 25
printf("number = %d\n", num);
numPtr = &num;
printf("numPtr points to num whereby the value is = %d\n",*numPtr);
printf("Address of numPtr : %d Contents of numPtr : %d\n", &numPtr, numPtr);
printf("Address of num : %d\n\n", &num);

*numPtr = 15;
printf("Dereferencing pointer, *numPtr = %d\n", *numPtr);
num = num + num1;
printf(“num = %d\n”, num);
printf("*numPtr = %d\n", *numPtr);
printf("*numPtr + num1 = %d\n", *numPtr + num1);
return 0;
}
8
Calling Functions by Reference
 Call by reference with pointer arguments
 Passes address of argument using & operator
 Allows you to change actual location in memory
 Arrays are not passed with ‘&’ because the array name is
already a pointer

 * operator
 Used as alias or nickname for variable inside of function

void fun1 (int *number)


{
*number = 2 * (*number);
}

 *number used as nickname for the variable passed


9
Enter character : f
Do you want to continue?y
Enter character : I
Do you want to continue?y

Remember..last time
Enter character : k
Do you want to continue?n
Number of vowel : 1
Number of consonant : 2
#include <stdio.h>
#include <string.h> void find_count_vc(char ch1, int *vowel, int *consonant)
{
char read(); switch(ch1)
void find_count_vc(char, int*, int*); { case 'A':
void print(int,int); case 'a': Functions that “return”
case 'E': more than one value i.e.
int main() case 'e': arguments are passed by
{ char ch, choice; int count_v=0,count_c=0; case 'I': ref
do case 'i':
{ ch = read(); case 'O':
find_count_vc(ch, &count_v, &count_c); case 'o':
printf("Do you want to continue?"); case 'U':
scanf("%c", &choice); case 'u': *vowel = *vowel +1;break;
getchar(); default: *consonant = *consonant + 1;
}while((choice == 'y') ||(choice =='Y')); }
print(count_v,count_c); }
return 0;
}
void print(int vowel, int consonant)
char read() {
{ char ch1; printf("Number of vowel : %d\n", vowel);
printf("Enter character : "); printf("Number of consonant : %d\n", consonant);
scanf("%c", &ch1); }
getchar();
return(ch1); 10
}
Pointer Expressions and
Pointer Arithmetic
 Arithmetic operations can be performed on
pointers
 Increment/decrement pointer (++ or --)
 Add an integer to a pointer (+ or += , - or -=)
 Pointers may be subtracted from each other
 Operations meaningless unless performed on an
array

11
Pointer Expressions and
Pointer Arithmetic
 5 element int array on machine with 4 byte ints
 vPtr points to first element v[ 0 ]
 at location 3000 (vPtr = 3000)

 vPtr += 2; sets vPtr to 3008


 vPtr points to v[ 2 ] (incremented by 2), but the

machine has 4 byte ints, so it points to address 3008


location
3000 3004 3008 3012 3016

v[0] v[1] v[2] v[3] v[4]

pointer variable vPtr


12
Pointer Expressions and
Pointer Arithmetic
 Subtracting pointers
 Returns number of elements from one to the
other. If
vPtr2 = &v[ 2 ];
vPtr = &v[ 0 ];
 vPtr2 - vPtr would produce 2

 Pointer comparison ( <, == , > )


 See which pointer points to the higher numbered
array element
 Also, see if a pointer points to 0

13
Example of Pointer Operations
#include <stdio.h> Address of vPtr : 1245064 Contents of vPtr : 1245020
int main() Address of v[0] : 1245020
{int *vPtr; int *vPtr2; Address of vPtr + 2: 1245028
int v[5] = {10,20,30,40,50}; int temp; Address of vPtr + 4: 1245036
int *p, *q; Contents of temp : 2
Contents of p : 2147323904 q: 2147323904
vPtr= v;
printf("Address of vPtr : %d Contents of vPtr
: %d\n", &vPtr, vPtr);
printf("Address of v[0] : %d\n", &v);
vPtr +=2;
printf("Address of vPtr + 2: %d\n", vPtr);
vPtr +=2;
printf("Address of vPtr + 4: %d\n", vPtr);

vPtr2=&v[2];
vPtr=&v[0];
temp=vPtr2-vPtr;
printf("Contents of temp : %d\n", temp);

p=q;
printf("Contents of p : %d q: %d\n", p,q);
return 0;}
14
The Relationship between
Pointers and Arrays
 Arrays and pointers are closely related
 Array name like a constant pointer
 Pointers can do array subscripting operations

 Define an array b[5] and a pointer bPtr


 To set them equal to one another use:
bPtr = b;
 The array name (b) is actually the address of first element
of the array b[5]
bPtr = &b[0];
 Explicitly assigns bPtr to the address of first element of b

15
The Relationship between
Pointers and Arrays
 Element b[3]
 Can be accessed by *(bPtr + 3)
 where * is the offset. Called pointer/offset notation

 Can be accessed by bPtr[3]


 Called pointer/subscript notation
 bPtr[3] same as b[3]

 Can be accessed by performing pointer


arithmetic on the array itself
*(b + 3)

16
Address of bPtr : 1245064 Contents of bPtr : 1245016
Address of b : 1245016 Contents of b[0]:10 10 10
bPtr points to b[0] = 10

I am accessing element b[3]!!

Example
Let see how many ways I can do it
b[3] = 40
*(bPtr + 3) = 40
*(b + 3) = 40
bPtr[3] = 40

b[0] = 10
b[1] = 20
b[2] = 30
b[3] = 40
b[4] = 50
b[5] = 0
#include <stdio.h> b[6] = 0
int main() b[7] = 0
{ int *bPtr ;int i; b[8] = 0
b[9] = 0
int b[10]={10,20,30,40,50};
bPtr = b;
printf("Address of bPtr : %d Contents of bPtr : %d\n", &bPtr, bPtr);
printf("Address of b : %d Contents of b[0]:%d %d %d\n", &b, b[0], *bPtr, *b);
printf("bPtr points to b[0] = %d\n", *bPtr);

printf("\nI am accessing element b[3]!!\nLet see how many ways I can do it\n");
printf("b[3] = %d\n", b[3]);
printf("*(bPtr + 3) = %d\n", *(bPtr + 3));
printf("*(b + 3) = %d\n", *(b + 3));
printf("bPtr[3] = %d\n\n", bPtr[3]);

for(i=0;i<10;i++)
printf("b[%d] = %d\n", i, *(bPtr+i));
return 0;
} 17
Arrays of Pointers
 Arrays can contain pointers
 For example: an array of strings
char *suit[4] = {“Hearts”,“Diamonds”,“Clubs”,“Spades”};

 Strings are pointers to the first character


 char * – each element of suit is a pointer to a char
 The strings are not actually stored in the array suit, only
pointers to the strings are stored

18
Arrays of Pointers
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

 suit array has a fixed size, but strings can


be of any size

19
Example
#include <stdio.h> Enter student[0] name : ali
#define N 5 You just entered :
ali
int main() Enter student[1] name : abu
{ You just entered :
char *studentName[N]; int i; abu
Enter student[2] name : cheah
for(i=0;i<5;i++) You just entered :
{ printf("Enter student[%d] name : ", i); cheah
scanf("%s", studentName + i); Enter student[3] name : dali
printf("You just entered :\n%s\n", studentName + i); You just entered :
} dali
Enter student[4] name : gheeta
return 0; You just entered :
} gheeta

20

You might also like