Title: CMPUT 201 Practical Programming Methodology
1CMPUT 201 Practical Programming Methodology
- Dekang Lin
- Department of Computing Science
- University of Alberta
- lindek_at_cs.ualberta.ca
2Outline
- Introduction
- Administrative issues
- Introduction to C
- Basic data types
- Basic control structures
- Input/output
- Summary
3Contact Information
- Email lindek_at_cs.ualberta.ca
- Phone 492-9920
- Office Athabasca Hall 357
- Office hours
- Tuesday and Thursday 2-3pm
- by appointment
4Calendar Description
- Introduction to the principles, methods, tools,
and practices of the professional programmer. The
lectures focus on the fundamental principles of
software engineering based on abstract data types
and their implementations. The laboratories offer
an intensive apprenticeship to the aspiring
software developer. Students use C and C and
software development tools of the UNIX
environment.
5Software Engineering Courses
- 201
- Programming in the small
- 301
- team work, object-oriented analysis and design
- 401
- Programming in the large
6Course Goals
- To understand programming language concepts such
as pointers and memory organization. - To be able to program to APIs
- using an API
- implementing an API
- To be familiar with techniques and tools for
debugging, profiling, documentation, - To be proficient in the C language.
7What to expect?
- Cmput201 is a hands-on course.
- The only way to learn a new programming language
is by writing programs in it. --Kernighan and
Richie - Learning by reading other peoples code.
- Most of the lectures consists of case studies of
different programs. - All example programs are available on line, you
are encouraged to experiment with them.
8Assignments
- Assignments are due by 1159pm on the due date.
- A 15 late penalty is assessed for each day (or a
fraction of a day) that the assignment is late,
including the weekends and holidays. - All assignments must be done individually
- Similarity between submissions may be checked.
9Midterm
- Worth 20
- 75 minutes
- Date Mar 2, 2004
10Labs
- There are 11 labs, staring on January 12th
- In CSC 159
- Worth 11 of term marks
- TAs will walk through examples, answer your
questions. - Lab exercises are due at the end of the labs
- Submit by e-mail
- A maximum of 3 late days are allowed.
- Lab material may be questioned in the midterm and
the final exam.
11Evaluation Mechanism
- Assignments 30
- Labs 11
- Midterm 20
- Final Exam 39
- Must get 40 of the Final Exam marks to pass the
course
12Textbooks (Highly Recommended)
- Walter Savitch Absolute C, Addison Wesley, 1st
edition, 2002. ISBN 0-201-70927-9 - Arnold Robbins UNIX in a Nutshell, OReilly, 3rd
edition, 1999. ISBN 1-56592-427-4
13Course Information
- Course home page http//ugweb.cs.ualberta.ca/c201
. - Announcement, Assignment, Lecture schedule and
notes, Student Feedback, and Related Resources. - Course news group ualberta.courses.cmput.201
14Plagiarism and Cheating
- Make sure you have read and are familiar with the
Code of Student Behaviour in the University of
Alberta Calendar (online at http//www.ualberta.ca
/unisecr/policy/sec30.html). Plagiarism and
other forms of cheating are considered to be
serious academic offences.
15History of C
- Invented in 1980s by Bjarne (Be-ar-neh)
Stroustrup at ATT Bell Labs. - Inspired by C and Simula67 (class, virtual
functions). - C started as a one-person project in an
informal setting. - During early stage, there was no paper design, no
committee, no C project, (so were http,
perl, Java(?), ).
16Example Program hello.cpp
- include ltiostreamgt
- using namespace std
- int main()
-
- char name100
- cout ltlt "What is your name? "
- cin gtgt name
- cout ltlt "Hello " ltlt name ltlt "\n"
- cout ltlt "Welcome to CMPUT201!" ltlt endl
17Things to Note in hello.cpp
- Include files
- Name space
- The main() function
- Entry point
- One main() function per program
- Standard input and output
- Normally the keyboard and screen
- May be redirected
- Escape sequence
18- Phases of C Programs
- Edit
- Preprocess
- Compile
- Link
- Load
- Execute
19Relevant Unix Commands
- Edit emacs, vi,
- Preprocess /lib/cpp (called by the compiler)
- Compiler g, gcc
- Linker ld (often called by the compiler)
- default executable file a.out the output of
the assembler
20C Compilers
- Solaris
- CC (Suns compiler) and g GNU compiler
- OpenBSD/Linux
- g GNU compiler
- Cygwin http//www.cygwin.com
- g
- Microsoft Visual C
- Savitch comes with a light version of VC
21Flow of Control
- Sequence of Statements
- Conditional Statement
- if, if-else, nested if, switch
- Loops
- while
- for
- do-while
22Example Program calculator
- Four binary operators , -, , /
- No precedence
- Evaluate from left to right
- Expressions are terminated by
23include ltiostreamgt using namespace std int
main() double operand1, operand2, result
char op cin gtgt operand1 gtgt op //the first
operand and the operator for ( cin op !
'' operand1 result) cin gtgt operand2
if (op'') result operand1
operand2 else if (op'-') result
operand1 - operand2 else if (op'')
result operand1 operand2 else if
(op'/') result operand1 / operand2
else cerr ltlt "Unknown operator '" ltlt op ltlt
"'" ltltendl cin gtgt op cout ltlt result
ltlt "\n"
calc1.cpp
24include ltiostreamgt using namespace std int
main() int operand1, operand2, result
char op cin gtgt operand1 gtgt op //the first
operand and the operator for ( cin op !
'' operand1 result) cin gtgt operand2
if (op'') result operand1
operand2 else if (op'-') result
operand1 - operand2 else if (op'')
result operand1 operand2 else if
(op'/') result operand1 / operand2
else cerr ltlt "Unknown operator '" ltlt op ltlt
"'" ltltendl cin gtgt op cout ltlt result
ltlt "\n"
25Common Pitfalls
- Operator vs. operator
- One means assignment ()
- One means equality ()
- VERY different in C!
- Exampleif (x 12) ?Note operator used!
Do_Somethingelse Do_Something_Else
by Frederick H. Colclough, Colorado Technical
University
26switch Statement Syntax
27Example of switch statement
switch (op) case '' result
operand1 operand2 break case '-'
result operand1 - operand2 break
case '' result operand1 operand2
break case '/' result operand1 /
operand2 break default cerr ltlt
"Unknown operator '" ltlt op ltlt "'" ltltendl
28switch Pitfalls/Tip
- Forgetting the break
- No compiler error
- Execution simply falls thru other cases until
break - Deliberate use of falls thru
- Use multiple labels to provide same entry
- Biggest use MENUs
- Provides clearer big-picture view
- Shows menu structure effectively
- Each branch is one menu choice
by Frederick H. Colclough, Colorado Technical
University
29The break and continue Statements
- Flow of Control
- Recall how loops provide graceful andclear
flow of control in and out - In RARE instances, can alter natural flow
- break
- Forces loop to exit immediately.
- continue
- Skips rest of loop body
- These statements violate natural flow
- Only used when absolutely necessary!
by Frederick H. Colclough, Colorado Technical
University
30int main() double operand1, operand2 char
op cin gtgt operand1 while (cingtgtop) if
(op'') cout ltlt operand1 ltlt "\n"
cin gtgt operand1 continue if
(op'' op'-' op'' op'/')
cin gtgt operand2 if (op'')
operand1 operand2 else if (op'-')
operand1 - operand2 else if
(op'') operand1 operand2
else if (op'/') operand1 / operand2
else cerr ltlt "Unknown operator
'" ltlt op ltlt "'" ltltendl break
calc2.cpp
31Character I/O
- cin.get(ch)
- Read the next character in the stand input and
store it in ch. - Compared with cin gtgt ch
- cin.get(ch) does not skip white space.
- cout.put(ch)
- Same as cout gtgt ch
32Example unix command cat
cat.cpp
include ltiostreamgt using namespace std int
main() char ch while (cin.get(ch))
cout ltlt ch return 0
33What does This Program Do?
include ltiostreamgt using namespace std int
main() char ch bool isSpaceOrTab false
while (cin.get(ch)) if (ch!' '
ch!'\t') cout ltlt ch isSpaceOrTab
false else if (!isSpaceOrTab)
cout ltlt ' ' isSpaceOrTab true
34Program Style
- Bottom-line Make programs easy to read and
modify - Programs must be written for people to read, and
only incidentally for machines to execute.
Abelson Sussman - Comments, two methods
- // Two slashes indicate entire line is to be
ignored - /Delimiters indicates everything between is
ignored/ - Both methods commonly used
- Comments should be brief
- Do not paraphrase what C code explicitly says.
35Comments
- Make the program more readable
- Comments must
- be meaningful
- describe the program and
- be up to date.
- Comments should not repeat what the programming
language itself says - a b c // a becomes the sum of b and c
- count // increment the counter
36Stroustrups Advice on Comments
- For each file
- summary of the contents of the file
- reference to manuals
- general hints for maintenance, etc.
- For each class/template/name space
- function and purpose
- For each nontrivial function
- purpose, algorithm used, assumptions about input
37- For each global and namespace variable and
constant - A few comments where the code is non-obvious
and/or non-portable - Very little else
38Examples Good or Bad?
if (allocFlag NEW_MEMBER) // if allocating
new member if (allocFlag NEW_MEMBER)
// if allocFlag is NEW_MEMBER
Focus on WHY instead of HOW.
39Document the Non-obvious
for (int i 0 iltelmtCount i) / Use
right shift to divide by 2. Compared with
elmti elmti/2 this cuts the loop
time by 75 / elmti elmti gtgt 1
40Identifier Naming Convention
- ALL_CAPS for constants
- lowerToUpper for variables
- Capitalized words for user defined data types and
classes. - Most important MEANINGFUL NAMES!
by Frederick H. Colclough, Colorado Technical
University
41Examples
- Bad
- X X XX
- XXX AreTha SalesTax(AreTha)
- Good
- balance balance lastPayment
- monthlyTotal newPurchases
salesTax(newPurchanses)
42Length of Variable Name
- Too Long
- averageNumberOfStudentsInASection
- totalNumberOfVisitors
- Too Short
- n, avg, num
- v, ttl
- Just Right
- avgNumStudents
- totalVisitors
43Summary 1
- C is case-sensitive
- Use meaningful names
- For variables and constants
- Variables must be declared before use
- Should also be initialized
- Use care in numeric manipulation
- Precision, parentheses, order of operations
by Frederick H. Colclough, Colorado Technical
University
44Summary 2
- include C libraries as needed
- I/O objects cin, cout, and cerr
- Used for standard input, standard output, and
error messages - Use comments to aid understanding ofyour program
- Do not overcomment
by Frederick H. Colclough, Colorado Technical
University