Title: CPS120 Introduction to Computer Science
1CPS120 Introduction to Computer Science
2Compilers
- An engine that works on your behalf to process
instructions and allow you to deal with various
basic rules of the language - The compilers job is to make sure you follow the
rules, to require that you provide enough
information that the compiler can translate you
instructions into languages the components can
understand
3Fundamental Programming Concepts
- One-after-another (Sequence)
- Decision-making (Selection)
- Making choices between 2 or more alternatives
- Repetition (Iteration)
- Concerned with repetitive tasks (and the
termination conditions of loops) - Invocation
- Delegation of sub-tasks to functions / procedures
4Common Flowchart Symbols
5Rules for Pseudocode
- Make the pseudocode language-independent
- Indent lines for readability
- Make key words stick out by showing them
capitalized, in a different color or a different
font - Punctuation is optional
- End every IF with ENDIF
- Begin loop with LOOP and end with ENDLOOP
- Show MAINLINE first all others follow
- TERMINATE all routines with an END instruction
6Syntax Logic Errors
- A syntax error is simply the violation of the
rules of a language misuse of structure and form
in programming or a violation of the compilers
rules. These errors are detected by the compiler - A logic error is a mistake that complies with the
rules of the compiler that causes the program to
generate incorrect output
7Compiling and Debugging
- Executable code will not be created until you
correct all of the syntax errors in your source
code
8Linker Errors
- Not all syntax errors are detectable by the
compiler - These errors do not become apparent until files
are put together to create an executable - These errors are not linked to a specific line of
code
9Alphanumeric Codes
- American Standard Code for Information
Interchange (ASCII) - 7-bit code
- Since the unit of storage is a bit, all ASCII
codes are represented by 8 bits, with a zero in
the most significant digit - H e l l o W o r l d
- 48 65 6C 6C 6F 20 57 6F 72 6C 64
10Decimal Equivalents
- Assuming the bits are unsigned, the decimal value
represented by the bits of a byte can be
calculated as follows - Number the bits beginning on the right using
superscripts beginning with 0 and increasing as
you move left - Note 20, by definition is 1
- Use each superscript as an exponent of a power of
2 - Multiply the value of each bit by its
corresponding power of 2 - Add the products obtained
11Binary to Hex
- Step 1 Form four-bit groups beginning from the
rightmost bit of the binary number - If the last group (at the leftmost position) has
less than four bits, add extra zeros to the left
of the group to make it a four-bit group - Step 2 Replace each four-bit group by its
hexadecimal equivalent - 19EAA7(16
12Converting Decimal to Other Bases
- Step 1 Divide the number by the base you are
converting to (r) - Step 2 Successively divide the quotients by (r)
until a zero quotient is obtained - Step 3 The decimal equivalent is obtained by
writing the remainders of the successive division
in the opposite order in which they were obtained - Know as modulus arithmetic
- Step 4 Verify the result by multiplying it out
13Representing Negatives
- It is necessary to choose one of the bits of the
basic unit as a sign bit - Usually the leftmost bit
- By convention, 0 is positive and 1 is negative
- Positive values have the same representation in
all conventions - However, in order to interpret the content of any
memory location correctly, it necessary to know
the convention being used used for negative
numbers
14Sign-Magnitude
- For a basic unit of N bits, the leftmost bit is
used exclusively to represent the sign
15Sign-magnitude Operations
- Addition of two numbers in sign-magnitude is
carried out using the usual conventions of binary
arithmetic - If both numbers are the same sign, we add their
magnitude and copy the same sign - If different signs, determine which number has
the larger magnitude and subtract the other from
it. The sign of the result is the sign of the
operand with the larger magnitude
16Ones Complement
- Positive numbers are represented in the usual way
- For negatives
- STEP 1 Start with the binary representation of
the absolute value - STEP 2 Complement all of its bits
17One's Complement Operations
- Treat the sign bit as any other bit
- For addition, carry out of the leftmost bit is
added to the rightmost bit end-around carry
18Twos Complement Convention
- A positive number is represented using a
procedure similar to sign-magnitude - To express a negative number
- Express the absolute value of the number in
binary - Change all the zeros to ones and all the ones to
zeros (called complementing the bits) - Add one to the number obtained in Step 2
19Twos Complement Operations
- Addition
- Treat the numbers as unsigned integers
- The sign bit is treated as any other number
- Ignore any carry on the leftmost position
- Subtraction
- Treat the numbers as unsigned integers
- If a "borrow" is necessary in the leftmost place,
borrow as if there were another invisible
one-bit to the left of the minuend
20C Usages Conventions
- C is absolutely case sensitive
- For Instance A is 97 in ASCII and a is 65
- Remember in ASCII , , and ( are not equivalent
- No keywords in ANSI standard are even partially
uppercase - While is not a keyword, while is
- Be careful if you define new keywords
21Comments
- Document what is happening, why it is happening
and other issues - Commentary is ignored by the compiler
- C has inline, block and documentary comments
- Inline comments are within line of code
- Use the // symbols
- Block comments are long comments delimited with
/ and /
22Compiler Directives
- Instructions to the compiler rather than part of
the C language - Most common directive is include
- include ltiostream.hgt
- A .h file is a header file. It serves as a link
between program code and standard C code needed
to make programs run
23Functions
- A function is a block of code that carries out a
specific task - Every C program has a main function that
executes when a program initiates - Includes open parenthesis to designate a function
- Ends with a return 0 statement
24Scope Delimiters
- A symbol or pair of symbols used to define a
region or area which is considered a locale - In programming, many structures need to have
their scope defined because they should not
affect the entire program - In C, the symbols and are used
25Semicolons
- There must be a semicolon after every statement
- To tell the compiler that the statement is
complete - Function definitions and compiler directives are
exempt
26C Control Structures
- "Sequence statements" are imperatives
- "Selection" is the "if then else" statement
- AND, OR, NOT and parentheses ( ) can be used for
compound conditions - "Iteration" is satisfied by a number of
statements - "while"
- " do "
- "for"
- The case-type statement is satisfied by the
"switch" statement. - CASE statements are used for most non-trivial
selection decisions
27Data Types - Characters
- To store a letter or a single character (such as
, , , etc.), we use a variable of the char
data type. - A char variable only uses 1 byte of memory.
- A char variable can only hold one letter, digit,
or character.
28Data Types Words / Phrases
- To store a word or phrase (string value), we use
a variable that is a string - Technically string is not a data type but a class
29Using Variables in C
- Variables must be declared before they are used
in C. Get into the habit of doing this at the
top of your functions
30Variable Names
- Choose your own variable names but you must be
careful to use valid ones - do not use keywords that are defined in the
programming language (Reserved Words) - do not include spaces or other disallowed
characters - do not use more than 255 characters
- do begin the identifier with a letter
31Initializing Variables
- C does not automatically initialize all
variables
32The Assignment Operator
- The assignment operator is the equal symbol ()
- The assignment operator changes the value of the
variable to its left after evaluating the
expression on its right
33Decision Making In Computers
- When decisions are made in a computer program,
they are simply the result of a computation in
which the final result is either TRUE or FALSE - The value zero (0) is considered to be FALSE by
C. Any positive or negative value is considered
to be TRUE
34Using Relational Operators
- Relational operators provide the tools with
which programs make decisions
equal to NOTE this is two equals
symbols next to each other, not to be confused
with the assignment operator, gt greater
thanlt less thangt greater than or
equal tolt less than or equal to!
not equal to
35Complete order of operations
- The complete order of operations including all of
the arithmetic, relational, and logical operators
including all of the basic arithmetic,
relational, logical operators is - , /,
- , -
- lt, gt, lt, gt, , !
- !
-
-
36Character Arrays
- An array is a group of variables of the same data
type that appear together in memory - In this case each variable holds a character and
the last variable in the string holds the null
terminator (/0)
37Input Operations
- The operator gtgt is known as the input operator.
It is also known as the extraction operator - You use the input operator in statements like,
- cin gtgt numItems
- which would allow the user to input a value to
be stored in the variable numItems.
38Complexities of Word Input
- Some things are done automatically with gtgt
- get does not skip over line breaks and spaces
- If the user enters a string longer than the
length specified in the call to the get function,
the remaining characters are left in the input
stream - Get always ignores the new line character (\n)
and leaves it in the stream - Use the ignore function to flush the contents of
the input stream - cin.ignore(80, \n)
39Decision Making in C
- if statement
- switch statement
- ? conditional operator statement
- goto statement
40General Form
- if (test expression)
-
- True-block statements
-
- else
-
- False-block statements
-
- next statement
41Iterate
- A program loop is a form of iteration. A computer
can be instructed to repeat instructions under
certain conditions.
42Syntax of a for Loop
- for (initializing expression control expression
step expression) // one or more
statements - The initializing expression sets the counter
variable for the loop to its initial value. - The control expression ends the loop at the
specified moment. - The step expression changes the counter variable
- Semi-colons, not commas, divide the expressions
43While Loop Syntax
- while (control expression) // one or
more statements - The control expression must evaluate to TRUE in
order for the while loop to iterate even once
44Do While Syntax
- do // body statements would be placed
herewhile (control expression) - Don't forget to include the required semicolon
after the control expression
45Break and Continue
- continue causes while, do while, and for loops
to start over - break causes while, do while, for and switch
statements to end
46An Example of A Function
- include ltiostream.hgt
- void printMyMessage(int numOfTimes) //
PROTOTYPE and NAME - int main( )
-
-
-
- printMyMessage (userInput) // CALL
STATEMENT WITH ACTUAL PARAMETER -
-
- return 0
- // end of main
- void printMyMessage(int numOfTimes) // FUNCTION
HEADER - int i0 // LOCAL VARIABLE WITHIN THE FUNCTION
-
- for (i0 ilt numOfTimes i) // BODY
- cout ltlt "Let's Go State!!" ltlt endl // OF THE
- //end of printMyMessage // FUNCTION
47Scope of Variables
- The scope of a variable is the area in which it
can be legally referenced - Variables are either global or local in nature
- Global variables are ones that are declared
outside and above the main function - They can be used in any function throughout the
program. - It is not wise to use global variables any more
than you have to. - Local variables are ones that are declared inside
of a function, including main. They cannot be
used or referred to in other functions
48Reading From a File
- Declare a file pointer as an ifstream object
with - ifstream infile
- ifstream is a keyword and infile is the name for
the file pointer. - Open the actual file for reading with
- infile.open("mydata.txt", iosin) infile.
open("mydata.txt")
49Writing Output
- To write data to a sequential-access data file
you would use a statement like - outfile ltlt "John Doe" ltlt endl
- to print that name to the next line in the data
file pointed to by the file pointer, outfile.
50Appending Data
- Adding data to the end of a sequential-access
data file is called appending - Open the file using the iosapp stream operation
mode as in - outfile.open("myfile.txt", iosapp)
- where the app is short for append.
- If you accidentally open the file with the
iosout mode, you will end up overwriting data
in the file because C will write the first
piece of outputted data at the beginning of the
sequential-access data file
51Declaring an Array
- To declare an array before it is used in the body
of your program, you must use a statement like - int scores10
- This would declare an array of integers, named
"scores". - In this case, scores can store up to 10 different
integer values. - The positions of the array are identified by
their index positions which run from 0 to 9 (not
1 to 10.) - Each one of the 10 variables in scores is called
an element
52Initializing an Array
- If you wish to initialize each element of an
array to a specific value, you can use the
statement,int scores 65, 76, 45, 83, 99 - You don't even have to specify a size of the
array in this case since the initialization
statementwould cause the compiler to declare an
array of size 5 since there are five values in
the set of curly braces
53Declaring a Multi-dimensional Array
- To declare an array of integers called
studentGrades to be a 2-dimensional array with 3
rows and 4 columns, you would use the
statementint studentGrades3 4where the
first integer value is used to specify the number
of rows in the array and the second value
specifies the number of columns - Think of remote control