computer science

Card Set Information

Author:
jimmiej
ID:
136310
Filename:
computer science
Updated:
2012-02-20 23:52:30
Tags:
computer science
Folders:

Description:
exam 1
Show Answers:

Home > Flashcards > Print Preview

The flashcards below were created by user jimmiej on FreezingBlue Flashcards. What would you like to do?


  1. why programming
    • Computer – programmable machine designed to follow
    • instructions

    • Program (Software) – instructions in computer memory to make
    • computer do something

    • Programmer (Software Developer)– person who writes
    • instructions (programs) to make computer perform a task

    • So, without programmers, no programs; without
    • programs, a computer cannot do anything
  2. Central Processing Unit (CPU)
    Comprised of:

    Control Unit

    • Retrieves and decodes
    • program instructions

    • Coordinates activities of
    • all other parts of computer

    • Arithmetic & Logic Unit
    • (ALU)

    • Hardware optimized for
    • high-speed numeric calculation

    • Hardware designed for
    • true/false, yes/no decisions, and comparisons
  3. CPU Organization
  4. Main Memory
    • lIt
    • is volatile
    • (temporary). Main memory is erased when program
    • terminates or computer is turned off

    • lAlso
    • called Random Access Memory (RAM)

    • lOrganized
    • as follows:

    • lbit: smallest piece of
    • memory. Has values 0 (off, false:
    • negative electrical charge) or 1 (on, true: positive electrical charge)

    • lbyte: 8 consecutive bits. Bytes
    • have addresses.

    • lAddresses – Each byte in memory
    • is identified by a unique number known as an address.

    • lAll
    • data that is stored in a computer is converted to sequences of 0s and1s (binary
    • numbering system)
  5. Main Memory
    • lComputer memory is made of tiny storage
    • locations known as bytes.

    • lOne byte is 8 bits (stands for binary digit) and is only enough memory to store a letter
    • of the alphabet or a small number.

    • Most computers today have billions of bytes
    • of memory
    • Decimal (base
    • 10) Hexadecimal (base 16) Binary(base 2)

    14 e 00001110



    • For example, the
    • hexadecimal number 2AF3 is equal, in decimal, to (2 × 163)
    • + (10 × 162)
    • + (15 × 16) + 3, or 10,995.

    • What if you need to
    • store a number larger than 255?
  6. Storing Characters in Memory: ASCII
    • lAny piece of data that is stored in a
    • computer’s memory must be stored as a binary number. This includes characters
    • e.g. letters and punctuation marks.

    • lWhen a character is stored in a memory, it is
    • first converted to a numeric code. The numeric code is then stored in memory as
    • a binary code.

    • lMany coding schemes have been developed but
    • the most famous one is American Standard Code Information Interchange (ASCII).

    • lASCII is a set of 128 numeric codes that
    • represent the English letters, various punctuations, and other characters.

    • lFor example: The ASCII
    • value of A is 65,
    • while a is 97, B is 66, C is 67 etc.
  7. Secondary Storage
    • lNon-volatile
    • (permanent): data retained when program is not running or computer is turned
    • off

    • lComes
    • in a variety of media:

    • lmagnetic: floppy disk, zip disk,
    • hard drive

    loptical: CD-ROM

    • lFlash drives, connected to the
    • USB port
  8. Software –
    Programs
    That Run on a Computer
    lCategories of software:

    • lOperating system:
    • programs that manage the computer hardware and the programs that run on
    • them. Examples: MacOS, Windows, UNIX, Linux

    • lApplication software:
    • programs that provide services to the user. Examples : word processing, games, programs to solve specific problems
  9. CPU is dummy
    • lCPU
    • is designed to do operations such as the followings: reading a piece of data
    • from memory, adding two numbers, subtracting one number from another,
    • multiplying, dividing, moving a piece of data from one memory location to
    • another location, determining whether one value is equal to another etc.

    • lAs
    • you can see from the list, the CPU performs very simple operations.

    • lIt
    • has to be told what to do. And we tell the CPU what to do with programs. So,
    • you can think programs as languages that we communicate with the CPU.

    • lHere
    • is a very simple example program in binary:

    • l10110000 (It tells the Intel
    • microprocessor (CPU) to move a value into the CPU

    • lTo you and me this is only 1s and
    • 0s; however, to the CPU this is an instruction to perform an operation (move a
    • value into the CPU)

    • lCPU only understands instructions
    • that are written in machine language: binary representation
  10. Example Algorithm for Calculating Gross Pay
  11. Machine Language
    • lAlthough
    • the previous algorithm defines the steps for calculating the gross pay, it is
    • not ready to be executed on the computer.

    • lThe
    • computer only executes machine language instructions.
  12. Programs and
    Programming Languages
    Types of languages:

    • Low-level (e.g. assembly):
    • used for communication with computer hardware directly. Often written in binary machine code
    • (0’s/1’s) directly. Program languages which are closer to the language the
    • computer itself uses.



    • High-level (e.g. C++, Java
    • etc.): closer to human language
  13. Language:
    • lMachine
    • language: First generation programming language in
    • which data is represented in 1’s and 0’s.

    • lAssembly
    • language:
    • Second generation of programming language which used abbreviations for
    • program instructions.

    • lProcedural
    • languages: Programming language designed to express the
    • logic – the procedures - that can solve general problems. Examples of
    • procedural languages are: Ada,
    • BASIC, C/C++, COBOL, FORTRAN, HTML, Java, and Pascal.

    • lProblem-oriented
    • languages: Programming language designed to solve
    • specific problems e.g. Lisp, prolog etc..

    • lNatural
    • languages: Language designed to give people a more human
    • connection with computers. These are
    • still being developed.
  14. From a High-level Program to an Executable
    File
    • a)Create
    • file containing the program with a text editor.

    • b)Run preprocessor to convert source file directives to source
    • code program statements.

    • c)Run compiler to convert source program/code (a
    • program written by a programmer) into object program/code (the
    • machine code version of the object code).

    • d)Run linker to combine files generated by compilers and
    • assemblers and generates an executable file.

    • lSteps b–d are often performed by a single
    • command or button click.

    • lErrors detected at any step will prevent
    • execution of following steps.
  15. Integrated Development Environments (IDEs)
    • lAn
    • integrated development environment, or IDE, combine all the tools needed to
    • write, compile, and debug a program into a single software application.

    • lExamples
    • are Microsoft Visual C++, Borland C++ Builder, CodeWarrior, etc.
  16. What Is a Program Made Of?
    • lCommon
    • elements in programming languages:

    lKey Words

    lOperators

    lSyntax

    lProgrammer-Defined Identifiers

    lPunctuation
  17. Key Words
    • lAlso
    • known as reserved
    • words

    • lHave
    • a special meaning in C++

    • lCannot be used for
    • any other purpose

    • lKey
    • words in the next Program are: using, namespace, int, main, double, and return.
  18. C++ key words
  19. Operators
    • lProgramming
    • languages have Operators to perform various operations on data

    • lUsed
    • to perform operations on data

    • lMany
    • types of operators:

    lArithmetic - ex: +,-,*,/

    lAssignment – ex: =



    • lSome
    • operators in the following Program:
    • << >> = *
  20. Syntax
    • lThe
    • rules of grammar that must be followed when writing a program

    • lEach
    • language has its own syntax.

    • lSyntax
    • rules dictate how key words, operators, and various punctuations must be used
    • in a program.

    • lE.g.
    • In C++ syntax every instruction ends with semicolon “;”
  21. Punctuation
    • lCharacters
    • that mark the end of a statement, or that separate items in a list

    • lIn
    • Program 1-1: , and ;
  22. Variable Declarations
    • lThere are many different
    • types of data, which you will learn about in this course.


    • lA variable holds a
    • specific type of data.


    • lThe variable declaration
    • specifies the type of data a variable can hold, and the variable name.
  23. Variables
    • lA variable is a named
    • storage location in the computer’s memory for holding a piece of data.

    • lIn the Program above, we
    • used three variables:

    • lThe hours variable was used to hold the
    • hours worked

    • lThe rate variable was used to hold the
    • pay rate

    • lThe pay variable was used to hold the
    • gross pay
  24. Input, Processing, and Output
    • Three steps that a program typically
    • performs:

    1)Gather input data:

    • lfrom
    • keyboard

    • lfrom
    • files on disk drives

    2)Process the input data

    3)Display the results as output:

    • lsend
    • it to the screen

    • lwrite
    • to a file
  25. The Programming Process
  26. Special Characters
  27. The cout Object
    • lDisplays
    • output on the computer screen


    • lYou
    • use the stream insertion operator << to send output to cout:


    • cout << "Programming is
    • fun!";
    • lCan
    • be used to send more than one item to cout:


    • cout << "Hello "
    • << "there!";

    Or:


    cout << "Hello ";

    • cout << "there!";
    • lThis
    • produces one line of output:

    • cout << "Programming is ";
    • cout << "fun!";
  28. The endl Manipulator
    • lYou
    • can use the endl manipulator to start a new line of output.
    • This will produce two lines of output:


    • cout << "Programming is" <<
    • endl;
    • cout << "fun!";
    • cout <<
    • "Programming is" << endl;
    • cout <<
    • "fun!";
    • lYou
    • do NOT put quotation marks around endl


    • lThe
    • last character in endl is a lowercase L, not the number 1.

    l
  29. The \n Escape Sequence
    • You can also use the \n escape sequence to start a new line of
    • output. This will produce two lines of output:
  30. The #include Directive
    • lInserts
    • the contents of another file into the program

    • lThis
    • is a preprocessor directive, not part of C++ language. Performs some action
    • before the compiler translates the source program into machine code (object
    • code).

    • l#include
    • lines are not seen by compiler

    • lDo
    • not place a semicolon at end of #include line
  31. Variables and Literals
    • lVariable:
    • a storage location in memory

    • lSyntax: data-type
    • variable-name;


    • lHas a name and a type of data it
    • can hold

    • lMust be declared before it can be
    • used:


    int item;
  32. table
  33. Literal:
    • lLiteral:
    • a value that is written into a program’s code.


    "hello, there" (string literal)

    • 12 (integer
    • literal)
  34. identifier
    • lAn
    • identifier is a programmer-defined name for some part of a program: variables,
    • functions, etc.
  35. You cannot use any of
    the C++ key words as an identifier. These words have reserved meaning.
    • You cannot use any of
    • the C++ key words as an identifier. These words have reserved meaning.
  36. variable name
    • lA
    • variable name should represent the purpose of the variable. For
    • example:

    items_ordered

    • The purpose of this variable is to hold the
    • number of items ordered.
  37. Rules for Naming Variables
    • lVariable
    • names in Visual C++ can range from 1 to 255 characters. To make variable names
    • portable to other environments stay within a 1 to 31 character range.

    • lAll
    • variable names must begin with a letter of the alphabet or an
    • underscore( _ ). For beginning programmers, it may be easier to begin all
    • variable names with a letter of the alphabet.

    • lAfter
    • the first initial letter, variable names can also contain letters and
    • numbers. No spaces or special characters, however, are allowed.

    • lUppercase
    • characters are distinct from lowercase characters. Using all uppercase
    • letters is used primarily to identify constant variables.

    • You cannot use a C++ keyword (reserved words)
    • as a variable name
  38. Valid and Invalid Identifiers
  39. Is
    there any difference between int and long?

    Answer:
    Under Windows they are the same, but for example on Alpha systems (Linux, MacOS etc.) a long was 64
    bits whereas an int was 32 bits.
    • Integer variables can hold
    • whole numbers such as 12, 7, and -99 etc.
  40. Declaring Variables
    • lVariables of the same type
    • can be declared

    - On separate lines:

    int length;

    int width;

    unsigned int area;

    - On the same line:

    int length, width;

    unsigned int area;

    • lVariables of different
    • types must be in different declarations
  41. integer literal
    • An integer literal is an
    • integer value that is typed into a program’s code. For example:

    items_ordered = 15;

    In this code, 15 is an integer literal
  42. The char Data Type
    • lUsed
    • to hold characters or very small integer values

    • lUsually
    • 1 byte of memory

    • lNumeric
    • value of character from the character set is stored in memory:
  43. lCharacter
    literals must be enclosed in single quote marks. Example:

    'A'
    • lCharacter
    • literals must be enclosed in single quote marks. Example:

    'A'
  44. Character Strings
    • lA series of characters in
    • consecutive memory locations:

    "Hello"

    • lAlways
    • stored with the null terminator, \0, at
    • the end:



    • lComprised of the
    • characters between the " "
  45. floating-point numbers
    • lThe floating-point data
    • types are:
    • float
    • double
    • long double


    • lThey can hold real numbers
    • such as:

    12.45 -3.8


    • lStored in a form similar
    • to scientific notation
    • e.g. 1.79769e+308

    • lAll floating-point numbers
    • are signed
  46. Floating-point Literals
    lCan be represented in

    • lFixed point (decimal)
    • notation:

    31.4159 0.0000625

    • lE notation (scientific
    • notation):

    3.14159E1 6.25e-5

    • lAre double by
    • default
  47. Variable Assignments and Initialization
    • lAn
    • assignment statement uses the = operator to store a value in a
    • variable.

    item = 12;

    l

    • lThis
    • statement assigns the value 12 to the item variable.
  48. Assignment
    • lThe
    • variable receiving the value must appear on the left side of the = operator.

    • lThis
    • will NOT work:

    • //
    • ERROR!
    • 12 = item;
  49. Variable Initialization
    • lTo
    • initialize a variable means to assign it a value when it is declared:


    int length = 12;


    lCan initialize some or all variables:

    int length = 12, width = 5, area;
  50. Arithmetic Operators
    • lUsed
    • for performing numeric calculations

    • lC++
    • has unary, binary, and ternary operators:

    lunary (1 operand) -5

    lbinary (2 operands) 13 – 7

    lTernary (3 operands) ( ? : )

    • lE.g. (condition 1) ? (expression
    • 1) : (expression 2 )

    so .. if condition 1 is true, then use expression 1 .. else use expression 2
  51. comments
    • lUsed
    • to document parts of the program

    • lExplanatory
    • remarks made within the program

    • lIntended
    • for persons reading the source code of the program:

    • lIndicate the purpose of the
    • program

    lDescribe the use of variables

    lExplain complex sections of code

    • lAre
    • ignored by the compiler
  52. Single-Line Comments
    • Begin with //
    • through to the end of line:
  53. Single-Line Comments
    • lBegin
    • with /*,
    • end with */

    • lCan
    • span multiple lines:

    /* this is a multi-line


    comment

    */

    • lCan
    • begin and end on the same line:

    int area; /* calculated area */
  54. Programming Style
    • lThe
    • visual organization of the source code

    • lIncludes
    • the use of spaces, tabs, and blank lines

    • lDoes
    • not affect the syntax of the program

    • lAffects
    • the readability of the source code
  55. Programming Style
    Common elements to improve readability:

    • lBraces { }
    • aligned vertically

    • lIndentation of statements
    • within a set of braces

    • lBlank lines between
    • declaration and other statements

    • lLong statements
    • wrapped over multiple lines with aligned
    • operators
  56. ignores all whitespace
    • Except for strings, double
    • quotes, identifiers, and keywords, C++ ignores all whitespace (whitespace is any
    • combination of one or more blank spaces, tabs, or new lines). For example, this is a valid program;
    • however, very bad example, difficult to read:



    • #include
    • <iostream>

    int main

    (

    ){

    cout <<

    • "Welcome
    • to UCA!";

    return 0;}
  57. l
    • Although
    • the previous version of the program works, it is an example of extremely poor
    • programming style. It is difficult to
    • read and understand. The main( ) function should always be written in
    • the standard form below:
  58. Standard and Prestandard C++
    Older-style C++ programs:

    lUse .h at end of header files:

    l #include <iostream.h>

    lDo not use using namespace convention

    • lMay not compile with a standard
    • C++ compiler
  59. The cin Object
    • lStandard
    • input object

    • lLike
    • cout, requires iostream file

    • lUsed
    • to read input from keyboard

    • lUsed
    • to enter data into a program while it is executing

    • lInformation
    • retrieved from cin with >>
    • (the extraction
    • operator – “get from”)

    • lInput
    • (value) is stored directly into a memory location (variable)
  60. cin objec
    • lThe
    • cin object puts the computer into a temporary pause
    • (or wait) state for as long as it takes the user to type a value and press the
    • enter key.

    • lcin converts data to the type that matches the
    • variable:
  61. Displaying a Prompt
    • lA
    • prompt is a message that instructs the user to enter data.

    • You should always use cout to display a prompt before each cin
    • statement.
  62. The cin Object
    • lCan
    • be used to input more than one value:

    • cin >> height >>
    • width;


    • lMultiple
    • values from keyboard must be separated by spaces


    • lOrder
    • is important: first value entered goes to first variable, etc.
  63. summary
    • lThe
    • cin object is used for data input. This object accepts a stream of data from the
    • keyboard and assigns the data to variables which are memory
    • locations. The general form of a statement using cin
    • is


    • cin >> variable; or cin >> var1 >> var2 >> . . .
    • varn;



    • lThe
    • extraction operator, >> , must be used to separate the
    • variables’ names. All variables must be
    • declared
    • before they can be used.



    • lWhen
    • a cin statement is encountered, the computer
    • temporarily suspends statement execution until sufficient data have been
    • entered for the number of variables contained in the cin function. Each variable must be whitespace separated.



    • lIt
    • is a good programming practice to display, prior to a cin statement, a message that alerts the user to
    • the type and number of data items to be entered. Such a message is called a prompt.
  64. Mathematical Expressions
    lSyntax of a simple arithmetic expression: operand operator operand
  65. Mathematical Expressions
    • l Order of operations (rules
    • of precedence):

    • l(
    • ) parenthesis (evaluated inside
    • out)

    • l* %
    • / (evaluated left to right)

    • l+ -
    • (evaluated left to right)

    l

    • lNote:
    • Parentheses cannot be used to indicate multiplication; the
    • multiplication operator, *, must be used.


    • Example, the expression(3 + 4)(5 + 1) is invalid. The correct expression
    • is (3 + 4)*(5 + 1)
    • lCan create complex
    • expressions using multiple mathematical operators

    • lAn expression can be a
    • literal, a variable, or a mathematical combination of constants and variables
  66. Order of Operations
    • In an expression with more than one operator,
    • evaluate in this order:

    • 1.
    • - (unary negation), in
    • order, left to right

    • 2.
    • * / %, in order, left to right

    • 3.
    • + -, in order, left to right

    In the expression 2 + 2 * 2 – 2
  67. Associativity of Operators
    • lparentheses ( ) can be
    • used to override the order of operations:
  68. Parentheses
    • Parentheses can be used to
    • change the usual order; expressions inside (
    • ) are evaluated first. Inner most parentheses will be calculated first
  69. Algebraic Expressions
    • lMultiplication
    • requires an operator:

    Area=lw is written as Area = l * w;

    • lThere
    • is no exponentiation operator:

    Area=s2 is written as Area = pow(s, 2);

    • lParentheses
    • may be needed to maintain order of operations:

    • is
    • written as

    m = (y2-y1) /(x2-x1
  70. When You Mix Apples and Oranges: Type Conversion
    • lOperations
    • are performed between operands of the same type.

    • lIf
    • not of the same type, C++ will convert one
    • to be the type of the other

    • lThis
    • can impact the results of calculations.
  71. Type Coercion
    • lType Coercion: automatic conversion of an operand to
    • another data type

    • lPromotion:
    • convert to a higher type

    • lDemotion:
    • convert to a lower type
  72. Coercion rule
    • 1) char, short, unsigned short
    • automatically promoted to int

    • 2)
    • When operating on values of different data types, the lower one is
    • promoted to the type of the higher one.

    • 3)When using the =
    • operator, the type of expression on right will be converted to type of variable
    • on left
  73. Assignment operator =
    Variable = Expression;



    The Expression on right is evaluated first.

    • Then the resulting value is stored in the
    • memory location of Variable
    • on left.

    • NOTE:
    • An automatic type coercion occurs after evaluation but before the value is stored if the types differ for Expression and Variable
  74. lvalues vs rvalues
    • lvalue – can appear on both the left side and the
    • right side of an assignment operator ( = ).

    lcan have a value assigned to it.

    lmust be a variable.

    lcannot be a constant.

    • rvalue - can appear only on the right side of the
    • equal sign in an assignment operator ( = ).

    • lcan be a value (literal), lvalue, a constant, or a
    • variable.
  75. Overflow and Underflow
    • lOccurs when assigning a
    • value that is too large (overflow) or too small (underflow) to be held in a
    • variable

    • lVariable contains value
    • that is ‘wrapped around’ set of possible values

    • lDifferent systems may
    • display a warning/error message, stop the program, or continue execution using
    • the incorrect value
  76. Type casting
    lUsed for manual data type conversion

    • lUseful for floating point
    • division using ints:

    ldouble m;

    lm = (80 + 90)/ 3;

    lcout<<m<<endl;

    • ldouble m;
    • m = (double)(80 + 90)/ 3;

    lcout<<m;

    • lUseful to see int
    • value of a char variable:


    char ch = 'C';

    • cout
    • << ch << " is "

    • <<
    • (int)(ch);
  77. C-Style and Prestandard Type Cast Expressions
    • lC-Style
    • cast: data type name in ()

    • cout
    • << ch << " is " << (int)ch;

    lPrestandard C++ cast: value in ()

    cout << ch << " is " << int(ch);

    • lBoth
    • are still supported in C++, although static_cast is preferred
  78. Named (Symbolic) Constants
    • lNamed constant (constant variable): variable whose content cannot be changed
    • during program execution; read-only

    • lUsed for representing
    • constant values with descriptive names:

    const double TAX_RATE = 0.0675;

    const int NUM_STATES = 50;

    • lOften named in uppercase
    • letters
  79. What happens?
    const double PI=3.14;

    PI = 1.12;
    ERROR:

    • error
    • C3892: 'PI' : you cannot assign to a variable that is const
  80. Multiple Assignment and Combined Assignment
    • lThe
    • =
    • can be used to assign a value to multiple variables:

    • x
    • = y = z = 5;

    • lValue
    • of =
    • is the value that is assigned

    • lAssociates
    • right to left:

    x = (y = (z = 5));
  81. Combined Assignment
    • lLook
    • at the following statement:


    sum = sum + 1;

    • Recall: assignment operator (=)
    • precedence starts from right, right to left.


    This adds 1 to the variable sum and assignd result to the variable sum.
  82. Combined Assignment
    • lThe
    • combined assignment operators provide a shorthand for these types of
    • statements.

    • lThe
    • statement

    sum = sum + 1;

    is equivalent to

    sum += 1;

    Also equivalent to

    sum++;
  83. Formatting Output
    • lCan
    • control how output displays for numeric, string data:

    lsize

    lposition

    lnumber of digits

    • lRequires
    • iomanip header file

    • lSo you should include following
    • line in your program

    l#include <iomanip>
  84. Stream Manipulators
    • lUsed to control how an
    • output field is displayed


    • lSome affect just the next
    • value displayed:

    • lsetw(x): print in a field at least
    • x number of spaces wide. So, x
    • should be integer value. Use more spaces if field is not wide enough
  85. Stream Manipulators
    • lSome affect values until
    • changed again:

    • lfixed: use decimal notation for
    • floating-point values

    • lsetprecision(x): when used with fixed, print floating-point value
    • using x digits after the
    • decimal. Without fixed, print floating-point value
    • using x significant digits

    • lshowpoint:
    • always print decimal for floating-point values
  86. More About Member Functions
    lMember Function: procedure that is part of an object

    • l
    • cout, cin are objects

    • lSome
    • member functions of the cin object:

    lgetline

    lget

    lignore
  87. More Mathematical Library Functions
    • lRequire
    • math.h header file

    • lTake
    • double as input, return a double

    • lCommonly
    • used functions:





    sin


    Sine




    cos


    Cosine




    tan


    Tangent




    sqrt


    Square root




    log


    Natural (e) log




    • abs
    • pow



    • Absolute value (takes
    • and returns an int)
    • Exponents
  88. Hand Tracing a Program
    • lHand trace a program: act
    • as if you are the computer, executing a program:

    • lstep through and ‘execute’
    • each statement, one-by-one

    • lrecord the contents of
    • variables after statement execution, using a hand trace chart (table)

    • lUseful to locate logic or
    • mathematical errors
  89. 1
    • Components and Order of statements in a
    • program:

    Purpose: to develop well-structured programs.

    • 1.Preprocessor
    • directives [#include <iostream> ]

    • 2.Constants
    • [cannot change] Name of constants should
    • be all uppercase letters.

    3.Include namespaces: e.g.using namespace std;

    • 4.main( )
    • function heading or header line [e.g.int main( ) ]

    • 5.Declaration
    • statements [e.g. int total =
    • 0; ] All variables names should be lowercase.

    • 6.Statement
    • section [program code that makes the body of the function – Should follow the
    • flow of: INPUT, PROCESS, & OUTPUT]
  90. Basic control structures
    • lSequence: a
    • series of statements that execute one after another

    • lSelection (branch): to execute different statements depending on
    • certain conditions

    (if, if-else, switch)

    • lLooping (repetition): to repeat statements while certain conditions
    • are met.

    (while, do_while, for)

    lSubprogram (functions): to break the program into smaller units
  91. Relational Expressions
    • lCan
    • be assigned to a variable:

    bool result; result = x <= y;

    • lAssigns
    • 0 for false,
    • 1 for true

    • ltrue and false are
    • reserved keywords

    • lDo
    • not confuse = and ==

    lExamples:

    lint x=3,y=3;

    lbool result=x>y;

    lcout<<result<<endl;//displays 0 on screen

    lint x=3,y=3;

    lbool result=x==y;

    lcout<<result<<endl;//displays ? on screen
  92. n
    Like all C++ expressions,

    • relational
    • expressions are

    evaluated to yield a numerical result.

    • A
    • condition that we would interpret as true



    evaluates to an integer value of 1;


    • a false
    • condition results in an integer value of 0.




    Samples:

    • cout <<
    • “The value of 3 < 4 is “ << (3 < 4) << endl;

    • cout <<
    • “The value of 2.0 > 3.0 is “ <<
    • (2.0 > 3.0);


    Results:

    • The value of 3
    • < 4 is 1

    • The value of 2.0
    • > 3.0 is 0
  93. The if Statement
    • lAllows
    • statements to be conditionally executed or skipped over

    • lModels
    • the way we mentally evaluate situations:

    • l"If it is raining, take an
    • umbrella."

    • l"If it is cold outside, wear
    • a coat."
  94. if statement – what
    happens
    To evaluate:

    if (expression)

    statement;

    • lIf
    • the expression is true, then statement is executed.

    • lIf
    • the expression is false,
    • then statement is skipped.
  95. if statement
    • lDo
    • not place ; after (expression)

    • lPlace
    • statement; on a
    • separate line after (expression), indented:

    • if
    • (score > 90)

    grade = 'A';

    • lBe
    • careful testing floats and doubles for equality

    • l0 is false; any
    • other value is true
  96. Expanding the if Statement
    • lTo
    • execute more than one statement as part of an if
    • statement, enclose them in { }:

    if (score > 90)

    {

    grade = 'A';

    cout << "Good Job!\n";

    }

    • l
    • { }
    • creates a block of code
  97. The if/else Statement
    • lProvides
    • two possible paths of execution

    • lPerforms
    • one statement or block if the expression is true, otherwise
    • performs another statement or block.
  98. if-else provides two-way selection between executing one of 2
    clauses:
    the if clause or the else clause
    • if-else provides two-way selection between executing one of 2
    • clauses:
    • the if clause or the else clause
  99. compound statement
    A compound statement consists of


    individual statements enclosed within braces
  100. The if/else if Statement
    or if-else Chain or Extended
    if-else
    • lChain
    • of if
    • statements that test in order until one is found to be true

    • lAlso
    • models thought processes:

    • l“If it is raining, take an
    • umbrella,
    • else, if it is windy, take a hat,
    • else, take sunglasses”
  101. Using a Trailing else
    • lUsed
    • with if/else if statement when none of the expressions are true

    • lProvides
    • default statement/action

    • lUsed
    • to catch invalid values, other exceptional situations
  102. Nested if Statements
    • lAn if
    • statement that is part of the if or else part of another if
    • statement

    • lCan be used to evaluate
    • more than one condition:


    if (score < 100)

    {

    • if
    • (score > 90)

    • grade
    • = 'A';
  103. Notes on coding nested ifs
    • lAn
    • else matches the nearest previous unmatched if that
    • does not have an else:

    if (score < 100)

    if (score > 90)

    grade = 'A';

    else ...// goes with second if,

    // not first one

    • lProper
    • indentation helps greatly
  104. Writing Nested if Statements
    • 1.Your
    • city classifies a pollution index

    lless than 35 as “Pleasant”,

    l35 through 60 as “Unpleasant”,

    • l and above 60 as “Health
    • Hazard.”

    • lDisplay the correct description
    • of the

    • pollution
    • index value.
  105. answer
    if ( index < 35 )



    • cout
    • << “Pleasant”;



    • else if ( index <= 60
    • )



    • cout
    • << “Unpleasant”;



    else



    • cout
    • << “Health
    • Hazard”;
  106. Logical Operators
    • lUsed
    • to create relational expressions from other relational expressions

    • lOperators,
    • meaning, and explanation:
  107. Logical Operators – notes, precedence
    • l! has
    • highest precedence, followed by &&, then ||

    • lIf
    • the value of an expression can be determined by evaluating just the
    • sub-expression on left side of a logical operator, then the sub-expression on
    • the right side will not be evaluated (short circuit evaluation)

    • l3
    • logical operators order of precedence

    • First,
    • ! Second, && Third, ||
  108. Checking Numeric Ranges with Logical
    Operators
    • lUsed to test to see if a
    • value falls inside a range:

    if (grade >= 0 && grade <= 100)

    • cout << "Valid
    • grade";

    • lCan also test to see if
    • value falls outside of range:

    if (grade < 0 || grade > 100)

    • cout << "Invalid
    • grade";

    l

    lIMPORTANT:

    lCannot use mathematical notation:

    if (0 <= grade <= 100) //doesn’t work
  109. Validating User Input
    • lInput validation: inspecting input data to determine whether
    • it is acceptable

    • lBad output will be
    • produced from bad input

    lCan perform various tests:

    lRange

    lReasonableness

    lValid menu choice

    lDivide by zero
  110. More About Variable
    Declarations and Scope
    • lScope of a
    • variable is the block in which it is defined, from the point of declaration to
    • the end of the block

    • lUsually
    • declared at the beginning of a function

    • lMay
    • be defined close to first use
  111. Still
    More About
    Variable Declarations and Scope
    • lVariables
    • declared inside { } have local or block scope

    • lWhen
    • inside a block within another block, can declare variables with the same name
    • as in the outer block.

    • lWhen in inner block, outer
    • definition is not available

    lNot a good idea
  112. Control in switch statement
    • lcontrol branches to the
    • statement following the case label that matches the value of IntegralExpression. Control proceeds through all remaining
    • statements, including the default, unless redirected with break

    • lif no case label matches
    • the value of IntegralExpression,
    • control branches to the default label, if present--otherwise control passes to
    • the statement following the entire switch statement

    • lforgetting to use break can cause logical
    • errors because after a branch is taken, control
    • proceeds sequentially until either break
    • or the end of the switch statement occurs
  113. The switch Statement
    • lUsed
    • to select among statements from several alternatives

    • lIn
    • some cases, can be used instead of if/else
    • if statements
  114. switch statement
    requirements
    • expression must be an integer variable or an expression that evaluates to
    • an integer value (e.g. char)

    • 2)exp1 through expn must be constant integer expressions or
    • literals, and must be unique in the switch statement

    • 3) default is
    • optional but highly recommended
  115. switch statement – how it
    works
    ) expression is evaluated

    • 2)The
    • value of expression is compared against exp1 through expn.

    • 3)If expression matches value expi, the program branches to the statement
    • following expi and continues to the end of the switch

    • 4)If no
    • matching value is found, the program branches to the statement after default:
  116. break statement
    • lUsed
    • to exit a switch statement

    • lUseful
    • to execute a single case statement without executing the statements
    • following it

    • lIf it is left out,
    • the program "falls through" the remaining statements in the switch statement

    • lUsed
    • to stop execution in the current block
  117. j
    • A switch
    • statement is used in place of
    • many if
    • statements.
  118. j
    • The
    • break keyword means
    • "jump out of the switch statement, and do not execute any more code
    • This
    • feature of switch statements can
    • sometimes be used to a programmers' advantage.
  119. Menus
    • lMenu-driven program: program execution controlled by user
    • selecting from a list of actions

    • lMenu:
    • list of choices on the screen

    • lMenus
    • can be implemented using if/else if or switch statements
  120. Menu-driven program organization
    • lDisplay
    • list of numbered or lettered choices for actions

    • lPrompt
    • user to make selection

    • lTest
    • user selection in expression

    • lif a match, then execute code for
    • action

    lif not, then go on to next expression
  121. Using switch with a menu
    • lswitch
    • statement is a natural choice for menu-driven program:

    ldisplay the menu

    • lthen, get the user's menu
    • selection

    luse user input as expression in switch statement

    luse menu choices as expr in case statements

What would you like to do?

Home > Flashcards > Print Preview