0% found this document useful (0 votes)
4 views65 pages

Programming Logic and Design

The document is a laboratory manual for the Computer Engineering Department, focusing on Logic Circuits and Switching Theory. It includes safety guidelines for the computer lab, assessment rubrics for programming tasks, and exercises on flowcharts, C++ programming, data types, and expressions. Each section outlines objectives, theory, lab activities, and assessments to enhance students' understanding of programming concepts.

Uploaded by

Vien Ako Revilo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views65 pages

Programming Logic and Design

The document is a laboratory manual for the Computer Engineering Department, focusing on Logic Circuits and Switching Theory. It includes safety guidelines for the computer lab, assessment rubrics for programming tasks, and exercises on flowcharts, C++ programming, data types, and expressions. Each section outlines objectives, theory, lab activities, and assessments to enhance students' understanding of programming concepts.

Uploaded by

Vien Ako Revilo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

COLLEGE OF ENGINEERING

Computer Engineering Department

LABORATORY MANUAL

LOGIC CIRCUITS AND SWITCHING


THEORY

Developed by:

Engr. Mark Mercado, CMAE

Computer Engineering Department


COMPUTER LAB DO’S AND DON’T

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

Trait Exceptional Acceptable Amateur Unsatisfactory


[10-8] [7-5] [4-3] [2-0]
Compilation Program compiles with Program has few syntax Program has few Application does not
15% zero error and zero error but logically correct. syntax error but not compile or compiles but
warnings. even logically correct. crashes.

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

Laboratory Exercise No.1


FLOWCHARTS AND ALGORITHM

I. Objective(s):

1. This laboratory exercise aims to introduce flowcharts emphasizing on


algorithms.

II. Theory:

A flowchart is a graphical representation of an algorithm. These flowcharts play a


vital role in the programming of a problem and are quite helpful in understanding the
logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes
easy to write the program in any high level language. Often we see how flowcharts are
helpful in explaining the program to others. Hence, it is correct to say that a flowchart is
a must for the better documentation of a complex program.

Flowcharts are usually drawn using some standard symbols; however,

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching


Connector or joining of two parts of program

The following are some guidelines in flowcharting:

a. In drawing a proper flowchart, all necessary requirements should be listed out in


logical order.
b. The flowchart should be clear, neat and easy to follow. There should not be any
room for ambiguity in understanding the flowchart.
c. The usual direction of the flow of a procedure or system is from left to right or top
to bottom.
d. Only one flow line should come out from a process symbol.

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.

f. Only one flow line is used in conjunction with terminal symbol.

h. If the flowchart becomes complex, it is better to use connector symbols to reduce


the number of flow lines. Avoid the intersection of flow lines if you want to make it
more effective and better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple
test data.
III. Lab Activities:

1. Write an algorithm and draw the flowchart for finding the average of two numbers

Algorithm:

Input: two numbers x and y

Output: the average of x and y START

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

2. Create flowcharts to represent these short tasks:

a. “If it’s raining, bring an umbrella.”

b. “Take twenty paces, then turn and shoot.”

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:

 define the inputs and the outputs


 define the steps
 draw the flowchart
Name/Section Rating

Date performed
Date submitted

Laboratory Exercise No.2


INTRODUCTION TO C++ PROGRAMMING

I. Objective(s):

1. This laboratory exercise aims to present the fundamentals of C++ Language.

II. Theory

C++ Program Structure

Let us look at a simple code that would print the words Hello World.

#include

<iostream> using

namespace std;

// main() is where program execution

begins. int main() {

cout << "Hello World"; // prints Hello World

Let us look at the various parts of the above program –


• The C++ language defines several headers, which contain information that is
either necessary or useful to your program. For this program, the header
<iostream> is needed.

• 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.

• In C++, the semicolon is a statement terminator. That is, each individual


statement must be ended with a semicolon. It indicates the end of one logical
entity.

• 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.

III. Lab Activities:

1. Run the following program and check the output

#include<iostream> using namespace std;


int main()
{
cout << "hello world" << endl; //prints hello world and endl means end the line system("pause");
//to stop output window
return 0;
}

2. Write a C++ program to print the following lines:

You are 10 years old.


You are too young to play the game.

IV. Assessment:

Write five C++ statements to print the asterisk pattern as shown below.

**************** **************** ****************


**************** **************** ****************
** ** ** **
** ** ** **
** ** ** **
** **************** ****************
** **************** ****************
** ** **
** ** **
** ** **
**************** ** ****************
**************** ** ****************
Name/Section Rating

Date performed
Date submitted

Laboratory Exercise No.3


DATA TYPES, VARIABLES, CONSTANTS, AND ARITHMETIC
OPERATORS

I. Objective(s):

1. To be familiar with different data types, operators and expressions in C++.


2. To be able to define the different data types of variables, operators and expressions
in C++.

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;

Variable Initialization in C++


A variable can be initialized at the time of declaration or even after that. Basically
initialization means storing some actual meaningful data inside the variable.
int a=2;
char b=’x’;
float c=2.907;

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:

III. Lab Activities:


1. Type and save the following programs in Visual Studio. Run these programs and
observe their output.
2. Take two integers as input from the user apply athematic operations on them(+,-,*,/)
as print them on screen.
3. Write the output of the following code:

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

Laboratory Exercise No.4


EXPRESSIONS, TYPE CASTING, COERCION, FORMATTING, RANDOM
NUMBERS

I. Objective(s):

1. To apply expressions, type casting, coercion, formatting, and random numbers in a


simple C++ program.

II. Theory:

Implicit conversion (coercion)


Implicit conversions are automatically performed when a value is copied to a
compatible type. For example
Short a= 2000;
Int b;
b=a;
When an operator works with two values of different data types, the lower-
ranking value is promoted to the type of the higher-ranking value.
When the final value of an expression is assigned to a variable, it will be converted to
the data type of that variable.

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:

III. Lab Activities:


1. Assume that the following variables are defined:
int age;
double pay;
char section;
Write a single cin statement that will read input into each of these variables.
2. Complete the following table by writing the value of each expression in the Value
column according C++ language rules.

3. Assume a program has the following variable definitions:


int units;
float mass;
double weight;
weight = mass * units;

Which automatic data type conversion will take place?


[Link] is demoted to an int, units remains an int, and the result of mass * units
is an int.
[Link] is promoted to a float, mass remains a float, and the result of mass * units
is a float.
[Link] is promoted to a float, mass remains a float, and the result of mass * units
is a double.
IV. Assessment:
1. Each of the following programs has some errors. Locate as many as you can.
Program-1
using namespace std; void main ()
{
double number1, number2, sum; cout << "Enter a number: ";
cin << number1;
cout << "Enter another number: "; cin << number2;
number1 + number2 = sum;
cout "The sum of the two numbers is " << sum
}

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

Laboratory Exercise No.5


LOGICAL CONTROL ( IF STATEMENT)

I. Objective(s):

1. To learn how to use IF Statement as logical control in C++ programming.


2. Make a C++ program that includes an IF statement.

II. Theory:

Uses of IF Statement

To specify the conditions under which a statement or group of statements should


be executed.

The if statement evaluates the test expression inside parenthesis. If test


expression is evaluated to true, statements inside the body of if is executed. If test
expression is evaluated to false, statements inside the body of if is skipped.
How if statement works?

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.

How if...else statement works?

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.

Syntax of Nested if...else

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.

2. Program to check whether an integer is positive, negative or zero.

3. Write a program for the following requirements:


Input : Mark
Process : If mark greater than and equal to 75, score will be A
If mark less than 75 and greater than and equal to 60, score will be B If mark less than
60 and greater than and equal to 45, score will be C If mark less than 30, score will be
D
Output : Print the grade of your score.

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

Laboratory Exercise No.6


INTRODUCTION TO FOR LOOPS AND SWITCH CASE

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:

Defining a Variable in the for Loop’s Initialization Expression:


Not only may the counter variable be initialized in the initialization expression, it
may be defined there as well. The following code shows an example.

Using Multiple Statements in the Initialization and Update Expressions:


It is possible to execute more than one statement in the initialization expression
and the update expression. When using multiple statements in either of these
expressions, simply separate the statements with commas. For example
Omitting the for Loop’s Expressions:
The initialization expression may be omitted from inside the for loop’s
parentheses if it has already been performed or no initialization is needed. Here is an
example

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.

III. Lab Activities:


1. Write a C++ program to Print Table of any Number.
The concept of generating table of any number is multiply particular number from 1 to
10.
num * 1

num * 2

num * 3

num * 4

num * 5

num * 6

num * 7

num * 8

num * 9
num * 10

2. Find power of any number using for loop.


3. Sum of Natural Numbers using loop.
4. C++ program to find sum of digits of a number.
Sum of digits means add all the digits of any number, for example we take any number
like 358. Its sum of all digit is 3+5+8=16. Using given code we can easily write c++
program.

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;
}

2. What will be the output of the C program, if input is 6?

#include<stdio.h>
int main()
{
int i;
for(i = 0; i>9; i+=3)
{
cout<<"for ";
}
return 0;
}

3. What will be the output of the C ++ program?


4. What will be the output of the C program?

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

Laboratory Exercise No.7


WHILE & DO WHILE LOOPS
I. Objective(s):
1. To have better understanding regarding loops.

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:

We can make this loop finite by adding a line as shown below:

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

III. Lab Activities:


1. Write a program to print all natural numbers from 1 to n using while loop
2. Write a program to print natural numbers in reverse from n to 1 using while loop
3. Write a program to print all even numbers between i to n using while loop.
4. Write a program to Generate Fibonacci Sequence up to a Certain Number. The
Fibonacci sequence is a series of numbers where a number is found by adding up the
two numbers before it. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13,
21, 34, and so forth.
1. Write a do-while loop that asks the user to enter two numbers. The
numbers should be added and the sum displayed. The user should be
asked if he or she wishes to perform the operation again. If so, the loop
should repeat; otherwise it should terminate.
IV. Assessment:
1. What will the following program segments display?

2. What’s wrong with the following while loop?


Name/Section Rating

Date performed
Date submitted

Laboratory Exercise No.8


FUNCTIONS
I. Objective(s):
1. Able to demonstrate the different modified functions based on specific
requirements.
2. Create functions with multiple parameters.

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 Header void displayMessage()


 Functions may also be called in a hierarchical, or layered, fashion.

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.

Sending Data into a Function:


When a function is called, the program may send values into the function. Values
that are sent into a function are called arguments. In the following statement the
function pow is being called and two arguments, 2.0 and 4.0, are passed to it:
result = pow(2.0, 4.0);
By using parameters, you can design your own functions that accept data this
way. A parameter is a special variable that holds a value being passed into a function.
Here is the definition of a function that uses a parameter:
void displayValue(int num)
{ cout << "The value is " << num << endl; }
The return Statement and Returning a Value from a Function :
The return statement causes a function to end immediately. A function may send
a value back to the part of the program that called the function this is known as
returning a value. Here is an example of a function that returns an int value:

However, we could have eliminated the result variable and returned the
expression num1 + num2, as shown in the following code:

A function can also return a Boolean value instead of integer or double or


character. The following example shows that.

Examples: The following example demonstrates a function with a parameter.


Example OUTPUT
I am passing several values to displayValue.
The value is 5
The value is 10
The value is 2
The value is 16

III. Lab Activities:


1. Write a function named times Ten . The function should have an integer
parameter named number. When times Ten is called, it should display the
product of number times ten. (Note: just write the function. Do not write a
complete program.)

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.

3. Write a function accepts an integer argument and tests it to be even or


odd. The function returns true if the argument is even or false if the
argument is odd. The return value should be bool. In main take a integer
input from user and pass it to the function.
4. Write a program with a function that takes two int parameters, adds them
together, then returns the sum. The program should ask the user for two
numbers, then call the function with the numbers as arguments, and tell
the user the sum.

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

Laboratory Exercise No.9


FUNCTION OVERLOADING AND RECURSION

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.

Example 1: Overloading Using Different Types of Parameter

// Program to compute absolute value


// Works for both int and float

#include <iostream>
using namespace std;

// function with float type parameter


float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

// function with int type parameter


int absolute(int var) {
if (var < 0)
var = -var;
return var;
}

int main() {

// call function with int type parameter


cout << "Absolute value of -5 = " << absolute(-5) << endl;
// call function with float type parameter
cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}

Output

Example 2: Overloading Using Different Number of Parameters


#include <iostream>
using namespace std;

// function with 2 parameters


void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}

// function with double type single parameter


void display(double var) {
cout << "Double number: " << var << endl;
}

// function with int type single parameter


void display(int var) {
cout << "Integer number: " << var << endl;
}

int main() {
int a = 5;
double b = 5.5;

// call function with int type parameter


display(a);

// call function with double type parameter


display(b);
// call function with 2 parameters
display(a, b);

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++.

III. Lab Activities:


1. Write an overloaded function to calculate and return the area of a square, a circle
,a rectangle. Then call it from the main function.
#include <iostream>
using namespace std;
double area(int r)
{ return r*r*3.14;}
double area(float s)
{
return s*s;
}
double area(int l,int w)
{
return l*w;
}
void main()
{
cout<<area(3);
cout<<area(3,4);
cout<<area(3.0);
}
2. Write a recursive function to calculate and return the power of any2 positive
integer
numbers.
int power(int base,int pwr)
{
if (pwr==0)
return 1;
else return power (base,pwr-1)*base;}

void main()
{
cout<<power(2,5);
}

IV. Assessment:
1. Write a recursive C++ function to calculate and return:
Sum=1!+2!+3!+…+n!

then call your function from the main.


2. Write a C++recursive function to check out if any given integer is prime or not.
3. Write a C++recursive function to calculate.
X*Y (the multiplication of X by Y where X,Y are integers)

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 };

This statement declares an array that can be represented like this:

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:

Will create an array like this:

The initializer can even have no values, just the braces:

This creates an array of five int values, each initialized with a value of zero:

Accessing the values of an array:


The values of any of the elements in an array can be accessed just like the value of a
regular variable of the same type. The syntax is:
name[index]
Following the previous examples in which foo had 5 elements and each of those
elements was of type int, the name which can be used to refer to each element is the
following:

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:

Therefore, the expression foo[2] is itself a variable of type int.


Examples: the following examples displays the sum of elements of array.
Example OUTPUT
12206

The following example shows how to Find the Highest and Lowest Values in a Numeric
Array
HIGHEST LOWEST

Implicit Array Sizing:


It’s possible to define an array without specifying its size, as long as you provide an
initialization list. C++ automatically makes the array large enough to hold all the
initialization values. For example, the following definition creates an array with five
elements:
double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

Printing the Contents of an Array:

Suppose we have the following array definition:


const int SIZE = 5; int numbers [SIZE] = {10, 20, 30, 40, 50};

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

III. Lab Activities:

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.

3. Write a C++ function that multiplies two matrices using arrays.

4. Write a program in C++ to find the transpose of a matrix.

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

Laboratory Exercise No.11


POINTERS
I. Objective(s):
1. Students will learn the memory concept of variables, pointers and how to use
variable identifiers and pointers to refer to the variable.
2. Students will develop a program using pointer variable declarations and
initialization.
3. Students will apply the direct and indirect referencing a variable using the pointer
operators.

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;

III. Lab Activities:


1. Write a c++ program that defines an integer variable var1 and a pointer Ptr that
points to var1. Assign and print value to var1, then assign and print a new value to
var1 using Ptr.
2. Correct the errors in the following program.

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

Laboratory Exercise No.12


USING FILES
I. Objective(s):
1. Create a file using simple program.
2. Read and write in a file using simple program.

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.

How to Close Files


Once a C++ program terminates, it automatically
 flushes the streams
 releases the allocated memory
 closes opened files.
However, as a programmer, you should learn to close open files before the
program terminates.
The fstream, ofstream, and ifstream objects have the close() function for closing
files. The function takes this syntax:
How to Write to Files
You can write to file right from your C++ program. You use stream insertion
operator (<<) for this. The text to be written to the file should be enclosed within
double-quotes.

Let us demonstrate this.

How to Read from Files


You can read information from files into your C++ program. This is possible using
stream extraction operator (>>). You use the operator in the same way you use it
to read user input from the keyboard. However, instead of using the cin object,
you use the ifstream/ fstream object.
III. Lab Activities:
1. Create an empty text file using c++ program and set its location
#include<fstream.h>
int main()
{
fstream file_op("c:\\test_file.txt",ios::in);
file_op.close() ;
return 0;
}

2. Read value from empty text file using c++ program


#include<fstream.h>
int main()
{
fstream file_op("c:\\test_file.txt",ios::in);
int x;
file_op >>x;
cout<<x;

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

You might also like