Lecture Data Structures and Practise
Download
Report
Transcript Lecture Data Structures and Practise
Lecture 5
Introduction to Programming
in C
Arne Kutzner
Hanyang University / Seoul Korea
Further loop structures:
for structures,
do-while statements
for structure
• Syntax:
for(initialization; loop_repetition_condition; update)
statement;
• For-loops have three loop control statements:
– Initialization of the loop control variable.
– Test of the loop repetition condition
– Update of the loop variable
Introduction to C
L3.3
for structure with compound
• Syntax:
for(initialization; loop_repetition_condition; update)
{
statement_1;
statement_2;
…
statement_n;
}
Introduction to C
L3.4
for structure (cont.)
• Any for-loop may be represented as whileloop as follows:
for (stat1; expr2; stat3) {
statement;
}
Introduction to C
stat1;
while (expr2) {
statement;
stat3;
}
L3.5
Example while versus for
initialization
update
initialization
i = 0;
while (i < N) {
printf("*");
i = i + 1;
}
loop repetition
condition
for (i = 0;
i < N;
printf("*");
Introduction to C
loop repetition condition
update
statement
i = i + 1)
L3.6
Caution:
common error
• The following loop does not sum up the
values from 0 to n. (only up to n – 1)
for (i=0; i<n; i = i + 1)
sum = sum + i;
Introduction to C
L3.7
Caution (weird C)
Adding a semicolon at the end of the for
clause before the loop body is a common
mistake:
int i;
for (i = 0; i < 10; i = i + 1);
{
printf("i is %d", i);
}
Introduction to C
Wrong
L3.8
do-while Statement
• Syntax
do {
statement_1;
statement_2;
…
statement_n;
} while (loop_repetition_condition);
• The for and while statements both evaluate the loop repetition
condition before the execution of the loop body
• The do-while loop checks the repetition condition at the
end of the loop body
Introduction to C
L3.9
while versus do-while
do {
printf("Enter a letter from A to Z>");
scanf("%c", &letter_choice);
} while (letter_choice => 'A' && letter_choice <= 'Z');
printf("Enter a letter from A to Z>");
scanf("%c", &letter_choice);
while (letter_choice => 'A' && letter_choice <= 'Z') {
printf("Enter a letter from A to Z>");
scanf("%c", &letter_choice);
};
Introduction to C
L3.10
Caution (weird C)
The problem with while, do-while and the semicolon.
int i=0;
while (i<10);
Wrong
{
printf("i is %d", i);
i = i + 1;
}
In the case of the do loop, the following semicolon is needed to
end the loop.
int i=0;
do {
printf("i is %d“, i);
i = i + 1;
} while (i<10);
Correct
Introduction to C
L3.11
break, continue and goto
break and continue
Statements
• A break statement causes the innermost
enclosing loop to be exited immediately.
• continue causes the next iteration of the
enclosing for, while, or do-while loop to
begin.
• When continue statement is used in while
and do-while loops, then this means that
the condition part is executed immediately;
in the for loop, control passes to loop
variable update step.
Introduction to C
L3.13
Flowchart continue statement
(for while loop)
Continue
condition?
false
true
Statement(s)
continue;
Statement(s)
Next
Statement
Introduction to C
L3.14
Flowchart break statement
(for while loop)
Continue
condition?
false
true
Statement(s)
break;
Statement(s)
Next
Statement
Introduction to C
L3.15
Example continue
int sum = 0;
int n = 1;
while (n <= 100) {
if ((n % 2) == 0) {
n = n + 1;
continue;
}
sum = sum + n;
n = n + 1;
}
• In the above program the sum of all odd
numbers from 1 to 99 is calculated.
Introduction to C
L3.16
The goto statement
• General Syntax:
If the program flow
goto label;
reaches the goto
…
statement it continues at
the position marked with
label:
label:
…
• The goto statement is only for very
special situations and almost never
used.
Introduction to C
L3.17
The goto statement (cont.)
• Example:
for (…)
for (…) {
…
if (disaster)
goto error;
}
…
error:
error related code
Introduction to C
L3.18
switch Structures
switch structure
• Syntax
switch (expression) {
case const-expr :
statements;
break;
case const-expr :
statements;
break;
…
default :
statements;
}
Introduction to C
L3.20
switch structure
• To select one of several alternatives.
• Selection is based on the value of an
expression.
• Expression can be a single value.
• The type of expression can be either
int or char, but not double.
Introduction to C
L3.21
switch structure / Flow diagram
case A
true
case A actions
break
case B actions
break
case N actions
break
false
case B
true
false
case N
true
false
default actions
Introduction to C
L3.22
switch structure (Example)
switch (class) {
case 'B':
case 'b': printf ("Battleship\n");
break;
case 'C':
case 'c': printf ("Cruiser\n");
break;
case 'D':
case 'd': printf ("Destroyer\n");
break;
case 'F':
case 'f': printf ("Frigate\n");
break;
default:
printf ("Unknown ship class%c\n", class);
}
Introduction to C
L3.23
Conditional Operator,
decrement and increment
Operators, Shortcut
assignments
Conditional Operator
• General form:
(booleanExp) ? exp1 : exp2
• Example:
if (x > 0)
y = 1
Ternary operator
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
Introduction to C
L3.25
Increment and
Decrement Operators
suffix
x++; // Same as x = x + 1;
prefix
++x; // Same as x = x + 1;
suffix
x––; // Same as x = x - 1;
prefix
––x; // Same as x = x - 1;
Introduction to C
L3.26
Increment and
Decrement Operators, cont.
int i=10;
int newNum = 10*(i++);
int i=10;
int newNum = 10*(++i);
Equivalent to
Equivalent to
Introduction to C
int newNum = 10*i;
i = i + 1;
i = i + 1;
int newNum = 10*i;
L3.27
Shortcut Assignment
Operators
Operator Example
Equivalent
+=
i+=8
i = i+8
-=
f-=8.0
f = f-8.0
*=
i*=8
i = i*8
/=
i/=8
i = i/8
%=
i%=8
i = i%8
Introduction to C
L3.28
Functions
Functions: Introduction
•
Functions are program modules written to
– avoid the repetition of identical code parts
– solve “a bigger problem” by decomposing it into
“smaller problems”
•
•
Example:
A Function max that delivers the maximum
of two values.
Functions
1. take one or several arguments,
2. compute some statements and
3. return a single value
Introduction to C
L3.30
Function Definition in C
• Syntax
Data type of
the returned
value
Function name Formal
(identifier)
Arguments
data_type identifier (arg_1, arg_2,…) {
local variable declarations
executable statements
}
Introduction to C
L3.31
Function Arguments /
Local Variables
• Syntax of a single formal argument:
data_type identifier
• Local variables are variables that are
known inside a function only
– Different functions may have local
variables with identical names
Introduction to C
L3.32
Scope of Local Variables
• Scope of a variable:
The part of the program where a
variable can be referenced.
• The scope of a local variable starts from
its declaration and continues to the end
of the function that contains the variable.
Introduction to C
L3.33
The return statement
• Functions return a single value using
the return statement.
Syntax:
return expression ;
Introduction to C
L3.34
Example: max function
int max (int i, int j) {
int m;
Local variable
definition
if (i > j)
m = i;
else
m = j;
return m;
}
Introduction to C
L3.35
Function Calls
actual
arguments
• Syntax:
function_name(arg1, arg2, …);
– Actual arguments may be constants,
variables, or expressions.
– Example of function call
max(a, b)
– Example of function call plus assignment
x = max(a, b);
Introduction to C
L3.36
Example Function Call
pass i
void main() {
int a, b, x;
a = 5;
b = 2;
pass j
int max (int i, int j) {
int m;
if (i > j)
m = i;
else
m = j;
return m;
x = max (a, b);
printf("%d", x);
}
}
Introduction to C
L3.37
Example Function Call, cont.
• The values of a and b are copied to i
and j .Graphically:
The main method
a:
5
pass 5
The max method
pass 2
i:
5
parameters
b:
2
x:
5
j:
m:
2
5
return value
Introduction to C
L3.38
Call by Value Semantic
• Because the arguments are copied in C
we talk of a call by value semantic
Introduction to C
L3.39
Function without
Returned Value
• Syntax
void fname (arg1, arg2, …) {
local variable declarations
executable statements
}
• The keyword void indicates that the
function does not return any value
Introduction to C
L3.40
Iterative Programming
• The factorial function can be programmed by a for
loop as follows:
int factorial(int x) {
int prod, i;
prod = 1;
for (i = 1; i <= x; i = i + 1)
prod = prod * i;
}
return prod;
• Such a loop-based solution is called a “iterative
programming”
Introduction to C
L3.41
Recursion
• A function can call itself inside its body.
Example factorial function:
int factorial(int x) {
if (x > 1)
return x * factorial(x - 1);
else
return 1;
Recursive call of factorial
}
• This programming technique is called
Recursion
Introduction to C
L3.42
Computing Factorial, cont.
Main function:
factorial (4)
Step 9: factorial(4) returns 24 (4*6)
factorial(4) is called in the main
factorial (4) = 4*factorial(3)
Step 8: factorial(3) returns 6 (3*2)
Step 1: factorial(4) calls factorial(3)
Step 7: factorial(2) returns 2 (2*1)
factorial (3) = 3*factorial(2)
Step 2: factorial(3) calls factorial(2)
factorial (2) = 2*factorial(1)
Step 6: factorial(1) returns 1 (1*1)
Step 3: factorial(2) calls factorial(1)
factorial (1) = 1*factorial(0)
Step 5: factorial(0) returns 1
Step 4: factorial(1) calls factorial(0)
factorial (0) = 1
Introduction to C
L3.43
Function Declarations
• Function declaration format
return-value-type function-name (arguments'-type);
• return-value-type: data type of the result
(default int)
– void indicates that the function returns nothing
• function-name: any valid identifier
• Arguments' type: comma separated list of
arguments' type
Introduction to C
L3.44
Example: Function declaration
and definition in a program
A function named example that takes 2 arguments of type
double and returns no data, would look like:
double example(double, int);
int main()
{
…
}
double example (double a, int b);
{
…
}
Introduction to C
L3.45
Predefined Library
Functions
• Functions that are implemented as a part of C
toolkit.
Example: printf
• If a library function is used, then the
corresponding header file should be included
at the top of the program using an
appropriate preprocessor directive.
Example:
#include <stdio.h> for printf function.
Introduction to C
L3.46
Some Mathematical Library
Functions Defined in math.h
Function
Purpose
double ceil(double x)
returns the smallest integer greater than x
double exp(double x)
x
returns e
double fabs(double x)
returns the absolute value of x
double floor(double x)
returns the largest integer less than x
double log(double x)
returns the natural logarithm of x
double log10(double x)
returns the base 10 logarithm of x
double sqrt(double x)
returns the square root of x
Introduction to C
L3.47
Some Mathematical Library
Functions Defined in math.h
Function
Purpose
double sin(double x)
returns the sine of x
double cos(double x)
returns the cosine of x
double tan(double x)
returns the tangent of x
double pow(double x,
double y)
y
returns x
Defined in stdlib.h
int abs(int x)
returns the absolute value of x
Introduction to C
L3.48
Programming Technique:
Top-Down Design
• A problem-solving method in which a
given problem is first broken into its
major subproblems.
• Then the subproblems are solved to get
some solution for the original problem
• Subproblems are typically solved by use
of functions.
Introduction to C
L3.49
Example Top-Down Design:
Structure Chart for drawing a
**
* *
Stick
figure
**
/\
/ \
/
\
----/\
/ \
/
\
Draw a figure
Draw a circle
Draw a triangle
Draw intersection lines
Draw intersecting lines
Draw a base line
Introduction to C
L3.50
Program for drawing a stick figure
#include <stdio.h>
/* function declarations (prototypes) */
void draw_circle(void);
void draw_intersect(void);
void draw_base(void);
void draw_triangle(void);
int main() {
/* draw a circle */
draw_circle();
/* draw a triangle */
draw_triangle();
/* draw intersection lines */
draw_intersect();
}
Introduction to C
L3.51
Function Definitions used for Drawing a Stick Figure
/*
Draw a circle
*/
/*
Draw a intersection lines
*/
void draw_circle(void) {
printf(" **\n");
printf(" * *\n");
printf(" **\n");
}
void draw_intersect(void) {
printf(" /\\\n");
printf(" / \\\n");
printf("/
\\\n");
}
/*
Draw a base line
*/
/*
Draw a triangle
*/
void draw_base(void) {
printf ("------\n");
}
void draw_triangle(void) {
draw_intersect();
draw_base();
}
Introduction to C
L3.52