CSci 152: Programming II Fall 2004 - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

CSci 152: Programming II Fall 2004

Description:

CSci 152: Programming II Fall 2004 Review Programming Languages Programming language: A set of rules, symbols and special words. syntax tells which statements are ... – PowerPoint PPT presentation

Number of Views:43
Avg rating:3.0/5.0
Slides: 49
Provided by: facultyTa
Category:
Tags: csci | fall | programming

less

Transcript and Presenter's Notes

Title: CSci 152: Programming II Fall 2004


1
CSci 152 Programming IIFall 2004
  • Review

2
Programming Languages
  • Programming language A set of rules, symbols and
    special words.
  • syntax tells which statements are legal or
    accepted
  • semantics determine meanings of instructions

3
Basic Elements of C
  • A C Program (or any program in a procedural
    programming language)
  • Collection of 1 or more subprograms called
    functions
  • Which is a collection of statements that can
    accomplish something useful
  • sequence, selection, repetition
  • Special function called main

4
Hello World!
  • include ltiostreamgt
  • using namespace std
  • int main()
  • cout ltlt Welcome to C Programming. ltlt
    endl
  • return 0

5
C Tokens
  • Special Symbols
  • - / . ? , lt ! gt
  • Word Symbols
  • int, float, char, void, return
  • Identifiers
  • Identifiers are names of things that appear in
    programs, such as variables, constants, and
    functions.
  • Some are predefined others are defined by you,
    the programmer.

6
C Data Types
  • def Data type A set of values together with a
    set of operations
  • simple data type
  • structure data type
  • pointers

Cs Data types
Simple
Structured
Pointers
7
Simple Data Types
  • The simple data type is the fundamental data type
    in C, building block for the structured data
    type
  • Integral, deals with integers or numbers withut a
    decimal part
  • int, bool, char, short, long, unsigned variants
  • Floating-point, deals with decimal numbers
  • float, double, long double
  • Enumeration type, which is a user-defined data
    type
  • e.g. enum olympicSports basketball, volleyball,
    diving, swimming, trackAndField, marathon,
    archery

8
Arithmetic Operators and Expressions
  • - /
  • Expressions
  • 2 5
  • 10 6
  • x y / z (0.5 w)
  • Type Conversion (Casting)
  • float x float(24/7)

9
Identifiers
  • Identifier
  • Identifier A C identifier consists of letters,
    digits, and the under score character (_), and
    must begin with a letter or underscore.
  • C is case sensitiveuppercase and lower case
    letters are different.
  • Some of the predefined identifiers are cout and
    cin.
  • Unlike reserved words, pre-defined identifiers
    may be redefined, but it would not be wise to do
    so.

10
Declaring Variables
  • Storing data in the computers memory is a two
    step process.
  • Instruct the computer to allocate memory.
  • Include statements in the program to put data
    into the allocated memory.
  • Named constant A memory location whose content
    is not allowed to change during program execution
  • const double conversion 2.54
  • const int noOfStudents 20
  • const char blank
  • Variable A memory location whose content may
    change during program execution.
  • double amountDue
  • int counter
  • char ch
  • int x, y
  • string name
  • assignment
  • variable expression
  • x 4
  • y 4 5 11

11
Declaring Variables
  • 1. In C, all identifiers must be declared
    before they can be used. If we refer to an
    identifier without declaring it, the compiler
    will generate an error message indicating that
    the identifier is not declared.
  • 2. A data type is called simple if the variable
    (or named constant) of that type can store only
    one value at a time. For example, if x is an,
    say, int variable. Then at a given time only one
    value can be stored in x.

12
Putting Data into Variables
  • In C there are two ways that data can be placed
    into a variable
  • 1. Using Cs assignment statement, and
  • 2. Use input (read) statements.

13
Assignment Statement
  • The assignment statement takes the form
  • variable expression
  • The expression is evaluated and its value is
    assigned to the variable on the left side.
  • In C, is called the assignment operator.

14
Input / Output
  • Standard input (keyboard) cin
  • cin gtgt variable gtgt variable
  • int feet, inches
  • cin gtgt feet gtgt inches
  • Standard output (terminal) cout
  • cout ltlt expression or manipulator ltlt expression
    or manipulator
  • cout ltlt Hello there. ltlt endl

15
Input (Read) Statement
  • Syntax of cin together with gtgt
  • cingtgtvariablegtgtvariable. . .
  • In C, gtgt is called the extraction operator.
  • Suppose miles is a variable of the type double.
  • The statement
  • cingtgtmiles
  • causes the computer to get a value of the type
    double and place it in the memory cell miles.

16
Input (Read) Statement
  • By using more than one variable in cin, more than
    one value can be read at a time.
  • Suppose feet and inch are variables of the type
    int. A statement like
  • cingtgtfeetgtgtinch
  • gets two integers (entered at the keyboard)
    and places them in the memory location feet and
    inch, respectively.

17
Output
  • The syntax of cout together with ltlt is
  • coutltltexpression or manipulatorltltexpression or
  • manipulator...
  • In C, ltlt is called the insertion operator.
  • expression (that is, expression) is evaluated and
    its value is printed at the current cursor
    position on the screen.
  • manipulator manipulates the output. The simplest
    manipulator is endl (the last character is the
    letter el), which causes the cursor to move to
    the beginning of the next line.
  • This is called an output statement. Sometimes
    this is also called a cout statement.
  • In C, ltlt is called the stream insertion
    operator.
  • Strings and expressions involving only one
    variable or a single value are evaluated to
    itself.

18
Output
  • The output of the C statement
  • coutltlta
  • is meaningful provided the variable a has been
    given a value. For example, the sequence of C
    statements,
  • a 45
  • coutltlta
  • will produce an output of 45.

19
More on C I/O
  • In C, I/O is (always) conceptualized as a
    stream of bytes, or a stream
  • A stream is a sequence of characters from the
    source to the destination.
  • Input stream A sequence of characters from an
    input device to the computer.
  • Output stream A sequence of characters from the
    computer to an output device.
  • Standard input (cin) and standard output (cout)

20
Input predefined functions
  • istreamVar.get(varChar)
  • istreamVar.ignore(intExp, chExp)
  • istreamVar.putback(ch)
  • ch istreamVar.peek()

21
Output and Formatting Output
  • output stream manipulators
  • cout ltlt setprecision(2)
  • cout ltlt fixed cout.unsetf(iosfixed)
  • cout ltlt scientific cout.unsetf(iosscientific)
  • cout ltlt showpoint
  • cout ltlt setw(5) ltlt x ltlt endl
  • and many others

22
File I/O
  • File I/O is a five-step process
  • Include the header file fstream in the program
  • Declare file stream variables
  • Associate the file stream variables with the
    input/output sources
  • Use the file stream varaibles with gtgt, ltlt or
    other input/output functions
  • Close the file

23
File I/O
  • include ltfstreamgt
  • using namespace std
  • int main()
  • // Declare file stream variables such as the
    following
  • ifstream inData
  • ofstream outData
  • // declare additional varaibles if any
  • // Open files
  • inData.open(a\\prog.dat)
  • outData.open(a\\prog.out)
  • // Code for data manipulation
  • inData gtgt payRate
  • outData ltlt The paycheck is ltlt pay ltlt endl

24
Control Structures
  • There are really only three main types of control
    structures in standard procedural programming
    languages
  • Sequence steps are normally performed in a
    sequential manner
  • Selection One of several actions is selected and
    executed (branch, other actions are not
    executed).
  • Repetition One or more steps is performed
    repeatedly.

25
Control Structures Sequence
  • Normally in procedural programs, statements are
    executed in a sequential manner.
  • selection and repetition control structures break
    up this sequential execution by introduction
    branch points and loops respectively
  • Procedure/function calls also break up sequential
    execution to modularize algorithm into several
    small pieces

26
Control Structures Selection
  • Selection, or branch statements, chose one set of
    instructions among 2 or many to execute
    conditional on some test.
  • In C selection control structures are
  • if
  • if else
  • switch

27
Relational and Boolean Operators
  • C relational an boolean operators basis of
    conditional tests for selection control
    structures

Relational Operators
Logical (Boolean) Operators
28
Selection if and if .. else
  • if (expression)
  • statement
  • if (expression)
  • statement1
  • else
  • statement2

29
Compound (Block of) statements
  • A compound statement groups a sequence of
    expressions
  • if (age gt 18)
  • cout ltlt Eligible to vote. ltlt endl
  • cout ltlt No longer a minor. ltlt endl
  • else
  • cout ltlt Not eligible to vote. ltlt endl
  • cout ltlt Still a minor. ltlt endl

30
Multiple selections Nested if
  • if (balance gt 50000.00)
  • interestRate 0.07
  • else if (balance gt 25000.00)
  • interestRate 0.05
  • else if (balance gt 1000.00)
  • interestRate 0.03
  • else
  • interestRate 0.00

31
Multiple Selections switch statements
  • power to choose from among many alternatives
  • switch (grade)
  • case A
  • cout ltlt The grade is A.
  • break
  • case B
  • cout ltlt The grade is B.
  • break
  • case C
  • cout ltlt The grade is C.
  • break
  • case D
  • cout ltlt The grade is D.
  • break
  • case F
  • cout ltlt The grade is F.
  • break

32
Control Structures Repetition
  • Repetition is a common activity in algorithms,
    and very powerful
  • Repetition is another way in which we get away
    from the simple sequential execution of a
    sequence of statements
  • C looping structures
  • while
  • for

33
While looping structure
  • while (expression)
  • statement
  • i 0
  • while (i lt 20)
  • cout ltlt i ltlt
  • i i 5
  • cout ltlt endl

34
While looping structure
flag-controlled found false while
(!found) if (expression) found
true EOF-controlled infile gtgt
variable while (infile) infile gtgt
variable
  • counter-controlled
  • counter 0
  • while (counter lt N)
  • counter
  • sentinel-controlled
  • cin gtgt variable
  • while (variable ! sentinel)
  • cin gtgt variable

35
for looping structure
  • while loop is general enough to implement most
    (all?) forms of repetition
  • for loop is a specialized form to simplify
    writing of count-controlled loops (since they are
    so common).

36
for looping structure
  • for (initial statement loop condition update
    statement)
  • statement
  • for (i1 ilt5 i)
  • cout ltlt Hello! ltlt endl
  • cout ltlt ltlt endl

37
Break and Continue
  • break
  • exit early from a loop
  • skip the remainder of the switch structure
  • continue
  • skips remaining statements in the loop and
    proceeds with the next iteration of the loop

38
Increment and Decrement Operators
  • Frequent operation is to increment a count by 1
    (or decrement by 1)
  • count count 1
  • shorthand count
  • count count 1
  • count--
  • Post-increment vs. pre-increment
  • int count 5, res
  • res count
  • res count

39
Functions
  • A C Program (or any program in a procedural
    programming language)
  • Collection of 1 or more subprograms called
    functions
  • Which is a collection of statements that can
    accomplish something useful
  • sequence, selection, repetition
  • Special function called main

40
User-Defined Functions
  • To solve a problem you must learn to write your
    own functions
  • User-defined functions in C are classified into
    two categories
  • Functions that have a data type, called
    value-returning functions
  • Functions that do not have a data type, called
    void functions.

41
Value-Returning Functions
  • functionType functionName(formal parameter List)
  • statements
  • return value
  • int min(int number1, int number2)
  • if (number1 lt number2)
  • return number1
  • else
  • return number2

42
Value-Returning Functions
  • Once a value-returning function computes the
    value, the function returns this value via the
    return statement.
  • When a return statement executes in a function,
    the function immediately terminates and returns
    control back to the caller.
  • A value-returning function must return a value,
    therefore it must have at least 1 return
    statement somewhere in it.

43
Non Value-Returning Functions
  • called void functions
  • void functionName(formal parameter List)
  • statements
  • void printStars()
  • cout lt ltlt end
  • cout lt ltlt end

44
Reference Parameters
  • Normal simple data type parameters in C and C
    are passed by value.
  • Sometimes it is useful to pass in parameters by
    reference.
  • When you want to return more than one value from
    a function.
  • When the value of the actual parameter needs to
    be changed.
  • When passing the address would save memory space
    and time relative to copying a large amount of
    data.

45
Reference Parameters
  • Value parameter A formal parameter that receives
    a copy of the content of the corresponding actual
    parameter.
  • Reference parameter A formal parameter that
    receives the location (memory address) of the
    corresponding actual parameter.

46
Reference Parameters
  • int main()
  • int courseScore
  • cout ltlt This program computes the course
    grade.
  • ltlt endl
  • getScore(courseScore)
  • printGrade(courseScore)
  • return 0
  • void getScore(int score)
  • cout ltlt Enter the course score
  • cin gtgt score
  • cout ltlt endl ltlt Course score is ltlt score ltlt
    endl

47
Next Class
  • Quiz 1 Over review material
  • Data Types
  • simple
  • declaring
  • Control Structures
  • sequence, selection (if/then, case) and
    repetition (while, for)
  • functions
  • declaring, parameters, return values
  • I/O

48
Next Class
  • Log in/Sign up to Educator account
  • Some review of 1 Dimensional Arrays and C-strings
  • Ch 9 423-450
  • 2 Dimensional arrays
  • Ch 9 450-468
Write a Comment
User Comments (0)
About PowerShow.com