Title: CSci 152: Programming II Fall 2004
1CSci 152 Programming IIFall 2004
2Programming Languages
- Programming language A set of rules, symbols and
special words. - syntax tells which statements are legal or
accepted - semantics determine meanings of instructions
3Basic Elements of C
- A C Program (or any program in a procedural
programming language) - Collection of 1 or more subprograms called
functions - Which is a collection of statements that can
accomplish something useful - sequence, selection, repetition
- Special function called main
4Hello World!
- include ltiostreamgt
- using namespace std
- int main()
-
- cout ltlt Welcome to C Programming. ltlt
endl - return 0
5C Tokens
- Special Symbols
- - / . ? , lt ! gt
- Word Symbols
- int, float, char, void, return
- Identifiers
- Identifiers are names of things that appear in
programs, such as variables, constants, and
functions. - Some are predefined others are defined by you,
the programmer.
6C Data Types
- def Data type A set of values together with a
set of operations - simple data type
- structure data type
- pointers
Cs Data types
Simple
Structured
Pointers
7Simple Data Types
- The simple data type is the fundamental data type
in C, building block for the structured data
type - Integral, deals with integers or numbers withut a
decimal part - int, bool, char, short, long, unsigned variants
- Floating-point, deals with decimal numbers
- float, double, long double
- Enumeration type, which is a user-defined data
type - e.g. enum olympicSports basketball, volleyball,
diving, swimming, trackAndField, marathon,
archery
8Arithmetic Operators and Expressions
- - /
- Expressions
- 2 5
- 10 6
- x y / z (0.5 w)
- Type Conversion (Casting)
- float x float(24/7)
9Identifiers
- Identifier
- Identifier A C identifier consists of letters,
digits, and the under score character (_), and
must begin with a letter or underscore. - C is case sensitiveuppercase and lower case
letters are different. - Some of the predefined identifiers are cout and
cin. - Unlike reserved words, pre-defined identifiers
may be redefined, but it would not be wise to do
so.
10Declaring Variables
- Storing data in the computers memory is a two
step process. - Instruct the computer to allocate memory.
- Include statements in the program to put data
into the allocated memory. - Named constant A memory location whose content
is not allowed to change during program execution - const double conversion 2.54
- const int noOfStudents 20
- const char blank
- Variable A memory location whose content may
change during program execution. - double amountDue
- int counter
- char ch
- int x, y
- string name
- assignment
- variable expression
- x 4
- y 4 5 11
11Declaring Variables
- 1. In C, all identifiers must be declared
before they can be used. If we refer to an
identifier without declaring it, the compiler
will generate an error message indicating that
the identifier is not declared. - 2. A data type is called simple if the variable
(or named constant) of that type can store only
one value at a time. For example, if x is an,
say, int variable. Then at a given time only one
value can be stored in x.
12Putting Data into Variables
- In C there are two ways that data can be placed
into a variable - 1. Using Cs assignment statement, and
- 2. Use input (read) statements.
13Assignment Statement
- The assignment statement takes the form
- variable expression
- The expression is evaluated and its value is
assigned to the variable on the left side. - In C, is called the assignment operator.
14Input / Output
- Standard input (keyboard) cin
- cin gtgt variable gtgt variable
- int feet, inches
- cin gtgt feet gtgt inches
- Standard output (terminal) cout
- cout ltlt expression or manipulator ltlt expression
or manipulator - cout ltlt Hello there. ltlt endl
15Input (Read) Statement
- Syntax of cin together with gtgt
-
- cingtgtvariablegtgtvariable. . .
- In C, gtgt is called the extraction operator.
- Suppose miles is a variable of the type double.
- The statement
- cingtgtmiles
- causes the computer to get a value of the type
double and place it in the memory cell miles. -
16Input (Read) Statement
- By using more than one variable in cin, more than
one value can be read at a time. - Suppose feet and inch are variables of the type
int. A statement like - cingtgtfeetgtgtinch
- gets two integers (entered at the keyboard)
and places them in the memory location feet and
inch, respectively.
17Output
- The syntax of cout together with ltlt is
- coutltltexpression or manipulatorltltexpression or
- manipulator...
- In C, ltlt is called the insertion operator.
- expression (that is, expression) is evaluated and
its value is printed at the current cursor
position on the screen. - manipulator manipulates the output. The simplest
manipulator is endl (the last character is the
letter el), which causes the cursor to move to
the beginning of the next line. - This is called an output statement. Sometimes
this is also called a cout statement. - In C, ltlt is called the stream insertion
operator. - Strings and expressions involving only one
variable or a single value are evaluated to
itself.
18Output
- The output of the C statement
- coutltlta
- is meaningful provided the variable a has been
given a value. For example, the sequence of C
statements, - a 45
- coutltlta
- will produce an output of 45.
19Increment and Decrement Operators
- Frequent operation is to increment a count by 1
(or decrement by 1) - count count 1
- shorthand count
- count count 1
- count--
- Post-increment vs. pre-increment
- int count 5, res
- res count
- res count
20Preprocessor Directives
- Preprocessor directives are commands supplied to
the preprocessor that cause the preprocessor to
modify the text of a C program - All preprocessor commands begin with
- including files
- include ltiostreamgt
21Preprocessor Directives
- Only a small number of operations are explicitly
defined in C. - Many of the functions and symbols that are
necessary to run a C program are provided as a
collection of libraries. - Every library has a name and is referred as a
header file. For example, the descriptions of the
functions needed to perform I/O are contained in
the header file iostream. - The descriptions of some very useful mathematics
functions such as power, absolute, sine, etc.,
are contained in the header file cmath. - Preprocessor directives are commands supplied to
the preprocessor. - All preprocessor commands begin with .
- There is no semicolon at the end of these
commands since these are preprocessor commands
not C commands.
22Preprocessor Directives
- The general syntax to include a header file
(provided by the SDK) in a C program is - include ltheaderFileNamegt
- The preprocessor directive
- include ltiostreamgt
- causes the preprocessor to include the header
file iostream in the program.
23Preprocessor Directives
- In Standard C, header files have the file
extension .h - In Standsrd C, the descriptions of the
functions needed to perform I/O are contained in
the header file iostream.h - include ltiostream.hgt
- include ltmath.hgt
24namespace
- Partitioning mechanism of namespace of standard
variables - for example header file iostream (among many
others) declared in std namespace - stdcin gtgt feet
- or
- using namespace std
- cin gtgt feet
25Creating a C Program
- A C program is a collection of functions, and
one of the functions is the function main (which
is executed first when program started). - int main()
-
- statement1
- .
- .
- .
- statementn
- return 0
-
- Source code save in file with extension .cpp e.g.
FirstProgram.cpp - When program is compiled, the C compiler
generates the object code .obj - When object code is linked with the system
resources an executable program is produced an
usually saved with extension .exe
26Some Words about Program Style and Form
- First of all, program must be syntactically
correct or it will not compile - int x
- int y
- double z
- y w x
- Blanks separate tokens, you can use blank lines
and spacing (indentation) to indicate program
modules and structure - All C statements must end with a semicolon (
is called a statement terminator). - Documentation The programs you write should be
clear not only to you but others (me) who will
read your code. Use comments to document
concepts/procedures attempting to be realized by
code - / c-style multi-line comments /
- // C single line comments
- I like this document for a (well not too brief,
but not bad) summary of good programming style
and form - C Programming Style Guidelines
- http//geosoft.no/development/cppstyle.html
27More on C I/O
- In C, I/O is (always) conceptualized as a
stream of bytes, or a stream - A stream is a sequence of characters from the
source to the destination. - Input stream A sequence of characters from an
input device to the computer. - Output stream A sequence of characters from the
computer to an output device. - Standard input (cin) and standard output (cout)
28Input predefined functions
- istreamVar.get(varChar)
- istreamVar.ignore(intExp, chExp)
- istreamVar.putback(ch)
- ch istreamVar.peek()
29Output and Formatting Output
- output stream manipulators
- cout ltlt setprecision(2)
- cout ltlt fixed cout.unsetf(iosfixed)
- cout ltlt scientific cout.unsetf(iosscientific)
- cout ltlt showpoint
- cout ltlt setw(5) ltlt x ltlt endl
- and many others
30File I/O
- File I/O is a five-step process
- Include the header file fstream in the program
- Declare file stream variables
- Associate the file stream variables with the
input/output sources - Use the file stream varaibles with gtgt, ltlt or
other input/output functions - Close the file
31File I/O
- include ltfstreamgt
- using namespace std
- int main()
-
- // Declare file stream variables such as the
following - ifstream inData
- ofstream outData
- // declare additional varaibles if any
- // Open files
- inData.open(a\\prog.dat)
- outData.open(a\\prog.out)
- // Code for data manipulation
- inData gtgt payRate
- outData ltlt The paycheck is ltlt pay ltlt endl
32Control Structures
- There are really only three main types of control
structures in standard procedural programming
languages - Sequence steps are normally performed in a
sequential manner - Selection One of several actions is selected and
executed (branch, other actions are not
executed). - Repetition One or more steps is performed
repeatedly.
33Control Structures Sequence
- Normally in procedural programs, statements are
executed in a sequential manner. - selection and repetition control structures break
up this sequential execution by introduction
branch points and loops respectively - Procedure/function calls also break up sequential
execution to modularize algorithm into several
small pieces
34Control Structures Selection
- Selection, or branch statements, chose one set of
instructions among 2 or many to execute
conditional on some test. - In C selection control structures are
- if
- if else
- switch
35Relational and Boolean Operators
- C relational an boolean operators basis of
conditional tests for selection control
structures
Relational Operators
Logical (Boolean) Operators
36Selection if and if .. else
- if (expression)
- statement
- if (expression)
- statement1
- else
- statement2
37Compound (Block of) statements
- A compound statement groups a sequence of
expressions - if (age gt 18)
-
- cout ltlt Eligible to vote. ltlt endl
- cout ltlt No longer a minor. ltlt endl
-
- else
-
- cout ltlt Not eligible to vote. ltlt endl
- cout ltlt Still a minor. ltlt endl
38Multiple selections Nested if
- if (balance gt 50000.00)
- interestRate 0.07
- else if (balance gt 25000.00)
- interestRate 0.05
- else if (balance gt 1000.00)
- interestRate 0.03
- else
- interestRate 0.00
39Multiple Selections switch statements
- power to choose from among many alternatives
- switch (grade)
-
- case A
- cout ltlt The grade is A.
- break
- case B
- cout ltlt The grade is B.
- break
- case C
- cout ltlt The grade is C.
- break
- case D
- cout ltlt The grade is D.
- break
- case F
- cout ltlt The grade is F.
- break
40Control Structures Repetition
- Repetition is a common activity in algorithms,
and very powerful - Repetition is another way in which we get away
from the simple sequential execution of a
sequence of statements - C looping structures
- while
- for
41While looping structure
- while (expression)
- statement
- i 0
- while (i lt 20)
-
- cout ltlt i ltlt
- i i 5
-
- cout ltlt endl
42While looping structure
flag-controlled found false while
(!found) if (expression) found
true EOF-controlled cin gtgt variable while
(cin) cin gtgt variable
- counter-controlled
- counter 0
- while (counter lt N)
-
-
- counter
-
-
- sentinel-controlled
- cin gtgt variable
- while (variable ! sentinel)
-
-
- cin gtgt variable
-
43for looping structure
- while loop is general enough to implement most
(all?) forms of repetition - for loop is a specialized form to simplify
writing of count-controlled loops (since they are
so common).
44for looping structure
- for (initial statement loop condition update
statement) - statement
- for (i1 ilt5 i)
-
- cout ltlt Hello! ltlt endl
- cout ltlt ltlt endl
45Break and Continue
- break
- exit early from a loop
- skip the remainder of the switch structure
- continue
- skips remaining statements in the loop and
proceeds with the next iteration of the loop
46Functions
- A C Program (or any program in a procedural
programming language) - Collection of 1 or more subprograms called
functions - Which is a collection of statements that can
accomplish something useful - sequence, selection, repetition
- Special function called main
47Predefined Functions
48Using Predefined Functions
- Include the header file that contains the
functions specification - Call function with correct arguments
- Possibly handle errors returned as codes or
otherwise
49Example 6-1 // How to use predefined
functions. include ltiostreamgt include
ltcmathgt include ltcctypegt include
ltcstdlibgt using namespace std int main() int
x double u,v coutltlt"Line 1 Uppercase a
is " ltltstatic_castltchargt(toupper('a'))
ltltendl //Line 1 u 4.2 //Line
2 v 3.0 //Line 3 coutltlt"Line 4 "ltltultlt"
to the power of " ltltvltlt"
"ltltpow(u,v)ltltendl //Line 4 coutltlt"Line 5 5
to the power of 4 " ltltpow(5,4)ltltendl
//Line 5
50Example 6-1 // How to use predefined
functions. include ltiostreamgt include
ltcmathgt include ltcctypegt include
ltcstdlibgt using namespace std int main() int
x double u,v coutltlt"Line 1 Uppercase a
is " ltltstatic_castltchargt(toupper('a'))
ltltendl //Line 1 u 4.2 //Line
2 v 3.0 //Line 3 coutltlt"Line 4 "ltltultlt"
to the power of " ltltvltlt"
"ltltpow(u,v)ltltendl //Line 4 coutltlt"Line 5 5
to the power of 4 " ltltpow(5,4)ltltendl
//Line 5
51User-Defined Functions
- To solve a problem you must learn to write your
own functions - User-defined functions in C are classified into
two categories - Functions that have a data type, called
value-returning functions - Functions that do not have a data type, called
void functions.
52Value-Returning Functions
- functionType functionName(formal parameter List)
-
- statements
- return value
-
- int min(int number1, int number2)
-
- if (number1 lt number2)
- return number1
- else
- return number2
53Value-Returning Functions
- Once a value-returning function computes the
value, the function returns this value via the
return statement. - When a return statement executes in a function,
the function immediately terminates and returns
control back to the caller. - A value-returning function must return a value,
therefore it must have at least 1 return
statement somewhere in it.
54Non Value-Returning Functions
- called void functions
- void functionName(formal parameter List)
-
- statements
-
- void printStars()
-
- cout lt ltlt end
- cout lt ltlt end
55Reference Parameters
- Normal simple data type parameters in C and C
are passed by value. - Sometimes it is useful to pass in parameters by
reference. - When you want to return more than one value from
a function. - When the value of the actual parameter needs to
be changed. - When passing the address would save memory space
and time relative to copying a large amount of
data.
56Reference Parameters
- Value parameter A formal parameter that receives
a copy of the content of the corresponding actual
parameter. - Reference parameter A formal parameter that
receives the location (memory address) of the
corresponding actual parameter.
57Reference Parameters
- int main()
-
- int courseScore
- cout ltlt This program computes the course
grade. - ltlt endl
- getScore(courseScore)
- printGrade(courseScore)
- return 0
-
- void getScore(int score)
-
- cout ltlt Enter the course score
- cin gtgt score
- cout ltlt endl ltlt Course score is ltlt score ltlt
endl
58Scope of Identifiers in C
- Identifier A C identifier consists of letters,
digits, and the under score character (_), and
must begin with a letter or underscore. - C is case sensitiveuppercase and lower case
letters are different. - Some of the predefined identifiers are cout and
cin. - Unlike reserved words, pre-defined identifiers
may be redefined, but it would not be wise to do
so. - Identifiers are used to name user-defined
variables, constants, functions, structures and
classes, for example. - Q Are you allowed to access any identifier
anywhere in the program?
59Scope of Identifiers in C
- Q Are you allowed to access any identifier
anywhere in the program? - A No, certain rules exist that you must follow
(an know) to access an identifier. - The scope of an identifier refers to where in the
program an identifier is accessible.
60Scope of Identifiers in C
- Local identifier Identifiers declared within a
function (or block). - Global identifier Identifiers declared outside
of every function definition.
61Scope of Identifiers in C
- In general, the following rules apply when an
identifier is accessed. - Global identifiers (such as variables) are
accessible by a function or a block if - The identifier is declared before the function
definition (block), - The function name is different from the
identifier, - All parameters of the function have names
different than the name of the identifier, and - All local identifiers (such as local variables)
have names different than the name of the
identifier. - (Nested Block) An identifier declared within a
block is accessible - Only within the block from the point at which it
is declared until the end of the block, and - By those blocks that are nested within that block
if the nested block does not have an identifier
with the same name as that of the outside block
(the block that encloses the nested block.) - The scope of a function name is similar to the
scope of an identifier declared outside any
block. That is, the scope of a function name is
the same as the scope of a global variable.
62- include ltiostreamgt
- using namespace std
- const double rate 10.50
- int z
- double t
- void one(int x, char y)
- void two(int a, int b, char x)
- void three(int one, double y, int z)
- int main ()
-
- int num, first
- double x, y, z
- char name, last
- .
- .
- .
63- void one(int x, char y)
-
- .
- .
- .
-
- int w
- void two(int a, int b, char x)
-
- int count
- .
- .
- .
-
64- void three(int one, double y, int z)
-
- char ch
- int a
- .
- .
- .
- //Block four
-
- int x
- char a
- .
- .
- //end Block four
- .
- .
- .
65(No Transcript)
66Static and Automatic Variables
- The variables dicussed so far have followed two
simple rules - Memory for global variables remains allocated as
long as the program executes. - Memory for a variable declared within a block is
allocated at block entry and deallocated at block
exit. For example, memory for the formal
parameters and local variables of a function is
allocated when the function is called and
deallocated when the function exits.
67Static and Automatic Variables
- A variable for which memory is allocated at block
entry and deallocated at block exit is called an
automatic variable. - A variable for which memory remains allocated as
long as the program executes is called a static
variable. - Global variables are static variables and, by
default, variables declared within a block are
automatic variables. - You can declare a static variable within a block
by using the reserved word static.
68- Example 7-9
- //Program Static and automatic variables
- include ltiostreamgt
- using namespace std
- void test()
- int main()
-
- int count
- for(count 1 count lt 5 count)
- test()
-
- return 0
-
69- void test()
-
- static int x 0
- int y 10
- x x 2
- y y 1
-
- coutltlt"Inside test x "ltltxltlt" and y "
- ltlty ltltendl
-
- Output
- Inside test x 2 and y 11
- Inside test x 4 and y 11
- Inside test x 6 and y 11
- Inside test x 8 and y 11
- Inside test x 10 and y 11
70User-Defined Simple Data Types
- Recall the following categories of data types in
C - We now look to simple mechanisms for producing
user-defined data types
71Enumeration Type
- A data type is a set of values together with a
set of operations on those values. - In order to define a new simple data type, called
enumeration type, we need three things - A name for the data type.
- A set of values for the data type.
- A set of operations on the values.
- C allows the user to define a new simple data
type by specifying its name and the values, but
not the operations. - The values that we specify for the data type must
be identifiers.
72- The syntax for enumeration type is
- enum typeNamevalue1, value2, ...
- where value1, value2, are identifiers.
- value1, value2, are called enumerators.
- value1 lt value2 lt value3 lt...
- In C, enum is a reserved word.
- Enumeration type is an ordered set of values.
73- Example 8-1
- enum colorsbrown, blue, red, green, yellow
- defines a new data type, called colors
- The values belonging to this data type are brown,
blue, red, green, and yellow. - Example 8-2
- enum standingfreshman, sophomore, junior,
senior - defines standing to be an enumeration type.
- The values belonging to standing are freshman,
sophomore, junior, and senior.
74- Example 8-3
- The following are illegal enumeration types
because none of the values is an identifier. - //Illegal enumeration types
- enum grades'A', 'B', 'C', 'D', 'F'
- enum places1st, 2nd, 3rd, 4th
- The following are legal enumeration types
- enum gradesA, B, C, D, F
- enum placesfirst, second, third, fourth
75- If a value has already been used in one
enumeration type, it cannot be used by any other
enumeration type in the same block. - The same rules apply to enumeration types
declared outside of any blocks. - Example 8-4
- enum mathStudentJohn, Bill, Cindy, Lisa, Ron
- enum compStudentSusan, Cathy, John, William
//Illegal - Suppose that these statements are in the same
program in the same block. - The second enumeration type, compStudent, is not
allowed because the value John was used in the
previous enumeration type mathStudent.
76- Declaring Variables
- The syntax for declaring variables is the same as
before, that is, - dataType identifier, identifier,...
- The following statement defines an enumeration
type sports - enum sportsbasketball, football, hockey,
- baseball, soccer,volleyball
- The following statement declares variables of the
type sports. - sports popularSport, mySport
77Next Class
- Quiz 1 Over review material
- Data Types
- simple, structured
- declaring
- Control Structures
- sequence, selection (if/then, case) and
repetition (while, for) - functions
- declaring, parameters, return values
- I/O
78Next Class
- 1 Dimensional Arrays and C-strings (Ch 9)
- Ch9 405-430 (1ed) 423-450 (2ed)
- Active Reading
- I agree ?
- I disagree X
- Thats new
- Thats important !
- I wonder ?
- I dont understand ??
- Prepare 2 cards
- The most important point of the reading
assignment - The biggest question or thing you didnt
understand in the reading assignment.