CS 108 Computing Fundamentals September 8, 2004

Download Report

Transcript CS 108 Computing Fundamentals September 8, 2004

CS 108 Computing Fundamentals
Notes for Tuesday, January 27, 2015
GHP #1b and #2
• Due today at 8 AM… I am missing about 12 GHP #1b and 12
GHP #2 submissions
• I started grading GHP 1b late night
•I will grade the rest today and tomorrow
• If you have not yet submitted: do so ASAP to minimize the
impact of submitting late (I deduct 1.5 points for GHP 1b and 3
points for GHP #2 per day)… if you have not submitted, then you
lost 1.5 or 3 points for lateness already… you have until
Wednesday afternoon 8 AM to submit before you lose another 1.5
or 3 points for lateness
• I'm available for help… I'm your best resource for CS 108 help
Abstraction
• What is abstraction?
• Why is abstraction important?
• In computing, we heavily embrace abstraction
• As programmers, we LOVE abstraction
Abstraction Means:
1. We know what the “thing” does
2. We know how to make “inputs”
3. We get predictable/expected output for a given specific
input… an input is transformed into an expected output
4. We do not know HOW an input is transformed into an
expected output
Examples of Abstraction
• An automobile transmission
• A photo-taking booth at an arcade
• Airline travel
• Anything that acts like a "black-box"
Abstraction
• Each virtual machine layer is
an abstraction to the level
above it.
• The machines at each level
execute their own particular
instructions, calling upon
machines at lower levels to
perform tasks as required.
• Computer circuits ultimately
carry out the work.
Review of Abstraction
1. We know what the “thing” does
2. We know how to make “inputs”
3. We get predictable/expected output for a given specific
input… an input is transformed into an expected output
4. We do not know HOW an input is transformed into an
expected output
Abstraction and the C
Programming Language
• C and most programming language are all about abstraction
The "form" of C encourages us to break large objective into
smaller tasks and to write small pieces of code to
accomplish the smaller tasks
In C we use functions (from provided libraries of
functions or our own libraries) and we also write
functions to accomplish smaller tasks
C functions (both from libraries and the functions ones
we write) are grouped together to form programs which
accomplish a larger, overall objective
The “internals” of C functions are often hidden
Let's Jump Into Programming
• We are going to use C in this course as our programming language
of choice
 The higher-level concepts that we are going to learn are not
"C specific"
• C programs are collections of statement and functions
(subroutines or sub-programs) woven together to solve a problem or
accomplish a task.
• Key point to remember: C (like UNIX) is case sensitive.
You Have Already Learned Some of
the Thing's You'll Need to Program
• All of our CS 108 C programs start as text files on Fang (text
files that contain C code are call source-code files)
 For GHP #2 you created a text file on Fang that contained 3
algorithms… you used the pico text editor on Fang
 We will use pico on Fang to create our C text files (aka C
source-code files)
 Our C source code files may have any legal filename,
but they must be have a .c filetype
 Examples: practice.c ghp3.c stuff.c
Compiling a Source-code File
• Once you have a properly named C source code file, you must
use a compiler to transform a C source-code file into an
executable file
 Our compiler of choice is the gcc compiler
Compiling a Source-code File
• We compile a C source-code file by typing gcc followed by a
space followed by the name of the source-code file (we do this
at the Fang prompt)
 Examples:
gcc practice.c
gcc ghp3.c
gcc stuff.c
Let's Give It a Try
• Let’s logon to Fang using Putty
• After we logon we'll create a file named first.c
 first.c will contain only one blank space and nothing else
 Watch what happens when we compile first.c (remember, it
contains only a space):
gcc first.c
Let's Give It a Try
• We get an error… something like this:
/usr/lib/crt1.o(.text+0x85): In function `_start':
: undefined reference to `main'
• This is to be expected because our source-code file (first.c)
didn't contain anything more than a single space… the gcc
compiler was expecting to find text in first.c that is part of the C
programming language
 C source-code files must be composed of text that is part
of the C programming language
Let's Give It a Try
• Let's open first.c and add something from the C programming
language
 Into first.c let's add this line:
main ( ) { }
• Now let's save first.c and compile using the gcc compiler:
gcc first.c
• What happens?
Let's Give It a Try
•Now let's save first.c and compile using the gcc compiler:
gcc first.c
• What happened?
 There were no errors this time… this is a good thing
because it means that the source-code file was successfully
compiled (transformed into an executable program).
 How do we run the program?
 Type ./a.out at the Fang prompt
 What happens? Why?
Let's Give It a Try
• How do we run the program?
 Type ./a.out at the Fang prompt
 What happens? Why?
 Nothing happens because our source-code
essentially contained no instructions
 The executable file did, in fact, execute, but it did
nothing that we could see (it did interact with the
operating system and it did take up a few cycles of
the CPU)
Let's Give It a Try
• The bare minimum code that's required in every, every,
EVERY C source-code text file is this:
main ( ) { }
Every source-code C
file must have a main
function definition
Every C function definition has
the function's name followed by a
( ) which encloses the formal
parameters/arguments list (this
one is empty)
Every C function definition
contains instructions that are
found between { (signifying the
start of the function's
instructions) and the }
(signifying the end of the
function's instructions)… there
are no instructions in this source
code
Win a Bet With Other C
Programmers
• The shortest legal compliable C program is just 8 characters:
main(){}
Name of
the function
is main
Open and
Close
Parenthesis
Open and
Close
Curly Brace
Some Syntax
• The first function in all C programs and the only function
required by all C programs: main( )
• main( ) controls the flow of a program… it’s the quarterback
• All functions (including main ( ) ) are composed of
statements
• Statements in C end in a ;
• Function statements are grouped together into blocks which
are all the statements between { }
More Syntax (1)
• We can make first.c a lot more readable if we rewrite it as
follows:
main ( )
{
}
• This is known as the Allman style (named for Eric Allman)
http://en.wikipedia.org/wiki/Indent_style#Allman_style
More Syntax (2)
• Normally we expect this in the main ( ) (main function):
main ( )
{
C instruction statement ;
C instruction statement ;
C instruction statement ;
}
• This is known as the Allman style (named for Eric Allman)
http://en.wikipedia.org/wiki/Indent_style#Allman_style
More Syntax (3)
• Additionally, we normally return values when our functions
complete their work
 The main ( ) normally returns an integer value to the
operating system when it's complete (think of this as a "signal
flag")… the integer value 0 is returned when the program runs
successfully… here's how we make this happen :
main( )
int main ( )
"returned"
Function's
{
value
"returned"
return ( 0 ) ;
}
data type
return is a special statement in C and it performs a specific
task, but it is not a function (even though it looks like a
function)… this also works:
return 0 ; ( notice no ( ) )
More Syntax (4)
• One more thing: the ( ) holds information that's received from
the calling environment for the function to use/work
upon/digest… if the function is designed to receive nothing,
then we should put the keyword void inside the formal
parameters list or formal arguments list ( ) … here's first.c
rewritten:
int main ( void )
{
return ( 0 ) ;
}
• Let's recompile (using gcc) and rerun the resulting executable
file ( ./a.out )
More Syntax (5)
int main ( void )
{
return ( 0 ) ;
}
•The ( ) in a function definition:
 Holds information that's received into from the calling
environment… the function then uses, manipulates,
transforms that received information)
 If we have nothing received into a function, then we
should put the keyword void inside the ( ) of the definition
 Everything contained inside the ( ) in a function
definition is called the function’s formal parameters list or
the function’s formal arguments list
More Syntax (6)
• Although our source-code compiles and executes, it does nothing…
let's add a statement that does something
int main ( void )
{
printf ( " C programming is slice of pie. " ) ;
return ( 0 ) ;
}
• printf( ) is a function in C that is found in a "library" of related
functions… libraries hold functions for us to use that have been
written by other programmers
• In the code above, I am calling the printf( ) and sending it a string
constant " C programming is slice of pie. "
• Let's recompile (using gcc) and see what happens
More Syntax (7)
printf ( " C programming is slice of pie. " ) ;
•The ( ) in a function call:
 Holds information that is being passed to the function for
the function to work on (use, manipulate, transform)
 If we have nothing to send the function, then we should
leave the ( ) empty ( do not use void in a function’s call )
 Everything contained inside the ( ) in a function call is
known as the function’s actual parameters list or the
function’s actual arguments list
More Syntax (8)
• Compiling the source-code below resulted in an error… why?
int main ( void )
{
printf ( " C programming is slice of pie. " ) ;
return ( 0 ) ;
}
More Syntax (9)
• Compiling the source-code below resulted in an error… why?
 Because we didn't tell the compiler where to find the function
that we called ( printf ( ) )… we need to "include" the specific
library necessary
 We need to include a preprocessor directive ( # include ) that
explicitly states the name of the library (< stdio.h >) which we wish
to use ( <stdio.h> is where the printf ( ) source-code is located)
Preprocessor
# include <stdio.h>
command
int main ( void )
{
printf ( " C programming is a slice of pie. " ) ;
return ( 0 ) ;
}
More Syntax (10)
• The output is not as nice as it could be
• Let's add some line-feeds/new-line characters ( \n ) to make the
output a little more readable
Line-feed
"escape
sequence"
# include <stdio.h>
int main ( void )
{
printf ( " \n C programming is a slice of pie. \n " ) ;
return ( 0 ) ;
}
•
The output was not as nice as it could be, so I added the "linefeeds" escape sequences before and after the text string to improve
the appearance
More Syntax (11)
• Comments are very useful/helpful/required in my CS 108 world
/* This is an example program written for
class on January 27, 2015 by Chris Urban…
it does nothing but display a line of text
to the screen.
*/
# include <stdio.h> // My file first.c
int main ( void )
{
printf (" \n I hope you C things my way. \n\n\n " ) ;
return ( 0 ) ;
}
/* End of program */
More Syntax (12)
• main( )
can be read as
 the function named main
 the line of code in the function named main that is literally
main( )
• Functions are of two different types:
 Standard-library (predefined) functions
Source-code is found in code libraries
 Programmer-created functions (PCFs)
Programmers create the source-code themselves
• main( ) is followed by { which signifies the beginning
of the main( ) function block of statements
• eventually } is used to signify the end of the main( )
block of statements
A Real C Example of Abstraction
• Do we know exactly HOW printf( ) works?
printf (" \n I hope you C things my way. \n\n\n " ) ;
• All the details are abstracted away… those details reside in the
stdio.h library file… that’s why we have to “link” to that library
(the compiler needs the contents of the library file for printf( ) so
it can obtain and use printf( ) source-code with our source-code
during compilation)
Variables
• Variables are basic data objects
• Variables are "declared" or created before they are used
• Every variable has characteristics or properties
– Name (also called an identifier)
– Data type (this determines encoding/decoding)
– Value
– An address in main memory
• Variables may be/should be "initialized“ when they are declared
• A variable name is the symbolic representation of the memory
location that is allocated when a variable is declared
Variables
• A variable name is the symbolic representation of the memory
location that is allocated when a variable is declared
• Let’s do some chalk talk and discuss the concept of a “symbol
table”
More on Variables
• First character of a variable name/identifier must be a letter
• Only 31 spaces are allowed in any identifier
• Can’t use reserved words (like main or int)
• Suggestions: short, sweet, meaningful, lowercase, use
underscores
• ;
• We often use the assignment operator ( = ) to assign a value to a
variable
Data Types
•
A variable’s data type specifies (de facto):
 the kind of value that variable can store
 the range of values that a variable can store on the specific
machine (computer) we are using
 the set of operations that can be applied to that variable
•
Four main data types
int
float
double
char
Declaration of Variable Statements
(The following is a “snippet” of C code)
# include <stdio.h>
int main(void)
{
int first_val = 0 , second_val = 0 , sum = 0 ;
float batting_ average = 0.0 ;
char selection = 'z' ;
printf( )
• This is a standard output function found in stdio.h library
• Display info to the monitor
• The arguments list (aka "actual parameters list") is enclosed in
parentheses… notice " " which signifies a string constant… this
string constant may contain text, punctuation, and escape-sequence or
escape characters, and format specifiers/placeholders/conversion
specifiers
printf ( " \n I hope you C things my way. \n " ) ;
• Try Google’ing this phrase: “C escape sequences”
More printf( )
printf ( " The batting average is %f " , batting_average ) ;
• Arguments / actual arguments / actual parameters: everything between
the ( ) of a function's call
 Format string or string constant (everything between the " " )
 Placeholder or format specifier or conversion specifier… in this
case: %f … must match the data type of the corresponding data list
item
 Data list ( variable name(s), constant(s), expressions, or function
call(s)… each of which resolves to a single value )… in this case
a variable name: batting_average
Data list identifiers must correspond one-to-one with the format
specifiers in the format string/string constant
scanf( )
• scanf( ) is standard input function found in stdio.h
• Copies the data from an input device into the variable specified as an
argument
scanf( " %f ", &batting_average ) ;
• Arguments / argument list (everything between the ( ) )
 Format string/string constant
 Format specifier or placeholder or conversion specifier
 Address list ( variable name(s) ) including &
"Address of "
 & is the “address of” operator and translates to
“the address of variable____ ”
Operator
Google is Your Friend
• Google : c escape characters …the top response is:
http://msdn.microsoft.com/en-us/library/h21280bw.aspx
• Google: c format specifiers …top response is:
http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output
• Google: c keywords …top response is (C has 32 keywords):
http://tigcc.ticalc.org/doc/keywords.html
• Google: c operators …4th response is:
http://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/CONCEPT/expressions.html
Key Things to Understand and
Commit to Memory From Today
abstraction
compiler
functions
.c file type
actual parameters
formal parameters
,
function return data type
int
char
format specifier
&
assignment operator
{}
include
void
source code
compilation
main function
syntax
actual arguments
formal parameters
escape sequences
return
float
format string
data list
address of operator
formal parameters
statement
<stdio.h>
function definition
executable code
gcc
main( )
white space
block
;
\n
variables
double
placeholder
address list
=
()
pre-processor directive
int main (void)
function call