0% found this document useful (0 votes)
2 views

[All]Ppt C Programming New

The document outlines the agenda for a programming course in C, detailing chapters and topics covered over 393 pages. It includes an introduction to C, programming basics, data structures, functions, and file input/output. Additionally, it provides insights into the history of computing and the structure of C programs, along with practical examples and commands for compiling and running programs.

Uploaded by

Bí Danh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

[All]Ppt C Programming New

The document outlines the agenda for a programming course in C, detailing chapters and topics covered over 393 pages. It includes an introduction to C, programming basics, data structures, functions, and file input/output. Additionally, it provides insights into the history of computing and the structure of C programs, along with practical examples and commands for compiling and running programs.

Uploaded by

Bí Danh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 395

AGENDA

Chapter 1: Introduction to C 21 pages: 1 -> 21 /393


Chapter 2: Your first program 26 pages: 22 -> 47 /393
Chapter 3: Variables and Expressions 67 pages: 48 -> 114 /393
Chapter 4A: Repetition/Looping 29 pages: 115 -> 143 /393
Chapter 4B: Looping Subtasks 40 pages: 144 -> 183 /393
Chapter 5: Making Decisions 34 pages: 184 -> 217 /393
Chapter 6A: Arrays 23 pages: 218 -> 240 /393
Chapter 6B: Array Subtasks 17 pages: 241 -> 257 /393
Chapter 7: Programmer-Defined Functions 27 pages: 258 -> 284 /393
Chapter 8: Structures 27 pages: 285 -> 311 /393
Chapter 8A: Payroll Lookup using Structure 12 pages: 312 -> 323 /393
Chapter 9: Strings 22 pages: 324 -> 345 /393
Chapter 10: Pointers 28 pages: 346 -> 373 /393
Chapter 15: File Input/ Output 20 pages: 374 -> 393 /393
Buổi 1 (3t): Tổng quan về ngôn ngữ lập trình và phương pháp lập trình
Chapter 1: Introduction to C 21 pages
Chapter 2: Your first program 26 pages
Buổi 2 (3t): Các thành phần trong ngôn ngữ C
Chapter 3: Variables and Expressions 67 pages
Buổi 3 (3t): Cấu trúc rẽ nhánh có điều kiện
Chapter 5: Making Decisions 34 pages
Buổi 4,5 (6t): Cấu trúc lặp
Chapter 4A: Repetition/Looping 29 pages
Chapter 4B: Looping Subtasks 40 pages
Buổi 6 (3t) Lập trình với hàm
Chapter 7: Programmer-Defined Functions 27 pages
Buổi 7,8 (6t) Mảng, con trỏ và chuỗi ký tự
Chapter 6A: Arrays 23 pages
Chapter 6B: Array Subtasks 17 pages
Chapter 10: Pointers 28 pages
Chapter 9: Strings 22 pages
Buổi 9 (3t): Kiểu dữ liệu cấu trúc
Chapter 8: Structures 27 pages
Chapter 8A: Payroll Lookup using Structure 12 pages
Buổi 10 (3t): Tập tin
Chapter 15: File Input/ Output 20 pages
1 / 393

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

Babbage Difference Engine, reconstructed by


the British Government in 1991.

4
5 / 393

The ENIAC

Vacuum
Tube

5
6 / 393

The size of a cell phone built with


Vacuum Tubes

6
7 / 393

The IBM 360

7
8 / 393

The PDP-8

8
9 / 393

The Microprocessor

 A computer chip that


contains on it the entire CPU
 Mass produced at a very low
price
 Computers become smaller and
cheaper
 Intel 4004 – the first
computer on a chip, more
powerful than the original
ENIAC.
 Intel 8088 – used in IBM PC

9
10 / 393

Famous Quotes about Computers


 “I think there is a world market for maybe five
computers.” – Thomas Watson, chairman of IBM,
1943
 “There is no reason anyone in the right state of
mind will want a computer in their home.” – Ken
Olson, President of Digital Equipment Corp, 1977.

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

 CPU (Central Processing Unit)


 CPU (machine) cycle – retrieve, decode, and execute
instruction, then return result to RAM if necessary
 CPU speed measured in gigahertz (GHz)
 GHz – number of billions of CPU cycles per second
 RAM (Random Access Memory)
 Also called Memory, Main Memory, or Primary Storage
 Measured in gigabytes (GB, billions of bytes) today
 Byte → Character
 RAM is volatile
 Temporary storage for instructions and data

12
13 / 393

Capacity of Secondary Storage Devices


 Kilobyte (KB or K) – about 1 thousand bytes
 Megabyte (MB or M or Meg) – about 1 million bytes
 Gigabyte (GB or Gig) – about 1 billion bytes
 Terabyte (TB) – about 1 trillion bytes

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

Best Programming Language?

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

Basics of a Typical C Environment


Program is created in
Editor Disk the editor and stored
on disk.
Phases of C Programs:
Preprocessor Preprocessor program
Disk processes the code.
1. Edit
Compiler creates
Compiler object code and stores
2. Preprocess Disk
it on disk.
Linker links the object
3. Compile Linker Disk
code with the libraries,
creates a.out and
stores it on disk

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

GCC Program Basics


 The basic program writing sequence:
1. create or modify a file of instructions using an editor
 Unix: Pico, vi, gEdit, emacs, …
2. compile the instructions with GCC
3. execute or run the compiled program
 repeat the sequence if there are mistakes

Pico:
http://www.bgsu.edu/departments/compsci/docs/pico.html

5
27 / 393

Structure of a C Program

Every C program must


main function
have a main function

function 1
.
.
.

function n

6
28 / 393

Functions
 Each function consists of a header
followed by a basic block.
 General format:

<return-type> fn-name (parameter-list) header


basic block

7
29 / 393

The Basic Block


{
declaration of variables
executable statements
}

 A semi-colon (;) is used to terminate a statement


 A block consists of zero or more statements
 Nesting of blocks is legal and common
 Each interior block may include variable declarations

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

SSH Secure Shell


 On-Campus / VPN  Off-Campus
 SSH to one of the  SSH to access.cs.clemson.edu
machines in the list  ssh machine.cs.clemson.edu
 machine.cs.clemson.edu

10
32 / 393

Unix Commands: mkdir & cd


mkdir cpsc1110
 Creates a new directory / folder

cd cpsc1110
 Changes the current directory

pico ch02First.c
 Runs the pico editor to edit file ch02First.c

11
33 / 393

Our First Program

Go Tigers!!!
12
34 / 393

Compiling and Running a Program


 To compile and print all warning messages, type
gcc –Wall prog-name.c

 If using math library (math.h), type


After
gcc –Wall prog-name.c -lm

 By default, the compiler produces the file a.out

13
35 / 393

Compiling and Running a Program


 To execute the program type
./a.out
 The ./ indicates the current directory
 To specify the file for the object code,
for example, p1.o, type
gcc –Wall prog1.c –o p1.o
then type
./p1.o
to execute the program

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

Preprocessor Directive: #include


 A C program line beginning with # that is processed by
the compiler before translation begins.
 #include pulls another file into the source

 causes the contents of the


named file, stdio.h, to be inserted where the #
appears. File is commonly called a header file.
 <>’s indicate that it is a compiler standard header file.
 causes the contents of
myfunctions.h to be inserted
 “’s indicate that it is a user file from current or specified
directory
#include: Chapter 12 p. 311
16
38 / 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

Program Input / Output


 The C run-time system automatically opens two files
for you at the time your program starts:
 stdin – standard input (from the keyboard)
 stdout – standard output (to the terminal window in
which the program started)
 Later, how to read and write files on disk
1. Using stdin and stdout
2. Using FILE’s

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

Console Output - printf


 Print to standard output,
typically the screen
 General format (value-list may not be required):
printf("format string", value-list);

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

Terminal Output - Examples

 Sends string "Hello World" to display, skipping to next


line

 Displays the lines


Good morning
Ms Smith.

23
45 / 393

Program Output: Escape Character \


 Indicates that a “special” character is to be output
Escape Description
Sequence
\n Newline. Position the screen cursor to the beginning of
the next line.
\t Horizontal tab. Move the screen cursor to the next tab
stop.
\r Carriage return. Position the screen cursor to the
beginning of the current line; do not advance to the next
line.
\a Alert. Sound the system bell.

\\ Backslash. Used to print a backslash character.

\" Double quote. Used to print a double quote character.


24
46 / 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

Reserved Words and Identifiers


 Reserved word
 Word that has a specific meaning in C
 Ex: int, return

 Identifier
 Word used to name and refer to a data element
or object manipulated by the program.

2
50 / 393

Valid Identifier Names


 Begins with a letter or underscore symbol
 Consists of letters, digits, or underscores only
 Cannot be a C reserved word
 Case sensitive
 Total ≠ total ≠ TOTAL

 Examples:
distance
milesPerHour
_voltage
goodChoice
high_level
MIN_RATE
3
51 / 393

Invalid Identifier Names


 Does not begin with a letter or underscore symbol or
 Contains other than letters, digits, and underscore or
 Is a C reserved word
 Examples
x-ray
2ndGrade
$amount
two&four
after five
return

4
52 / 393

Identifier Name Conventions


 Standard practice, not required by C language
 Normally lower case
 Constants upper case
 Multi-word
 Underscore between words or
 Camel case - each word after first is capitalized

distance
TAX_RATE CONSTANT
miles_per_hour
milesPerHour

5
53 / 393

Variable

 Name is a valid identifier name


 Is a memory location where a value can be stored for
use by a program
 Value can change during program execution
 Can hold only one value
 Whenever a new value is placed into a variable, the
new value replaces the previous value.

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;

 optional_modifier – type modifier

 Used to distinguish between signed and unsigned integers

 The default is signed

 Used to specify size (short, long)

 Used to specify named constant with const keyword


 data_type - specifies the type of value; allows the compiler to
know what operations are valid and how to represent a
particular value in memory
 name_list – program identifier names
 Examples:
int test-score;
const float TAX_RATE = 6.5;

8
56 / 393

Numeric Data Types

Whole numbers Real numbers


(Integer) (Floating-point)

short int long float double long double

9
57 / 393

Data Types and Typical Sizes


Type Name Memory Size Range Precision Guarantee
Used
short 2 bytes -32,768 to 32,767 N/A 16 bits
(= short int)
int 4 bytes -2,147,483,648 to N/A 16 bits
2,147,483,647

long 8 bytes -9,223,372,036,854,775,808 to N/A 32 bits


(= long int) 9,223,372,036,854,775,807

float 4 bytes approximately 7 digits 6 digits


10-38 to 1038
double 8 bytes approximately 15 digits 10 digits
10-308 to 10308

long double 10 bytes approximately 19 digits 10 digits


10-4932 to 104932

10
58 / 393

Determining Data Type Size


 sizeof operator
 Returns size of operand in bytes
 Operand can be a data type
 Examples:

11
59 / 393
Type Name Memory Sample Size Range
Used

Characters char 1 byte All ASCII characters

ASCII = American Standard Code for Information Interchange

www.asciitable.com
12
60 / 393

Boolean Data Type


 Data type: _Bool
 Can only store 0 & 1
 Non zero value will be stored as 1
 Data type : bool
 <stdbool.h> defines bool, true, and false

 Any expression
 0 is false
 Non-zero is true

Basic Data Types: Table 4.1 p. 30


More types: Table A.4 p. 431
13
61 / 393

Variable Declaration Examples

14
62 / 393

Assigning Values to Variables


 Allocated variables without initialization have an
undefined value.
 We will use three methods
for assigning a value to a variable
 Initial value
 In the declaration statement
 Processing
 the assignment statement
 Input
 scanf function

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

Example Assignment Statement


 Statement 5 is literal value
or constant

 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

Other Example Assignments


 Example:

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

Syntax: printf function


printf(format_string, expression_list)

 Format_string specifies how expressions are to be


printed
 Contains placeholders for each expression
 Placeholders begin with % and end with type
 Expression list is a list of zero or more expressions
separated by commas
 Returns number of characters printed

21
69 / 393

Typical Integer Placeholders


 %d or %i - for integers, %l for long

 %o - for integers in octal

 %x – for integers in hexadecimal

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

Printing the value of a variable


 We can also include literal values that will appear in the
output.
 Use two %’s to print a single percent

\n is new line

24
72 / 393

Output Formatting Placeholder


%[flags][width][.precision][length]type
 Flags
- left-justify
+ generate a plus sign for positive values
# puts a leading 0 on an octal value and 0x on
a hex value
0 pad a number with leading zeros
 Width
 Minimum number of characters to generate
 Precision
 Float: Round to specified decimal places

25
73 / 393

Output Formatting Placeholder


%[flags][width][.precision][length]type
 Length
l long
 Type
d, i decimal unsigned int
f float
x hexadecimal
o octal
% print a %

26
74 / 393

Output Formatting Placeholder


%[flags][width][.precision][length]type
 Examples:

[ 123] [+0123] [ 0173] [ 0x7b]


[123.456000] [123.46] [ 123%]

Format codes w/printf:


http://en.wikipedia.org/wiki/Printf
27
75 / 393

Return from printf


 A successful completion of printf returns the
number of characters printed. Consequently, for
the following:

if printf() is successful,
the value in printCount should be 13.

28
76 / 393

Literals / Literal Constants


 Literal – a name for a specific value
 Literals are often called constants
 Literals do not change value

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

Floating Point Constants


 Contain a decimal point.
 Must not contain a comma
 Can be expressed in two ways
,
decimal number: 23.8 4.0
scientific notation: 1.25E10

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

Keyboard Input using scanf


 General format
scanf(format-string, address-list)
 Example & (address of operator)
is required

 The format string contains placeholders (one per


address) to be used in converting the input.
 %d – Tells scanf that the program is expecting an ASCII
encoded integer number to be typed in, and that scanf
should convert the string of ASCII characters to internal
binary integer representation.
 Address-list: List of memory addresses
to hold the input values

37
85 / 393

Addresses in scanf()
 Address-list must consist of addresses only
 scanf() puts the value read into the memory address

 The variable, age, is not an address; it refers to the


content of the memory that was assigned to age
 & (address of) operator causes the address of the
variable to be passed to scanf rather than the value in
the variable
 Format string should consist of a placeholder for each
address in the address-list
Format codes w/scanf:
http://en.wikipedia.org/wiki/Scanf
38
86 / 393

Return from scanf()


 A successful completion of scanf() returns the number of
input values read. Returns EOF if hits end-of-file reading
one item.

Consequently, we could have

 If scanf() is successful,
the value in dataCount should be 2
 Spaces or new lines separate one value from another

39
87 / 393

Keyboard Input using scanf


 When using scanf for the terminal, it is best to first
issue a prompt

 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

 scanf stops at the first bad character.


 The value of y was never set. The value 4 is what was
left in the memory location named num2 the last time
the location was assigned a value.

43
91 / 393

Format Placeholder for Input


 When reading data, use the following format
specifiers / placeholders
%d - for integers, no octal or hexadecimal
%i – for integers allowing octal and hexadecimal
%f - for float
%lf – for double (the letter l, not the number 1)
 Do not specify width and other special printf options

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):

Operator(s) Operation(s) Order of evaluation (precedence)


() Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost pair
is evaluated first. If there are several pairs
of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
*, /, or % Multiplication Evaluated second. If there are several, they
Division are evaluated left to right.
Modulus
+ or - Addition Evaluated last. If there are several, they are
Subtraction evaluated left to right.

 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

The Division Operator


 Generates a result that is the same data type of the
largest operand used in the operation.
 Dividing two integers yields an integer result.
Fractional part is truncated.
5/2 → 2
17 / 5 → 3

Watch out: You will not be warned!

49
97 / 393

The Division Operator


 Dividing one or more decimal floating-point values
yields a decimal result.

5.0 / 2 → 2.5
4.0 / 2.0 → 2.0
17.0 / 5.0 → 3.4

50
98 / 393

The modulus operator: %


 % modulus operator returns the remainder

7%5 → 2
5%7 → 5
12 % 3 → 0

51
99 / 393

Evaluating Arithmetic Expressions


 Calculations are done ‘one-by-one’ using
precedence, left to right within same precedence
 11 / 2 / 2.0 / 2 performs 3 separate divisions.
1. 11 / 2 → 5
2. 5 / 2.0 → 2.5
3. 2.5 / 2 → 1.25

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

Evaluating Arithmetic Expressions


2 * (-3) -6
4 * 5 - 15 5
4+2*5 14
7/2 3
7 / 2.0 3.5
2/5 0
2.0 / 5.0 0.4
2/5*5 0
2.0 + 1.0 + 5 / 2 5.0
5%2 1
4 * 5/2 + 5 % 2 11

54
102 / 393

Data Assignment Rules


 In C, when a floating-point value is assigned to an
integer variable, the decimal portion is truncated.

 Only integer part ‘fits’, so that’s all that goes


 Called ‘implicit’ or ‘automatic type conversion’

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

Given the following:

result is 0, because of integer division

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:

Type cast operator

 This is different from (double) (m/n)

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

Abreviated/Shortcut Assignment Operators

 Assignment expression abbreviations


a = a + 3; can be abbreviated as a += 3;
using the addition assignment operator
 Examples of other assignment operators include:

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

Shorthand Operators: Two Options


 Post-Increment
x++
 Uses current value of variable,
THEN increments it
 Pre-Increment
++x
 Increments variable first,
THEN uses new value

63
111 / 393

Shorthand Operators: Two Options


 ‘Use’ is defined as whatever ‘context’ variable is
currently in
 No difference if ‘alone’ in statement:
x++; and ++x;  identical result

64
112 / 393

Post-Increment in Action
 Post-Increment in Expressions:

 This code segment produces the output:


4
3
 Since post-increment was used

65
113 / 393

Pre-Increment in Action
 Now using pre-increment:

 This code segment produces the output:


6
3
 Because pre-increment was used

66
114 / 393

Programming in C

THE END

67
115 / 393

Programming in C

1
116 / 393

Example 1

 What if we want to process


three different pairs of integers?

2
117 / 393

Example 2
 One solution is to copy and paste the necessary lines
of code. Consider the following modification:

 What if you wanted to process four sets?


Five? Six? ….

3
118 / 393

Processing an arbitrary number of pairs


 We might be willing to copy and paste to process a
small number of pairs of integers but
 How about 1,000,000 pairs of integers?
 The solution lies in mechanisms used to control the
flow of execution
 In particular, the solution lies in the constructs that
allow us to instruct the computer to perform a task
repetitively

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

The while Repetition Structure


 Repetition structure
 Programmer specifies
 Condition under which actions will be executed
 Actions to be repeated
 Psuedocode
While there are more items on my shopping list
Purchase next item and cross it off my list

 while loop repeated


 As long as condition is true
 Until condition becomes false

6
121 / 393

The while Repetition Structure


• The condition is
tested false
condition
• If the condition is
true, the loop body
is executed and the true

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

 Expression = Condition to be tested


 Resolves to true or false
 Basic Block = Loop Body
 Reminder – Basic Block:
 Single statement or
 Multiple statements enclosed in braces

8
123 / 393

Loop Control Variable (LCV)


 The loop control variable is the variable whose value
controls loop repetition.
 For a while loop to execute properly, the loop control
variable must be
 declared
 initialized
 tested
 updated in the body of the loop in such a way that the
expression/condition will become false
 If not we will have an endless or infinite loop

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

Enter value or zero to end: 2

What is wrong with my


program? It just sits there!

12
127 / 393

Loop Pitfalls: Misplaced semicolon

 Notice the ‘;’ after the while condition!


 Body of loop is between ) and ;
 Result here: INFINITE LOOP!
Ctrl-c = Kill foreground process

13
128 / 393

The for Repetition Structure


 A natural 'counting' loop
 Steps are built into for structure!
1. Initialization initialization
2. Loop condition test
3. Increment or decrement false
condition

true
loop body

increment

next stmt
14
129 / 393

Review: Assignment Operators


 Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;

 Examples of assignment operators:


a += 5 (a = a + 5)
a -= 4 (a = a - 4)
b *= 5 (b = b * 5)
c /= 3 (c = c / 3)
d %= 9 (d = d % 9)

15
130 / 393

Review: Pre-increment operator


Pre-increment operator: ++n
i) Stand alone: add 1 to n
If n equals 1, then after execution of the statement

the value of n will be 2.


ii) In an expression:
Add 1 to n and then use the new value of n in the expression.

If n is initially 1, the above statement will print the value 2.


After execution of printf, n will have the value 2.

16
131 / 393

Review: Post-increment operator


Pre-increment operator: n++
i) Stand alone: add 1 to n
If n equals 1, then after execution of the statement

the value of n will be 2.


ii) In an expression:
Use the value of n in the expression and then add 1 to n.

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

Pre- and Post-decrement operator


 Pre- and post-decrement operators, --n, n-- ,
behave in a similar manner
 Use caution when using in an expression

 Do not use unless you know what you are doing!

18
133 / 393
2
The for Repetition Structure
 Syntax:

for (initialization; test; increment)


basic block

19
134 / 393

for loop example


 Prints the integers from one to ten

20
135 / 393

for Loop Example

How many times does loop body execute?

21
136 / 393

for Loop Example

How many times does loop body execute?

Bite 1 -- Yum!
Bite 2 -- Yum!
Bite 3 -- Yum!

22
137 / 393

The do-while Repetition Structure


 The do-while repetition structure is similar to the
while structure
 Condition for repetition tested after the body of the loop
is executed

loop body

true
condition

false

23
138 / 393
3
The do-while Repetition Structure
 Syntax:
do {
statements
} while ( condition );

24
139 / 393

The do-while Repetition Structure


 Example

 Prints the integers from 1 to 10

25
140 / 393

The do-while Repetition Structure


 Example

 Makes sure that the user enters a valid weight

26
141 / 393

The break Statement


 break
 Causes immediate exit from
a while, for, do/while or switch structure
 We will use the break statement
only to exit the switch structure!

27
142 / 393

The continue Statement


 continue
 Control passes to the next iteration
 We will not use the continue statement!

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

 The type of state that must be maintained by the program


depends on the nature of the problem and can include:
 indicator (true/false) variables
 counter variables
 sum variables
 previous input value variables

3
147 / 393

Counter-Controlled Repetition
 Number of items is known before loop

 Suppose the problem becomes:


Develop a class-averaging program that will process an
arbitrary number of grade scores each time the program
is run.

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 Priming Read


 For sentinel-controlled loops
1. Read before the loop (priming read)
2. Test input to make sure it is not the sentinel value
3. Process
4. Read again at the bottom of the loop
 Use the following model:
read before entering the loop
while (value_read != SENTINEL)
{
// process

read at bottom of loop
(before entering loop again)
}
6
150 / 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

Example of sentinel-controlled loop


25 43
67 96
12 58
44 99
-1

9
153 / 393

Processing an arbitrary number of pairs


 Sometimes it is not possible
to find a sentinel value
 We can use
 End-of-input controlled loops
 Uses return from scanf
 Can be fooled by invalid data
 End-of-file controlled loops
 Uses function feof

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

Example: End-of-input controlled loop


using items read & priming read
25
43
67
96
12
58
44

13
157 / 393

Example: End-of-input controlled loop


using just items read

25
43
67
96
12
58
44

14
158 / 393

Example: End-of-input controlled loop


using number of items read
25 43
67 96
12 58
44 99

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

Example: End-of-file controlled loop


25
43
67
96
12
58 End of File
44

17
161 / 393

Example: end-of-file controlled loop


25 43
67 96
12 58 End of File
44 99

18
162 / 393

Looping Subtask: Counting


 Example: Find the number of scores in a file
 Here the program state that must be maintained
is a counter that maintains the number of scores
that have been read so far.
 Steps
 Declare an int variable for the count
 Initialize the count to zero
 Increment the count
in the body of the loop

19
163 / 393

Looping Subtask: Counting

20
164 / 393

Looping Subtask: Counting

21
165 / 393

Looping Subtask: Counting

22
166 / 393

Looping Subtask: Counting

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

Looping Subtask: Counting

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

Looping Subtask: Counting

27
171 / 393

Looping Subtask:
Accumulation (Summing)

 The state that must be maintained is the sum of all


values that have been seen so far.
 Declare a variable to hold the sum (accumulator)
 Initialize the sum to zero
 In the body of the loop, add the new value to the sum

28
172 / 393

Accumulating Example

29
173 / 393

Counting & Accumulating Example


 Problem
 A class of ten students took a quiz.
 The grades (integers in the range 0 to 100) for this quiz
are available to you.
 Determine the class average on the quiz.

 Hint: Requirements for an average


 Count of number of items
 Sum of the items

30
174 / 393

Counting & Accumulating Example


 Pseudocode:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average

31
175 / 393

Looping Subtasks: Searching

 Need a variable to indicate whether or not the program


has encountered the target value, call it found
 Initialize found to 0 (false)
 Each time through the loop, check to see if the current
value equals the target value
 If so, assign 1 to found

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

Looping Subtasks: Searching

34
178 / 393

Searching Improvement
 Stop searching if target has been found

35
179 / 393

Looping Subtasks: Finding Extremes


 Finding Extreme Values (e.g. maximum, minimum)
 Need a variable (such as maxValue) to remember the
most extreme value encountered so far

25
43 96 is the max
67 12 is the min
96
12
58
44

36
180 / 393

Looping Subtasks: Finding Extremes


 Finding Extreme Values (e.g. maximum, minimum)
 Initialize the maxValue (minValue) to some value
 maxValue: Lower value than any data
 minValue: Higher value than any data
 Or for both: The first data value
 For each data item
 Compare the current value to maxValue (or minValue)
 If the current value is > maxValue (< minValue), replace maxValue
(minValue) with the current value.

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

Looping Subtasks: Finding Extremes

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 Operators (Compound Relationals)


Ch 6 p. 72
 && (logical AND)
 Returns true if both conditions are true

 || (logical OR)
 Returns true if either of its conditions is true

 ! (logical NOT, logical negation)


 Is a unary operator, only takes one operand following
 Reverses the truth/falsity of its condition
 Returns true when its condition is false

6
190 / 393

Logical Operators Truth Table


P Q P && Q P || Q !P

true true true true false

true false false true false

false true false true true

false false false false true

7
191 / 393

Precedence of Operators
1. (), []
2. Unary +, unary -, !, ++, --
3. Type casting
4. * , / , %
5. + , -
6. <, <=, >, >=
7. ==, !=
8. &&
9. ||
10. =

8
192 / 393

The if Selection Structure


 Selection structure
 used when we want the computer to choose between
two alternative courses of action

9
193 / 393

The if Selection Structure


 if Statement

true
Boolean
Expression

false true block

10
194 / 393

The if Selection Structure


General form of if:

if (Boolean Expression)
{
statement1;
statement2;
...
}

11
195 / 393

The if-else Selection Structure

 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

if-else Selection Structure


if-else statement

false true
Boolean
Expression

false block true block

13
197 / 393

The if-else Selection Structure


General form of if-else:
if (expression)
{
statement1A;
statement2A;
...
}
else
{
statement1B;
statement2B;
...
}
14
198 / 393

The if-else Selection Structure


 Nested if-else structures
 Test for multiple cases by placing if-else selection
structures inside if-else selection structures.

15
199 / 393

Nested if-else Structures

16
200 / 393

The if-else-if Construct

 Once a condition is met, the rest of the statements are skipped


17
201 / 393

The if-else-if Construct


The standard way to indent the previous code is

18
202 / 393

The if-else Selection Structure


 Compound statement:
 Set of statements within a pair of braces
 Example:

19
203 / 393

The if-else Selection Structure


–Without the braces, only one statement is executed.
e.g. given the following code:

• The statement,

will be executed independent of the value of grade.


• The statement,

will execute only if grade is


greater than or equal to 90.
20
204 / 393

The dangling else

Note: the compiler matches an else with the closest unmatched if


The above will be treated as

21
205 / 393

The dangling else


If the else is to match the outer if, use braces.

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

The switch Multiple-Selection Structure


 switch
 Useful when variable or expression is tested for multiple
values
 Consists of a series of case labels and an optional
default case

27
211 / 393

The switch Multiple-Selection Structure


With Breaks
case a case a action(s) break

case b case b action(s) break

case z case z action(s) break

default action(s)

28
212 / 393

The switch Multiple-Selection Structure


Without Breaks
case a case a action(s)

case b case b action(s)

case z case z action(s)

default action(s)

29
213 / 393

switch Statement Syntax


switch (switch_expression)
{
case constant1:
statementSequence1
break;
case constant2:
statementSequence2
break;

case constantN:
statementSequenceN
break;
default:
defaultStmtSequence
}

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

switch Statement Reminder


 The switch statement ends
 break statement
 end of the switch statement
 When executing the statements after a case label, it
continues to execute until it reaches a break
statement or the end of the switch.
 If you omit the break statements, then after executing
the code for one case, the computer will continue to
execute the code for the next case.

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

Defined Constant as Array Size


 Use defined/named constant for array size
 Improves readability
 Improves versatility
 Improves maintainability
 Examples:

5
223 / 393

Powerful Storage Mechanism


 Can perform subtasks like:
 "Do this to i-th indexed variable"
where i is computed by program
 "Fill elements of array scores from user input"
 "Display all elements of array scores“
 “Sort array scores in order”
 “Determine the sum or average score”
 "Find highest value in array scores"
 "Find lowest value in array scores"

6
224 / 393

Accessing Array Elements


 Individual parts called many things:
 Elements of the array
 Indexed or
subscripted variables
 To refer to an element:
 Array name and subscript or index
 Format: arrayname[subscript]
 Zero based
 c[0] refers to c0, c sub zero,
the first element of array c

7
225 / 393

Accessing Array Elements


 Example

 Note two uses of brackets:


 In declaration, specifies SIZE of array
 Anywhere else, specifies a subscript/index

8
226 / 393

Accessing Array Elements


 Example
 Given the declaration

 We reference elements of scores by

scores [0]

scores [1]

… subscript/index

scores [11]

9
227 / 393

Accessing Array Elements


 Size, subscript need not be literal constant
 Can be named constant or expression

10
228 / 393

Major Array Pitfall


 Array indexes go from 0 through size-1!
 C will 'let' you go out of the array’s bounds
 Unpredictable results – may get segmentation fault
 Compiler will not detect these errors!
 Up to programmer to 'stay in bounds‘
?

11
229 / 393

for-loops with Arrays


 Natural counting loop
 Naturally works well 'counting thru' elements
of an array
 General form for forward direction
 for (subscript = 0; subscript < size; subscript++)
 General form for reverse direction
 for (subscript = size-1; subscript >= 0; subscript--)

12
230 / 393

for-loops with Arrays Examples

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

Uses of Defined Constant


 Use everywhere size of array is needed
 In for-loop for traversal:

 In calculations involving size:

 When passing array a function:

14
232 / 393

Array as Function Parameter


 Include type and brackets []
 Size inside brackets is optional and is ignored
 Passes pointer/reference to array
 Function can modify array elements
 Common to also pass size
 Example:

15
233 / 393

Initializing Arrays
 Arrays can be initialized at declaration

 Size cannot be variable or named constant


 Equivalent to

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:

 Allocates array scores with size of 3

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’

 Requires two subscripts – row and column

19
237 / 393

Initializing
Multidimensional
 Nested lists
 Unspecified values set to zero
 2D Example:

20
238 / 393

Three-dimensional Visualization

21
239 / 393

Multidimensional Array Parameters


 Must specify size after first dimension

22
240 / 393

Programming in C

THE END

23
241 / 393

Programming in C

1
242 / 393

Programming with Arrays


 Subtasks
 Partially-filled arrays
 Loading
 Searching
 Sorting
 Sum, average
 Extremes

2
243 / 393

Partially-filled Arrays (Common Case)


 Must be declared some maximum size
 Program must maintain
 How many elements are being used
and/or
 Highest subscript

3
244 / 393

Sizeof and Arrays


 Operator sizeof returns the total bytes in the
argument
 Total elements = sizeof(array) / sizeof(data-type)
 Example

 Sizeof does not return total bytes being used


 You cannot use sizeof to determine the number of
elements being used in a partially filled array

4
245 / 393

Loading an Array
 Be careful not to overfill
 Do not read directly into array elements

5
246 / 393

Loading a Two-dimensional Array

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

Linear Search Example Using While

9
250 / 393

Linear Search Example Using For

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

Sum & Average Example


 Verify positive count before computing average
 Protects against division by zero

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

Extremes: Find Maximum Example

16
257 / 393

Programming in C

THE END

17
258 / 393

Programming in C

main

Level 2 Level 2 Level 2

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

Components of Function Use


 Three steps to implementing functions
1. Function declaration/prototype
 If not defined before use

2. Function definition
3. Function call
 Either prototype or definition must come first

 Prototype and/or definitions can go in either


 Same file as main()
 Separate file so other programs can also use it
 #include

4
262 / 393

Program Function Definition Structure


 main first (preferred) main
 Top down design
Level 2 Level 2 Level 2
 Some prototypes required
 Complete prototyping allows Level 3 Level 3
function definition in any
order
Level 3 Level 3
 main is last – lowest level
Level 2 Level 2 Level 2
functions first
 Bottom up design main
 Prototypes not required

 main in the middle


 Confusing: Do not do!
5
263 / 393

1. Function Declaration/Prototype
 An ‘informational’ declaration for compiler
 Tells compiler how to interpret calls
 Syntax:
<return_type> FnName(<formal-parameter-list>);

 Formal parameter syntax:


<data_type> Parameter-Name

 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

Alternative Function Declaration


 Function declaration is 'information' for compiler, so
 Compiler only needs to know:
 Return type
 Function name
 Parameter list
 Formal parameter names not needed but help readability

 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

 Use the value returned without storing

 Throw away return value

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 vs. Argument


 Names used interchangeably
 Technically parameter is 'formal' piece
while argument is 'actual' piece

Parameter! Argument!

13
271 / 393

Functions Calling Functions


 We're already doing this!
 main() IS a function calling printf!
 Only requirement:
 Function's declaration or definition must appear first
 Common for functions to call many other functions
 Function can call itself  Recursion

14
272 / 393

Declaring Void Functions


 Similar to functions returning a value
 Return type specified as 'void'
 Example prototype:

 Return-type is 'void'

15
273 / 393

Declaring Void Functions


 Nothing is returned
 Void functions cannot have return statement with an
expression
 Will return at end of function
 Non-void functions must have return statement with an
expression
 Example definition:

16
274 / 393

Calling Void Functions


 From some other function, like main():

 Cannot be used where a value is required


 Cannot be assigned to a variable,
since no value returned

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

 Tradition holds it should return an int


 Zero indicates normal ending of program

19
277 / 393

Scope of Identifier Names


 Region of a program where identifier is visible
 Begins at definition within block
 Ends at end of block
 Local variables
 Name given to variables defined within function block
 Can have different local variables with same name
declared in different functions
 Cannot have duplicate local names within a function

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

Global Constants and Global Variables


 Global variables?
 Possible, but SELDOM-USED
 Better alternative is to use parameters
 Dangerous: no control over usage!
 We do not use global variables in this class!

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

Static & Lifetime


 Variable definition modifier keyword: static
 Static variables are only allocated once
 Static variables are not deallocated until program ends

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

 Structures must defined before use


 C has three different methods to define a structure
 variable structures
 tagged structures
 type-defined structures
2
287 / 393

1) Struct variable
 A variable structure definition defines a struct variable

Member names

Variable name DON’T FORGET THE SEMICOLON

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

DON’T FORGET THE SEMICOLON

 Variable definitions:

 Variables point1, point2, and point3 all have members x and y.

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.

New type name DON’T FORGET THE SEMICOLON Member names

 Variable definition:

 Variable emp has members ssn, empType, and salary.


5
290 / 393

Dot Operator (.)


 Used to access member variables
 Syntax:
structure_variable_name.member_name
 These variables may be used like any other variables

6
291 / 393

Arrow Operator (->)


 Used to access member variables using a pointer
 Arrow Operator Syntax:
structure_variable_pointer->member_name
 Dot Operator Syntax:
(*structure_variable_pointer).member_name

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

Dynamic Allocation of Structures


 The sizeof() operator should always be used in
dynamic allocation of storage for structured data
types and in reading and writing structured data types

10
295 / 393

Arrays Within Structures


 A member of a structure may be an array

11
296 / 393

Arrays of Structures
 We can also create an array of structure types

12
297 / 393

Arrays of Structures Containing Arrays


 We can also create an array of structures that contain
arrays

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

Structure Pointers as Parameters


 More efficient: Pass the address of the struct
 Passing an address requires that only a single word be
pushed on the stack, no matter the size
 Called function can then modify the structure.

17
302 / 393

Structure Pointers as Parameters

18
303 / 393

Const Struct Parameter


 What if you do not want the recipient to be able to
modify the structure?
 Use the const modifier

19
304 / 393

Using the const Modifier

Compile time errors:

ch08.c: In function âchangePointâ:


ch08.c:213:7: error: assignment of member âxâ in read-only object
ch08.c:214:7: error: assignment of member âyâ in read-only object

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

Return Structure Pointer to Local Variable

ch08.c: In function âgetEmptyPixelâ:


22 ch08.c:293:7: warning: function returns address of local variable
307 / 393

Return Structure Pointer to Local Variable


 Reason: function is returning a pointer to a variable
that was allocated on the stack during execution of
the function

 Such variables are subject to being wiped out by


subsequent function calls

23
308 / 393

Function Return Structure Values


 It is possible for a function to return a structure.
 This facility depends upon the structure assignment
mechanisms which copies one complete structure to
another.
 Avoids the unsafe condition associated with
returning a pointer, but
 Incurs the possibly extreme penalty of
copying a very large structure

24
309 / 393

Function Return Structure Values

25
310 / 393

Arrays as Parameters & Return


 Array’s address is passed as parameter
 Simulates passing by reference
 Embedding array in structure
 The only way to pass an array by value
is to embed it in a structure
 The only way to return an array is
to embed it in a structure
 Both involve copying
 Beware of size

26
311 / 393

Programming in C

THE END

27
312 / 393

Programming in C

1
313 / 393

2
314 / 393

Memory Allocation & Structure

3
315 / 393

Memory Allocation & Structure

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

 Array with base type char


 One character per element
 One extra character: '\0'
 Called ‘null character’
 End marker
 Literal "Hello" stored as string

2
326 / 393

String Variable Declaration


 Array of characters:

 Declares a c-string variable to hold up to 9 characters


plus one null character
 No initial value

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:

 If s contains string “Hi Mom!”, then stored as:

4
328 / 393

String Variable Initialization


 Can initialize string:

 Need not fill entire array


 Initialization places '\0' at end

5
329 / 393

String Variable Initialization


 Can omit array-size:

 Automatically makes size one more than length of


quoted string
 NOT same as:

 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

String Index Manipulation


 Can manipulate array elements

 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

String Length: strlen


 Often useful to know length of string
strlen(string)
 Returns number of characters
 Does not include null
 Return type is size_t so type cast may be required

10
334 / 393

= with strings
 Strings are not like other variables, they are arrays
 Cannot assign:

 Must use string library function for assignment:


strcpy(destination, source)
 NO checks for size – up to programmer!
 ‘Assign’ value of msg to “Hello”:

 Or strncpy(destination, source, limit)


 No ending null character if limit is reached

11
335 / 393

== with strings
 Cannot use operator == to compare

 Must use strcmp string library function to compare:


strcmp(string1, string2)
 Returns zero int if string1 is equal to string 2
 Returns <0 int if string1 is less than string2
 Returns >0 int if string1 is greater than string2

12
336 / 393

String Concatenate: strcat


 Appends one string onto end of another
strcat(destination, source)

 Be careful when concatenating words


 msg1 is missing space after Hello
 msg2 is correct

13
337 / 393

String Parameters to Functions


 A string is an array, so
 String parameter is an array parameter
 Strings passed to a function can be changed by the
receiving function!
 Like all arrays, typical to send size as well
 Function could also use ‘\0’ to find end

14
338 / 393

String Input and Output


 Watch input size of string
 Must be large enough to hold entered string!
 + ‘\n’ perhaps
 + ‘\0’
 C gives no warnings of input size issues!

 Functions in stdio.h

15
339 / 393

Character Input: getchar


 Reads one character at a time from a text stream
int getchar( )
 Reads the next character from the standard input stream
and returns its value
 Return type is int!
 Will convert if assigned to char

16
340 / 393

Character Output: %s and putchar


 Format string placeholder for string: %s
 putchar: Writes one character at a time
int putchar (int outChar)
 Writes the parameter to standard output
 If successful, returns the character written

17
341 / 393
String variable

String Input: gets


char *gets (char *strPtr)
 Inputs a line (terminated by a newline)
from standard input
 Converts newline to \0
 If successful, returns the string
and also places it in argument
 Warning: Does not check length of input
 gcc may produce warning message

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

String Output: puts


int puts (const char *strPtr)
 Takes a null-terminated string from memory and writes
it to standard output
 Writes \n in place of \0

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

 The address of count is stored in countPtr


 We say, countPtr points to count

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:

1. To declare that a variable is a pointer


 Pre-pending a variable with a * in a declaration declares that the
variable will be a pointer to the indicated type instead of a
regular variable of that type

2. To access the location pointed to by a pointer


 Pre-pending a variable with a * in an expression indicates the value in
the location pointed to by the address stored in the variable

10
356 / 393

Simulating By Reference
 Invoked function uses * in formal parameters

 Invoking function uses & in actual parameters

11
357 / 393

Pointer Variables and Arrays


 Given

 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

Pointer Variables and Arrays


 Consider a block in memory consisting of ten
integers of 4 bytes in a row at location 10010
 Now, let's say we point an integer pointer aPtr at
the first of these integers

 What happens when we write


?

13
359 / 393

Pointer Variables and Arrays


 Because the compiler "knows"
 This is a pointer (i.e. its value is an address)
 That it points to an integer of length 4 at location 100
 Instead of 1, adds 4 to aPtr
 Now aPtr "points to" the next integer at location 104
 Same for: aPtr+=1, aPtr++, and ++aPtr

14
360 / 393

Pointer Variables and Arrays


 Since a block of 10 integers located contiguously
in memory is, by definition, an array of integers,
this brings up an interesting relationship between
arrays and pointers

15
361 / 393

Pointer Variables and Arrays


 Consider this array allocated at location 200

 We have an array containing 10 integers


 We refer to each of these integers by means of a
subscript to scores
 Using scores[0] through scores[9]

16
362 / 393

Pointer Variables and Arrays


 The name of an array and the address of the first
element in the array represent the same thing
 Consequently, we could alternatively access them
via a pointer:

17
363 / 393

Pointer Variables and Arrays


 The name of an array is a pointer constant to the
first element of the array
 So, we could also use :

18
364 / 393

Pointer Arithmetic and Arrays


 If scorePtr is pointing to a specific element in the
array and n is an integer,
scorePtr + n
is the pointer value n elements away
 We can access elements of the array either using
the array notation or pointer notation
 If scorePtr points to the first element, the following two
expressions are equivalent:
scores[n] Array notation

*(scorePtr + n) Pointer notation

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

2. Use memory through the pointer notation


3. Release allocated space when no longer needed,
so that it can be reused

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

Standard File Pointers


 Assigned to console unless redirected
 Standard input = stdin
 Used by scan function
 Can be redirected: cmd < input-file
 Standard output = stdout
 Used by printf function
 Can be redirected: cmd > output-file
 Standard error = stderr
 Can be specified in fputs function instead of stdout
 Can be redirected: cmd 2> output-file

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

User File Steps


1. Declare a file pointer variable
 Program connection to external user file
2. Open the file
 Creates a structure to store information needed for
processing file and buffer area(s)
 Makes file pointer connection to structure
3. Use functions for input and/or output
 Handles movement of data between program and buffer
and between buffer and external device
4. Close the file
 Writes the buffer to file if necessary
 Frees up memory associated with file

5
379 / 393

1. File Pointer Declaration


FILE * variable-name-list;
 Defines variables of type FILE*, file pointer
 Pointer is undefined unless initialized
 If not initialized to another value, initialize to NULL
 Examples:

 Following slides will use fp for file pointer

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

• If file does not exist, error returned

w Open text file for writing


• If file exists, it is emptied

• If file does not exist, it is created

a Open text file for append


• If file exists, the marker is positioned at the end

• If file does not exist, it is created


7
381 / 393

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:

 To go back to beginning without fclose then fopen:


void rewind(FILE *fp)

11
385 / 393

3. Input/Output Functions
 Formatted Input
 fscanf
 Formatted Output
 fprintf
 String Input
 fgets
 String Output
 fputs

12
386 / 393

Input

Formatted Input Functions


 Read and convert a stream of characters and store the
converted values in a list of variables found in the
address list
 scanf
scanf("format string", address list);
 Reads text data from standard input
 fscanf
fscanf(fp, "format string", address list);
 Reads input from the specified file

13
387 / 393

Output

Formatted Output Functions


 Displays output in human readable form
 printf
printf("format string", value list);
 Writes to standard output or standard error file
 fprintf
fprintf (fp, "format string", value list);
 Writes to the specified file

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

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

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

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)

18
392 / 393

End of File Controlled Loops


 feof
int feof(FILE *fp)
 Function to check if end of file has been reached.
 For an end of file controlled loop
 Read before the loop
 Test for end of file: while (!feof(fp))
 Inside loop:
 Process
 Read at the bottom of the loop

19
393 / 393

Programming in C

THE END

20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy