Transcript Topic2

Last Topic Review




Name the principle components of a
computer.
What are three responsibilities of the
operating system?
What advantage does assembly language
have over machine language?
What advantages do high-level languages
have over assembly language?
CISC 105 – Topic 2
Last Topic Review




What computer program translates a source
code file into an object file?
What program combines object files and
produces an executable file?
What part of the operating system is
responsible for the loading and scheduling of
programs?
What are the steps in the software
development method?
CISC 105 – Topic 2
Topic 2 – Introduction to the C
Programming Language
What is C?



C is a high-level language.
A C compiler takes a C source code file
as input and produces an executable
file, after compiling, assembling, and
linking.
C is the industry standard high-level
programming language.
CISC 105 – Topic 2
An Example C Program
/* Converts distances from miles to kilometers */
#include <stdio.h>
#define KMS_PER_MILE 1.609
int main(void)
{
double
miles,
/* distance in miles */
kms;
/* equiv. distance in kms */
/* Get the distance in miles */
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles);
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */
printf (“That equals %f kilometers.\n”,kms);
return(0);
}
CISC 105 – Topic 2
Comments



Comments are text provided by the
programmer to allow others (and the
programmer too) to better understand what
the program is doing
Any text between a “/*” and a “*/” is
considered to be a comment and is ignored
by the C preprocessor and the compiler itself.
Comments can appear anywhere in a
program and can be multiline.
CISC 105 – Topic 2
Comments
/* Converts distances from miles to kilometers */
#include <stdio.h>
#define KMS_PER_MILE 1.609
int main(void)
{
double
comment –
Ignored by the C preprocessor
and the compiler.
miles,
/* distance in miles */
kms;
/* equiv. distance in kms */
/* Get the distance in miles */
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles);
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */
printf (“That equals %f kilometers.\n”,kms);
return(0);
}
CISC 105 – Topic 2
Preprocessor Directives



A preprocessor directive is a command given
to the C preprocessor, which is a part of the
compilation process that modifies a C source
code file before it is compiled.
Preprocessor directives always begin with a
“#” character.
In the example program, there are two
preprocessor directives used, #include and
#define.
CISC 105 – Topic 2
#include


The #include directive tells the C
preprocessor to give a program access to a
library. By putting a #include in a program,
the preprocessor loads a header file, which
tells the compiler what functions and other
information is provided in the library.
In this program, #include <stdio.h>
indicates that this program uses the stdio
library which contains functions such as
printf(). Page 542 of Deitel lists standard
libraries.
CISC 105 – Topic 2
#define



The #define directive specifies a constant
macro.
This tells the preprocessor that every time it
encounters the first text, it should replace it
with the second text.
In this program, #define KMS_PER_MILE 1.609
tells the preprocessor to replace
KMS_PER_MILE with 1.609 every place
KMS_PER_MILE appears in the program.
CISC 105 – Topic 2
Preprocessor Directives
/* Converts distances from miles to kilometers */
#include directive –
#include <stdio.h>
Tells the preprocessor to
#define KMS_PER_MILE 1.609
include the stdio.h header file.
int main(void)
{
This file describes the functions
double
miles,
/* distance in miles */
other
information
included
kms;
/* equiv. and
distance
in kms
*/
#define directive –
/* Get the distance in miles */
in the
stdio library.
printf(“Enter the distance
Tells in
themiles>”);
preprocessor to
scanf (“%lf”, &miles);
replace every occurrence of
/* Convert the distance to kilometers */
in the program
kms = KMS_PER_MILE * KMS_PER_MILE
miles;
with 1.609.
/* Display the distance in kilometers */
printf (“That equals %f kilometers.\n”,kms);
return(0);
}
CISC 105 – Topic 2
Reserved Words


Reserved words are words that have
special meaning in the C language and
cannot be used for other purposes.
In this program, examples include int,
void, double, and return.
CISC 105 – Topic 2
Reserved Words
/* Converts distances from miles to kilometers */
#include <stdio.h>
#define KMS_PER_MILE 1.609
int main(void)
{
double
Reserved Words –
These have special meaning
in C and cannot be used for
inanything
miles */ else.
miles,
/* distance
kms;
/* equiv. distance in kms */
/* Get the distance in miles */
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles);
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */
printf (“That equals %f kilometers.\n”,kms);
return(0);
}
CISC 105 – Topic 2
Identifiers




Identifiers identify memory cells that hold
data or operations (and functions).
Standard identifiers have special meaning in
C, however they can be redefined by the
programmer.
Examples of standard identifiers in the
program are printf and scanf.
User-defined identifiers are memory cells that
hold data, operations, and functions that the
programmer defines.
CISC 105 – Topic 2
Identifiers
/* Converts distances from miles to kilometers */
#include <stdio.h>
#define KMS_PER_MILE 1.609
Standard Identifiers
int main(void)
{
double
miles,
/* distance in miles */
kms;
/* equiv. distance in kms */
/* Get the distance in miles */
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles);
User-defined Identifiers
/* Convert the distance to kilometers */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers */
printf (“That equals %f kilometers.\n”,kms);
return(0);
}
CISC 105 – Topic 2
What is a valid identifier?





Identifiers can only be composed of
letters, digits, and underscores.
Identifiers cannot begin with a digit.
Reserved words cannot be identifiers.
Identifiers can be as long as you want.
Upper and lower case letters are
different (i.e. kms and Kms are not
considered to be the same identifier).
CISC 105 – Topic 2
Review

Which of the following are valid identifiers?
For each that is not valid, why is it not?
This_is_a_long_identifier_but_is_it_valid?
8timesTheRadius
miles
Phil’s variable
kilometers_per_hour
x
“radius”
CISC 105 – Topic 2
Variables




A variable is a memory cell that is used to
hold data acted upon by the program.
A variable declaration tells the C compiler the
name and type of a variable used in a
program.
A variable declaration consists of a data type
and an identifier which is the name of that
variable.
Every variable that will be used in a program
must be declared.
CISC 105 – Topic 2
Variable Declarations
double
int


mile;
counter;
The first line declares a variable named
mile of the double data type.
The second line declares a variable
named counter of the int data type.
CISC 105 – Topic 2
Data Types



There are a large number of data types.
These are some of the most popular ones.
void – this keyword means “no data type”.
int – An integer (a whole number). This
data type can represent an integer in a
specific range, at least –32767 through
32767.
CISC 105 – Topic 2
Data Types



char – A character. One letter, digit, or
symbol. This is enclosed in single quotes.
float – A real number (an integer part and
a decimal part).
double – A real number. Note that this data
type is a memory cell double the size of a
float data type. This allows a bigger
number to be represented, or a specific
number to be represented more precisely.
This is referred to as a double-precision
floating point number.
CISC 105 – Topic 2
Bigger or More Precise?


Why can we represent either bigger
numbers or more precise numbers?
Because floating points numbers are
stored in scientific notation, consisting
of a number and an exponent, i.e.
1.2555 x 10^6
CISC 105 – Topic 2
Review of Variables

Write a #define preprocessor declaration for a
constant macro of STUDENTS_PER_SECTION to 22
and variable declarations of num_students as an
integer, GPA and class_GPA as double-precision
floating point numbers, and letter_grade as a
character data type.
#define STUDENTS_PER_SECTION 22
int
double
char
num_students;
GPA, class_GPA;
letter_grade;
CISC 105 – Topic 2
Assignment Statements


An assignment statement is one type of
executable statement.
An assignment statement uses the “=“
operator, and follows the form:
variable = expression;

This statement first evaluates the
expression on the right and stores the
result in the variable on the left.
CISC 105 – Topic 2
Assignment Statements

Here are some examples of assignment
statements:





x = 12;
negative_x = -x;
x = y + 12 + z * 5;
result = y;
Note that any variables in the right-side
expression are not modified by an assignment
statement.
CISC 105 – Topic 2
Function Calls




A function is a piece of code which performs
a specific task.
Functions can be created by programmers or
supplied as part of the C compiler toolset.
A function is called, which causes it to
execute.
A function call is composed of the function
name, an open paren, a set of function
arguments separated by commas, and a close
paren.
CISC 105 – Topic 2
Function Calls

A function call looks like this:
function_name(argument1, argument2, argument3);
function name
open paren
function arguments
close paren
CISC 105 – Topic 2
The printf Function


The C function for displaying output on
the screen to the user is printf.
printf is called in the following manner:
printf(“The final GPA of student number %d is %f.\n”,student_num, GPA);
format string
function arguments
CISC 105 – Topic 2
print list
The Format String
and Print List



The format string is the text that is to be
displayed on the screen.
The “%” characters are called placeholders.
They indicate the display position for
variables whose values are to be displayed.
The variable names to be displayed are
specified in the print list and appear in the
same order as their placeholders.
CISC 105 – Topic 2
Placeholders
printf(“The final GPA of student number %d is %f.\n”,student_num, GPA);
This pair specifies the location in the print
string to display the student_num value.
This pair specifies the location in the print
string to display the GPA value.
CISC 105 – Topic 2
Placeholders


All placeholders begin with a “%”.
The text after the “%” symbol indicates
how to format the output, i.e. what kind
of variable it is.



%d – decimal number (int)
%f – floating-point number (float or
double)
%c – character (char)
CISC 105 – Topic 2
Escape Sequences




All escape-sequences begin with a backslash,
“\”.
A letter after the “\” character denotes an
escape sequence, which has special meaning.
The “\n” sequence indicates a new-line
character, which cause any following text to
appear on the next line on the display.
In order to display a “\”, the format string
must contain a “\\”.
CISC 105 – Topic 2
Placeholders and the
Newline Escape Sequence
printf(“The final GPA of student number %d is %f.\n”,student_num, GPA);
Therefore, if the student_num variable was set to
10 and the GPA variable was set to 3.03
this to
printf
function
call would cause:
Specifies
display
student_num,
which is an integer.
The final GPA of student number 10 is 3.03.
to be displayed
on the
screenGPA,
and any
Specifies
to display
subsequent
output
begin on thenumber.
next line.
which
is anto
floating-point
CISC 105 – Topic 2
The scanf Function

The C function for reading input from
the user is scanf.
scanf(“%d %f”,&student_num, &GPA);
format string input list
function arguments
CISC 105 – Topic 2
The Format String


The format string is the set of placeholders
which specify what type of data is being
input.
The same placeholders are used as for printf,
except for when inputting a floating-point
number. A float type still uses the “%f”,
however the double type uses the “%lf”
placeholder.
CISC 105 – Topic 2
The Input List




The variables to store the inputted data are
specified in the input list. They must be in
the same order as their corresponding
placeholders.
Notice that each variable name is preceded
by a “&”.
The “&” is an operator which means “the
address of”.
Therefore, “&student_num” tells the scanf
function to store what it reads from the user
at the memory address of student_num.
CISC 105 – Topic 2
Placeholders and
the Input List
scanf(“%d %f”,&student_num, &GPA);
Therefore, if the input into this
This call
pair was:
specifies to read
scanf function
This pair specifies
to read
in <ENTER>
a single-precision floating
9 3.560
in an integer
and store point
itvariable
number
andbestore it
the student_num
would
at theset
memory
address
ofthe
at
memory
address
to 9 and
the GPA
variable
would
be of
student_num, thus set
setting
GPA,
thus setting the GPA
to
3.560
the student_num variable
variable to the inputted value.
to the inputted value.
CISC 105 – Topic 2
Review of printf and scanf

int
float
What happens when the following code
fragment is run?
student_num;
GPA;
printf(“Enter the student number>”);
scanf(“%d”,&student_num);
printf(“Enter student number %d’s GPA>”,student_num);
scanf(“%f”,&GPA);
printf(“Student number %d now has a %f GPA.\n”,student_num, GPA);
CISC 105 – Topic 2
Review of printf and scanf

int
What is the displayed output when the
following code fragment is run and the
inputs are 8 and 12?
x, y;
My name is Phil Viscito.
printf(“My name is”);
Enter two integers> 8 12
printf(“ Phil Viscito”);
printf(“\nEnter two integers> ”); Thanks! The answer is 22.
scanf(“%d%d”,&x, &y);
Bye now!
x = x + 2;
y = x + y;
printf(“Thanks! The answer is %d.\nBye now!”,y);
CISC 105 – Topic 2
Customizing Integer Output



The “%d” placeholder, used to display an
integer variable, can be altered to format how
the number is displayed.
Instead of “%d”, use a “%Xd” where the X is
an integer that is the field width, the number
of digits to display.
For example, “%4d” displays four digits of the
result. The negative sign (for negative
integers) is also considered a digit here.
CISC 105 – Topic 2
Customizing Integer Output


When there are more places (the field
width) than digits to be displayed, the
output is right-justified.
When there are more digits than places,
the field width is ignored, and the entire
integer is displayed.
CISC 105 – Topic 2
Customizing Integer Output

As an example:
Value
Placeholder
Output
643
%1d
643
643
%4d
643
%5d
-643
%2d
-643
%6d
CISC 105 – Topic 2
643
643
-643
-643
Customizing
Floating-Point Output




Floating point output (float and double)
can be formatted in the same manner, using
“%X.Yf”).
Here, X is the total number of digits to display
(the field width) and Y is the number of digits
to display to the right of the decimal point.
The same rules for field width apply as for
integer formatting.
The specified number of decimal digits is
always displayed.
CISC 105 – Topic 2
Customizing
Floating-Point Output

As an example:
Value
Placeholder
3.14159
%5.2f
3.14159
%3.2f
3.14
3.14159
%5.3f
3.142
0.1234
%4.2f
0.12
-0.006
%8.5f
-0.00600
CISC 105 – Topic 2
Output
3.14
The return Function



The return function terminates a running
function and returns control to the function
that called the function.
In the case of main(), the return function
returns control back to the computer’s
operating system and ends the program.
This function has one argument. The main()
function must return an integer, normally just
set to 0 (zero).
CISC 105 – Topic 2
Arithmetic Expressions



Arithmetic expressions are executable
statements that manipulate data.
Arithmetic expressions operate on both
integer (int) and floating-point (float and
double) numbers.
Arithmetic operators can operate on mixed
types (i.e. one int and one float). The
resulting type of such an expression is the
“highest” data type present.
CISC 105 – Topic 2
Resulting Data Types

The “highest” data type is always
considered to be a floating point
number, with double-precision floating
point numbers taking precedence over
single-precision floating point numbers.
int
int
int
float
+
+
+
+
int
float
double
double
=
=
=
=
CISC 105 – Topic 2
int
float
double
double
Arithmetic Expressions

All of the common arithmetic operators
are present in C:





+
*
/
%
(addition)
(subtraction)
(multiplication)
(division)
(modulus – or “remainder”)
CISC 105 – Topic 2
Note: Integer Division



If two integer values are divided, the
resulting data type is also an integer, as
previously described.
Therefore, only the integer portion of
the actual result will be the returned
result.
For example, 9 / 4 = 2
9 / 10
=0
CISC 105 – Topic 2
The Modulus Operator


The “%” operator is a modulus
operator, which also means the
remainder of the division.
For example,
9%3 =0
10 % 6 = 4
90 % 8 = 2
CISC 105 – Topic 2
Review of Basic
Arithmetic Expressions

int
float
What is the resulting output of this
program segment?
x, y, z;
a;
x=4
a=4.5
y=0
z=1
x = 9 * 0.5;
a = 9 * 0.5;
y = 15 % 15;
z = 15 % 2;
printf(“x=%d\n, a=%f\n, y=%d\n, z=%d\n”,x,a,y,z)
CISC 105 – Topic 2
More Complex
Arithmetic Expressions

C evaluates arithmetic expressions in
the same order rules as normal
mathematics.



Parentheses take priority over everything
else.
Then, multiplication, division, and modulus
operations from left to right.
Then, addition and subtraction from left to
right.
CISC 105 – Topic 2
More Complex
Arithmetic Expressions
x2 + 2xy + 4y2
(x * x) + (2 * x * y) +
(4 * y * y)
a+b
-------c2 * 4d
a * (4x % y2)
(a + b) / (c * c * 4 *
d)
x + y(x2 + y)
x + y * (x * x + y)
a * (4 * x % (y * y))
CISC 105 – Topic 2
Review

What is the resulting output of this
program segment?
#define PI 3.14159
int
float
x, y, z;
a, b;
x=5, y=10, z=4008
a=4008.14, b=4008.14159
x = 5;
y = 10;
z = x + (4 * y * y * y) + PI;
a = x + (4 * y * y * y) + PI;
b = (x / y) + a;
printf(“x=%d, y=%d, z=%d\na=%7.2f, b=%f\n”,x,y,z,a,b);
CISC 105 – Topic 2
Special Case:
Operations on a Variable


Often, one wishes to perform an
operation on a variable, such as adding
or subtracting a value.
C has a special syntax for an operation
performed on a variable (i.e. the
variable is used on the right side of the
assignment statement and is the target
of the assignment as well.)
CISC 105 – Topic 2
Special Case:
Operations on a Variable

This syntax follows the form:
variable (operation)= expression;

This statement first computes the
operation on the right side of the equals
sign. Then, it performs the (operation)
on the variable and the expression.
CISC 105 – Topic 2
Special Case:
Operations on a Variable

For example,
x += 19;


This statement adds 19 to the value
contained in x.
This statement is exactly the same as
x = x + 19;
CISC 105 – Topic 2
Another Special Case:
Increment and Decrement


Incrementing (adding one) and
decrementing (subtracting one) are two
very common operations.
C has a special syntax for increment
and decrement operations that follows
this form:
x++; OR ++x;
Increment
x--; OR --x;
Decrement
CISC 105 – Topic 2
Another Special Case:
Increment and Decrement




Notice that the increment operator expression
x++ is the same as saying: x += 1;
So, why are there two forms of each operator?
The answer lies in when the increment (or
decrement) operation is actually performed.
This distinction only occurs when the ++ (or --)
operator is used on a variable in the same
expression in which the value of the variable is
used.
CISC 105 – Topic 2
Another Special Case:
Increment and Decrement

For example,
int x = 20, y;
int x = 20, y;
y = x++;
printf(“x=%d, y=%d\n”,x,y);
y = ++x;
printf(“x=%d, y=%d\n”,x,y);
x=21, y=20
x=21, y=21
y = x;
x += 1;
printf(“x=%d, y=%d\n”,x,y);
x += 1;
y = x;
printf(“x=%d, y=%d\n”,x,y);
CISC 105 – Topic 2
Another Special Case:
Increment and Decrement



The difference lies in when the expression
(x++ or ++x) gets evaluated in relation to
when the operator (++) gets performed.
The x++ expression is equal to the value of x
and the ++ operator is performed after the
evaluation is over.
The ++x expression indicates that the ++
operator is performed first (before ++x is
evaluated) and thus, is equal to the value of x
+ 1.
CISC 105 – Topic 2
Review

int
What is the output of the following
program fragment?
x, y, z;
x=7, y=10, z=55
x = 5;
y = 10;
z = x++ * y – 2;
z += ++x;
printf(“x=%d, y=%d, z=%d\n”,x,y,z);
CISC 105 – Topic 2