Computer Programming II
Computer Programming II
Computer Programming II
Programming II
M. A. Heman
Stages of Compilation
• Preprocessor copies content of the included header files, generate macrocode, and
replaces symbolic constants with their values
• The expanded source code file (macrocode) is converted into assembly language
for the platform
• The assembler code generated is assembled into object code for the platform
• The object codes are linked together using linker to link to any library used in
generating object to generate the executable file
Compilation In C++
• You could us CodeBlocks or
• NetBeans IDE
Variable
• Variable: a storage location on the RAM
• Types of variables:
Local variables: a variable declared within a function
Global variables: variable declared to be used in more than one function in a
program
Arithmetic Operations
• To make addition before multiplication:
dToBePaid = dTotal * (1 + dTaxpacentage)
• Priority rule:
Other Mathematical Functions
Arithmetic Operations Conn’d
Constant
• Is a variable whose value never change throughout a program
• Its cleared in c++ as const. e.g.
const double pi = 3.14;
const double radius = 4.6;
Statement
• Each individual instruction in a program that are executed in the order they appear
or as they are controlled and end with semicolon, “;”.
• Statements include:
Declarative
Assignments
Procedures/methods
Controls statements
Select statement
Loop/iteration
Declarative Statement
• The are used for initializing of declaring variables
E.g. int iNo;
float price;
string whatisYourName;
char yourCGPA;
Assignment Statement
• int grossPrice = 4.15
• Int price = grossPrice * tax * discount
• num = num + 1
• sum -= 1
Control Statement
• If
• If /else
• Nested if
• If/else if
• Flags
• Logical operator
• Conditional
• Switch
IF Statement
Yes
If int A, B;
Print A
A>B cin >> A;
No cin >> B;
if (A > B)
cout << A;
Stop
IF/Else
int A, B;
cin >> A;
If A > B Print A cin >> B;
if (A > B)
{
cout << A;
} else
{
Print B cout << B;
}
Stop
Nested If Statement
• Testing more than one condition
The switch statement lets the value of a variable or expression determine where the
program will branch
Switch Statement
Conn’d
NB:
• The expression of each case statement in the block must be unique.
• The expression following the word case must be an integer literal or constant. It
cannot be a variable, and it cannot be an expression such as x < 22 or n == 50
Example: Menu
Program
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int choice; // To hold a menu choice
int months; // To hold the number of months
double charges; // To hold the monthly charges
case CHILD_CHOICE:
cout << "For how many months? ";
cin >> months;
charges = months * CHILD;
cout << "The total charges are N" << charges << endl;
break;
Loop Statement
A loop is a form of iteration such that values are read or written by incrementing or
decrementing process
• ++ and -- are operators that add and subtract 1 from their operands.
• Incrementing/decrementing value by 1
num = num + 1;
num += 1;
num = num - 1;
num -= 1;
Unary operators
++n or n++
--n or n--
Types of loops in C++
• While
• Do while
• for
While loop
• pretest loop
Infinite while loop
Do While loop
• The do-while loop is a posttest loop, which means its expression is tested after
each iteration.
do
{
statement ;
statement ;
// Place as many statements here
// as necessary.
} while ( expression );
int main()
{
cout << "I am starting in function main.\n";
first(); // Call function first
second(); // Call function second
cout << "Back in function main again.\n";
return 0;
}
// Definition of function first. *
// This function displays a message. *
void first()
{
cout << "I am now inside the function first.\n";
}
void second()
{
cout << "I am now inside the function second.\n";
}
Function prototypes
• A function prototype eliminates the need to place a function definition before all
calls to the function.
• In other words prototyping is function declaration
• When an argument is passed into a parameter, only a copy of the argument’s
value is passed. Changes to the parameter do not affect the original argument.
• Argument: is a value that is sent into function
Sending data into function
void changeMe(int);
int main()
{
int number = 12;
// Display the value in number.
cout << "number is " << number << endl;
// Call changeMe, passing the value in number
// as an argument.
changeMe(number);
// Display the value in number again.
cout << "Now back in main again, the value of ";
cout << "number is " << number << endl;
return 0;
}
// Definition of function changeMe. *
// This function changes the value of the parameter myValue. *
//**************************************************************
void changeMe(int myValue)
{
// Change the value of myValue to 0.
myValue = 0;
// Display the value in myValue.
cout << "Now the value is " << myValue << endl;
}
Changing argument variable
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r = a + b;
return r;
}
int main()
{
int x, y, z;
cout << "Enter First Number: ";
cin >> x;
cout << "Enter Second Number: ";
cin >> y;
z = addition (x, y);
cout << "The result =" << z <<endl;
}
Array
• A collection of finite data type stored in consecutive memory locations that could
be declared under one variable
• It can be declared any type
• It has name
• Each element of an array is identified by subscripts 0 - n
• The size of an array could be declared within rectangular brackets
• If an array is defined globally, all of its elements are initialized to zero by default.
Local arrays, however, have no default initialization value.
Array declaration
• const int NUM_DAYS = 6;
int days[NUM_DAYS];
• float temperatures[100]; // Array of 100 floats
• string names[10]; // Array of 10 string objects
• long units[50]; // Array of 50 long integers
• double sizes[1200]; // Array of 1200 doubles
? How many bytes does each declaration occupy of the computer memory
Storing a value in an array
• hours[0] = 20; //hours sub zero is assigned twenty
• Data is input to array memory location one after the other the spite it declared
with one variable
• Thus for loop is must suitable for input data to array
Input/Output array contents
int main()
{
const int NUM_EMPLOYEES = 6;
int hours[NUM_EMPLOYEES];
// Get the hours worked by each employee.
cout << "Enter the hours worked by "
<< NUM_EMPLOYEES << " employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
cin >> hours[4];
cin >> hours[5];
// Display the values in the array.
cout << "The hours you entered are:”;
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
return 0;
}
Using “for” loop to enter and display numbers
int main()
{
const int NUM_EMPLOYEES = 6; // Number of employees
int hours[NUM_EMPLOYEES]; // Each employee's hours
int count; // Loop counter
// Input the hours worked.
for (count = 0; count < NUM_EMPLOYEES; count++)
{
cout << “Enter the hours worked by employee ”
<< (count + 1) << ": "; //it could be count - 1
cin >> hours[count];
}
// Display the contents of the array.
cout << "The hours you entered are:";
for (count = 0; count < NUM_EMPLOYEES; count++)
cout << " " << hours[count];
cout << endl;
return 0;
}
Reading the content of a file to an
array
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int ARRAY_SIZE = 10; // Array size
int numbers[ARRAY_SIZE]; // Array with 10 elements
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
// Open the file.
inputFile.open("TenNumbers.txt");
// Read the numbers from the file into the array.
while (count < ARRAY_SIZE && inputFile >> numbers[count])
count++;
// Close the file.
inputFile.close();
// Display the numbers read:
cout << "The numbers are: ";
for (count = 0; count < ARRAY_SIZE; count++)
cout << numbers[count] << " ";
cout << endl;
return 0;
}
No bounds checking in
c++
• When size of an array is declared c++ doesn’t have way to ensure the attempted
input size equals the declared array size. E.g:
int main()
{
const int SIZE = 3; // Constant for the array size
int values[SIZE]; // An array of 3 integers
int count; // Loop counter variable
// Attempt to store five numbers in the three-element array.
cout << "I will store 5 numbers in a 3-element array!\n";
for (count = 0; count < 5; count++)
values[count] = 100;
// If the program is still running, display the numbers.
cout << "If you see this message, it means the program\n";
cout << "has not crashed! Here are the numbers:\n";
for (count = 0; count < 5; count++)
cout << values[count] << endl;
return 0;
}
Off-by-one Error
const int SIZE = 100;
int numbers[SIZE];
for (int count = 1; count <= SIZE; count++)
numbers[count] = 0;
• The loop starts from memory location 1 instead of 0
• The first element in the array will be skipped
• The program will write data beyond array boundaries (here 100 is an invalid
subscript) since 100 > the highest expected subscript
Array Initialization
• Finite arrays can be initialized as follow
int main()
{
const int MONTHS = 12;
int days[MONTHS] = { 31, 28, 31, 30, //note that MONTH != 12
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < MONTHS; count++)
{ cout << "Month " << (count + 1) << " has ";
cout << days[count] << “ days.\n";
} return 0;
}
The size of the array can be copie from the document type in the like of microsoft word.
Base on the diagramatical rario of the content base on the directly scripture on windows
from the program file in Linux and windows which will take you directly
Implicit Initialization
• Elements are entered to arrays without defining the size of the array
double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};
Range-Base “for” loop
• The range-based for loop is a loop that iterates once for each element in an array.
Each time the loop iterates, it copies an element from the array to a variable
int main()
{
string planets[] = { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus",
"Neptune", "Pluto (a dwarf planet)" };
cout << "Here are the planets:\n";
// Display the values in the array.
for (string val : planets)
cout << val << endl;
return 0;
}
Using “for” loop to sum
elements of an array
• Regular loop:
int total = 0; // Initialize accumulator
for (int count = 0; count < NUM_UNITS; count++)
total += units[count];
• Range loop
int total = 0; // Initialize accumulator
for (int val : units)
total += val;
Two dimensional
arrays
• An array type that hold two dimensional data, the like of Metrix
• Declaration
• 3D array declaration
double seats[3][5][8];
Example of Array Manipulation at the
Hardware level
.data
x: .word 1,2,3,4,5,6,7,8,9,10 #55
iterator: .word 0
size: .word 9
prompt: .asciiz "The total sum of the array is: "
.text
main:
la $s0, prompt
la $s0, x
lw $t1, iterator
lw $t2, size
begin_loop:
bgt $t1, $t2 exit_loop
sll $t3, $t1, 2 #4.i
addu $t3, $t3, $t0 #x[i]
lw $t6, 0($t3)
addu $t7, $t7, $t6
addi $t1, $t1, 1
j begin_loop
exit_loop:
li $v0 4
la $a0, ($s7)
syscall
li $v0, 1
la $a0, ($s7)
syscall
Searching and Sorting Arrays
Procedures
• It is advisable to use scope resolution “::” in situation where derived class used
multiple base classes having member variables of functions with the same name
(no function overload)
Exceptions, Templates and
Standard Template Libraries
(STL)
• Exceptions are used to signal errors or unexpected events that occur while a
program is running
Example of Exception
OO Exception
Multiple Exception
• Where multiple exception is required, each exception should have its own class
Typical Example of Multiple Exception