Programming Logic and Design
Programming Logic and Design
LABORATORY MANUAL
Developed by:
DO’S
1. Know the location of the fire extinguisher and the first aid box and how to use
them in case of an emergency.
2. Read and understand how to carry out an activity thoroughly before coming to
the laboratory.
3. Report fires or accidents to your lecturer/laboratory technician immediately.
4. Report any broken plugs or exposed electrical wires to your lecturer/laboratory
technician immediately.
DON’TS
1. Do not eat or drink in the laboratory.
2. Avoid stepping on electrical wires or any other computer cables.
3. Do not open the system unit casing or monitor casing particularly when the
power is turned on. Some internal components hold electric voltages of up to
30000 volts, which can be fatal.
4. Do not insert metal objects such as clips, pins and needles into the computer
casings. They may cause fire.
5. Do not remove anything from the computer laboratory without permission.
6. Do not touch, connect or disconnect any plug or cable without your
lecturer/laboratory technician’s permission.
7. Do not misbehave in the computer laboratory.
LABORATORY RUBRICS
Functionality The program works and The code is fairly efficient The code is The code is huge and
And efficiency meets all of the without sacrificing readability unnecessarily long and does not meet any
30% specifications and is and understanding and also inefficient and meets specifications
extremely efficient meets almost all of its only few of its
without sacrificing specifications but not all. specifications
readability and
understanding.
Output The program produces The program works and The program produces The program is producing
5% correct results and produces the correct results correct results but does incorrect results.
display them correctly in and displays them correctly not display them
an organized way. correctly
Input All the inputs entered by In case of wrong input the Some of the inputs are No input validation.
user are properly programs continues validated leaving the
Validation*
validated, in case of execution. others.
20%
wrong input entered by
user the program
displays to the user to
enter the correct input.
Delivery The code was delivered The code was delivered The code was delivered The code was more than 2
30% within the deadline. within the deadline few hours passed the days overdue.
deadline.
Name/Section Rating
Date performed
Date submitted
I. Objective(s):
II. Theory:
or
e. Only one flow line should enter a decision symbol, but two or three flow lines,
one for each possible answer, should leave the decision symbol.
1. Write an algorithm and draw the flowchart for finding the average of two numbers
Algorithm:
Steps:
Input x
1. input x
2. input y
3. sum = x + y
Input y
4. average = sum /2
5. output average
Sum = x + y
Average = sum/2
Output
Average
END
c. “Go forward until the Touch Sensor (on port 1) is pressed in, then stop.”
d. “Follow Liberty Avenue for 2 miles, then take a left turn onto 40th Street. Go
until you reach the bridge, but don’t cross the bridge. Instead, make a right turn
onto Foster Street, then take the first left turn. Follow that road until you reach the
National Robotics Engineering Consortium building.”
e. “Turn on oven. Cook turkey for 4 hours or until meat thermometer reaches 180
degrees.”
IV. Assessment
Write an algorithm for finding the area of a rectangle. Show your flowchart.
Hints:
Date performed
Date submitted
I. Objective(s):
II. Theory
Let us look at a simple code that would print the words Hello World.
#include
<iostream> using
namespace std;
• The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.
• The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the
end of the line.
• The line int main() is the main function where program execution begins.
• The next line cout << "Hello World"; causes the message "Hello World" to be
displayed on the screen.
• The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.
• Program comments are explanatory statements that you can include in the C++
code. These comments help anyone reading the source code. All programming
languages allow for some form of comments. C++ supports single-line and multi-
line comments. All characters available inside any comment are ignored by C++
compiler. C++ comments start with /* and end with */. A comment can also start
with //, extending to the end of the line.
IV. Assessment:
Write five C++ statements to print the asterisk pattern as shown below.
Date performed
Date submitted
I. Objective(s):
II. Theory:
Data Types:
A variable provides us with named storage that our programs can manipulate.
Each variable in C++ has a specific type, which determines the size and layout of
the variable's memory, this type is known as data type of that variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C++ is case- sensitive.
Variable Declaration in C++
A variable declaration provides assurance to the compiler that there is one
variable existing with the given type and name so that compiler proceed for further
compilation.
int a;
char b;
float c;
Constants
Constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.
Defining Constants
There are two simple ways in C++ to define constants: Using #define
preprocessor
Using const keyword
#define LENGTH 10
#define WIDTH 5
const int LENGTH = 10;
const int WIDTH = 5;
Legal Identifiers:
Regardless of which style you adopt, be consistent and make your variable
names as sensible as possible. Here are some specific rules that must be followed with
all identifiers.
• The first character must be one of the letters a through z, A through Z, or an
underscore character (_).
• After the first character you may use the letters a through z or A through Z, the
digits 0 through 9, or underscores.
• Uppercase and lowercase characters are distinct. This means ItemsOrdered is
not the same as itemsordered.
Escape Sequence:
cout << "\t";
Fundamental Arithmetic Operators:
4. Write a C++ program to calculate the distance between the two points. Note: x1, y1,
x2, y2 are all double values.
Formula:
IV. Assessment
1. Calculate the Area of a Circle (area = PI * r2)
2. Calculate the Area of a Rectangle (area = length * width)
3. Calculate the Area of a Triangle (area = base * height * .5)
4. Total Purchase A customer in a store is purchasing five items. The prices of
the five items are: Price of item 1 = $12.95
Price of item 2 = $24.95 Price of item 3 = $6.95 Price of item 4 = $14.95 Price of
item 5 = $3.95
5. Write a program that holds the prices of the five items in five variables.
Display each items price, the subtotal of the sale, the amount of sales tax, and
the total. Assume the sales tax is 6%.
Name/Section Rating
Date performed
Date submitted
I. Objective(s):
II. Theory:
Type casting
C++ is a strong-typed language. Many conversions, specially those that imply a
different interpretation of the value, require an explicit conversion, known in C++ as
type-casting. There exist two main syntaxes for generic type-casting: functional and c-
like:
double x = 10.3;
int y;
y = int (x); // functional notation
y = (int) x; // c-like cast notation
Expressions:
Multiplication, mode and division have higher precedence than addition and
subtraction. Associativity: left to right.
Random Function:
cout << rand();
Library used <cstdlib>
Formatting:
Program-2
#include <iostream> using namespace std; void main()
{
int number1, number2; float quotient;
cout << "Enter two numbers and I will divide\n"; cout << "the first by the second
for you.\n";
cin >> number1, number2;
quotient = float<static_cast>(number1) / number2; cout << quotient
}
3. Average of Values to get the average of a series of values, you add the
values up and then divide the sum by the number of values. Write a
program that stores the following values in five different variables: 28, 32,
37, 24, and 33. The program should first calculate the sum of these five
variables and store the result in a separate variable named sum. Then, the
program should divide the sum variable by 5 to get the average. Display
the average on the screen.
Name/Section Rating
Date performed
Date submitted
I. Objective(s):
II. Theory:
Uses of IF Statement
Flowchart of if Statement
if...else
The of executes the codes inside the body
of statement if the test expression is true and skips the
codes inside the body of [Link] the test expression is false, it
executes the codes inside the body of statement and skips the
codes inside the body of if.
Flowchart of if...else
C++ Nested if...else
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
Nested If:
In C++ we can use if statement in the
another else block. or we can also
include if block in the another if block.
Syntax : C++ Nested If
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}
Example : Nested If
Example : Nested If-else
#include <iostream>
using namespace std;
int main ()
{
int marks = 55;
if( marks >= 80) {
cout << "U are 1st class !!";
}
else {
if( marks >= 60) {
cout << "U are 2nd class !!";
}
else {
if( marks >= 40) {
cout << "U are 3rd class !!";
}
else {
cout << "U are fail !!";
}
}
}
return 0;
}
III. Lab Activities:
1. Write a program to print positive number entered by the user. If the user enters
negative number print number entered is positive otherwise print number is negative.
IV. Assessment:
1. Find Largest Number Using Nested if...else statement.
Check whether the number entered by the user is positive or not. If it is positive then
calculate how many digits the number have.
Name/Section Rating
Date performed
Date submitted
I. Objective(s):
1. To practice for loops and switch cases and to get better understanding of how to use
them.
II. Theory:
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
Syntax:
The syntax of a for loop in C++ is –
Example
int main (){
Output:
Nested Loops:
A loop that is inside another loop is called a nested loop. A clock is a good
example of something that works like a nested loop. The second hand, minute hand,
and hour hand all spin around the face of the clock. Each time the hour hand
increments, the minute hand increments 60 times. Each time the minute hand
increments, the second hand increments 60 times. Here is a program segment with a
for loop that partially simulates a digital clock. It displays the seconds from 0 to 59:
Output:
Switch case
Switch...case is a branching statement used to perform action based on available
choices, instead of making decisions based on conditions. Using switch...case you can
write more clean and optimal code than if...else statement. switch...case only works with
integer, character and enumeration constants.
num * 2
num * 3
num * 4
num * 5
num * 6
num * 7
num * 8
num * 9
num * 10
IV. Assessment:
1. What will be the output of the C program?
#include<stdio.h>
int main()
{
for(5;2;2)
{
cout<<"Hello";
}
return 0;
}
#include<stdio.h>
int main()
{
int i;
for(i = 0; i>9; i+=3)
{
cout<<"for ";
}
return 0;
}
int main()
{
int fun=5;
cout<<"C++ for loop ";
int x = 5;
for(x=0;x<=fun;x++)
{
cout<<x;
}
return 0;
}
Name/Section Rating
Date performed
Date submitted
II. Theory:
Loops
A loop is part of a program that repeats. The while loop has two important parts:
(1) an expression that is tested for a true or false value, and (2) a statement or block
that is repeated as long as the expression is true.
The while Loop Is a Pretest Loop ,which means it tests its expression before
each iteration whereas the do- while loop is a posttest loop, which means its expression
is tested after each iteration.
Infinite Loops:
If a loop does not have a way of stopping, it is called an infinite loop. An infinite
loop continues to repeat until the program is interrupted. Here is an example of an
infinite loop:
Examples:
The following example averages a series of three test scores for a student. After the
average is displayed, it asks the user if he or she wants to average another set of test
scores. The program repeats as long as the user enters Y for yes.
Example OUTPUT
Date performed
Date submitted
II. Theory:
A function is a collection of statements that performs a specific task. So far you
have experienced functions as you have created a function named main in every
program you’ve written. Functions are commonly used to break a problem down into
small manageable pieces. This approach is sometimes called divide and conquer
because a large problem is divided into several smaller problems that are easily
solved.
This benefit of using functions is known as code reuse because you are writing
the code to perform a task once and then reusing it each time you need to perform
the task.
Defining and Calling Functions:
A function call is a statement that causes a function to execute. A function
definition contains the statements that make up the function. When creating a
function, you must write its definition. All function definitions have the following parts:
1. Return type: A function can send a value to the part of the program that executed
it. The return type is the data type of the value that is sent from the function.
2. Name: You should give each function a descriptive name. In general, the same
rules that apply to variable names also apply to function names.
3. Parameter list: The program can send data into a function. The parameter list is a
list of variables that hold the values being passed to the function.
4. Body: The body of a function is the set of statements that perform the function’s
operation. They are enclosed in a set of braces.
Void Functions:
It isn’t necessary for all functions to return a value, however. Some functions
simply perform one or more statements, which follows terminate. These are called
void functions. The display Message function, which follows, is an example.
Calling a Function:
A function is executed when it is called. Function main is called automatically
when a program starts, but all other functions must be executed by function call
statements. When a function is called, the program branches to that function and
executes the statements in its body
Function prototype:
A function prototype eliminates the need to place a function definition before all
calls to the function. You must place either the function definition or either/the function
prototype ahead of all calls to the function. Otherwise the program will not compile.
However, we could have eliminated the result variable and returned the
expression num1 + num2, as shown in the following code:
2. Write a function asks the user to enter the radius of the circle and then
returns that number as a double. Write another function that takes this
radius as input and returns the area of circle.
5. Write a value returning function that receives three integers and returns
the largest of the three. Assume the integers are not equal to one another.
IV. Assessment:
1. What is the output of the following program?
2. The following program skeleton asks for the number of hours you’ve worked and
your hourly pay rate. It then calculates and displays your wages. The function
showDollars, which you are to write, formats the output of the wages.
Name/Section Rating
Date performed
Date submitted
I. Objective(s):
1. Understand the idea of Overloading Functions and be able to write an
overloaded function.
2. The student should be prepared to understand the idea of operator
overloading in general.
3. Convert a program written using loops into a recursive one.
II. Theory:
Function signature is both the name and parameter list of that function
To overload a function is to write at least two functions at the same
scope(workspace)with different signatures [i.e. the same name but with
different parameter list (make the parameters in every list differ in
types ,number, or appearance)].
A recursive function is a function that calls itself.
In C++, two functions can have the same name if the number and/or type of
arguments passed is different.
These functions having the same name but different arguments are known as
overloaded functions. For example:
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions.
Notice that the return types of all these 4 functions are not the same.
Overloaded functions may or may not have different return types but they must
have different arguments. For example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and the same
number of arguments. Hence, the compiler will throw an error.
#include <iostream>
using namespace std;
int main() {
Output
int main() {
int a = 5;
double b = 5.5;
return 0;
}
Output
Note: In C++, many standard library functions are overloaded. For example, the
sqrt() function can take double, float, int, etc. as parameters. This is possible
because the sqrt() function is overloaded in C++.
void main()
{
cout<<power(2,5);
}
IV. Assessment:
1. Write a recursive C++ function to calculate and return:
Sum=1!+2!+3!+…+n!
Name/Section Rating
Date performed
Date submitted
Laboratory Exercise No.10
ARRAYS
I. Objective(s):
1. To be able to declare an array.
2. To be able to perform fundamental operations on a two-dimensional array.
3. To be able to pass two-dimensional arrays as parameters.
4. To be able to view a two-dimensional array as an array of arrays.
II. Theory:
Array
An array is a series of elements of the same type placed in contiguous memory
locations that can be individually referenced by adding an index to a unique
identifier.
That means that, for example, five values of type int can be declared as an array
without having to declare 5 different variables (each with its own identifier). Instead,
using an array, the five int values are stored in contiguous memory locations, and all
five can be accessed using the same identifier, with the proper index.
For example, an array containing 5 integer values of type int called foo could be
represented as:
where each blank panel represents an element of the array. In this case, these
are values of type int. These elements are numbered from 0 to 4, being 0 the first
and 4 the last; In C++, the first element in an array is always numbered with a zero
(not a one), no matter its length.
Initializing arrays:
By default, regular arrays of local scope (for example, those declared within a
function) are left uninitialized. This means that none of its elements are set to any
particular value; their contents are undetermined at the point the array is declared.
But the elements in an array can be explicitly initialized to specific values when it
is declared, by enclosing those initial values in braces {}. For example:
int foo [5] = { 16, 2, 77, 40, 12071 };
The number of values between braces {} shall not be greater than the number of
elements in the array. For example, in the example above, foo was declared having 5
elements (as specified by the number enclosed in square brackets, []), and the braces {}
contained exactly 5 values, one for each element. If declared with less, the remaining
elements are set to their default values (which for fundamental types, means they are
filled with zeroes). For example:
This creates an array of five int values, each initialized with a value of zero:
For example, the following statement stores the value 75 in the third element of foo:
and, for example, the following copies the value of the third element of foo to a variable
called x:
The following example shows how to Find the Highest and Lowest Values in a Numeric
Array
HIGHEST LOWEST
You now know that an array’s name is seen as the array’s beginning memory address.
This explains why the following statement cannot be used to display the contents of
array :
cout << numbers << endl; //Wrong!
When this statement executes, cout will display the array’s memory address, not the
array’s contents. You must use a loop to display the contents of each of the array’s
elements, as follows.
for (int count = 0; count < SIZE; count++)
cout << numbers[count] << endl;
Example:
Example OUTPUT
1. Write a program that asks for the number of hours worked by six employees. It
stores the values in an array.
2. Write a program that asks the user to type 10 integers of an array. The program
must compute and write how many integers are greater than or equal to 10.
IV. Assessment:
1. Correct the errors in the following program.
2. The following program skeleton contains a 20-element array of int s called fish.
When completed, the program should ask how many fish were caught by
fishermen 1 through 20, and store this data in the array. Complete the program.
3. Is each of the following a valid or invalid array definition? (If a definition is invalid,
explain why.)
Name/Section Rating
Date performed
Date submitted
II. Theory:
When declaring a variable, it is located at a specific location in memory, the
memory address. The task of locating variables is automatically performed by the
operating system during runtime. In some cases we need to know the address
where the variable is being stored during runtime.
Variable which stores a reference to another variable is called a pointer. We can
directly access the value stored in the variable using a pointer which points to it.
Syntax:
1. Pointer Declaration:
Syntax: Pointer_type *Pointer_name;
Example: int *Ptr1; double *Ptr2;
2. Pointer initialization:
Syntax: Pointer_name=NULL;
Pointer_name=&variable_name;
Example: int *Ptr1, var;
Ptr1=&var;
IV. Assessment:
1. Write a c++ program that use pointers to swap two integer values.
2. What will be the output of the following code?
Name/Section Rating
Date performed
Date submitted
II. Theory:
What is file handling in C++?
Files store data permanently in a storage device. With file handling, the output
from a program can be stored in a file. Various operations can be performed on the
data while in the file.
A stream is an abstraction of a device where input/output operations are
performed. You can represent a stream as either a destination or a source of
characters of indefinite length. This will be determined by their usage. C++ provides
you with a library that comes with methods for file handling.
The fstream Library
The fstream library provides C++ programmers with three classes for working
with files. These classes include:
ofstream– This class represents an output stream. It’s used for creating
files and writing information to files.
ifstream– This class represents an input stream. It’s used for reading
information from data files.
fstream– This class generally represents a file stream. It comes with
ofstream/ifstream capabilities. This means it’s capable of creating files,
writing to files, reading from data files.
It is possible to use two modes at the same time. You combine them using
the | (OR) operator.
file_op.close;
return 0;
}
IV. Assessment:
1. Write a program to find the maximum digit throw any integer number and print
the
value in text file
2. Write a program to read four integer numbers from file, then find and print the
second maximum one among these numbers.
REFERENCES:
1. [Link]
2. [Link]
3. [Link]
4. [Link]
LAB_MANUAL.pdf