SMJP 1043: Programming (C++) For Engineers

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 51

SMJP 1043 Programming

(C++) for Engineers


Dr. A.K.M. Muzahidul Islam
(Dr. Sheikh)
Department of Electronic Systems Engineering (ESE)
April 21, 2014
Important Notes

Presentation : December 13
Project Assessment : Total Marks 20
Report : 10
Presentation : 5
Knowledge (Q & A) : 5
Project : May 21 or May 28
Test 2 : May . (3 Ques)
1- Function and 1- Array 1-Loop
Lab Test 2 : May (3 Ques)
Function, Array, Loop

Project Writing Guideline
Cover page
Project Title
Course Name
Students Names and IDs
Table of Contents
Introduction
Project Background
Project Explanations
Write Pseudo code, draw Flow chart
You can use Figures, Tables, etc., if required.
Conclusion
References
Appendix
Results/Outputs





Title of the Project
Students Information






December 2013
4

Contents:
1.Introduction
- Project Background
2.Project Explanations
- Pseudo code
- Draw Flow chart
- Explanation of the codes (by class,
function, etc.)
(You can use Figures, Tables, etc.)
3. Conclusion
References
- List of bibliography
Appendix
- Results/Outputs


Arrays Hold Multiple Values
Array: An array allows to store and work with
multiple values of the same data type
Values are stored in adjacent memory locations
8-5
Declaring variables so far
Can hold only one value at a time
int val = 5; // enough memory (4B) for 1 int

char letter = A; // enough memory for (1B) 1
char

Double price = 56.981; // enough memory
(8B) for 1 double

8-6
5
A
56.981
Array Storage in Memory
Works like a variable to store a group of values
Declared using [] operator
int tests[5]; // [arrays size declarator]
tests : name of the array, read as tests sub 5
5 : the number of elements or values tests can hold
The definition
int tests[5]; // size is 5
allocates the following memory
8-7
Element 0 Element 1 Element 2 Element 3 Element 4
Array Terminology
const int ISIZE = 5;
int tests[ISIZE];
Or
int tests[5]; // [arrays size declarator]


8-8
Accessing Array Elements
An array has only one name, the elements may be
accessed and used as individual variables
Each array element has a subscript, used to access
the element.
Subscripts start at 0


8-9
subscripts
0 1 2 3 4
Accessing Array Elements
Array elements
can be used as regular variables
accessed by array name and subscript



tests[0] = 79; // tests[0]-array elements
cout << tests[0];
cin >> tests[1];
tests[4] = tests[0] + tests[1];
cout << tests; // illegal due to
// missing subscript
8-10
0 1 2 3 4
tests
Inputting and Displaying
Array Contents
cout and cin can be used to display values
from and store values into an array
const int ISIZE = 5;
int tests[ISIZE]; // Define array with 5
cout << "Enter first test score ";
cin >> tests[0];// NOT cin >> tests
cout << tests[0];// NOT cout << tests
8-11
Array Subscripts
Array subscript can be
integer constant,
integer variable, or
integer expression
Examples: Subscript is
cin >> tests[3]; int constant
cout << tests[i]; int variable
cout << tests[i+j]; int expression

8-12
(Program Continues)
Exercise-1
Here are the contents of the hours array, with the values
entered by the user in the example output:
Inputting and Displaying
All Array Elements
To access each element of an array
Use a loop
Let the loop control variable be the array
subscript
A different array element will be
referenced each time through the loop
for (i = 0; i < 5; i++){
cout << tests[i] << endl;
}
8-15
(Program Continues)
Exercise-2
Display the inputs using for loop.
Getting Array Data from a File
const int ISIZE = 5, sales[ISIZE];
ifstream dataFile;
datafile.open("sales.dat");
if (!dataFile){
cout << "Error opening data file\n";
}
else{ // Input daily sales
for (int day = 0; day < ISIZE; day++){
dataFile >> sales[day];
}
dataFile.close();
}
8-18
Default Initialization
Global array all elements initialized to 0 by
default

Local array all elements uninitialized by
default
No Bounds Checking
There are no checks in C++ that an array
subscript is in range
An invalid array subscript can cause program to
overwrite other memory
Example:
const int ISIZE = 3;
int i = 4;
int num[ISIZE];
num[i] = 25;
8-20
num
[0] [1] [2]
25
Off-By-One Errors
An off-by-one error happens when you use
array subscripts that are off by one.
This can happen when you start subscripts at
1 rather than 0:
// This code has an off-by-one error.
const int SIZE = 100;
int numbers[SIZE];
for (int count = 1; count <= SIZE; count++){
numbers[count] = 0;
}
Off-By-One Errors
Dont confuse the ordinal number of an array
element (first, second, third) with its subscript
(0, 1, 2)
8-22
Array Initialization
Can be initialized during program execution
with assignment statements
tests[0] = 79;
tests[1] = 82; // etc.
Can be initialized at array definition with an
initialization list
const int ISIZE = 5;
int tests[ISIZE] = {79,82,91,77,84};
8-23
Example
Start at element 0 or 1?
int tests[ISIZE+1] = {0,79,82,91,77,84};

tests [1] = 79
tests [2] = 82
----
----
----

COMMENTS: NOT PREFERABLE
8-25
Partial Array Initialization
If array is initialized at definition with fewer
values than the size declarator of the array,
remaining elements will be set to 0 or NULL
int tests[ISIZE] = {79, 82};


Initial values used in order; cannot skip over
elements to initialize noncontiguous range
8-26
79 82 0 0 0
Implicit Array Sizing
Can determine array size by the size of the
initialization list
short quizzes[]={12,17,15,11};



Must use either array size declarator or
initialization list when array is defined
8-27
12 17 15 11
Exercise-3
Write a program that defines array of 5
elements.
Find max of the elements.
Find min of the elements.
Processing Array Contents
Array elements can be
treated as ordinary variables of the same
type as the array
used in arithmetic operations, in relational
expressions, etc.
Example:
if (principalAmt[3] >= 10000){
interest = principalAmt[3] * intRate1;
}
else{
interest = principalAmt[3] * intRate2;
}
8-29
Processing Array Contents
Comparison with working with variables :
// principalAmt is a integer type variable
if (principalAmt >= 10000){
interest = principalAmt * intRate1;
}else{
interest = principalAmt * intRate2;
}
// principalAmt is an integer type ARRAY
if (principalAmt[3] >= 10000){
interest = principalAmt[3] * intRate1;
}else{
interest = principalAmt[3] * intRate2;
}
8-30
Using Increment and Decrement Operators
with Array Elements

When using ++ and -- operators, dont
confuse the element with the subscript
tests[i]++; // adds 1 to tests[i]
tests[i++]; // increments i, but has
// no effect on tests
8-31
Copying One Array to Another
Arrays: tests and tests2
Cannot copy with an assignment statement:
tests2 = tests; //wont work
Must instead use a loop to copy element-by-
element:
for (int indx=0; indx < ISIZE; indx++){
tests2[indx] = tests[indx];
}
8-32
Are Two Arrays Equal?
Like copying, cannot compare in a single
expression:
if (tests2 == tests)
Use a while loop with a boolean variable:
bool areEqual=true;
int indx=0;
while (areEqual && indx < ISIZE){
if(tests[indx] != tests2[indx]{
areEqual = false;
break;
}
indx++;
}
8-33
Example: Finding size of array
#include<iostream>
using namespace std;
int main() {
int a[]={1,2,3,4,5,6};
int size;
//total size of array/size of array data type
size=sizeof (a)/sizeof(int);
cout<<size;
return 0;
}
Largest Array Element
Use a loop to examine each element and find the
largest element (i.e., one with the largest value)
int largest = tests[0];
for (int tnum = 1; tnum < ISIZE; tnum++){
if (tests[tnum] > largest){
largest = tests[tnum];
}
}
cout << "Highest score is " << largest;
A similar algorithm exists to find the smallest
element
8-35
Exercise:
Write a program that sums all the elements of
arrays with size 10. Once summed, compute
their average.

Write a program that implements linear search
algorithm
x= 15
12 17 15 11
Arrays as Function Arguments
To define a function that has an array
parameter, use empty [] to indicate the array
argument
To pass an array to a function, just use the
array name
// Function prototype
void showScores(int []);
// Function header
void showScores(int tests[])
// Function call
showScores(tests);
8-37
Passing an Array Element
Passing a single array element to a function is
no different than passing a regular variable of
that data type
Function does not need to know that the value
it receives is coming from an array
displayValue(score[i]); // call
void displayValue(int item){// header
cout << item << endl;
}
8-38
Passing an Entire Array
Use the array name, without any brackets, as the
argument
Can also pass the array size so the function knows
how many elements to process
showScores(tests, 5); //call
void showScores(int[], int); //prototype
void showScores(int A[],int size) //header
8-39
Exercise:
Write a program that tests a boolean function
to determine whether the given array is
nondecreasing.
True


False
12 17 15 11
11 12 15 17
Using typedef with a Passed Array
Can use typedef to simplify function
prototype and heading
// Make intArray an integer array
// of unspecified size
typedef int intArray[];
// Function prototype
void showScores(intArray, int);
// Function header
void showScores(intArray tests,
int size)

8-41
Partially-Filled Arrays
The exact amount of data (and, therefore,
array size) may not be known when a program
is written.
Programmer makes best estimate for maximum
amount of data, sizes arrays accordingly. A
sentinel value can be used to indicate end-of-
data.
Programmer must also keep track of how many
array elements are actually used
8-42
C-Strings and string Objects
Can be processed using array name
Entire string at once, or
One element at a time by using a subscript
string city;
cout << "Enter city name: ";
cin >> city;
8-43
'S' 'a' 'l' 'e' 'm'
city[0] city[1] city[2] city[3] city[4]
8.6 Using Parallel Arrays
Parallel arrays: two or more arrays that
contain related data
Subscript is used to relate arrays
elements at same subscript are related
The arrays do not have to hold data of the
same type
8-44
Parallel Array Example
const int ISIZE = 5;
string name[ISIZE]; // student name
float average[ISIZE]; // course average
char grade[ISIZE]; // course grade
8-45
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
name average grade
Parallel Array Processing
const int ISIZE = 5;
string name[ISIZE]; // student name
float average[ISIZE]; // course average
char grade[ISIZE]; // course grade
...
for (int i = 0; i < ISIZE; i++)
cout << " Student: " << name[i]
<< " Average: " << average[i]
<< " Grade: " << grade[i]
<< endl;
8-46
8.7 The typedef Statement
Creates an alias for a simple or structured data
type
Format:
typedef existingType newName;
Example:
typedef unsigned int Uint;
Uint tests[ISIZE]; // array of
// unsigned ints
8-47
Uses of typedef
Used to make code more readable
Can be used to create alias for array of a
particular type
// Define yearArray as a data type
// that is an array of 12 ints
typedef int yearArray[MONTHS];
// Create two of these arrays
yearArray highTemps, lowTemps;
8-48
Modifying Arrays in Functions
Array parameters in functions are similar
to reference variables
Changes made to array in a function are
made to the actual array in the calling
function
Must be careful that an array is not
inadvertently changed by a function

8-49

You might also like