0% found this document useful (0 votes)
11 views

Programming Language I: C++ Programming: From Problem Analysis To Program Design, by D.S. Malik

ftyrtyrty,//q. bnm,.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Programming Language I: C++ Programming: From Problem Analysis To Program Design, by D.S. Malik

ftyrtyrty,//q. bnm,.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 317

Programming Language I

C++ Programming: From Problem


Analysis to Program Design,
by D.S. Malik
Computation

(input) data Code (output)


data

• Input: from keyboard, files, other input devices, other


programs, other parts of a program
• Computation: what our program will do with the input
to produce the output.
• Output: to screen, files, other output devices, other
programs, other parts of a program
The Language of a Computer
(cont’d.)
The Language of a Computer
(cont'd.)
• ASCII (American Standard Code for
Information Interchange)
– 128 characters
– A is encoded as 1000001 (66th character)
– 3 is encoded as 0110011
ASCII
C++

C, C++, Java, and C# are very similar. C++


evolved from C. Java was modeled after C++.
C# is a subset of C++ with some features
similar to Java. If you know one of these
languages, it is easy to learn the others.
Processing a C++ Program (cont'd.)
• To execute a C++ program:
– Use an editor to create a source program in
C++
– Preprocessor directives begin with # and are
processed by a the preprocessor
– Use the compiler to:
• Indicates something that must be fixed
before the code can be compiled.
• Translate into machine language (object
program)
Processing a C++ Program (cont'd.)

• To execute a C++ program (cont'd.):


– Linker:
• Combines object program with other programs
provided by the SDK to create executable code
– Loader:
• Loads executable program into main memory
– The last step is to execute the program
Processing a C++ Program (cont'd.)
Source code (developed by the programmer)
Create/Modify Source Code
#include <iostream>
using namespace std;

Creating, int main()


{
// Display Welcome to C++ to the console
Saved on the disk

Compiling,
cout << "Welcome to C++!" << endl; Source Code
return 0;
}

and Running Compiler


If compilation errors

Programs stored on the disk

An object file (e.g., Welcome.obj) is created.


Machine Code
program

Linker

stored on the disk

An executable file (e.g., Welcome.exe) is created.


Executable Code

Run Executable Code


e.g., Welcome

Result

If runtime errors or incorrect result


Processing a C++ Program
#include <iostream>
using namespace std;
int main()
{
cout << "My first C++ program." <<
endl;
return 0;
}

Sample Run:
My first C++ program.
Hello World
// Hello World program comment

#include <iostream.h> Allows access to


an I/O library
int main() {
Starts definition of special
function main()
cout << "Hello World\n";
output (print) a
return 0; string
}
Program returns a
status code (0 means
OK)
Basic Elements of C++
Comments

• Comments contain text that is not


converted to machine language (it's just
there for humans).
• Everything after "//" is ignored by the
compiler.
• Everything between "/*" and "*/" is
ignored.
Comment Example
Two types:
– Single line
// This is a C++ program. It prints the
sentence:
// Welcome to C++ Programming.
– Multiple line
/*
This is a C++ program. It prints the
sentence:
Welcome to C++ Programming.
*/
C++ Preprocessor

• C++ Compilers automatically invoke a


preprocessor that takes care of #include
statements and some other special
directives.
• You don't need to do anything special to
run the preprocessor - it happens
automatically.
Some common includes

• Basic I/O: iostream, iostream.h

• I/O manipulation: iomanip, iomanip.h

• Standard Library: stdlib.h


Variables
• The program now uses variables:
int integer1, integer2, sum;
• Variables are just names for locations in
memory.
• In C++ all variables must have a type.
• In C++ all variables must be declared
before they can be used.
Variables (cont.)

• C++ variables are declared like this:


type var_name;

• type indicates what kind of variable.


• C++ built in types include:
int char float double bool
Variable Names

• C++ variable names:


– made up of letters, digits and underscore.
– Must start with a non-digit.
– Case sensitive
• first is not the same name as First
• Can be any length
• Good variable names tell the reader what
the variable is used for!
Names
• A name in a C++ program
– Starts with a letter, contains letters, digits, and
underscores (only)
• x, number_of_elements, Fourier_transform, z2
• Not names:
– 12x
– time!to!market
– main line

– Users can't define names that are taken as keywords


• E.g.:
– int
– if
– while
– double
Reserved Words (Keywords)
• C++ keywords
– Cannot be used as variable names

Examples of C++ Keywords


int double float char const
case continue break bool static_cast
if else switch default return
short long do while for
Allocating Memory with Constants
and Variables
• Named constant: memory location whose
content can’t change during execution
• The syntax to declare a named constant
is:
• In C++, const is a reserved word
Allocating Memory with Constants
and Variables (cont'd.)
• Variable: memory location whose content
may change during execution
• The syntax to declare a named constant
is:
Assignment Statement
Declaring & Initializing Variables

• Variables can be initialized when declared:


int first=13, second=10;
char ch=' ';
double x=12.6;
• All variables must be initialized before they
are used
Input (Read) Statement

• cin is used with >> to gather input

• The stream extraction operator is >>


• For example, if miles is a double variable
cin >> miles;
– The computer will get a value of type double
and places it in the variable miles.
Input (Read) Statement (cont'd.)
• Using more than one variable in cin
allows more than one value to be read at a
time
• For example, if feet and inches are
variables of type int, a statement such
as:
cin >> feet >> inches;
– Inputs two integers from the keyboard
– Places them in variables feet and inches
respectively
Input (Read) Statement (cont'd.)
Variable Initialization

• There are two ways to initialize a variable:


int feet;
– By using the assignment statement
feet = 35;
– By using a read statement
cin >> feet;
Increment and Decrement Operators
• Increment operator: increment variable by 1
– Pre-increment: ++variable
– Post-increment: variable++
• Decrement operator: decrement variable by 1
– Pre-decrement: --variable
– Post-decrement: variable—
• What is the difference between the following?
x = 5; x = 5;
y = ++x; y = x++;
More on Assignment Statements

• C++ has special assignment statements


called compound assignments
+=, -=, *=, /=, and %=
• Example:
x *= y;
Assignment and increment

a:
// changing the value of a variable
int a = 7; // a variable of type int called a 7

// initialized to the integer value 7


a = 9; // assignment: now change a's value to 9
9
18
a = a+a; // assignment: now double a's value

20
a += 2; // increment a's value by 2

21
++a; // increment a's value (by 1)
Output
• The syntax of cout and << is:

– Called an output statement


• The stream insertion operator is <<
• Expression evaluated and its value is
printed at the current cursor position on
the screen
Output (cont'd.)

• A manipulator is used to format the output


– Example: endl causes insertion point to
move to beginning of next line
• Example:
Output (cont'd.)
• The new line character is '\n'
– May appear anywhere in the string
cout << "Hello there.";
cout << "My name is James.";
• Output:
Hello there.My name is James.
cout << "Hello there.\n";
cout << "My name is James.";
• Output :
Hello there.
My name is James.

36
Form and Style

• Consider two ways of declaring variables:


– Method 1
int feet, inch;
double x, y;
– Method 2
int feet,inch;double x,y;
• Both are correct; however, the second is
hard to read
Output (cont'd.)
1 // Example 1
2 // Addition program that displays the sum of two numbers.
3 #include <iostream> // allows program to perform input and output
4 using namespace std;
5 // function main begins program execution
6 int main() Declare integer variables
7 {
8 // variable declarations
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
Use stream operator with
12 standard input stream to
13 cout << "Enter first integer: "; // prompt user for data obtain user input
14 cin >> number1; // read first integer from user into number1
15
16 cout << "Enter second integer: "; // prompt user for data
17 cin >> number2; // read second integer from user into number2 Stream manipulator
18
endl outputs a newline
19 sum = number1 + number2; // add the numbers; store result in sum
20
21 cout << "Sum is " << sum << endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24 Output
25 } // end function main

Enter first integer: 45


Enter second integer: 72
Sum is 117
Another C++ Program
//
// C++
C++ Addition
Addition of
of integers
integers
#include
#include <iostream.h>
<iostream.h>

int
int main()
main() {{
int
int integer1,
integer1, integer2,
integer2, sum;
sum;

cout
cout <<
<< "Enter
"Enter first
first integer\n";
integer\n";
cin
cin >>
>> integer1;
integer1;
cout
cout <<
<< "Enter
"Enter second
second integer\n";
integer\n";
cin
cin >>
>> integer2;
integer2;
sum
sum == integer1
integer1 ++ integer2;
integer2;
cout
cout <<
<< "Sum
"Sum is
is "" <<
<< sum
sum <<
<< endl;
endl;
return
return 0;
0;
}}
Types and literals
• Built-in types
– Boolean type • Boolean literals
• bool – true false
– Character types • Character literals
• char – 'a', 'x', '4', '\n', '$'
– Integer types • Integer literals
• Int – 0, 1, 123, -6, 245, -698

– Floating-point types • Floating point literals


• double – 1.2, 13.345, .3, -0.54
– and float
Expressions

• C++ expressions are used to express


computation.
• Expressions include operations and the
operands on which the operations are
applied.
• Operands can be variables, literals or
function calls.
Precedence
Operators Precedence
() highest (applied
first)
* / %
+ -
< <= > >=
== !=
=
lowest (applied last)
Precedence
• Precedence controls the order of
evaluation of operators.
– A high precedence means an operator is
evaluated (applied) before any lower
precedence operators.
• Operators that have the same precedence
can happen in either order, but in C++ the
one on the left is evaluated first.
Arithmetic Operators and Operator
Precedence
• C++ arithmetic operators:
– + addition
– - subtraction
– * multiplication
– / division
– % modulus operator
• +, -, *, and / can be used with integral and
floating-point data types
• Operators can be unary or binary
Order of Precedence
• All operations inside of () are evaluated
first
• *, /, and % are at the same level of
precedence and are evaluated next
• + and – have the same level of
precedence and are evaluated last
• When operators are on the same level
– Performed from left to right (associativity)
• 3 * 7 - 6 + 2 * 5 / 4 + 6 means
(((3 * 7) – 6) + ((2 * 5) / 4 )) + 6
Expressions
• If all operands are integers
– Expression is called an integral expression
• Yields an integral result
• Example: 2 + 3 * 5
• If all operands are floating-point
– Expression is called a floating-point
expression
• Yields a floating-point result
• Example: 12.8 * 17.5 - 34.50
Mixed Expressions
• Mixed expression:
– Has operands of different data types
– Contains integers and floating-point
• Examples of mixed expressions:
2 + 3.5
6 / 4 + 3.9
5.4 * 2 – 13.6 + 18 / 2
Mixed Expressions (cont'd.)
• Evaluation rules:
– If operator has same types of operands
• Evaluated according to the type of the operands
– If operator has both types of operands
• Integer is changed to floating-point
• Operator is evaluated
• Result is floating-point
– Entire expression is evaluated according to
precedence rules

10/24/2024 49
Precedence Evaluation
What is the value of the expression at the bottom of the
screen?
42

32

0 32

0 4

3 30 8

( 1 + 2 ) % 3 * 4 + 5 * 6 / 7 * ( 8 % 9 ) + 10
Type Conversion (Casting)

• Implicit type coercion: when value of one


type is automatically changed to another
type
• Cast operator: provides explicit type
conversion
static_cast<dataTypeName>(expression)
Type Conversion (cont'd.)
Relational and Equality Operators
• Relational and Equality operators are
used to compare values:
• Relational Operators:
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
• Equality Operators:
== Equal to
!= Not Equal to
Syntax

• Errors in syntax are found in compilation


int x; //Line 1
int y //Line 2: error
double z; //Line 3

y = w + x; //Line 4: error
Another Program
#include <iostream.h>
Using namespace std;
int main() {

double fahr,celcius;

cout << "Enter Temperature in Fahrenheit\n";


cin >> fahr;

celcius = (fahr - 32.0)*5/9;


cout << fahr << " fahrenheit is " << celcius <<
" Celcius" << endl;

return 0;
}
Math Operator Quiz

What are the values printed?

const int five = 5;


int i = 7;
float x = 7.0;
cout << five + i/2 << endl;
cout << five + x/2 << endl;

10/24/2024 56
cin and the Extraction Operator >>

• The syntax of an input statement using


cin and the extraction operator >> is:

• The extraction operator >> is binary


– Left-side operand is an input stream variable
• Example: cin
– Right-side operand is a variable
Output and Formatting Output

• Syntax of cout when used with <<

• Expression is evaluated
• Value is printed
• Manipulator is used to format the output
– Example: cout<< endl;
Selection statements

59
Comparison Operators

Operator Name Example Result

< less than 1 < 2 true


<= less than or equal to 1 <= 2 true
> greater than 1 > 2 false
>= greater than or equal to 1 >= 2 false
== equal to 1 == 2 false
!= not equal to 1 != 2 true

60
Logical Operators
Operator Name Description

! not logical negation


&& and logical conjunction
|| or logical disjunction

61
Truth Table for Operator !
p !p Example (assume age = 24, gender = 'M')

true false !(age > 18) is false, because (age > 18) is true.
false true !(gender != 'F') is true, because (grade != 'F') is false.

62
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, gender = 'F')

false false false (age > 18) && (gender == 'F') is true, because (age
false true false > 18) and (gender == 'F') are both true.

true false false (age > 18) && (gender != 'F') is false, because
(gender != 'F') is false.
true true true

63
Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, gender = 'F')

false false false (age > 34) || (gender == 'F') is true, because (gender
false true true == 'F') is true.

true false true (age > 34) || (gender == 'M') is false, because (age >
true true true 34) and (gender == 'M') are both false.

64
Examples
int x =4, y=6 ;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
y=x+3 7 (true)
 11>5 || 6<15 && 7>= 8 (true or
False????)
 5 + 3 <= 9 && 2 >3 (true or
False????)
Short-Circuit Operator

When evaluating p1 && p2, C++ first evaluates p1 and then

evaluates p2 if p1 is true; if p1 is false, it does not evaluate p2.

When evaluating p1 || p2, C++ first evaluates p1 and then evaluates

p2 if p1 is false; if p1 is true, it does not evaluate p2.


if Statements

if if – else - if

if - else
Selection statements
are used to choose an action depending on the
current situation in your program as it is
running:

1. (One Way) Selection Structure (if)


2. (Two-Way) Selection Structure (if … else)
3. (Multi-Way) Selection Structure (if…else if… else)
4. Special selection structure (Switch statement)
One-way if Statements
if (radius >= 0)
if (booleanExpression) {
{ area = radius * radius * PI;
statement(s); cout << "The area for the circle of " <<
} " radius " << radius << " is " << area;
}

false false
Boolean (radius >= 0)
Expression

true true

Statement(s) area = radius * radius * PI;


cout << "The area for the circle of " <<
" radius " << radius << " is " << area;

(a) (b)
if Selection Structure (One Way)
– If the condition is true
• Print statement executed, program continues to
next statement.

– If the condition is false


• Print statement ignored, program continues
if Selection Structure (One Way)
• Translation into C++
If student’s grade is greater than or equal to 50
Print “Passed”
true
condition
if ( grade >= 50 )
cout << "Passed";
• (decision symbol): false
– Contains an expression that can be true or false
• Test condition, follow path
A decision can be made on any expression.
zero - false
nonzero - true
Example: (3 – 4) is true
These are equivalent. Why?

int number=0; int number=0;


if (number==0) if (! number )
cout << number; cout<<number;

Each expression is only true when number


has value 0.
if Statement
Syntax:
Syntax: Don’t forget
ifif (expression)
(expression)
statement;
statement;
or
or
ifif (expression)
(expression) {{ Don’t forget
statement1;
statement1;
statement2;
statement2;
}} ifif(<condition>)
(<condition>){{
statement
statement11
statement
statement22
……
statement
statementkk
}}
if Statement Syntax

if
true
(Expression) condition Statement

statement false

Eg1. Eg2.
if (grade >= 50) if (age < 18)
cout<< “ Passed “ ; cout<< “Not eligible“ ;
Compound Statements
• Example
if (x < 5) The compound
{ statement
x = x + 10;
cout << x;
}
if Statement
Example:
Example:
int
intnum1,
num1,num2,
num2,min;
min;
cout
cout<<<<“Key-in
“Key-in22numbers:
numbers:";"; num1 20
?
cin 20 > 15?
cin>>num1>>
>>num1>>num2
num2;;
min
min==num1;
num1; num2 15
?
ifif(num1
(num1>>num2)
num2)
min
min==num2; min
num2; 15
20
?
cout
cout<<<<""Smallest:
Smallest:""<<
<<min
min;;

Key-in 2 numbers: 20
_ 15
_Smallest: 15
_
if Statement
Example:
Example:
int
intmark;
mark;
cout
cout<<
<<""Mark:
Mark:"";;
92 > 80? mark ?
92
cin
cin>>
>>mark
mark;;
ifif(mark
(mark>>80)
80){{
cout
cout<<
<<""Category:
Category:Excellent\n
Excellent\n"";;
cout
cout<<
<<""Congratulations!
Congratulations!"";;
}}

Mark: 92
_
_
Category: Excellent
Congratulations!
Note

Outer parentheses required Braces can be omitted if the block contains a single
statement

if ((i > 0) && (i < 10)) Equivalent if ((i > 0) && (i < 10))
{ cout << "i is an " <<
cout << "i is an " << "integer between 0 and 10";
"integer between 0 and 10";
}
(a) (b)

78
Common Errors in Selection Statements
Common Error 1: Forgetting Necessary Braces

if (radius >= 0) if (radius >= 0)


area = radius * radius * PI; {
cout << "The area " area = radius * radius * PI;
<< " is " << area; cout << "The area "
<< " is " << area;
}
(a) Wrong (b) Correct

79
Common Errors in Selection Statements
Common Error 2: Wrong Semicolon at the if Line
Logic Error Empty Body

if (radius >= 0); if (radius >= 0) { };


{ Equivalent {
area = radius * radius * PI; area = radius * radius * PI;
cout << "The area " cout << "The area "
<< " is " << area; << " is " << area;
} }
(a) (b)

80
Common Errors in Selection Statements
Common Error 3: Mistakenly Using = for ==

if (count = 1)
cout << "count is zero" << endl;
else
cout << "count is not zero" << endl;

81
The if...else Statement
if (booleanExpression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-false-case;
}

true false
Boolean
Expression

Statement(s) for the true case Statement(s) for the false case

82
Nested IF
Nested if Statements
if (i > k)
{
if (j > k)
cout << "i and j are greater than k";
}
else
cout << "i is less than or equal to k";
Nested IF
Control exists the nested if when a true condition is executed.
Example : A classic example of a nested if statement is to determine a
students letter grade given the numerical grade.

See the flowchart 


Multiple if Statements

if (score >= 90.0) if (score >= 90.0)


grade = 'A'; grade = 'A';
else else if (score >= 80.0)
if (score >= 80.0) Equivalent grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F';
grade = 'D';
else
grade = 'F';
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

87
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

88
animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

89
animation
Trace if-else-if statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

90
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';

91
Note
The else clause matches the most recent if clause in
the same block.

int i = 1; int i = 1;
int j = 2; int j = 2;
Equivalent
int k = 3; int k = 3;

if (i > j) if (i > j)
if (i > k) This is better if (i > k)
cout << "A"; with correct cout << "A";
else indentation else
cout << "B"; cout << "B";
(a) (b)
Note, cont.
Nothing is printed from the preceding statement. To force the
else clause to match the first if clause, you must add a pair of
braces:

int i = 1; int j = 2; int k = 3;

if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";

This statement prints B.


switch Statements
switch (status)
{
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(0);
}
94
switch Statement Flow Chart
status is 0
Compute tax for single filers break

status is 1
Compute tax for married file jointly break

status is 2
Compute tax for married file separatly break

status is 3
Compute tax for head of household break

default
Default actions

Next Statement
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
or int type and must
always be enclosed in case value1: statement(s)1;
parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
case valueN: statement(s)N;
The resulting statements in the
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch Statement Rules

The keyword break is optional, switch (switch-expression) {


but it should be used at the case value1: statement(s)1;
end of each case in order to
terminate the remainder of the break;
switch statement. If the break case value2: statement(s)2;
statement is not present, the
next case statement will be
break;
executed. …
case valueN: statement(s)N;
The default case, which is
break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the }
specified cases matches the
switch-expression. The case statements are executed in sequential
order, it is good programming style to follow the
logical sequence of the cases and place the default
case at the end.
animation

Trace switch statement


Suppose ch is 'a':

switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation

Trace switch statement


ch is 'a':

switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation

Trace switch statement


Execute next statement

switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}

Next statement;
animation

Trace switch statement


Suppose ch is 'a':

switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
animation

Trace switch statement


ch is 'a':

switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}

105
animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}

106
animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}

107
animation

Trace switch statement


Execute next statement

switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}

Next statement;

108
Operator Precedence
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and
remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Comparison)
• ==, !=; (Equality)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)

109
Repetition statements
“Loops”
Why Is Repetition Needed?
Suppose that you need to print a string:
(e.g., "Welcome to C++!") a hundred times.
 Write the following statement a hundred
times??
cout << "Welcome to C++!" << endl;

So, how do you solve this problem?


Why Is Repetition Needed?
How can you solve the following problem:
• What is the sum of all the numbers from 1
to 100.
• The answer will be
1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.
Why Is Repetition Needed?
Here’s some sample C++ code:
int sum=0;
sum = sum+1;
sum = sum +2;
sum = sum +3;
sum = sum +4;

sum = sum +99;
sum = sum +100;
Cout<<“The sum from 1 to 100 = “ <<sum<<endl;
Why Is Repetition Needed?
This solution has problems:
• It would take a long time to type in.
• There is a high risk of making an error
while typing it in.
• It doesn’t easily scale. This may work for
100 numbers but how would you handle
having to add from 1 to a 1000? Or to
1000000?Or to 1000000000?
Why Is Repetition Needed?
The Algorithm
Create a variable to hold the sum.
1. Initialize the sum to zero.
2. Create a variable to hold a counter from 1
to 100.
3. Initialize the counter to 1.
4. While the counter is <= to 100
5. add the counter to the sum.
6. add one to the counter.
7. Now repeat.
8. Print the sum.
The while Looping (Repetition)
Structure

• Infinite loop: is a loop that continues to execute


endlessly.
• So, expression is always true in an infinite loop.
• Statements must change value of expression to
false.
Example
i = 0
start
while (i <= 20)
{cout<<i<<endl; i = 0
i = i + 5;}
Next statment No
i <= 20
i
0
Output Yes
5 Print i
0
10 5
10 i = i + 5
15 15
20 end
20

25 What will happen if you omit (i= i + 5) ?


while Loop Flow Chart
while (loop-continuation-condition) int count = 0;
{ while (count < 100)
{
// loop-body;
cout << "Welcome to C++!\n";
Statement(s); count++;
} }
count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true true
Statement(s) cout << "Welcome to C++!\n";
(loop body) count++;

(a) (b)
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


Print Welcome to C++
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


(count < 2) is still true since count
int count = 0; is 1
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


Print Welcome to C++
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now

while (count < 2)


{
cout << "Welcome to C++!";
count++;
}
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Example
Write a C++ program to allow the
user to enter a set of (e.g 3) integer
numbers, then print the sum of these
numbers.
start
Start Program
Read setSize Read setSize
counter = 0
sum = 0
counter = 0
Loop while (counter <
setSize)
Read number
sum = sum + number sum = 0

counter = counter +
1
counter < No
End loop
Print Sum setSize
setSize
End Programcounter sum number
Yes
3 0 0 1 Read
number
Output 1 1 10
sum = sum + number
3 2 11 4
1 counter = counter + 1
10 3 15
4 Print sum
15
end
Counter-Controlled Loop:
Another way while loop
int counter = 1;
for expressing it while (counter <N)
.
.
counter ++;

for loop End while loop

int counter;
for(counter = 1; counter <N ; counter++)
.
.

End for loop


for loop
for (initialization; condition; update)
{
// loop body;
Statement (s);
}
int i;
for (i=0; i<100; i++)
cout << " Welcome to C++!\n " << endl;
int i;
for (i=10; i>=0; i--)
cout << "i is " << i << endl;
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++)
after-each-iteration)
{ {
// loop body; cout << "Welcome to C++!\n";
Statement(s); }
}
Initial-Action i=0

Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) cout<< "Welcome to C++\n";
(loop body)

Action-After-Each-Iteration i++

(A) (B)
animation

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


Print Welcome to C++!
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


Print Welcome to C++
int i;
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++)
{
cout << "Welcome to C++!";
}
for statement
???
Example: num
for ( int num = 1; num <= 3; num++ )
cout << num ;
1 _

_
for statement
1
Example: num
for ( int num = 1 ; num <= 3; num++ )
cout << num ;

_
for statement
1
Example: num
for (int num = 1; num <= 3; num++ )
cout << num ;

_
for statement
1
Example: num
for (int num = 1; num <= 3; num++ )
cout << num ;

1 _
for statement
2
Example: num
for (int num = 1; num <= 3; num++ )
cout << num ;

1 _
for statement
2
Example: num
for (int num = 1; num <= 3; num++ )
cout << num ;

1 _
for statement
2
Example: bil
for (int num = 1; num <= 3; num++ )
cout << num;

1 2 _
for statement
3
Example: num
for (int num = 1; num <= 3; num++ )
cout << num;

1 2 _
for statement
3
Example: num
for (int num = 1; num <= 3; num++ )
cout <<num;

1 2 _
for statement
3
Example: num
for (int num = 1; num <= 3; num++ )
cout <<num;

1 2 3 _
for statement
4
Example: num
for (int num = 1; num <= 3; num++ )
cout <<num;

1 2 3 _
for statement
4
Example: num
for (int num = 1; num <= 3; num++ )
cout <<num;

1 2 3 _
Note
The statement given below in (a), which is an infinite loop,
but better to use the equivalent loop in (b) :

for ( ; ; ) Equivalent while (true)


{ {
// Do something // Do something
} This is better }
(a) (b)
do-while Loop
do
Statement(s)
(loop body)
{
// Loop body; true Loop
Continuation
Condition?
Statement (s);
false

} while (condition);
do-while Loop
• Statements are executed first and then
expression is evaluated.
• Statements are executed at least once and then
continued if expression is true.
• Use When the testing of the conditions needs to
be done at the bottom.
do
statement
while ( condition );
Difference while Loop

do…while
Loop

for Loop
Example: do-while Loop

SECRET_CODE = 1234

Print input
msg
Read code

Yes
code !=
SECRET_CODE
No
Print
msg
Example: do-while Loop
int code, SECRET_CODE = 1234;
do {
cout<<"Type the secret code number to enter.\n";
cin>> code;
}while (code!=SECRET_CODE);
cout<< "Well done, you can now enter";

SECRET_CODE = 1234
Print input
msg
Read code
code != Yes
SECRET_CODE
No
Print
msg
do-while Loop
Example:

int sum = 0, data = 0;


do
{sum += data;
cout<<"Enter an int value, input 0 to sum
& exit: ";
cin >> data;}
while (data != 0);
cout << "The sum is " << sum << endl;
Using break and continue
• break – immediately end the loop that
contains it.

• continue – only ends the current


iteration, program goes to the end of the
loop body.
Using break and continue
Examples for using the break and continue:
I) int number =0, sum = 0;
while (number < 10) {
number++;
if (number == 5) break;
sum += number;}
cout << "The sum is " << sum<<endl;

II) int number =0, sum = 0;


while (number < 10) {
number++;
if (number ==5 || number ==7) continue ;
sum += number;}
cout << "The sum is " << sum<<endl;
Using break and continue
Examples for using the break and continue:
III) int number=0, sum=0 ;
while (number < 20){
number++;
sum += number;
if (sum >= 100) break;}
cout << "The number is " << number << endl;
cout << "The sum is " << sum << endl;

IV) int i=5;


do{ i--;
if (i==3) continue;
else if (i ==2) cout<< "Two";
else if (i ==1) cout<< "One";
cout << i<<endl;} while (i>0);
Using break and continue

V)
int i=1;
while (true){ // endless condition, it is always true
cout<<i;
if(i==5)
break; //Stop and exit the loop
i++; }

Output
1 2 3 4 5
Using break and continue
VI)
for (int x=1;x<=10;x++){
if(x==5)
break; //Exit before printing 5

cout<<x; }

Output
1 2 3 4
---------------------------------------------------------------------------------------------------
VII)
for( int x=1;x<=10;x++){
cout<<x;
if(x==5)
break; } // Exit after printing 5

Output
1 2 3 4 5
continue Statement
VIII)
for(int x=1;x<=10;x++){
if(x==5)
continue; // continue without printing 5
cout<<x<<“ ” ; }

Output : 1 2 3 4 6 7 8 9 10

• Implementing for using while


int x=1;
while (x<=10){
if (x==5)
continue; //continue goes direct to the condition (no increment)!
cout<<x<<“ ”;
x++; }
Output: 1 2 3 4
Recommendations
for loop may be used if the number of repetitions is known
For example, when you need to print a message 100 times.

A while loop may be used if the number of repetitions is not


known, as in the case of reading the numbers until the input is 0.

A do-while loop can be used to replace a while loop if the loop


body has to be executed before testing the continuation condition.
Note
Adding a semicolon at the end of the for , before
the loop body is a common mistake, as shown
below:
Logic Error
Nothing is done in the loop
int i; – the loop body is empty
{}
for (i=0; i<10; i++);
cout<<"i is " << i;
Note , cont.
Similarly, the following while loop is also wrong:

int i=0;
while (i < 10); Logic Error
{
cout<<"i is " << i;
i++; }
In the case of the do while loop, the following semicolon is needed to end
the loop.

int i=0;
do {
cout<<"i is " << i; Correct
i++;
} while (i<10);
Nested loop: loop in loop
Nested loops consist of an outer loop with
one or more inner loops.
Example:
Print the following using loops.
5 rows :
Row 1  1 star
* Row 2  2 stars

** Row 5  5 stars ………..
We need a loop for the rows
*** We need loops for columns
The number of stars in a row is equal to the row#
**** Need nested loop
***** Since the # of iterations are known  for loops
Nested loop: loop in loop
Solution:
for (int i=1; i<=5; i++)
{for (int j=1; j<=i; j++)
cout<<"*";
cout<<endl;}
Output:
*
**
***
****
*****
Nested Loops

Problem: Write a program that uses


nested for loops to print a
multiplication table?
Nested loop
Solution:
for (int i=1; i<=12; i++)
{for (int j=1; j<=12; j++)
cout<<setw(6)<<i*j;
cout<<endl;}
Output:
Functions
Introduction
Dividing a program into functions.
• To reduce the size of the program.
• Code re-use.
Motivations
A method is a construct for grouping statements
together to perform a function. Using a method, you
can write the code once for performing the function in
a program and reuse it by many other programs. For
example, often you need to find the maximum
between two numbers. Whenever you need this
function, you would have to write the following code:
int result; If you define this function for finding a
if (num1 > num2) maximum number between any two
result = num1; numbers in a method, you don’t have to
else repeatedly write the same code. You
result = num2; need to define it just once and reuse it by
any other programs.
C++ Predefined Functions
• C++ language is shipped with a lot of
functions which are known as predefined
functions.
• Predefined functions are groups in
different libraries which can be included in
the C++ program, e.g.
– Math functions are declared in <cmath>
library.
Predefined Functions (cont'd.)
• Some of the predefined mathematical
functions are:
sqrt(x)
pow(x, y)
floor(x)
• Predefined functions are organized into
separate libraries
• I/O functions are in iostream header
• Math functions are in cmath header
Example of Using
Predefined C++ Math Functions
#include <iostream>
#include <cmath>
int main()
{
double x;
cout << "Please enter a real number: ";
cin >> x;
// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;
return 0;}
<cmath> Functions
Function Description Example

abs(x) Returns the absolute value of the argument. abs(-2) is 2

ceil(x) x is rounded up to its nearest integer and ceil(2.1) is 3

returns this integer. ceil(-2.1) is -2

floor(x) x is rounded down to its nearest integer and floor(2.1) is 2

returns this integer. floor(-2.1) is -3

pow(x, y) Returns x raised to power y (xy). pow(2.0, 3) is 8

sqrt(x) Returns the square root of x. sqrt(4.0) is 2

fmod(x, y) Returns the remainder of x/y as double fmod(2.4, 1.3) is 1.1

max(a, b) Returns the maximum between the two numbers. max(5, 6)

min(a, b) Returns the minimum between the two numbers. min(5, 6)


Predefined Functions
In C++, the concept of a function,
either predefined or user-defined, is
similar to that Function in Algebra:

 Every Function has a name.


 Depending on the values.
 Does some computation.
Predefined Functions (cont'd.)
• pow(x,y) calculates xy
– pow(2.0, 3) = 8.0
– Returns a value of type double
– x and y are the parameters.
– 2.0 and 3 are arguments.
• The function has two parameters
Predefined Functions (cont'd.)
• sqrt(x) calculates the nonnegative
square root for x >= 0.0
sqrt(2.25) is 1.5
– Returns a value of type double
– x is the parameter (double).
– 2.25 is argument.
Predefined Functions (cont'd.)

• The floor function floor(x)


calculates largest whole number not
greater than x
– floor(48.79) is 48.0
– Type double
– Has only one parameter
User-Defined C++ Functions
• C++ provides its users with a way to
define their own functions (or user-defined
function).
• define a C++ function in two steps:
– Step #1 – declare the function.
– Step #2 – Implement the function.
What is The Structure of a C++
Function?
• A C++ function consists of two parts
– The function header, and
– The function body
• The function header has the following
syntax
<return value> <name> (<parameter list>)
• The function body is simply a C++ code
enclosed between { }
Example of User-defined
C++ Function

double computeTax (double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
Example of User-defined
C++ Function
Function
header

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
Example of User-defined
C++ Function
Function Function
header body

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
User-Defined Functions
User-Defined Functions in C++ are
classified into two categories:
• Value-returning functions:
have a return type
– Return a value of a specific data type using
the return statement
• Void functions: do not have a return
type
– Do not use a return statement to return a
value
Value-Returning Functions
• To use these functions you must:
– Include the header file in your program using
the include statement
– Know the following items:
• Data type of the value returned: called the type of
the function
• Name of the function
• Number of parameters, if any
• Data type of each parameter
Value-Returning Functions
(cont'd.)
• Because the value returned by a value-
returning function is unique, must:
– Save the value for further calculation
– Use the value in some calculation
– Print the value
• A value-returning function is used in an
assignment or in an output statement
Introducing Functions
A function is a collection of statements that are
grouped together to perform an operation.
Define a function Invoke (Call) a funciton

return value type Function name formal parameters

function int z = max(i, j);


int max(int num1, int num2)
header
{

function actual parameters


int result; parameter list (arguments)
body
if (num1 > num2)
result = num1;
else function
signature
result = num2;

return result; return value


}
Introducing Functions, cont.
Example: f (x) = 2x + 5,

then f (1) = 7, f (2) = 9, f (3) = 11

x- is formal parameter
1, 2, and 3 are arguments
7, 9, and 11 are return values
Introducing Functions, cont.
• Function signature is the combination of the
function name and the parameter list.
• The variables defined in the function header are
known as formal parameters.
• When a function is invoked, you pass a value to
the parameter. This value is referred to as actual
parameter or argument.
Function Call

• Save the value for further calculation.


• Use the value in some calculation.
• Print the value.
• Int m= 3*max ( 2 ,5);
• cout<< max (2, 5);
• cout<< max (2, max (4, 10));
Functions in C++
• Functions invoked by a function–call-statement which
consist of it’s name and information it needs (arguments)
• Boss To Worker Analogy
 A Boss (the calling/caller function) asks a worker (the
called function) to perform a task and return result when it
is done.
Boss
Main

Worker
Worker Worker
Function Z
Function A Function B

Worker Worker Note: usual main( ) Calls


other functions, but other
Function B1 Function B2
functions can call each other
Example 1
#include <iostream>
using namespace std;
int Max (int num1, int num2) Function Definition
{ int result;
if (num1 > num2) result= num1;
else result= num2;
return result;
}
int main ( ) {
int i = 5; Calling the function
int j = 2;
int k = max (i, j);
cout << "The maximum between " << i << "and "
<<j<< " is " << k;
return 0;
}
animation

Calling Functions, cont.

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


i is now 5

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


j is now 2

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


invoke max(i, j)

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


declare variable result

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


(num1 > num2) is true since num1
is 5 and num2 is 2

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


result is now 5

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


return result, which is 5

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


return max(i, j) and assign the
return value to k

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
animation

Trace Function Invocation


Execute the print statement

pass the value i


pass the value j

int main() int max(int num1, int num2)


{ {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
cout << "The maximum between " else
<< i << " and "<<j<< " is " result = num2;
<< k;
return 0; return result;
} }
Example 2
#include <iostream>
using namespace std;
int Max (int num1, int num2)
{ if (num1 > num2)
return num1;
else
return num2;
}
int main ( ) {
int i = 5;
int j = 2;
int k = max (i, j);
cout << "The maximum between " << i << "and "
<<j<< " is " << k;
return 0;
}
Example 3
#include <iostream>
using namespace std;
int Sum (int num1, int num2) {
return (num1+num2);
}

int main ( ) {
int N1, N2, S;
cout<<"\n Please Enter N1 and N2: ";
cin>>N1>>N2;
S = Sum(N1,N2);
cout<<"\nSum= "<<S<<endl;
return 0;}
Example 4
#include <iostream>
using namespace std;
bool Positive (int num)
{ if (num > 0) return true;
else return false;
}
int main ( ) {
int num;
cout<<"Enter Any Number: ";
cin>> Number;
if (Positive(Number))
cout<<"the number is positive" <<endl;
else
cout<<"the number is negative" <<endl;
return 0;}
Function Prototype
• Function prototype: function heading
without the body of the function
• Syntax:
Function Prototype (cont'd.)
Function Prototype (cont'd.)
Exercise 1
Write a function to compute the perimeter of a right triangle
when given length of two sides (a and b).

a c

The following formula may be helpful:

c 2 = a2 + b2
Exercise 2
What is the output of the following code?

int f2(int z)
{
return z*z;
}

int f1(int x)
{
int y;
y = f2(x)+3;
return y;
}

int main()
{
cout << f1(5);
return 0;
}
Function Prototyping
• The prototype describes the function
interface to the compiler by giving details
such as:
– The number and type of arguments
– The type of return values.

• When the function is called, the compiler


ensure that proper arguments are passed,
and the return value is treated correctly.
Function Prototyping
• Each argument variable must be declared
independently inside the parentheses.

float avg ( int x, int y) ; // correct


float avg ( int x, y) ; // illegal

• In a function declaration, the names of the


arguments are dummy variables and
therefore they are optional.
Introduction
void Function( ); /* Function declaration// prototype */
int main( )
{
----
Function( ); /* Function call */
----
return 0;
}
void Function( ) /* Function definition */
{
----
---- /* Function body */
}
The main( ) Function
• The main( ) returns a value of type int to
the operating system by default.

• The functions that have a return value


should use the return statement for
termination.

• Use void main( ), if the function is not


returning any value.
Functions & Memory
• Every function needs a place to
store its local variables. This Memory
storage is called the stack location
• Instead of using raw addresses, i
we use variables to attach a d2
name to an address
d1
• All of the data/variables for a
y
particular function call are located
in a stack frame x

void Func1(int x, int


y) {
double d1, d2;
int i;
}
Functions & Memory (cont)
• When a function is called, a new
stack frame is set aside
• Parameters and return values are
passed by copy (ie, they’re copied
into and out of the stack frame)

void Func1(int x, int y)


{
double d1 = x + y;
}
int main( ) {
int x = 7; d1
Func1(1, 2);
Func1(2, 3); y Func1
return 0;
} x
x 7 main
Obtaining Memory Addresses

• The address of a variable can be obtained by using the


address-of operator &

int x; 2000 2002 2006


float number; x number y
double y;
cout << “Address of x is “ << &x << endl;
cout << “Address of number is “ << &number << endl;
cout << “Address of y is “ << &y << endl;
Function Call by Value
void func1 (int x)
{ cout << “value of x = “ << x << endl;
x = 4; }
int main() { int v = 5;
func1(v);
cout << “value of v = “ << v << endl;
return 0;}
Output: Value of x = 5
Value of v = 5
– When a variable v is passed by value to a
function func1, its value is copied to the
variable x in func1
– Any changes to the value of x does NOT
affect the value of v
Function Call by Reference
void func1 (int &x)
{ cout << “value of x = “ << x << endl;
x = 4; }
int main() { int v = 5;
func1(v);
cout << “value of v = “ << v << endl;
return 0;}

Output: Value of x = 5
Value of v = 4
– When a variable v is passed by reference to a parameter x
of function func1, v and the parameter x refer to the same
variable
– Any changes to the value of x DOES affect the value of v
C++ Variables
• A variable is a place in memory that has
– A name or identifier (e.g. income, taxes, etc.)
– A data type (e.g. int, double, char, etc.)
– A size (number of bytes)
– A scope (the part of the program code that can use it)
• Global variables – all functions can see it and using it
• Local variables – only the function that declare local
variables see and use these variables
– A life time (the duration of its existence)
• Global variables can live as long as the program is executed
• Local variables are lived only when the functions that define
these variables are executed
I. Using Global Variables
#include <iostream>
using namespace std;
int x = 0;
void f1() { x++; }
void f2() { x+=4;
f1(); }
int main()
{
f2();
cout << x << endl;
return 0;}
I. Using Global Variables
#include <iostream>
x 0
using namespace std;
int x = 0;
void f1() { x++; }
void f2() { x+=4;
f1(); }
int main()
{
f2();
cout << x << endl;
return 0;}
I. Using Global Variables
#include <iostream>
x 0
using namespace std;
int x = 0;
void f1() { x++; }
void f2() { x+=4;
f1(); }
int main()
{
f2();
int main()
cout << x << endl; {
return 0;} 1 f2();
cout << x << endl ;
return 0;}
I. Using Global Variables
#include <iostream>
x 0
4
using namespace std;
int x = 0;
void f1() { x++; }
void f2() { x+=4;
f1(); } void f2()
{
int main() 2 x += 4;
{ f1();
}
f2();
int main()
cout << x << endl; {
1 f2();
return 0;}
cout << x << endl ;
return 0;}
I. Using Global Variables
#include <iostream>
x 5
4
using namespace std;
int x = 0; void f1()
{
void f1() { x++; } 4 x++;
}
void f2() { x+=4;
f1(); } void f2()
{
int main() x += 4;
{ 3 f1();
}
f2();
int main()
cout << x << endl; {
1 f2();
return 0;}
cout << x << endl ;
return 0;}
I. Using Global Variables
#include <iostream>
x 5
4
using namespace std;
int x = 0; void f1()
{
void f1() { x++; } x++;
void f2() { x+=4; 5 }
f1(); } void f2()
int main() {
x += 4;
{ 3 f1();
f2(); }
cout << x << endl; int main()
return 0;} {
1 f2();
cout << x << endl;
return 0;}
I. Using Global Variables
#include <iostream>
x 5
4
using namespace std;
int x = 0;
void f1() { x++; }
void f2() { x+=4;
f1(); } void f2()
{
int main() x += 4;
{ f1();
6 }
f2();
int main()
cout << x << endl; {
1 f2();
return 0;}
cout << x << endl;
return 0;}
I. Using Global Variables
#include <iostream>
Using namespace std; x 5
4
int x = 0;
void f1( ) { x++; }
void f2( ) { x+=4;
f1(); }
int main( )
{
f2( );
cout << x << endl;
int main()
return 0;} {
f2();
7 cout << x << endl;
Return 0;}
I. Using Global Variables
#include <iostream>
using namespace std; x 5
4

int x = 0;
void f1( ) { x++; }
void f2( ) { x+=4;
f1(); }
int main( ) {
f2( );
cout << x << endl;
return 0; int main()
} {
f2();
cout << x << endl;
8 return 0;}
I. Using Global Variables
#include <iostream>
using namespace std;
int x = 0;
void f1( ) { x++; }
void f2( ) { x+=4;
f1(); }
int main( ) {
f2( );
cout << x << endl;
return 0;
}
II. Local Variables

• Local variables are declared inside the function


body and exist as long as the function is running
and destroyed when the function exit
• You have to initialize the local variable before
using it
• If a function defines a local variable and there
was a global variable with the same name, the
function uses its local variable instead of using
the global variable
Example of Defining and Using
Global and Local Variables
#include <iostream>
using namespace std;
int x; // Global variable
void fun( ); // function
prototype
int main( )
{
x = 4;
fun();
cout << x << endl;
return 0;}
void fun( )
{
int x = 10; // Local
variable
cout << x << endl;
}
Example of Defining and Using
Global and Local Variables
#include <iostream> x 0
using namespace std;
int x; // Global variable Global variables are
automatically initialized to 0
void fun( ); // function
prototype
int main( ) {
x = 4;
fun();
cout << x << endl;
return 0;
}
Example of Defining and Using
Global and Local Variables
#include <iostream> x 0
using namespace std;
int x; // Global variable
void fun( ); // function
prototype
int main( ) {
x = 4;
fun( );
cout << x << endl;
return 0;}
void fun( ) {
int x = 10; // Local
variable int main()
cout << x << endl; {
1 x = 4;
}
fun();
cout << x << endl;
return 0;}
Example of Defining and Using
Global and Local Variables
#include <iostream> x 4
using namespace std;
int x; // Global variable
void fun( ); // function
prototype void fun()
int main( ) {
x = 4; x ????
fun( ); {
cout << x << endl; 3 int x = 10;
return 0;} cout << x << endl;
void fun( ) { }
int x = 10; // Local
variable int main()
cout << x << endl; {
2 x = 4;
}
fun();
cout << x << endl;
return 0;}
Example of Defining and Using
Global and Local Variables
#include <iostream>
using namespace std; x 4
int x; // Global variable
void fun( ); // function
prototype
int main( ) { void fun()
x = 4; x 10
fun( );
cout << x << endl; {
return 0;} 3 int x = 10;
cout << x << endl;
void fun( ) {
}
int x = 10; // Local
variable int main()
cout << x << endl; {
} x = 4;
2 fun();
cout << x << endl;
return 0;}
Example of Defining and Using
Global and Local Variables
#include <iostream> x 4
using namespace std;
int x; // Global variable
void fun( ); // function
prototype
int main( ) void fun()
{
x = 4; x 10
fun(); {
cout << x << endl; int x = 10;
return 0;} 4 cout << x << endl;
void fun( ) }
{
int x = 10; // Local int main()
variable {
cout << x << endl; x = 4;
} 2 fun();
cout << x << endl;
return 0;}
Example of Defining and Using
Global and Local Variables
#include <iostream> x 4
using namespace std;
int x; // Global variable
void fun( ); // function
prototype
int main( ) void fun()
{
x = 4; x 10
fun(); {
cout << x << endl; int x = 10;
return 0;} cout << x << endl;
void fun( ) 5 }
{
int x = 10; // Local int main()
variable {
cout << x << endl; x = 4;
} 2 fun();
cout << x << endl;
return 0;}
Example of Defining and Using
Global and Local Variables
#include <iostream> x 4
using namespace std;
int x; // Global variable
void fun( ); // function
prototype
int main( )
{
x = 4;
fun();
cout << x << endl;
return 0;}
void fun( )
{
int x = 10; // Local int main()
variable {
cout << x << endl; x = 4;
} fun();
6 cout << x << endl;
return 0;}
Example of Defining and Using
Global and Local Variables
#include <iostream>
using namespace std; x 4
int x; // Global variable
void fun( ); // function
prototype
int main( )
{
x = 4;
fun();
cout << x << endl;
return 0;} int main()
void fun() {
{ x = 4;
int x = 10; // Local 7 fun();
variable cout << x << endl;
cout << x << endl; return 0;}
}
Default Arguments in C++

A default argument is a value


provided in a function declaration that is
automatically assigned by the compiler if
the caller of the function doesn’t provide a
value for the argument with a default
value.
Default Arguments in C++
#include <iostream>
using namespace std;
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.

int sum(int x, int y, int z=0, int w=0)


{ return (x + y + z + w); }

int main() {
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0; }

Output:
25
50
80
Function Overloading

With function overloading, multiple


functions can have the same name with
different parameters:

int myFunction(int x)

float myFunction(float x)

double myFunction(double x, double y)


Function Overloading
Example:
int plusFunc(int x, int y) {
return x + y; }

double plusFunc(double x, double y) {


return x + y; }

int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
STORAGE (static/auto)
The scope (visibility) and life-time of variables
within a C++ Program.
The auto storage is the default for all local variables.
{ int mount;
auto int month; }

The static storage instructs the compiler to keep a local


variable in existence during the life-time of the program
instead of creating and destroying it each time it comes
into and goes out of scope.
static int count = 10; /* Global variable */
Recursive functions
• An algorithm is called recursive if it solves a
problem by reducing it to one or more instances
of the same problem with smaller input
• A recursive algorithm can be implemented using
a recursive function which includes:
– base case
– recursive call(s) to the function with a smaller instance
of the problem
A recursive function:
Factorial
n! can be defined as follows:
n! = 1 for n = 0
n! = n (n - 1)! otherwise
4! =
4 (3!) =
4 (3 (2!)) =
4 (3 (2 (1!))) =
4 (3 (2 ( 1 (0!)))) =
4 (3 (2 (1 (1)))) = 24
Factorial example:
C++ implementation
int Factorial (int n)
{
if (n == 0)
return 1;
else
return n * Factorial (n - 1);
}
Factorial example:
Trace of invocations
24
Factorial(4) 6

Factorial(3) 2

Factorial(2) 1

Factorial(1)
1

Factorial(0)
One Dimensional
Array
Motivations
Suppose, you need to read one hundred numbers,
compute their average, and find out how many numbers
are above the average. Your program first reads the
numbers and computes their average, and then
compares each number with the average to determine
whether it is above the average. The numbers must all be
stored in variables in order to accomplish this task. You
have to declare one hundred variables and repeatedly
write almost identical code one hundred times. From the
standpoint of practicality, it is impossible to write a
program this way. So, how do you solve this problem?
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double myList [10];

myList[0] 5.6
myList[1] 4.5
myList[2] 3.3
myList[3] 13.2
myList[4] 4.0
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34.0

myList[7] 45.45

myList[8] 99.993

myList[9] 111.23
Declaring Array Variables
datatype arrayname[arraySize];
Example:
double myList[10];

C++ requires that the array size used to declare an array must
be a constant expression.
For example, the following code is illegal:
int size = 4;
double myList[size]; // Wrong
But it would be OK, if size is a constant as follow:
const int size = 4;
double myList[size]; // Correct
Declaration of Arrays
float scores[100];
// 100 floats

char chs[20];
// 20 chars

int nums[30];
// 30 integers

string allNames[100];
// 100 strings
Indexed Variables
The array elements are accessed through the index. Array
indices are start from 0 to arraySize-1.
In the example, myList holds ten double values and the
indices are from 0 to 9.

Each element in the array is represented using the following


syntax, known as an indexed variable:
double myList [10];

arrayName[index]; myList[0] 5.6


myList[1] 4.5
myList[2] 3.3

For example, myList[9] myList[3] 13.2


myList[4] 4.0
represents the last element Array element at
index 5
myList[5] 34.33 Element value

in the array myList. myList[6]


myList[7]
34.0
45.45

myList[8] 99.993

myList[9] 111.23
Memory Allocation for Array

int nums[30];
// 30 integers
// Address: the first element
// How many bytes?
nums // 30 * 4=120 bytes

10 15 20 50 . . . . 30 18

264
Array Element and Array Index
int nums[30];
Array Element

10 15 20 50 . . . . 30 18

0 1 2 3 28 29

Array Indices

Array Element

nums[0] nums[1] nums[29]


265
Using Indexed Variables
After an array is created, an indexed
variable can be used in the same way as a
regular variable. For example, the following
code adds the value in myList[0] and
myList[1] to myList[2].

myList[2] = myList[0] + myList[1];


No Bound Checking
C++ does not check array’s boundary.

(e.g., myList[-1] and myList[11]),

does not does cause syntax errors

So, accessing array elements using indices


Array Initializers

Declaring, creating, initializing in one step:


dataType arrayName[arraySize] = {value0,
value1, ..., valuek};

double myList[4] = {1.9, 2.9, 3.4, 3.5};


Declaring, creating, initializing
Using the Shorthand Notation
double myList[4] = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the
following statements:

double myList[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
Note
Using the shorthand notation, you
have to declare, create, and
initialize the array all in one
statement. Splitting it would cause
a syntax error. For example, the
following is wrong:
double myList[4];
myList = {1.9, 2.9, 3.4, 3.5};
Implicit Size
C++ allows you to omit the array size when
declaring and creating an array using an
initilizer.
For example, the following declaration is fine:
double myList[] = {1.9, 2.9, 3.4, 3.5};

C++ automatically figures out how many


elements are in the array.
Partial Initialization
C++ allows you to initialize a part of the array.
For example, the following statement assigns
values 1.9, 2.9 to the first two elements of the
array. The other two elements will be set to
zero. Note that if an array is declared, but not
initialized, all its elements will contain
“garbage”, like all other local variables.

double myList[4] = {1.9, 2.9};


Initializing Character Arrays
char city[] = {'D', 'a', 'l', 'l', 'a', 's'};

char city[] = "Dallas";


This statements are equivalent, except that C++
adds the character '\0', called the null terminator, to
the end of the string, as shown in Figure:
'D' 'a' 'l' 'l' 'a' 's' '\0'
city[0] city[1] city[2] city[3] city[4] city[5] city[6]
animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

int main()
{ After the array is created

int values[5];
0 0
for (int i = 1; i < 5; i++) 1 0
{ 2 0
values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
i becomes 1

int main()
{
After the array is created
int values[5];
for (int i = 1; i < 5; i++) 0 0

{ 1 0

values[i] = i + values[i-1]; 2 0

} 3 0

0
values[0] = values[1] + values[4]; 4

}
animation
Trace Program with Arrays
i (=1) is less than 5

int main()
{
int values[5]; After the array is created

for (int i = 1; i < 5; i++) 0 0


{ 1 0
values[i] = i + values[i-1]; 2 0

} 3 0

values[0] = values[1] + values[4]; 4 0

}
animation
Trace Program with Arrays
After this line is executed, value[1] is 1

int main()
{ After the first iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 0
values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
After i++, i becomes 2

int main()
{
int values[5]; After the first iteration

for (int i = 1; i < 5; i++) 0 0

{ 1 1

0
2
values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] +
values[4];
}
animation
Trace Program with Arrays
i (= 2) is less than 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++) After the first iteration
{
values[i] = i + values[i-1]; 0 0
1
} 1
0
2
values[0] = values[1] + 3 0
values[4]; 4 0
}
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
After this, i becomes 3.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
i (=3) is still less than 5.

int main()
{ After the second iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = i + values[i-1]; 3 0

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = i + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
After this, i becomes 4

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = i + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
i (=4) is still less than 5

int main()
{ After the third iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = I + values[i-1]; 3 6

} 4 0

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

int main()
{ After the fourth iteration

int values[5]; 0 0
for (int i = 1; i < 5; i++) 1 1
{ 2 3
values[i] = i + values[i-1]; 3 6

} 4 10

values[0] = values[1] + values[4];


}
animation
Trace Program with Arrays
After i++, i becomes 5
int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{
values[i] = i + values[i-1]; After the fourth iteration
}
values[0] = values[1] + values[4]; 0 0
} 1 1

2 3

3 6

4 10
animation

Trace Program with Arrays


i ( =5) < 5 is false. Exit the loop

int main()
{
int values[5];
for (int i = 1; i < 5; i++)
{ After the fourth iteration

values[i] = i + values[i-1]; 0 0
} 1 1

values[0] = values[1] + values[4]; 2 3

} 3 6

4 10
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)

int main()
{
int values[5];
for (int i = 1; i < 5; i++) 0 11

{ 1 1

values[i] = i + values[i-1]; 2 3

} 3 6

values[0] = values[1] + values[4]; 4 10


}
Printing arrays
To print an array, you have to print each element in
the array using a loop like the following:

for (int i = 0; i < ARRAY_SIZE; i++)


{
cout << myList[i] << " ";
}
Printing Character Array
For a character array, it can be printed using one print
statement. For example, the following code displays
Dallas:

char city[] = "Dallas";


cout << city;
Copying Arrays
Can you copy array using a syntax like this?
list = myList;

This is not allowed in C++. You have to copy


individual elements from one array to the other as
follows:

for (int i = 0; i < ARRAY_SIZE; i++)


{
list[i] = myList[i];
}
Arrays
const int ARRAY_SIZE=340;
float nums[ARRAY_SIZE];

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

3.56 3.44 4.03 3.96 3.77 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout << nums[6] << endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

3.56 3.44 4.03 3.96 3.77 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout << nums[6] << endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

3.56 3.44 4.03 3.96 3.77 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout<<nums[6]<< endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

45.1 3.44 4.03 3.96 3.77 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout << nums[6] << endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

45.1 3.44 4.03 3.96 3.77 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout << nums[6] << endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

45.1 3.44 4.03 3.96 12.1 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout << nums[6] << endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

45.1 3.44 4.03 3.96 12.1 3.49 3.92 … 4.01 3.83 3.21
Accessing Elements
nums[0]=45.1;
nums[4]=12.1;
cout << nums[6] << endl;

[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

45.1 3.44 4.03 3.96 12.1 3.49 3.92 … 4.01 3.83 3.21
Access Mistakes
const int ARRAY_SIZE=340;
float nums[ARRAY_SIZE];
...
cout << nums[ARRAY_SIZE];
[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]

45.1 3.44 4.03 3.96 12.1 3.49 3.92 … 4.01 3.83 3.21
Access Mistakes
const int ARRAY_SIZE=340;
float nums[ARRAY_SIZE];
...
cout << nums[ARRAY_SIZE];
[340
[0] [1] [2] [3] [4] [5] [6] … [337] [338] [339]
]

45.1 3.44 4.03 3.96 12.1 3.49 3.92 … 4.01 3.83 3.21 ?

“Walking off the array” !! - This is not your program’s memory


Initializing Arrays
const int SIZE=5;
int array[SIZE]={7,2,4,5,1};

[0] [1] [2] [3] [4]

7 2 4 5 1
Initializing Arrays
const int SIZE=5;
int array[SIZE]={0};

[0] [1] [2] [3] [4]

0 0 0 0 0
Initializing Arrays
const int SIZE=5;
int array[SIZE]={9,1};

[0] [1] [2] [3] [4]

9 1 0 0 0
Initializing Arrays
int array[]={5,2,4};

[0] [1] [2]

5 2 4
Things You Can NOT Do
• Return an array from a function
• Output an array like int, float, or strings
int array[10];
cout << array << endl;
• Read in to an entire array
int array[10];
cin >> array;
Things You Can NOT Do
• Return an array from a function
• Output an array like int, float, or strings
int array[10];
cout << array << endl;
• Read in to an entire array
int array[10];
cin >> array;
Things You Can NOT Do
• Return an array from a function
• Output an array like int, float, or strings
int array[10];
cout << array << endl;
• Read in to an entire array
int array[10];
cin >> array;
Two Dimensional
Array
Two-Dimensional Arrays
In two-dimensional array you can store a
matrix or a table.
For example:
Declaring 2-D Arrays
An element in a two-dimensional array is
accessed through a row and column index.

The syntax for declaring a 2-d array is:


elementType arrayName[ROW_SIZE][COLUMN_SIZE];

As an example, here is how to declare a


two-dimensional array matrix of int values:

int matrix[5][5];
Declaring 2-D Arrays
Two subscripts are used in a 2-d array, one
for the row and the other for the column.

As in a one-dimensional array, the index


for each subscript is of the int type and
starts from 0
Declaring 2-D Arrays
Using an array initializer to declare
and initialize a 2-D array. For example:
Declaring 2-D Arrays
Using an array initializer to declare
and initialize a 2-D array. For example:
Passing 2-D Arrays to Functions
When passing a 2-D array to a
function, C++ requires that the column size
be specified in the function parameter type
declaration. For example:
Processing 2-D Arrays

 Summing elements by column

 Summing elements by row

 Summing elements by diagonal

 Random shuffling

You might also like