Professional Documents
Culture Documents
Outline
Introduction to Programming
Chapter 1:
Introduction to computers and
C++ Programming
Dr. Mohammad A. Alzubaidi
Yarmouk University
Computer Engineering Department
What is a Computer?
• Computer
– Device capable of performing computations and making
logical decisions
• Computer programs
– Sets of instructions that control computer’s processing of
data
• Hardware
– Various devices comprising computer
• Keyboard, screen, mouse, disks, memory, CD-ROM,
processing units, …
• Software
– Programs that run on computer
6. Execute CPU
Primary
Memory
• Comments
– Document programs
– Improve program readability
– Ignored by compiler
– Single-line comment
• Begin with //
• Preprocessor directives
– Processed by preprocessor before compiling
– Begin with #
Welcome to C++!
using statements
Eliminate use of std:: prefix
Write cout instead of std::cout
Welcome
to
C++!
Memory Concepts
• Variable names
– Correspond to actual locations in computer's memory
– Every variable has name, type, size and value
– When new value placed into variable, overwrites previous
value
– Reading variables from memory nondestructive
Memory Concepts
Arithmetic
• Arithmetic calculations
– *
• Multiplication
– /
• Division
• Integer division truncates remainder
– 7 / 5 evaluates to 1
– %
• Modulus operator returns remainder
– 7 % 5 evaluates to 2
Arithmetic
Introduction to Programming
Chapter 2:
Control Statements
Yarmouk University
Computer Engineering Department
Introduction
Algorithms
• Computing problems
– Solved by executing a series of actions in a specific order
• Algorithms are procedure determining
– Actions to be executed
– Order to be executed
– Example: recipe
• Program control
– Specifies the order in which statements are executed
Pseudocode
• Pseudocode
– Artificial, informal language used to develop algorithms
– Similar to everyday English
• Not executed on computers
– Used to think out program before coding
• Easy to convert into C++ program
– Only executable statements
• No need to declare variables
Control Structures
• Sequential execution
– Statements executed in order
• Transfer of control
– Next statement executed not next one in sequence
• 3 control structures
– Sequence structure
• Programs executed sequentially by default
– Selection structures
• if, if/else, switch
– Repetition structures
• while, do/while, for
Control Structures
• Flowchart
– Graphical representation of an algorithm
– Special-purpose symbols connected by arrows (flowlines)
– Rectangle symbol (action symbol)
• Any type of action
– Oval symbol
• Beginning or end of a program, or a section of code (circles)
• Single-entry/single-exit control structures
– Connect exit point of one to entry point of the next
– Control structure stacking
– Control structure nesting
if Selection Structure
• Selection structure
– Choose among alternative courses of action
– Pseudocode example:
If student’s grade is greater than or equal to 60
Print “Passed”
– If the condition is true
• Print statement executed, program continues to next statement
– If the condition is false
• Print statement ignored, program continues
– Indenting makes programs easier to read
• C++ ignores whitespace characters (tabs, spaces, etc.)
if Selection Structure
if ( grade >= 60 )
cout << "Passed";
if Selection Structure
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
Logical Operators
• || (logical OR)
– true if either of condition is true
if ( semesterAverage >= 90 || finalExam >= 90 )
cout << "Student grade is A" << endl;
Logical Operators
• if
– Performs action if condition true
• if/else
– Different actions if conditions true or false
• Pseudocode
if student’s grade is greater than or equal to 60
print “Passed”
else
print “Failed”
• C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
false true
grade >= 60
• Example
if ( grade >= 90 ) // 90 and above
cout << "A";
else if ( grade >= 80 ) // 80-89
cout << "B";
else if ( grade >= 70 ) // 70-79
cout << "C";
else if ( grade >= 60 ) // 60-69
cout << "D";
else // less than 60
cout << "F";
• Compound statement
– Set of statements within a pair of braces
if ( grade >= 60 )
cout << "Passed.\n";
else {
cout << "Failed.\n";
cout << "You must take this course again.\n";
}
– Without braces,
cout << "You must take this course again.\n";
always executed
• Block
– Set of statements within braces
case value2:
case value3: // taken if variable == value2 or == value3
statements
break;
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
You passed
Your grade is D
2003 Prentice Hall, Inc.
All rights reserved.
26
• Repetition structure
– Action repeated while some condition remains true
– Pseudocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
true
product <= 1000 product = 2 * product
false
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81 2003 Prentice Hall, Inc.
All rights reserved.
32
Formulating Algorithms
(Sentinel-Controlled Repetition)
• Suppose problem becomes:
Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run
– Unknown number of students
– How will program know when to end?
• Sentinel value
– Indicates “end of data entry”
– Loop ends when sentinel input
– Sentinel chosen so it cannot be confused with regular input
• -1 in this case
• Problem statement
A college has a list of test results (1 = pass, 2 = fail) for 10
students. Write a program that analyzes the results. If more
than 8 students pass, print "Raise Tuition".
• Notice that
– Program processes 10 results
• Fixed number, use counter-controlled loop
– Two counters can be used
• One counts number that passed
• Another counts number that fail
– Each test result is 1 or 2
• If not 1, assume 2
• Refine
Input the ten quiz grades and count passes and failures
to
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
• Refine
Print a summary of the exam results and decide if tuition should
be raised
to
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
• Program next
Assignment Operators
• Preincrement
– Variable changed before used in expression
• Operator before variable (++c or --c)
• Postincrement
– Incremented changed after expression
• Operator after variable (c++, c--)
• If c = 5, then
– cout << ++c;
• c is changed to 6, then printed out
– cout << c++;
• Prints out 5 (cout is executed before the increment.
• c then becomes 6
• Example upcoming
– Program to read grades (A-F)
– Display number of each grade entered
• Details about characters
– Single characters typically stored in a char data type
• char a 1-byte integer, so chars can be stored as ints
– Can treat character as int or char
• 97 is the numerical representation of lowercase ‘a’ (ASCII)
• Use single quotes to get numerical representation of character
cout << "The character (" << 'a' << ") has the value "
<< static_cast< int > ( 'a' ) << endl;
Prints
The character (a) has the value 97
• Example
for( int counter = 1; counter <= 10; counter++ )
cout << counter << endl;
– Prints integers from one to ten
No
semicolon
after last
statement
Sum is 2550
true
condition
false
1 2 3 4 5 6 7 8 9 10
• break statement
– Immediate exit from while, for, do/while, switch
– Program continues with first statement after structure
• Common uses
– Escape early from a loop
– Skip the remainder of switch
• continue statement
– Used in while, for, do/while
– Skips remainder of loop body
– Proceeds with next iteration of loop
• while and do/while structure
– Loop-continuation test evaluated immediately after the
continue statement
• for structure
– Increment expression executed
– Next, loop-continuation test evaluated
1 2 3 4 6 7 8 9 10 fig02_27.cpp
Used continue to skip printing the value 5 (2 of 2)
fig02_27.cpp
output (1 of 1)
Structured-Programming Summary
Intro to Programming
Chapter 3:
Functions
Yarmouk University
Computer Engineering Dept.
Introduction
Functions
• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
• Parameters
– Local variables passed to function when called
– Provide outside information
Function Definitions
• Function prototype
– Tells compiler argument type and return type of function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later
• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Function Definitions
Function Definitions
• Example function
int square( int y )
{
return y * y;
}
• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions
• Next: program examples
Function Prototypes
Function Prototypes
• Function signature
– Part of prototype with name and parameters
• double maximum( double, double, double );
Function signature
• Argument Coercion
– Force arguments to be of proper type
• Converting int (4) to double (4.0)
cout << sqrt(4)
– Conversion rules
• Arguments usually converted automatically
• Changing from double to int can truncate data
– 3.4 to 3
– Mixed type goes to highest type (promotion)
• Int * double
Function Prototypes
Da ta typ es
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool (false becomes 0, true becomes 1)
Fig . 3.5 Pro m o tio n hiera rc hy fo r b uilt-in d a ta typ es.
Header Files
Storage Classes
Storage Classes
Storage Classes
• Static storage class
– Variables exist for entire program
• For functions, name exists for entire program
– May not be accessible, scope rules still apply (more later)
• static keyword
– Local variables in function
– Initialized to zero
– Keeps value between function calls
– Only known in own function
• extern keyword
– Default for global variables/functions
• Globals: defined outside of a function block
– Known in any function that comes after it
2003 Prentice Hall, Inc. All rights reserved.
25
Scope Rules
• Scope
– Portion of program where identifier can be used
• File scope
– Defined outside a function, known in all functions
– Global variables, function definitions and prototypes
• Function scope
– Can only be referenced inside defining function
Scope Rules
• Block scope
– Begins at declaration, ends at right brace }
• Can only be referenced in this range
– Local variables, function parameters
• Function-prototype scope
– Parameter list of prototype
– Names in prototype optional
• Compiler ignores
– In a single prototype, name can be used once
int i = 8;
fig03_12.cpp
int square(int i);
(1 of 5)
int main()
{
cout << "Value of i is: " << i << endl;
{
int i = 6;
cout << "Value of i is: " << i << endl;
}
int i = 7;
cout << "Value of i is: " << i << endl;
i = square(i);
cout << "Value of i is: " << i << endl;
return 0;
}
local x in main is 5
• Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Prevent unwanted side effects
• Call by reference
– Function can directly access data
– Changes affect original
• Reference parameter
– Alias for argument in function call
• Passes parameter by reference
– Use & after data type in prototype
• void myFunction( int &data )
• Read “data is a reference to an int”
– Function call format the same
• However, original can now be changed
fig03_20.cpp
z = 4 before squareByReference
z = 16 after squareByReference
output (1 of 1)
• Pointers (chapter 5)
– Another way to pass-by-refernce
• References as aliases to other variables
– Refer to same variable
– Can be used within a function
int count = 1; // declare integer variable count
Int &cRef = count; // create cRef as an alias for count
++cRef; // increment count (using its alias)
x = 3
y = 3
x = 7
y = 7
Default Arguments
Function Overloading
• Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
• If not base case
– Break problem into smaller problem(s)
– Launch new copy of function to work on the smaller
problem (recursive call/recursive step)
• Slowly converges towards base case
• Function makes call to itself inside the return statement
– Eventually base case gets solved
• Answer works way back up, solves entire problem
Recursion
• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)
fig03_14.cpp
int main()
(1 of 2)
{
int x,y;
cin >> x;
y = factorial(x);
cout << "factorial " << x << " is " << y << endl;
return 0;
}
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
return 1 return 0
• Order of operations
– return fibonacci( n - 1 ) + fibonacci( n - 2 );
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Enter an integer: 5
fig03_15.cpp
Fibonacci(5) = 5
output (2 of 2)
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good
software engineering (recursion)
• Assignment:
– Rewrite the fibonacci series program without using recursion
(using iterations):
Intro to Programming
Chapter 4:
Arrays
Yarmouk University
Computer Engineering Dept.
Introduction
• Arrays
– Structures of related data items
– Static entity (same size throughout program)
Arrays
• Array
– Consecutive group of memory locations
– Same name and type (int, char, etc.)
• To refer to an element
– Specify array name and position number (index)
– Format: arrayname[ position number ]
– First element at position 0
• N-element array c
c[ 0 ], c[ 1 ] … c[ n - 1 ]
– Nth element as position N-1
Arrays
Arrays
Name of array (Note
that all elements of
this array have the
same name, c)
c[0] -45
c[1] 6
c[2] 0
c[3] 72
c[4] 1543
c[5] -89
c[6] 0
c[7] 62
c[8] -3
c[9] 1
c[10] 6453
c[11] 78
Declaring Arrays
• Initializing arrays
– For loop
• Set each element
– Initializer list
• Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements 0
• If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array
• Array size
– Can be specified with constant variable (const)
• const int size = 20;
– Constants cannot be changed
– Constants must be initialized when declared
– Also called named constants or read-only variables
• Arrays passed-by-reference
– Functions can modify original array data
– Value of name of array is address of first element
• Function knows where the array is stored
• Can change original memory locations
• Individual array elements passed-by-value
– Like regular variables
– square( myArray[3] );
Sorting Arrays
• Sorting data
– Important computing application
– Virtually every organization must sort some data
• Massive amounts must be sorted
• Bubble sort (sinking sort)
– Several passes through the array
– Successive pairs of elements are compared
• If increasing order (or identical), no change
• If decreasing order, elements exchanged
– Repeat these steps for every element
Sorting Arrays
• Example:
– Go left to right, and exchange elements as necessary
• One pass for each element
– Original: 3 4 2 7 6
– Pass 1: 3 2 4 6 7 (elements exchanged)
– Pass 2: 2 3 4 6 7
– Pass 3: 2 3 4 6 7 (no changes needed)
– Pass 4: 2 3 4 6 7
– Pass 5: 2 3 4 6 7
– Small elements "bubble" to the top (like 2 in this example)
Sorting Arrays
• Swapping variables
int x = 3, y = 4;
y = x;
x = y;
• What happened?
– Both x and y are 3!
– Need a temporary variable
• Solution
int x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3
Searching Arrays
Strings
• Strings
– Arrays of characters
– All strings end with null ('\0')
– Examples
• char string1[] = "hello";
– Null character implicitly added
– string1 has 6 elements
• char string1[] = { 'h', 'e', 'l', 'l',
'o', '\0’ };
– Subscripting is the same
String1[ 0 ] is 'h'
string1[ 2 ] is 'l'
Strings
Multiple-Subscripted Arrays
• Multiple subscripts
– a[ i ][ j ]
– Tables with rows and columns
– Specify row, then column
– “Array of arrays”
• a[0] is an array of 4 elements
• a[0][0] is the first element of that array
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
Multiple-Subscripted Arrays
• To initialize
– Default of 0
– Initializers grouped by row in braces 1 2
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 3 4
Row 0 Row 1
1 0
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; 3 4
Multiple-Subscripted Arrays
– Outputs 0 3 4
Multiple-Subscripted Arrays
Student0 95 85
Student1 89 80
Chapter 5:
Pointers and Strings
Yarmouk University
Computer Engineering Dept.
Introduction
• Pointers
– Powerful, but difficult to master
– Simulate pass-by-reference
– Close relationship with arrays and strings
• Pointer declarations
– * indicates variable is pointer
int *myPtr;
declares pointer to int, pointer of type int *
– Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;
• Can declare pointers to any data type
• Pointer initialization
– Initialized to 0, NULL, or address
• 0 or NULL points to nothing
Pointer Operators
y yptr y
5 500000 600000 600000 5
yPtr
address of y
is value of
yptr
Pointer Operators
• * (indirection/dereferencing operator)
– Returns synonym for object its pointer operand points to
– *yPtr returns y (because yPtr points to y).
– dereferenced pointer is lvalue
*yptr = 9; // assigns 9 to y
• * and & are inverses of each other
• const qualifier
– Value of variable should not be modified
– const used when function does not need to change a variable
• Principle of least privilege
– Award function enough access to accomplish task, but no more
• Four ways to pass pointer to function
– Nonconstant pointer to nonconstant data
• Highest amount of access
– Nonconstant pointer to constant data
– Constant pointer to nonconstant data
– Constant pointer to constant data
• Least amount of access
• Pointer arithmetic
– Increment/decrement pointer (++ or --)
– Add/subtract an integer to/from a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Pointer arithmetic meaningless unless performed on pointer to
array
• 5 element int array on a machine using 4 byte ints
– vPtr points to first element v[ 0 ], which is at location 3000
vPtr = 3000 location
3000 3004 3008 3012 3016
• Subtracting pointers
– Returns number of elements between two addresses
vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
vPtr2 - vPtr == 2
• Pointer assignment
– Pointer can be assigned to another pointer if both of same type
– If not same type, cast operator must be used
– Exception: pointer to void (type void *)
• Generic pointer, represents any type
• No casting needed to convert pointer to void pointer
• void pointers cannot be dereferenced
• Pointer comparison
– Use equality and relational operators
– Comparisons meaningless unless pointers point to members
of same array
– Compare addresses stored in pointers
– Example: could show that one pointer points to higher
numbered element of array than other pointer
– Common use to determine whether pointer is 0 (does not
point to anything)
Pointer/offset notation
*(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40
string1 = Hello
string3 = Good Bye
• Character constant
– Integer value represented as character in single quotes
– 'z' is integer value of z
• 122 in ASCII
• String
– Series of characters treated as single unit
– Can include letters, digits, special characters +, -, * ...
– String literal (string constants)
• Enclosed in double quotes, for example:
"I like C++"
– Array of characters, ends with null character '\0'
– String is constant pointer
• Pointer to string’s first character
– Like arrays
2003 Prentice Hall, Inc. All rights reserved. http://www.deitel.com
32
• String assignment
– Character array
• char color[] = "blue";
– Creates 5 element char array color
• last element is '\0'
– Variable of type char *
• char *colorPtr = "blue";
– Creates pointer colorPtr to letter b in string “blue”
• “blue” somewhere in memory
– Alternative for character array
• char color[] = { ‘b’, ‘l’, ‘u’, ‘e’, ‘\0’ };
int strcmp( const char *s1, Compares the string s1 with the string s2. The
const char *s2 ); function returns a value of zero, less than zero
or greater than zero if s1 is equal to, less than
or greater than s2, respectively.
Chapter 6:
Classes and Data Abstraction
Yarmouk University
Computer Engineering Dept.
Structure Definitions
• Structures
– Aggregate data types built using elements of other types
Structure Definitions
• struct definition
– Creates new data type used to declare variables
– Structure variables declared like variables of other types
– Examples:
• Time timeObject;
• Time timeArray[ 10 ];
• Time *timePtr = &timeobject;