Programming Language I: C++ Programming: From Problem Analysis To Program Design, by D.S. Malik
Programming Language I: C++ Programming: From Problem Analysis To Program Design, by D.S. Malik
Compiling,
cout << "Welcome to C++!" << endl; Source Code
return 0;
}
Linker
Result
Sample Run:
My first C++ program.
Hello World
// Hello World program comment
a:
// changing the value of a variable
int a = 7; // a variable of type int called a 7
20
a += 2; // increment a's value by 2
21
++a; // increment a's value (by 1)
Output
• The syntax of cout and << is:
36
Form and Style
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
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)
y = w + x; //Line 4: error
Another Program
#include <iostream.h>
Using namespace std;
int main() {
double fahr,celcius;
return 0;
}
Math Operator Quiz
10/24/2024 56
cin and the Extraction Operator >>
• Expression is evaluated
• Value is printed
• Manipulator is used to format the output
– Example: cout<< endl;
Selection statements
59
Comparison Operators
60
Logical Operators
Operator Name Description
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
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:
false false
Boolean (radius >= 0)
Expression
true true
(a) (b)
if Selection Structure (One Way)
– If the condition is true
• Print statement executed, program continues to
next statement.
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
79
Common Errors in Selection Statements
Common Error 2: Wrong Semicolon at the if Line
Logic Error Empty Body
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.
87
animation
Trace if-else statement
Suppose score is 70.0 The condition is false
88
animation
Trace if-else statement
Suppose score is 70.0 The condition is true
89
animation
Trace if-else-if statement
Suppose score is 70.0 grade is C
90
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement
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:
if (i > j)
{
if (i > k)
cout << "A";
}
else
cout << "B";
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
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
animation
switch (ch) {
case 'a': cout << ch;
case 'b': cout << ch;
case 'c': cout << ch;
}
Next statement;
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
105
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
106
animation
switch (ch) {
case 'a': cout << ch;
break;
case 'b': cout << ch;
break;
case 'c': cout << ch;
}
107
animation
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;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) cout << "Welcome to C++!\n";
(loop body) count++;
(a) (b)
animation
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 ++;
int counter;
for(counter = 1; counter <N ; counter++)
.
.
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
_
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) :
} 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:
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
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
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
Worker
Worker Worker
Function Z
Function A Function B
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
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.
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
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
int myFunction(int x)
float myFunction(float x)
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; }
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.
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
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};
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
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
} 3 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
int main()
{
int values[5]; After the first iteration
{ 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
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
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
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
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
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
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
2 3
3 6
4 10
animation
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
} 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
[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 ?
7 2 4 5 1
Initializing Arrays
const int SIZE=5;
int array[SIZE]={0};
0 0 0 0 0
Initializing Arrays
const int SIZE=5;
int array[SIZE]={9,1};
9 1 0 0 0
Initializing Arrays
int array[]={5,2,4};
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.
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.
Random shuffling