Title: Week 3
1Week 3
- Get some information in,
- Do something with it,
- Display the result.
2Learning Points
- Structure of a simple C Program
- TYPES of information
- Simple and Complex
- Variables, Constants and Literals
- Identifiers to Name memory
- Declarations
- Getting information into your program basics
- Operator basics
3(No Transcript)
4Problem Solving Techniques
- OVERCOME MENTAL BLOCK -- by rewriting the problem
in your own words - DRAW A FIGURE/DIAGRAM
- ASK QUESTIONS
- What information must be displayed? What is
information do you know? what do you NOT know and
need? what information can you assume to make
things simpler for yourself?, What kind of
information am I manipulating (whole numbers,
numbers with decimal points, text? What would be
good identifiers (names) for the information. - Where does the information come from? Is it
given? Can it be assumed? Do you get it from the
user? do you calculate it? do you get it from a
file? - Can you identify what is input and what is to be
output? - What are the processes?
- Do you need to repeat steps
- What are the conditions?
- Do you need to do different things in different
situations? - What are the conditions
5Problem Solving Techniques
- LOOK FOR FAMILIAR THINGS -- certain situations
arise again and again. E.g. Am I repeatedly
getting input from the user? creating tables,
adding up lists of numbers, reading from files,
Searching for maximum or minimum values. - Do you know any equations?
- Find the wall area of a room, find the stopping
distance of a car.
6Problem Solving Techniques
- Stepwise refinement -- break up large problems
into manageable units. - SIMPLIFY
- Can you solve a simpler but related problem?
- For example a program to calculate wall areas of
rooms for a decorating company. - Solve problem assuming simple rectangular rooms
without doors and windows. - Solve by analogy -- it may give you a place to
start. In a broader sense than looking for
familiar things. - E.g. Finding the student with the highest and
lowest score is analogous to finding the highest
and lowest temperature.
7Problem Solving
- USE MEANS-ENDS ANALYSIS
- Where you often know start conditions and know
what the end goal is. - Identify intermediate goals then think how you
get from start to the intermediary goals choosing
the most appropriate means for the problem. - E.g. I am hungry and I want to be full
- What's the difference between what I have and
what I want? An empty stomach. What changes the
emptiness of my stomach? Eating food. But I
don't have any food. I want to have some food.Â
What's the difference between what I have and
what I want? The presence of food. What changes
the presence of food? Searching, shopping,
hunting, growing food. I search for food, but
there is nothing available. I decide to shop for
food. What do I need to shop? Money. But I
don't have any money. I want some money. How do
I get money? Withdraw from the bank, sell
something, steal. I decide to withdraw from the
bank. I want some money from the bank. What do
I need to get money from the bank? I must be at
the bank. I want to be at the bank. What is the
difference between where I am now and where the
bank is? Distance. What changes distance?Â
Walk, cycle, drive, bus. ..... and so on
8Problem Solving Techniques
- BUILDING-BLOCK APPPROACH -- can you solve small
pieces of the problem? And then join them up - E.g. a large application like a word processor
has many functions. (Text manipulation, Tables,
drawing) - Do not try to solve all at once.
9Result of Problem solving
- One or more pages of rough work that sketches
your ideas of problem requirements, of user
inputs, of outputs, of constants, of conditions
for repetition and selection, of assumptions. - A formal written design that include.
- inputs, Processes, Outputs, assumptions.
- Write steps to process input unambiguously using
a semi formal notation (PDL, Flowchart or
structure diagram?) Can you translate each step
of the plan into C easily? - Verification/testing procedures documented (A
test table).
10What we are aiming for is Structured Methodical,
Systematic Approach to Programming
- Advantages
- Not one giant step, but breaks in to smaller and
smaller chunks. - Programmer concentrates on details
- Easy to do in teams
- Easy to keep track of development
- Creates more reliable and robust programs.
- Errors isolated
- Design written in code
- Improves reliability
- Minimizes risk of Failure
- Faster development
- Makes more possible reuse and extensibility.
11Summary
- So take any problem, apply problem solving
approaches. To find a solution, write it down in
English. - Write it down more formally in Pseudo-code (PDL),
or as a structure diagram or a flow chart. - Start your programming environment and convert
your pseudo-code to C - Order the computer to convert the C to machine
language (compile) - Order the computer to load the machine language
into memory and execute (Run).
12Recall from last week A Skeleton program
include ltiostreamgt using namespace std int
main ( ) return 0
type of returned value
name of function
We call main( ) a FUNCTION. Functions are used to
collect together instructions. main( ) is a
special function because it is the first thing
that is executed
13What happens?
- The operating system (XP) Loads the program
- Think of it as XP calling the main function.
- Instructions in main are carried out one at a
time. - Notice the int in front of main this line is
like a contract to the operating system - I will send you a piece of information in the
form of an integer. - Hence the NEED for a return instruction. return 0
sends a zero to windows XP
14Discussion of structure
- Your program must have a function called main
- Note that Main, MAIN, mAiN will cause an error
- The round brackets ( and )after main tells
the computer that main is a function rather than
a variable. - The curly brackets and mark the beginning
and end of instructions that form the body of
main. - The semi-colon after return 0 is an
instruction terminator or separator.
15The Hello World Program
accesses standard toolbox, i.e. we are using
the display (cout) tool, the send to tool and
the endl tool
include ltiostreamgt using namespace std int
main ( ) cout ltlt Hello World ltlt endl
return 0
Instructions that tell computer that I want to
use iostream toolbox and access the standard
(std) tools for input and output
16Discussion of Hello World Program
- There are now two instructions in main
- we added a display information instruction using
a tool cout - cout represents the display screen. It hides all
the complicated business of displaying things
from you. All you need to know is how to use
cout. - cout receives information using the ltlt send to
operator (insertion operator). - So we literally send the string Hello world to
the display! - endl (last letter is lowercase L not number 1!)
is also sent to the display, this is interpreted
by cout as a new-line command.
17Discussion of Hello World
- cout is an OBJECT that represents our screen.
- Screens are hardware.
- Sending information to screens varies greatly
from machine to machine. - So cout became standard. Customised couts were
created for all the major types of computer in
the world. - So that you can write one piece of code that
should compile on all the main types of computer
in the world.
18Discussion of Hello World
- Because cout NOT BUILT IN we need to tell the
computer that we want to make use of the
standard facilities for input and output - HENCE the lines
- include ltiostreamgt
- using namespace standard
This is one of the original reasons for C
popularity its relative ease of porting from one
type of computer to another
19Some Definitions
- Statements
- A statement is what programmers often call an
instruction. - Your code consists of many instructions/statements
- Statements end with a semi-colon
- blocks
- Any section of code which is surrounded by curly
brackets is a block
20Example A Block of 4 statements
-
- cout ltlt"A fraction "ltlt5.0/8.0 ltltendl
- cout ltlt"Big "ltlt 7000.07000.0ltltendl
- cout ltlt8 5 ltlt" is the sum of 8 5\n"
- cout ltlt Hello world
-
Block denoted by Curly braces
21TYPES of information computers use
- Simple (needs little or no effort to use)
- To hold whole numbers (integers)
- To hold numbers with fractions (float and double)
- To hold individual characters (char)
- Complex (needs a little more work to use)
- Strings
- cin and cout
22Simple Information
int
- Integer (Whole numbers)
- For counting things
- To represent values which only have whole numbers
- Pounds, Pence?
- Grades, Scores (Chelsea 0 Penge United 10)
- Categories (days of week codes as numbers 1-7)
23Simple Information
float
double
- Floating points numbers
- For representing numbers that may contain
fractions - Averages, measurements, money, pi
24Simple information
char
- Single characters
- Can represents your initials
- Can represent single key responses to questions
- y for yes and n for no
- Not much else??
25What about Strings
include ltstringgt
string
- Some languages this is a simple piece of
information - In C it is not. A string is complex in that it
is made up of lots of chars. - In C we use the standard string tools
26Recap!
- Your programs will usually entail
- Reserving and labelling some space to store
information - Getting information into the space you reserved
- This information will either be whole numbers,
floating point numbers, single characters or
strings. - More complex information we will cover at a later
date. - Doing something (operate on) with the information
(int, float, double, char or string) - Displaying results
27Constants, Variables and Literals
Fundamental building blocks of programs
- Remember at school
- Area of a circle is pr2
- Circumference of a circle is 2 pr
- p is a constant representing the number 3.142
- r is a variable representing the radius of a
circle - 2 literally represents itself, it is a literal
28Key programming concept
- You can categorise the information you are using
as either - constant
- variable
- literal
- Programs use, variables, constants and literals
to store information needed to solve problems
29Fundamental task isGetting information in to the
computer
- We enter values of literals directly into code.
- We instruct the computer to reserve space for a
constant and we enter the value of the constant
directly into code - We instruct the computer to reserve space for a
variable. We have a choice on how we enter values
of variables. - We can enter values directly in code
(assignments) - Values can be set interactively with a user.
- Values can be set interactively with a file on
disk.
30Using literals
- char, string, integer, and double values are
referred to by value not by a name. - We type these directly in to code
include ltiostreamgt using namespace std int
main() cout ltltThe sum of one plus three is
ltlt 1 3 ltlt endl return 0
string literal
2 integer literals
31char literals
include ltiostreamgt using namespace std int
main() cout ltltFirst letter of the alphabet is
ltlt A ltlt endl return 0
char literals in SINGLE QUOTES
32floating point literals
- floating point number can contain fractions.
- floating point literals are double
include ltiostreamgt using namespace std int
main() cout ltltone point one plus three point
two is ltlt 1.1 3.2 ltlt endl return 0
2 double literals
33Discussion
- You can enter information directly into code
using literals - This is obviously very limiting if a program
wanted to reuse a value we need to keep typing in
its value every time. - Also if a program makes use of a value many times
it is hard work to change all the CORRECT
references in a long program, especially is the
number, say 10 refers to a count in one part of
the program and the number 10 means a grade in
another. How can we differentiate between them? - It can also be very confusing for another person
to understand what the numbers mean.
34SolutionVariables and Constants
- These are NAMED areas of memory.
- The programmer instructs the computer to reserve
space for the kind of information he/she wants
and at the same time tell the computer the name
that will be used to refer to that bit of
information. - This kind of instruction is called a DECLARATION
35DECLARATION
- We can declare
- Integers
- floating point numbers
- chars
- strings
36Constants and Variable Declarations
- When a variable is declared the computer marks
the bit of memory reserves so that it allows its
contents to change (vary) at any time. - When a constant is declared the computer
effectively locks the memory reserved and
prevents the contents being updated.
37Creating Constants and Variables
include ltiostreamgt using namespace std int
main() const double Pi 3.142 double
radius double Area, Circumference Area
Piradiusradius Circumference
2Piradius return 0
Declarations are instructions to reserve
memory space big enough to store our
information. It also creates an identifier (a
name) for us to refer to this memory space
38Rules for Creating Constants
const lttypegt ltidentifiergt ltvaluegt
lttypegt choose one of int char float double string
ltvaluegt You provide the constant value e.g. for
Pi value was 3.142
ltidentifiergt You create a name. It must obey the
rules for identifiers (see rules in a minute)
39Examples
const int maxnumber 10 const double Pi
3.142 const char AGrade A const string
MyName Chris
40Rules for Creating Variables
lttypegt ltidentifiergt or lttypegt ltidentifiergt
ltvaluegt or lttypegt ltidentifiergt, ltidentifiergt,
41Examples
int number double Result char response string
UserName
int n1, n2, n3, n4
Declare a double variable and set its initial
value
double x 5.6
42Rules for Creating Identifiers
- An identifier must start with a letter or
underscore, and be followed by zero or more
letters - (A-Z, a-z), digits (0-9), or underscores
-
- VALID
- age_of_dog taxRateY2K
- PrintHeading ageOfHorse
- NOT VALID (Why?)
- age 2000TaxRate Age-Of-Cat
- Age of Cat
43Meaningful Identifiers
Age-Of-Cat Age of Cat
ILLEGAL!!
Use underscore to link words or run words
together and capitalise the start of each word
LEGAL!!
Age_Of_Cat AgeOfCat
44More About Identifiers
- C is case sensitive so
- NUMBER Number number
- are all legitimate but DIFFERENT identifiers
- BE CONSISTENT in your code!
- It is NOT good practice to have long identifiers
- Why?
45Long Identifier Names
- Some C compilers recognize only the first 32
characters of an identifier as significant - then these identifiers are considered the same
- age_Of_This_Old_Rhinoceros_At_My_Zoo
- age_Of_This_Old_Rhinoceros_At_My_Safari
- Also it is very annoying to keep typing in!
46Meaningful Identifiers
- It is common sense to try to create identifiers
that are - Meaningful- they describe the information they
refer to - E.g. Height, Count, BloodPressure, CarSpeed
- Terse- They are only as long as necessary to
convey meaning.
47Reserved Words
- Identifiers CANNOT be a reserved word.
- Reserved words are built in words that have
special meanings in the language. They must be
used only for their specified purpose. Using them
for any other purpose will result in a error. - e.g. do if switch while else return
48Reserved Words
- C is case sensitive. ALL reserved words are
lower case
WHILE While while Are all different identifiers
only the last is a reserved word
49Operators
- All the data types we have seen (int, float,
double, char and string) have a set of operators
that can be applied to them - E.g. Numerical data uses the familiar - / for
add subtract and divide. - The asterisk is used for multiplication
- These work in the usual manner
50string operators
- arithmetic is not meaningful when applied to
strings - You do not multiply first names!
- strings operators do other things
- E.g. The operator applied to strings joins them
(concatenates) together - We will see other operations we want to do with
strings like searching a string for a substring
or comparing strings.
51Expressions
- A VALID arrangement of variables, constants,
literals and operators
Expressions are evaluated and compute to a VALUE
of a given type E.g. Expression 9 4 computes
to 13
52A special OPERATOR
The assignment operator
Causes much confusion! IT DOES NOT WORK LIKE
EQUALS IN MATHS
53variable expression
Interpretation of Takes the value of or
becomes
- number 4
- result 10 number
- number number 1
expression simply consists of the literal int 4.
number takes the value of 4
expression evaluates to 40. result takes the
value of 40
expression evaluates to 5 number takes the value
of 5
KEY POINT expression is evaluated BEFORE it is
applied
54Using assignments to get information into the
computer
- int myage
- string myname
- double mysalary
- myage 21
- myname Chris
- mysalary 1000.00
55Interactive input formally covered later
- using cin and cout
- using data files
56Bye Bye