Title: C and
1C and Object-Oriented Programming Basic
Program Coding
2Basic Program Coding
- Goals of this Lesson
- Understand how to reuse existing code in your
programs (using include) - Obtain input data from the user and display
information to the user (with cin and cout) - Evaluate and create arithmetic expressions
- Understand operations common to many objects
(such as int, double, and string) - Construction, Output, Assignment, and Input
3The C Programming Language A Start
- A C program is a human-readable sequence of
characters, usually created with a text editor
and stored as a file. - this is the source code
- The filename has specific extension
- .cc or .C or.cpp
- others too
4General Forms
- General forms provide information to create
syntactically correct programs - Anything in yellow boldface must be written
exactly as shown (cout ltlt for example) - Anything in italic represents something that must
be supplied by the user - The italicized portions are defined elsewhere
5General Form A program
- // Comments
- include-directive(s)
- int main()
-
- object-initializations
- statement(s)
- return 0
// Comments include-directive(s) void
main() object-initializations
statement(s)
6Example C Program
- // This C program gets a number from the
- // user and displays that value squared
- include ltiostream.hgt // for cout cin endl
- int main()
-
- double x 0.0
- cout ltlt "Enter a number "
- cin gtgt x
- cout ltlt "x squared " ltlt (x x) ltlt endl
- return 0
-
7The Compiler
- The compiler
- reads source code in a character by character
fashion (tokenization) - reports errors whenever possible
- reports warnings to help avoid errors
- conceptually replaces include with the source
code of the include file
8include Directives
- General form include - directive
- include ltinclude-filegt
- -or-
- include "include-file"
- lt gt causes a search of the system folder(s)
- these files should be found automatically.
- The form with " " first searches the working
folder before searching the system folder(s) - the " " indicates an author supplied file name
that you may need in your working folder
9The Smallest Pieces of a C Program
- A token is the smallest recognizable unit in a
programming language. - There are four types of tokens
- special symbols
- keywords
- identifiers
- constants
10A "tokenized program"
- Each color represents either a different token
special symbol reserved word identifier
constant comment (gray), or include directive
(cyan) - // Comment This is a complete C program
- include ltiostreamgt
- using namespace std
- int main()
-
- cout ltlt "Hello World!"
- return 0
-
11Special Symbols
- One or two character sequences (no spaces).
- // lt gt ( ) ltlt !
- Some special symbols mean different things in
different contexts.
12C Keywords
- Word like tokens with a pre-defined meaning that
can't be changed (reserved) - double int
- Some of the keywords in the text
- bool class for operator typedef
- case do if return void
- char else long switch while
13Identifiers
- There are some standard (must be available with
the C compiler) identifiers - endl sqrt string width std
- The programmer can make up new identifiers
(programmer-defined) - test1 x1 aNumber MAXIMUM A_1
- Note main is a programmer-defined identifier,
cout is a standard identifier
14Self-Help Exercise
- Identifiers have from 1 to 32 characters
- 'a'..'z', 'A'..'Z', '0'..'9', '_'
- identifiers should start with a letter a1 is
legal, 1a is not (can also start with underscore
_ ) - C is case sensitive. A and a are different.
- Which of these are valid identifiers?
- a) abc e) ABC i) a_1
- b) m/h f) 25or6to4 j) student Number
- c) main g) 1_time k) string
- d) double h) first name l) ______
15Constants
- floating-point constants
- 1.234 -12.5 0.0 0. .0 1e10 0.1e-5
- string constants
- "character between double quotes"
- integer constants
- -1 0 1 -32768 32767
- character constants
- 'A' 'b' '\n' '1'
16Comments
- Example comments
- // on one line
- /
- between slash star and star slash
- /
- Provide internal documentation
- Helps us understand program that we must
read--including our own. - Can be used as "pseudocode" within a program and
later changed into C or left as is to provide
documentation
17Common Operations on Objects
- Common Operations for many classes of objects
include these four - Declaration Construct an object
- Initialization or optionally initialize its
state - Assignment Modify the state of an object
- Input Modify the state of an object
- Output Inspect the state of an object
18Object Constructions
- Use default initial state double is garbage
- class-name identifier
- -or-
- class-name identifier , identifier ,
, identifier - Allow client to supply initial state
- class-name identifier initial-state
- -or -
- class-name identifier ( initial-state )
- -or -
- class-name identifier initial-state ,
identifier ( initial-state ) - , , identifier
initial-state
19Examples Object Constructions
- Construct seven objects qualityPoints is
undefined - double credits 15.5, qualityPoints
- string firstName, lastName("Harrison")
- double x 0.0, y 0.0
- double z // garbage state (unknown)
- Note strings have the default value of the null
string "", which has 0 characters. - A double object has no default value--it's
garbage unless an initial value is supplied.
20Output with cout
- Programs must communicate with users
- This can be done with keyboard input statements
and screen output statements - A C statement is composed of several components
properly grouped together to perform some
operation. - Here is the first statement used to display
constants and object state to the screen
21The cout Statement
- The general form of a cout statement
- cout ltlt expression-1 ltlt expression-2 ltlt
expression-n - Example
- cout ltlt "Grade " ltlt courseGrade ltlt endl
22What happens with cout?
- When a cout statement is encountered, the
expressions are displayed on the screen in a
manner appropriate to the expression. - New Lines with endl
- When encountered in a cout statement, endl
generates a new line on the monitor - To properly use cout and endl, your program must
have this code at the top of the file - include ltiostreamgt // for cout and endl
- using namespace std
23Self-Help Exercise Write the output generated
by this program
- include ltiostream.hgt // for cout
- int main()
-
- double aDouble 0.0
- cout ltlt "12345678" ltlt endl
- cout ltlt (2.5 3) ltlt (23) ltlt endl
- cout ltlt aDouble
- return 0
-
- Output?
24Assignment
- Certain objects have undefined state
- double dunno, do_you
- cout ltlt dunno ltlt endl // Output? ______
- The programmer can set the state of objects with
assignment operations of this form - object-name expression
- Examples
- dunno 1.23
- do_you dunno - 0.23
25Memory before and after
- Object Old Modified
- Name State State
- dunno ? 1.23
- do_you ? 1.0
- The expression must be a value that the object
can store (assignment compatible) -
- dunno "Ohhh no, you can't do that" //
lt-Error - string s
- s 1.23 // lt-Error
26Self-Help Exercise
- Write the values for bill and name
-
- double bill
- string name
-
- bill 10.00
- bill bill (0.06 bill)
- name "Bee Bop"
- name "Hip Hop"
- // bill is ___________?
- // name is now ________?
-
27Input with cin
- General forms
- cin gtgt object-1
- -or-
- cin gtgt object-1 gtgt object-2 gtgt object-n
- Example cin gtgt test1
- When a cin statement is encountered
- the program pauses for user input.
- the characters typed by the user are processed
- the object's state is changed to the value of the
input
28Input is separated with Whitespaceblanks, tabs,
and newlines
- include ltiostream.hgt // for cout, cin, endl
- include string.h // for class string
- int main()
-
- string name
- cout ltlt "Enter your name "
- cin gtgt name
- cout ltlt "Hello " ltlt name
- return 0
-
- Dialogue when the user enters Kim McPhee
- McPhee is still waiting to be processed by a
non-existent future cin statement - Enter your name Kim McPhee
- Hello Kim
29Arithmetic Expressions
- Arithmetic expressions consist of operators such
as - / and operands such as 1.0, payRate,
and hoursWorked - Example expression used in an assignment
- grossPay payRate hoursWorked
- Another example expression
- (40payRate) 1.5payRate(hoursWorked-40)
- The previous expression has how many
- operators ?___ ?
- operands ?___ ?
30Arithmetic Expressions
An arithmetic expression can be written in these
forms
a numeric object x or a numeric
constant 100 or 99.5 or expression
expression 1.0 x or expression -
expression 2.5 - x or expression
expression 2 x or expression / expression
x / 2.0 or ( expression ) (1 2.0)
31Precedence of Arithmetic Operators
- Expressions with more than one operator require
some sort of precedence rules - / // evaluated left to right order
- - // evaluated left to right order
- What is 2.0 4.0 - 6.0 8.0 / 6.0 ____?
- Use (parentheses ) for readability or to
intentionally alter an expression - double C
- double F 212.0
- C 5.0 / 9.0 (F - 32) // C _____?
32Self-Help Exercise Write the complete dialogue
with input 2.3 5.0 2.0
- include ltiostream.hgt // for cin, cout, and endl
- int main()
- // Declare Objects
- double x, y, z, average
- // Prompt for and get input from the user
- cout ltlt "Enter three numbers "
- cin gtgt x gtgt y gtgt z
- // Process
- average (x y z) / 3.0
- // Output
- cout ltlt "Average " ltlt average ltlt endl
- return 0
33const objects
- It is sometimes convenient to have objects that
cannot have altered state. - const class-name identifier expression //
use this form - -or-
- const class-name identifier ( expression )
- Examples
- const double PI 3.1415926
- const string ERROR_MESSAGE "Nooooooo"
- Errors
- PI 9.8
- cin gtgt ERROR_MESSAGE
34Another Algorithm Pattern Prompt then Input
- The Input/Process/Output programming pattern can
be used to help design many programs in the first
several chapters - The Prompt then Input pattern also occurs
frequently. - The user is often asked to enter data
- The programmer must make sure the user is told
what to enter
35Prompt then Input Pattern
36Examples
- Instances of the Prompt then Input pattern
- cout ltlt "Enter your first name "
- cin gtgt firstName
- cout ltlt "Enter accumulated credits "
- cin gtgt credits
- Write code that gets the current temperature from
the user - ? ________ ?
Optional Demo average3.cpp to see prompt then
input used three times