[All]Ppt C Programming New
[All]Ppt C Programming New
Programming in C
1
2 / 393
The Abacus
The abacus, a simple counting aid, may have been
invented in Babylonia (now Iraq) in the fourth century
B.C.
2
3 / 393
Jacquard Loom
3
4 / 393
4
5 / 393
The ENIAC
Vacuum
Tube
5
6 / 393
6
7 / 393
7
8 / 393
The PDP-8
8
9 / 393
The Microprocessor
9
10 / 393
10
11 / 393
Hardware
Hardware – the physical devices that make up a
computer (often referred to as the computer system)
11
12 / 393
Hardware Core
12
13 / 393
13
14 / 393
Software
Programs – instructions that tell
the computer what to do
Categories
Application software - enables you to solve specific
problems or perform specific tasks.
System software - handles tasks specific to technology
management and coordinates the interaction of all
technology devices
Utility software - provides additional functionality to
your operating system software
14
15 / 393
System Software
Operating System
UNIX / Linux
Windows
MAC OS
Palm OS
Android
Language Translators
C, C++, Basic, Java, …
Device Drivers
15
dDwtNzI3 16 / 393
C Programming Language
Developed at AT&T Bell Labs in early 1970s
Unix also developed at Bell Labs
All but core of Unix is in C
Standardized by
American National Standards Institute (ANSI)
16
17 / 393
C Development Environment
17
18 / 393
Execution Environment
Optionally
under control
of a Debugger
18
19 / 393
IDE
Integrated Development Environment
Editor
Compiler
Debugger
Ex:
MS Visual C++
Xcode
19
20 / 393
20
21 / 393
Programming in C
THE END
21
22 / 393
Programming in C
Soon I will
control the world!
Hello World!
1
23 / 393
Introduction to C
C language
Facilitates a structured and disciplined approach to
computer program design
Provides low-level access
Highly portable
2
24 / 393
Program Basics
The source code for a program is the set of instructions
written in a high-level, human readable language.
X = 0;
MOVE 0 TO X.
X := 0
The source code is transformed into object code by a
compiler. Object code is a machine usable format.
The computer executes a program in response to a
command.
3
25 / 393
4. Link Primary
Memory
Loader
5. Load Loader puts program
in memory.
6. Execute Disk ..
..
..
Primary
Memory
CPU CPU takes each
instruction and
executes it, possibly
storing new data
values as the program
..
.. executes.
..
4
26 / 393
Pico:
http://www.bgsu.edu/departments/compsci/docs/pico.html
5
27 / 393
Structure of a C Program
function 1
.
.
.
function n
6
28 / 393
Functions
Each function consists of a header
followed by a basic block.
General format:
7
29 / 393
8
30 / 393
Return statement
return expression
1. Sets the return value to the value of the expression
2. Returns to the caller / invoker
Example:
9
31 / 393
10
32 / 393
cd cpsc1110
Changes the current directory
pico ch02First.c
Runs the pico editor to edit file ch02First.c
11
33 / 393
Go Tigers!!!
12
34 / 393
13
35 / 393
14
36 / 393
Comments
Make programs easy to read and modify
Ignored by the C compiler
Two methods:
1. // - line comment
- everything on the line following // is ignored
2. /* */ - block comment
- everything between /* */ is ignored
15
37 / 393
Introduction to Input/Output
Input data is read into variables
Output data is written from variables.
Initially, we will assume that the user
enters data via the terminal keyboard
views output data in a terminal window on the screen
17
39 / 393
18
40 / 393
Console Input/Output
Defined in the C library included in <stdio.h>
Must have this line near start of file:
#include <stdio.h>
Includes input functions scanf, fscanf, …
Includes output functions printf, fprintf, …
19
41 / 393
20
42 / 393
Console Output
What can be output?
Any data can be output to display screen
Literal values
Variables
Constants
Expressions (which can include all of above)
Note
Values are passed to printf
Addresses are passed to scanf
21
43 / 393
Console Output
We can
Control vertical spacing with blank lines
Use the escape sequence "\n“, new line
Should use at the end of all lines unless you are building lines
with multiple printf’s.
If you printf without a \n and the program crashes, you will not
see the output.
Control horizontal spacing
Spaces
Use the escape sequence “\t”, tab
Sometimes undependable.
22
44 / 393
23
45 / 393
Template: a.c
Starting point for a new program
Read into (^R in pico) or
Copy into (cp command) a new file
Ex: cp a.c prog1.c
25
47 / 393
Programming in C
THE END
26
48 / 393
Programming in C
1
49 / 393
Identifier
Word used to name and refer to a data element
or object manipulated by the program.
2
50 / 393
Examples:
distance
milesPerHour
_voltage
goodChoice
high_level
MIN_RATE
3
51 / 393
4
52 / 393
distance
TAX_RATE CONSTANT
miles_per_hour
milesPerHour
5
53 / 393
Variable
6
54 / 393
Variables Names
C: Must be a valid identifier name
C: Variables must be declared with a name and a data type
before they can be used in a program
Should not be the name of a standard function or variable
Should be descriptive; the name should be reflective of
the variable’s use in the program
For class, make that must be descriptive except subscripts
Abbreviations should be commonly understood
Ex. amt = amount
7
55 / 393
Variable/Named Constant
Declaration Syntax
optional_modifier data_type name_list;
8
56 / 393
9
57 / 393
10
58 / 393
11
59 / 393
Type Name Memory Sample Size Range
Used
www.asciitable.com
12
60 / 393
Any expression
0 is false
Non-zero is true
14
62 / 393
15
63 / 393
Initializing Variables
Initializing variables in declaration statements
16
64 / 393
Assignment Operator =
Assigns a value to a variable
Binary operator (has two operands)
Not the same as "equal to" in mathematics
General Form:
l_value = r_value
Most common examples of l_values (left-side)
A simple variable
A pointer dereference (in later chapters)
r_values (right side) can be any valid expression
Assignment expression has value of assignment
Allows us to do something like
a = b = 0;
17
65 / 393
Means:
Evaluate the expression on the right and put the
result in the memory location named x
If the value stored in y is 18,
then 23 will be stored in x
18
66 / 393
l_value: distance
r_value: rate * time
Other Examples:
19
67 / 393
Go Tigers!
Terminal Output
What can be output?
Any data can be output to standard output (stdout),
the terminal display screen
Literal values
Variables
Constants
Expressions (which can include all of above)
printf function:
The values of the variables are passed to printf
20
68 / 393
21
69 / 393
22
70 / 393
Floating-point Placeholders
%f, %e, %g – for float
%f – displays value in a standard manner.
%e – displays value in scientific notation.
%g – causes printf to choose between %f and %e and to
automatically remove trailing zeroes.
%lf – for double (the letter l, not the number 1)
23
71 / 393
\n is new line
24
72 / 393
25
73 / 393
26
74 / 393
if printf() is successful,
the value in printCount should be 13.
28
76 / 393
29
77 / 393
Integer Constants
Must not contain a decimal point
Must not contain a comma
Examples
-25
68
17895
. ,
30
78 / 393
Integer Constants
May be expressed in several ways
decimal number 120
hexadecimal number 0x78
octal number 0170
ASCII encoded character 'x'
All of the above represent the 8-bit byte
whose value is 01111000
31
79 / 393
Integer Constants
Constants of different representations may be
intermixed in expressions:
Examples
32
80 / 393
33
81 / 393
char Constants
Enclosed in apostrophes, single quotes
Examples:
'a'
'A'
'$'
'2'
'+'
Format specification: %c
34
82 / 393
String Constants
Enclosed in quotes, double quotes
Examples:
"Hello"
"The rain in Spain"
"x"
Format specification/placeholder: %s
35
83 / 393
Terminal Input
We can put data into variables from the standard
input device (stdin), the terminal keyboard
When the computer gets data from the terminal, the
user is said to be acting interactively.
Putting data into variables from the standard input
device is accomplished via the use of the scanf
function
36
84 / 393
37
85 / 393
Addresses in scanf()
Address-list must consist of addresses only
scanf() puts the value read into the memory address
If scanf() is successful,
the value in dataCount should be 2
Spaces or new lines separate one value from another
39
87 / 393
Waits for user input, then stores the input value in the
memory space that was assigned to number.
Note: ‘\n’ was omitted in printf
Prompt ‘waits’ on same line for keyboard input.
Including printf prompt before scanf maximizes
user-friendly input/output
40
88 / 393
scanf Example
41
89 / 393
Input using scanf()
Instead of using scanf() twice,
we can use one scanf() to read both values.
42
90 / 393
Bad Data
43
91 / 393
44
92 / 393
Executable Code
Expressions consist of legal combinations of
constants
variables
operators
function calls
45
93 / 393
Executable Code
Operators
Arithmetic: +, -, *, /, %
Relational: ==, !=, <, <=, >, >=
Logical: !, &&, ||
Bitwise: &, |, ~, ^
Shift: <<, >>
See Expressions
4th Edition: p. 443-450
3rd Edition: p. 439-445
46
94 / 393
Arithmetic
Rules of operator precedence (arithmetic ops):
Average a + b + c / 3 ?
47
95 / 393
Precedence Example
Find the average of three variables a, b and c
Do not use: a + b + c / 3
Use: (a + b + c ) / 3
48
96 / 393
49
97 / 393
5.0 / 2 → 2.5
4.0 / 2.0 → 2.0
17.0 / 5.0 → 3.4
50
98 / 393
7%5 → 2
5%7 → 5
12 % 3 → 0
51
99 / 393
52
100 / 393
Arithmetic Expressions
math expression C expression
a
b
a/b
2x 2*x
x -7
2 3y (x-7)/(2 + 3*y)
53
101 / 393
54
102 / 393
55
103 / 393
Arithmetic Precision
Precision of Calculations
VERY important consideration!
Expressions in C might not evaluate as you ‘expect’!
‘Highest-order operand’ determines type of
arithmetic ‘precision’ performed
Common pitfall!
Must examine each operation
56
104 / 393
Type Casting
Casting for Variables
Can add ‘.0’ to literals to force precision
arithmetic, but what about variables?
We can’t use ‘myInt.0’!
type cast – a way of changing a value of one type to a
value of another type.
Consider the expression 1/2: In C this expression
evaluates to 0 because both operands are of type
integer.
57
105 / 393
Type Casting
1 / 2.0 gives a result of 0.5
58
106 / 393
Type Casting
To get floating point-division, you must do a type cast
from int to double (or another floating-point type),
such as the following:
59
107 / 393
Type Casting
Two types of casting
Implicit – also called ‘Automatic’
Done for you, automatically
17 / 5.5
This expression causes an ‘implicit type cast’ to take place,
casting the 17 17.0
Explicit type conversion
Programmer specifies conversion with cast operator
(double)17 / 5.5
(double) myInt / myDouble
60
108 / 393
Assignment Shortcut
d=d-4 d -= 4
e=e*5 e *= 5
f=f/3 f /= 3
g=g%9 g %= 9
61
109 / 393
Shorthand Operators
Increment & Decrement Operators
Just short-hand notation
Increment operator, ++
intVar++; is equivalent to
intVar = intVar + 1;
Decrement operator, --
intVar--; is equivalent to
intVar = intVar – 1;
62
110 / 393
63
111 / 393
64
112 / 393
Post-Increment in Action
Post-Increment in Expressions:
65
113 / 393
Pre-Increment in Action
Now using pre-increment:
66
114 / 393
Programming in C
THE END
67
115 / 393
Programming in C
1
116 / 393
Example 1
2
117 / 393
Example 2
One solution is to copy and paste the necessary lines
of code. Consider the following modification:
3
118 / 393
4
119 / 393
Repetition (Looping)
Use looping when you want to execute a block of code
several times
Block of code = Body of loop
C provides three types of loops
while statement
1 Most flexible
No ‘restrictions’
for statement
2 Natural ‘counting’ loop
do-while statement
3 Always executes body at least once
5
120 / 393
6
121 / 393
condition is
loop body
retested.
• When the condition
is false, the loop is
exited. next stmt
7
122 / 393
1
The while Repetition Structure
Syntax:
while (expression)
basic block
8
123 / 393
9
124 / 393
Counter-Controlled Repetition
Requires:
1. Counter variable , LCV, initialized to beginning value
2. Condition that tests for the final value of the counter
(i.e., whether looping should continue)
3. Constant increment (or decrement) by which the
control variable is modified each time through the
loop
Definite repetition
Loop executes a specified number of times
Number of repetitions is known
10
125 / 393
Example 3
EXECUTION CHART
count count<5 repetition
0 true 1
1 true 2
2 true 3
3 true 4
4 true 5
5 false
11
126 / 393
Loop Pitfalls
12
127 / 393
13
128 / 393
true
loop body
…
increment
next stmt
14
129 / 393
15
130 / 393
16
131 / 393
If n is initially 1, the above statement will print the value 1 and then
add 1 to n. After execution, n will have the value 2.
17
132 / 393
18
133 / 393
2
The for Repetition Structure
Syntax:
19
134 / 393
20
135 / 393
21
136 / 393
Bite 1 -- Yum!
Bite 2 -- Yum!
Bite 3 -- Yum!
22
137 / 393
loop body
true
condition
false
23
138 / 393
3
The do-while Repetition Structure
Syntax:
do {
statements
} while ( condition );
24
139 / 393
25
140 / 393
26
141 / 393
27
142 / 393
28
143 / 393
Programming in C
THE END
29
144 / 393
Programming in C
1
145 / 393
Looping Subtasks
We will examine some basic algorithms that use the
while and if constructs. These subtasks include
Reading unknown quantity of data
Counting things
Accumulating (summing) totals
Searching for specific values
Finding extreme values
2
146 / 393
Looping Subtasks
Examples will be based upon common models:
Priming Read or Input Count
Initialize program state Initialize program state
Read the first value (priming read) While (input count OK)
While (data exists) update program state as needed
update program state as needed Output final state
read next value(s)
Output final state
3
147 / 393
Counter-Controlled Repetition
Number of items is known before loop
4
148 / 393
Sentinel-Controlled Repetition
One way to handle an arbitrary number of
input values is to have the user enter a
special value to indicate the end of input.
Such a value is a sentinel value.
Indicates end of valid input
25
Loop ends when sentinel value is read 43
Must choose a sentinel value that cannot be 67
confused with a regular input value. 96
12
58
44
-1
5
149 / 393
Sentinel-Controlled Loop
using Priming Read
25
43
67
96
12
58
44
-1
7
151 / 393
Sentinel-Controlled Loop
using Input Count
25
43
67
96
12
58
44
-1
8
152 / 393
9
153 / 393
10
154 / 393
End of Data
Hardware & Software
End-Of-File
Keyboard
Ctrl-d (Does not work on Mac!)
25 43
67 96
12 58
44 99
Ctrl-d The End Is Here!
11
155 / 393
Redirection
Redirection: Read / Write to actual file
stdin: cmd < input-file
Ex: ./a.out < nums.txt
stdout: cmd > output-file
Ex: ./a.out > report.txt
stdout (append): cmd >> output-file
Ex: ./a.out >> report.txt
Both: cmd < input-file > output-file
Ex: ./a.out < nums.txt > report.txt
Leave out prompts when designing for redirection
12
156 / 393
13
157 / 393
25
43
67
96
12
58
44
14
158 / 393
15
159 / 393
Detecting End-of-File
Function: feof
Syntax: feof(file-pointer)
Returns true or false
Standard input: feof(stdin)
Use in a while loop -
while (!feof(stdin))
16
160 / 393
17
161 / 393
18
162 / 393
19
163 / 393
20
164 / 393
21
165 / 393
22
166 / 393
23
167 / 393
Counting Example
What if we want to print the number of passing scores
(scores >= 70)?
We need a mechanism that allows us to count only if the
score is greater than or equal to 70
Use if stmt
24
168 / 393
25
169 / 393
Counting Example
What if we want to print the number of passing scores
(scores >= 70) and the number of failing scores?
Use if -else
26
170 / 393
27
171 / 393
Looping Subtask:
Accumulation (Summing)
28
172 / 393
Accumulating Example
29
173 / 393
30
174 / 393
31
175 / 393
32
176 / 393
Searching Exercise
Write a C program that
1. Reads a target score at the beginning of the file
2. Reads a set of scores and determines if the target
score is in the set of scores
3. If found prints
Target ## was found
otherwise prints
Target ## was not found
33
177 / 393
34
178 / 393
Searching Improvement
Stop searching if target has been found
35
179 / 393
25
43 96 is the max
67 12 is the min
96
12
58
44
36
180 / 393
37
181 / 393
Extremes Exercise
Write a C program that
1. Reads a set of scores from a file
2. Determines and prints the maximum score
38
182 / 393
39
183 / 393
Programming in C
THE END
40
184 / 393
Programming in C
1
185 / 393
Flow of Control
Flow of control
The order in which statements are executed
Transfer of control
When the next statement
executed is not the next
one in sequence
2
186 / 393
Flow of Control
Control structures
combination of individual statements into a logical unit
that regulates the flow of execution in a program or
function
Sequence
Selection (Making Decisions)
Repetition (Looping)
3
187 / 393
Boolean Expressions
Evaluate to true or false
Forms
Relational expression: <expr> <relational operator> <expr>
Examples:
7 < 5
a + b > 6
Logical expression: <Boolean expr> <logical operator> <Boolean expr>
Examples:
(x < 7) && (y > 3)
4
188 / 393
Relational Operators
Standard Algebraic C Relational C Condition
Relational Operator Operator Example Meaning of C Condition
Inequality
< < x<y x is less than y
<= x <= y x is less than or equal to y
> > x>y x is greater than y
>= x >= y x is greater than or equal to y
Equality
= == x == y x is equal to y
!= x != y x is not equal to y
4th: Ch 4 p. 46
3rd: Ch 5 p. 46
5
189 / 393
|| (logical OR)
Returns true if either of its conditions is true
6
190 / 393
7
191 / 393
Precedence of Operators
1. (), []
2. Unary +, unary -, !, ++, --
3. Type casting
4. * , / , %
5. + , -
6. <, <=, >, >=
7. ==, !=
8. &&
9. ||
10. =
8
192 / 393
9
193 / 393
true
Boolean
Expression
10
194 / 393
if (Boolean Expression)
{
statement1;
statement2;
...
}
11
195 / 393
if
Only performs an action if the condition is true
if-else
A different action is performed when condition is
true and when condition is false
12
196 / 393
false true
Boolean
Expression
13
197 / 393
15
199 / 393
16
200 / 393
18
202 / 393
19
203 / 393
• The statement,
21
205 / 393
22
206 / 393
if-else Construct
To avoid confusion, and possible errors, it is best to
use braces even for single statements.
However, code will be longer
23
207 / 393
Conditionals
C uses an integer to represent Boolean values
Zero is interpreted as false
Any other integer value is interpreted as true
24
208 / 393
Conditionals
is not a syntax error in C.
The expression, n = 0, assigns zero to n and the value of
the expression is 0. Zero is interpreted as false, and the
false branch of the if statement will be taken.
is not a syntax error in C.
The expression assigns 5 to n. 5 is interpreted as true,
and the true branch of the if statement will be taken.
25
209 / 393
Conditionals
Remember to use the == operator to test for equality.
To help catch the error when the equality check
involves a constant, put the constant on the left hand
side of the ==.
For example, use
instead of
Since is not a valid assignment in C, the compiler
will detect this error when == is intended.
26
210 / 393
27
211 / 393
default action(s)
28
212 / 393
default action(s)
29
213 / 393
30
214 / 393
switch Statement
The switch_expression is compared against the values
constant1, constant2, …, constantN
constant1, constant2, …, constantN must be simple
constants or constant expressions.
Can be a char or an int
Best to use the same type constant as the switch expression
If not, a type conversion will be done.
31
215 / 393
32
216 / 393
Example of
switch
33
217 / 393
Programming in C
THE END
34
218 / 393
Programming in C
1
219 / 393
Introduction to Arrays
A collection of variable data
Same name
Same type
Contiguous block of memory
Can manipulate or use
Individual variables or
‘List’ as one entity
Celsius
temperatures:
I’ll name it c.
Type is int.
2
220 / 393
Introduction to Arrays
Used for lists of like items
Scores, speeds, weights, etc.
Avoids declaring multiple simple variables
Used when we need to keep lots of values in memory
Sorting
Determining the number of scores above/below the
mean
Printing values in the reverse order of reading
Etc.
3
221 / 393
Declaring Arrays
General Format for declaring arrays
<data type> <variable> [<size>];
Declaration
Declaring the array allocates memory
Static entity - same size throughout program
Examples
Type is int.
Name is c.
4
222 / 393
5
223 / 393
6
224 / 393
7
225 / 393
8
226 / 393
scores [0]
scores [1]
… subscript/index
scores [11]
9
227 / 393
10
228 / 393
11
229 / 393
12
230 / 393
Score 1 is 56 Score 12 is 87
Score 2 is 52 Score 11 is 97
Score 3 is 80 Score 10 is 86
Score 4 is 74 Score 9 is 80
... ...
Score 12 is 87 Score 1 is 56
13
231 / 393
14
232 / 393
15
233 / 393
Initializing Arrays
Arrays can be initialized at declaration
16
234 / 393
Auto-Initializing Arrays
If fewer values than size supplied:
Fills from beginning
Fills 'rest' with zero of array base type
Declaration
Performs initialization
17
235 / 393
Auto-Initializing Arrays
If array size is left out
Declares array with size required based on number of
initialization values
Example:
18
236 / 393
Multidimensional Arrays
Arrays with more than one dimension
Declaration: Additional sizes each enclosed in brackets
Two dimensions
Table or ‘array of arrays’
19
237 / 393
Initializing
Multidimensional
Nested lists
Unspecified values set to zero
2D Example:
20
238 / 393
Three-dimensional Visualization
21
239 / 393
22
240 / 393
Programming in C
THE END
23
241 / 393
Programming in C
1
242 / 393
2
243 / 393
3
244 / 393
4
245 / 393
Loading an Array
Be careful not to overfill
Do not read directly into array elements
5
246 / 393
6
247 / 393
Safer 2D Load
7
248 / 393
Searching an Array
Linear search
Simple
Binary search
Requires sorted array
74?
Generally faster for
large arrays
May require the use of
an indicator to denote
found or not found
8
249 / 393
9
250 / 393
10
251 / 393
Sorting
Place array into some
order
Ascending or descending
Many types
Simple: Selection
More intelligent: Bubble,
selection, insertion, shell,
comb, merge, heap, quick,
counting, bucket, radix,
distribution, timsort,
gnome, cocktail, library,
cycle, binary tree, bogo,
pigeonhole, spread, bead,
pancake, …
11
252 / 393
Selection Sort
Compare element to all elements below and then
move to next element, swap when appropriate
12
253 / 393
Bubble/Sinking Sort
Compare adjacent elements, swap when appropriate
Stop if no swaps on a pass
13
254 / 393
14
255 / 393
Extremes
Same techniques as chapter 5 – best:
Assume first is extreme
Compare others to current extreme
Replace extreme when finding new extreme
15
256 / 393
16
257 / 393
Programming in C
THE END
17
258 / 393
Programming in C
main
Level 3 Level 3
1
259 / 393
Programmer-Defined Functions
Modularize with building blocks of programs
Divide and Conquer
Construct a program from smaller pieces or components
Place smaller pieces into functions
Pieces are more manageable than one big program
Makes other functions smaller
Pieces can be independently implemented and tested
2
260 / 393
Programmer-Defined Functions
Readability
Function name should indicate operations performed
Reuse
Functions may be used multiple times in same program
Functions may be used in other programs
3
261 / 393
2. Function definition
3. Function call
Either prototype or definition must come first
4
262 / 393
1. Function Declaration/Prototype
An ‘informational’ declaration for compiler
Tells compiler how to interpret calls
Syntax:
<return_type> FnName(<formal-parameter-list>);
Example:
6
264 / 393
Function Declaration/Prototype
Placed before any calls
Generally above all functions in global space
May be placed in declaration space of calling function
Example
7
265 / 393
Example
8
266 / 393
2. Function Definition
Actual implementation/code for what function does
Just like implementing function main()
General format – header & basic block:
<return-type> fn-name (parameter-list) header
basic block
Example:
9
267 / 393
Return Statements
Syntax: return return-value-expression
Two actions
Sets return value
Transfers control back to 'calling' function
Good programming & course requirement:
One return per function
Return is last statement
10
268 / 393
3. Function Call
Using function name transfers control to function
1. Values are passed through parameters
2. Statements within function are executed
3. Control continues after the call
For value-returning functions, either
Store the value for later use
11
269 / 393
Parameters (Arguments)
Formal parameters/arguments
In function declaration
In function definition's header
'Placeholders' for data sent in
'Variable name' used to refer to data in definition of
function
Actual parameters/arguments
In function call
12
270 / 393
Parameter! Argument!
13
271 / 393
14
272 / 393
Return-type is 'void'
15
273 / 393
16
274 / 393
17
275 / 393
Function documentation
Used to aid in program maintenance
Comments at non-main definition header
Purpose of function
Parameters
Return
Class standard example:
18
276 / 393
main(): ‘Special’
Recall: main() IS a function
'Special'
It is the first function executed
Called by operating system or run-time system
Can return value to operating system
Value can be tested in command scripts
19
277 / 393
20
278 / 393
Scope Rules
Local variables preferred
Maintain individual control over data
Need to know basis (Hidden)
Functions should declare whatever local data
needed to 'do their job'
21
279 / 393
Global Scope
Names declared 'outside' function bodies
Global to all functions in that file
Global declarations typical for constants:
Declare globally so all functions have scope, can use
22
280 / 393
23
281 / 393
Block Scope
Declare data inside nested blocks
Has 'block-scope'
Note: All function definitions are blocks!
24
282 / 393
Lifetime
How long does it last
Allocation Deallocation
Normally variables are allocated when defined
Normally variables are deallocated at the end of block
25
283 / 393
26
284 / 393
Programming in C
THE END
27
285 / 393
Programming in C
1
286 / 393
Structures
A structure can be used to define a new data type that
combines different types into a single (compound) data
type
Definition is similar to a template or blueprint
Composed of members of previously defined types
1) Struct variable
A variable structure definition defines a struct variable
Member names
3
288 / 393
2) Tagged Structure
A tagged structure definition defines a type
We can use the tag to define variables, parameters, and return types
Structure tag
Member names
Variable definitions:
4
289 / 393
3) Typedef Structure
A typed-defined structure allows the definition of variables without
the struct keyword.
We can use the tag to define variables, parameters, and return types.
Variable definition:
6
291 / 393
7
292 / 393
Nested Structures
A member that is of a structure type is nested
8
293 / 393
Initializing Structures
A structure may be initialized at the time it is declared
Order is essential
The sequence of values is used to initialize the
successive variables in the struct
It is an error to have more initializers than members
If fewer initializers than members, the initializers
provided are used to initialize the data members
The remainder are initialized to 0 for primitive types
9
294 / 393
10
295 / 393
11
296 / 393
Arrays of Structures
We can also create an array of structure types
12
297 / 393
13
298 / 393
Structures as Parameters
A struct, like an int, may be passed to a function
The process works just like passing an int, in that:
The complete structure is copied to the stack
Called function is unable to modify
the caller's copy of the variable
14
299 / 393
Structures as Parameters
15
300 / 393
Structures as Parameters
Disadvantage of passing structures by value:
Copying large structures onto stack
Is inefficient
May cause stack overflow
16
301 / 393
17
302 / 393
18
303 / 393
19
304 / 393
20
305 / 393
Return Structure
Scalar values (int, float, etc) are efficiently returned in
CPU registers
Historically, the structure assignments and the return
of structures was not supported in C
But, the return of pointers (addresses), including
pointers to structures, has always been supported
21
306 / 393
23
308 / 393
24
309 / 393
25
310 / 393
26
311 / 393
Programming in C
THE END
27
312 / 393
Programming in C
1
313 / 393
2
314 / 393
3
315 / 393
4
316 / 393
Traversing Records
5
317 / 393
ch08PayType.h
6
318 / 393
ch08Pay.c
7
319 / 393
8
320 / 393
9
321 / 393
10
322 / 393
11
323 / 393
Programming in C
THE END
12
324 / 393
Programming in C
1
325 / 393
Strings
“Hello” is string
We’ve used strings literal constant
2
326 / 393
3
327 / 393
String Variable
Typically a partially filled array
Declare large enough to hold max-size string, including
the null character.
Given a standard array:
4
328 / 393
5
329 / 393
IS same as:
6
330 / 393
String Indexes
A string IS an array
Can access indexed variables of:
hi[0] is ‘H’
hi[1] is ‘i’
hi[2] is ‘\0’
hi[3] is unknown
hi[4] is unknown
7
331 / 393
Be careful!
Here, ‘\0’ (null) was overwritten by a ‘!’
If null overwritten, string no longer ‘acts’ like a string!
Unpredictable results!
8
332 / 393
String Library
Used for string manipulations
Normally want to do ‘fun’ things with strings
Requires library string.h:
http://en.wikipedia.org/wiki/String.h
9
333 / 393
10
334 / 393
= with strings
Strings are not like other variables, they are arrays
Cannot assign:
11
335 / 393
== with strings
Cannot use operator == to compare
12
336 / 393
13
337 / 393
14
338 / 393
Functions in stdio.h
15
339 / 393
16
340 / 393
17
341 / 393
String variable
18
342 / 393
String variable
Use stdin for now
String Input: fgets
char *fgets (char * strPtr, int size, FILE *fp)
Inputs characters from the specified file pointer
through \n or until specifed size is reached
Puts newline (\n) in the string if size not reached!!!
Appends \0 at the end of the string
If successful, returns the string & places in argument
19
343 / 393
String variable or constant
20
344 / 393
String variable
Use stdout for now
String Output: fputs
int fputs (const char *strPtr, FILE *fp)
Takes a null-terminated string from memory and writes
it to the specified file pointer
Drops \0
Programmer's responsibility: Make sure the newline is
present at the appropriate place(s)
21
345 / 393
Programming in C
THE END
22
346 / 393
Programming in C
1
347 / 393
Pointer Variable
A variable that stores a memory address
Allows C programs to simulate call-by-reference
Allows a programmer to create and manipulate dynamic
data structures
Must be defined before it can be used
Should be initialized to NULL or valid address
2
348 / 393
Declaring Pointers
Declaration of pointers
<type> *variable
<type> *variable = initial-value
Examples:
3
349 / 393
Pointers
A pointer variable has two associated values:
Direct value
address of another memory cell
Referenced by using the variable name
Indirect value
value of the memory cell whose address is the pointer's
direct value.
Referenced by using the indirection operator *
4
350 / 393
Pointer Operators
Come before a variable name
* operator
Indirection operator or dereferencing operator
Returns a synonym, alias or nickname to which its operand points
& operator
Address of operator
Returns the address of its operand
5
351 / 393
Pointer Variables
One way to store a value in a pointer variable
is to use the & operator
6
352 / 393
Pointer Variables
Assume count will be stored in memory at location
700 and countPtr will be stored at location 300
causes 5 to be stored in count
causes the address of count to be stored in countPtr
7
353 / 393
Pointer Variables
We represent this graphically as
8
354 / 393
Pointer Variables
The indirection / dereferencing operator is *
stores the value 10 in the address pointed to by countPtr
9
355 / 393
Pointer Variables
The character * is used in two ways:
10
356 / 393
Simulating By Reference
Invoked function uses * in formal parameters
11
357 / 393
The compiler will know how many bytes to copy into the
memory location pointed to by xPtr
Defining the type that the pointer points to permits a
number of other interesting ways a compiler can
interpret code
12
358 / 393
13
359 / 393
14
360 / 393
15
361 / 393
16
362 / 393
17
363 / 393
18
364 / 393
19
365 / 393
Pointers and
Dynamic Allocation of Memory
So far, we have always allocated memory for
variables that are located on the stack
Size of such variables must be known at compile time
Sometimes convenient to allocate memory at run
time
System maintains a second storage area called the heap
Functions calloc and malloc allocate memory as needed
of size needed
20
366 / 393
Pointers and
Dynamic Allocation of Memory
1. Use allocating function (such as malloc(),
calloc(), etc.)
Returns void pointer
void * indicates a pointer to untyped memory
Will have to cast the returned value to the specific type needed
21
367 / 393
Pointers and
Dynamic Allocation of Memory: calloc
calloc
Used to dynamically create an array in the heap
Contiguous allocation
Initialized to binary zeros
Must
Takes two arguments
1. Number of array elements
2. Amount of memory required for one element
Use sizeof function / operator
Returns
Void pointer if successful
NULL if unsuccessful
22
368 / 393
Pointers and
Dynamic Allocation of Memory: calloc
Example 1: String
Example 2: Integers
23
369 / 393
Pointers and
Dynamic Allocation of Memory: malloc
malloc
Used to dynamically get memory from heap
Contiguous allocation
No initialization
Must
Takes one argument
Total amount of memory required
Returns
Void pointer if successful
NULL if unsuccessful
24
370 / 393
Pointers and
Dynamic Allocation of Memory: malloc
Example 1: String
Example 2: Integers
25
371 / 393
Pointers and
Dynamic Allocation of Memory: free
free
Used to dynamically release memory back to heap
Contiguous deallocation
Must
Takes one argument
Pointer to beginning of allocated memory
Good idea to also NULL pointer if reusing
26
372 / 393
Pointers and
Dynamic Allocation of Memory: free
Example 2 with free
27
373 / 393
Programming in C
THE END
28
374 / 393
Programming in C
Input Output
1
375 / 393
2
376 / 393
Files
A collection of related data treated as a unit
Two types
Text
Binary
Stored in secondary storage devices
Buffer
Temporary storage area that holds data while they are
being transferred to or from memory.
3
377 / 393
Text Files
Data is mainly stored as human-readable characters
Each line of data ends with a newline character
= \n
C666666666 20 8.55
A222222222 50 12.5
F333333333 45 8.5
B444444444 50 9
G555555555 30 6
E111111111 40 10
H777777777 40 12
D888888888 40 11.11
I999999999 45 15
4
378 / 393
5
379 / 393
6
380 / 393
2. fopen
FILE * fopen(char * filename, char * mode)
Parameters
filename – string that supplies the name of the file as
known to the external world
Default path is current directory
mode Meaning
r Open file for reading
• If file exists, the marker is positioned at beginning
fopen
FILE * fopen(char * filename, char * mode)
Return
If successful, file pointer
If not successful, NULL
Always check return
If not successful, print error message and exit
or some other corrective action
8
382 / 393
fopen
FILE * fopen(char * filename, char * mode)
Examples
9
383 / 393
4. fclose
int fclose(FILE *fp)
Used to close a file when no longer needed
Prevents associated file from being accessed again
Guarantees that data stored in the stream buffer is
written to the file
Releases the FILE structure so that it can be used with
another file
Frees system resources, such as buffer space
Returns zero on success, or EOF on failure
10
384 / 393
fclose
Examples:
11
385 / 393
3. Input/Output Functions
Formatted Input
fscanf
Formatted Output
fprintf
String Input
fgets
String Output
fputs
12
386 / 393
Input
13
387 / 393
Output
14
388 / 393
Input
String Input
Reminder: Watch size of string
Must be large enough to hold largest input string
Plus \n perhaps
Plus \0 perhaps
C generally gives no warning of this issue
Standard Input
getchar: Read one character and return value as int
int getchar()
gets(): Read line & convert \n to \0, no size check
char *gets (char *strPtr)
15
389 / 393
Input
16
390 / 393
Output
String Output
Standard Output
putchar: Write one character
int putchar(int outChar)
puts(): Write line & converting \0 to \n
int puts (const char *strPtr)
17
391 / 393
Output
18
392 / 393
19
393 / 393
Programming in C
THE END
20