Академический Документы
Профессиональный Документы
Культура Документы
COMPUTING
LAB MANUAL
DEPARTMENT OF ELECTRICAL
ENGINEERING,
FAST-NU, LAHORE
Introduction to Computing Lab Manual
Created by: Dr. Usman Shahid , Ms. Hina Tariq and Ms.Tooba Javed
Last Updated by: Mr. Muhammad Waheed Faraz, Ms. Sara Kiran & Mr. Umar Bashir
Page | 4
Introduction to Computing Lab Manual
Table of Contents
Sr. Description Pg.
No. No.
1 List of Equipment 06
4 Experiment No. 03: Introduction to Visual Studio 2012 and C++ Basics 19
Experiment No. 04: Basic arithmetic operators and If – Else Statement 26
5
Programming using Arduino Nano
Experiment No. 05: Control Structures: Nested If-else statement and Switch 32
6
statement
7 Experiment No. 06: Control Structures (Basic For Loop & While Loop) 36
14 Project 61
Page | 5
Introduction to Computing Lab Manual
List of Equipment
Sr. No. Description
1 Workstations (PCs)
Page | 6
Introduction to Computing Lab Manual
Experiment No. 01
Introduction to Scratch
OBJECTIVE:
Scratch:
Scratch is a free visual programming language developed to help simplify the process of creating
and programming animations, games, music, interactive stories and more.
Scratch is designed to be fun, educational, and easy to learn. The Scratch programming language
is primarily targeted at children and new programming students, and is designed to teach
computational thinking using a simple but powerful building-block approach to software
development that focuses more on problem solving than on specific syntax.
It has the tools for creating interactive stories, games, art, simulations, and more. Users program in
Scratch by dragging blocks from the block palette and attaching them to other blocks like a jigsaw
puzzle. Structures of multiple blocks are called scripts. This method of programming (building
code with blocks) is referred to as "drag-and-drop programming".
Page | 7
Introduction to Computing Lab Manual
VARIABLES:Variables are containers which hold values. Think of a box as a variable which
may have any number of apples in it. As the box may have 1 apple or 2 or 5 so on it can hold
variable number of apples and hence termed as ‘variable’.
We need variables in programs to store values input by the user. Variables can be made under
data tab by pressing ‘Make a variable’ button.
OPERATORS:
Operators perform operations on data. Following are some useful operators in scratch.
Mathematical operators (as shown in Figure 1) perform addition, subtraction,
multiplication and division of two numbers.
Figure 1 Random operator let the program choose any number between
the limits. Relational and Logical operators shown in Figure 2&3
Relational operators are used to compare two numbers
Logical operators to decide actions based on scenarios.
Figure 3
Figure 2
Figure 4
REPITITION:
We use repetitions control if we want to do something again and again.
Shown in Figure 5
TASK:1 Figure 5
Design a program in which user input age is determined on the basis of comparison with the age
of a sprite. After comparison the program should state the age as:
1. If age is less (<) than the sprite age then user is younger.
2. If age is equal (=) to the sprite age then user is of same age.
3. If age is greater (>) than the sprite age then user is elder.
Page | 8
Introduction to Computing Lab Manual
SOLUTION:
First of all we input age from the user in a variable and then to compare this variable with the
age of sprite we will use if blocks.
Follow these simple steps to perform this task:
Step:1 Open scratch.
Step:2 From the ‘Sensing tab’, drag and drop the ask
block to sprite editor in
order to get input from the user as depicted in Figure 6.
Figure 6
Figure 7
Step:5 When you click ‘ok’ you will see the icon
of that variable along with other options.
(shown in Figure 9)
Figure 9
Page | 9
Figure 10
Introduction to Computing Lab Manual
Figure 11
Figure 12
Figure 11
Figure 12
Fill in the second part of the ‘less than control block’ with the sprite age which is 7. So you
should have less than control block like shown here .
Page | 10
Figure 14
Introduction to Computing Lab Manual
Step:15 From the Data tab drag input_age block and merge it in equal to block as performed in
step 10. In other part of equal to block type 7. You will have equal to block like this at the end:
.
Now merge this equal to block in if-then block as performed in
step 11. You will have if-then block like shown here.
Figure 19
Figure 20
Step:17 Merge all if-then block.
Figure 17
Introduction to Computing Lab Manual
Figure 18
Running the code:
Step:1 Press space. You will see sprite asking about
your age. Enter your age in the textbox highlighted
by red rectangle in figure 23.
Task:2
Modify the task 1 by incorporating repetition control and let the program ask user’s age for 3
times.
SOLUTION:
Place existing code inside repletion control and set repetitions to 3.
Step:1 Separate the blocks as shown in figure 24.
Figure 24
Page | 12
Introduction to Computing Lab Manual
Step:2 Under ‘Control’ tab drag repeat block to sprite editor as shown in figure 25.
Figure 25
Figure 26
Step:4 Merge repeat block around the block of code as shown in figure 27.
Figure 27
Page | 13
Introduction to Computing Lab Manual
Step:5 Now join both blocks together. At the end you should have something similar to Figure 28.
Figure 28
Step:6 Press space just one. You will see code repeating by itself by 3 times.
Figure 29
Figure 30
Figure 31 Page | 14
Introduction to Computing Lab Manual
Run a loop that exits when the mouse is clicked. In the loop you have to:
Make your sprite walk 10 steps and then Point the direction of sprite to a random direction. So it
would appear to you that the sprite is walking randomly.
Hint: you can use the following:
This type of motion is a form of a more general type of motion called random walk. In physics
there is a natural phenomenon known as ‘Brownian motion’. You would be surprised to know how
many applications this type of process has not only to explain many natural processes like working
of the brain, flow of ink through water, etc. Also, in computer science we use it for solving various
problems in artificial intelligence.
Create a simple animation in which a sprite of your choice walks in a line and bounces along the
edges. You can use:
Now you can extend the animation to do something interesting like walk the sprite in a circle or a
rectangle.
Create a simple animation in which makes your sprite move in circular path. Make sure your sprite
does not just rotate 360 at one spot, it should move in proper circle.
Hints: You can use these
and
Post Lab
Page | 15
Introduction to Computing Lab Manual
Experiment No. 02
Making game using Scratch
OBJECTIVE:
TASK: 1
Design a program in which a user catches things falling from the sky using the following steps.
STEP-1: Go to the top (select a ball as your sprite1) as shown in the Figure 1 below
Figure 1
STEP-2: Fall down (Design a program to randomly change the position of sprite from -240 to 240
on x-axis while keeping the y-axis fixed to 180) as shown below in figure 2.
Figure 20
Figure 2
Page | 16
Introduction to Computing Lab Manual
STEP-3: Move the catcher (Select a sprite2 for catcher and then design a program to make the
catcher to move left or right using left arrow key and right arrow key) as shown in Figure 3
Figure 3
Page | 17
Introduction to Computing Lab Manual
Figure 4
STEP-5: Keep score (Design a program to keep score of your catches) shown in Figure 5
Figure 5
Page | 18
Introduction to Computing Lab Manual
Experiment No. 03
Introduction to Visual Studio 2012 and C++ Basics
OBJECTIVE:
Figure 1
Page | 19
Introduction to Computing Lab Manual
Figure 2
Figure 3
Page | 20
Introduction to Computing Lab Manual
Figure 4
1
2
Figure 5
Page | 21
Introduction to Computing Lab Manual
#include <iostream>
using namespace std;
void main()
{
cout<<”hello world”;
}
Figure 6
5) Compiling code:
Build Menu->Build Solution
6) Executing Code:
To see output of your code press Ctrl+F5, A black window will be opened. It is called console as
shown below in Figure 7.
Page | 22
Introduction to Computing Lab Manual
Figure 7
Page | 23
Introduction to Computing Lab Manual
The ‘type’ of a variable determines what kinds of values it may take on. There are only a few basic data types
in C++. The first ones we'll be encountering and using are:
‘char’ a character
‘int’ an integer, in the range -32,767 to 32,767
‘long int’ a larger integer (up to +-2,147,483,647)
‘float’ a floating-point number
‘double’ a floating-point number, with more precision and perhaps greater range than float
Declaration:
A declaration tells the compiler the name and type of a variable you'll be using in your program. In its
simplest form, a declaration consists of the type, the name of the variable, and a terminating semicolon:
char c;
int i;
float f;
Exercise - 1 (5 points)
Write a code in C++ to display your name, roll number, degree and semester on console in
following way. Use “\t” to give tab space between each field
*******************************
Name Roll Number Degree Semester
*******************************
Exercise - 3 (5 points)
Write a code in C++ to display following on console:
*
**
***
****
Page | 24
Introduction to Computing Lab Manual
You can also use iomanip library for formatting the output more neatly on console. Setfill() and
setw() are the useful functions that helps in displaying output in uniform manner.
Post Lab
a. Write a C++ program to take the value of “V” and “R” from the user and display the output
of the following expression.
𝑉2
𝑃=
𝑅
Note: Carefully choose the data types of the declared variables to hold data. Which should
be int (if any) and which should be float (if any).
Figure 8
Page | 25
Introduction to Computing Lab Manual
Experiment No. 04
Basic arithmetic operators and If – Else Statement Programming using
Arduino Nano
OBJECTIVE:
To program a microcontroller using C/C++ language and to implement “if else”
statements in it.
Basic Operators:
An ‘operator’ computes new values out of old ones. An ‘expression’ consists of variables, constants, and
operators combined to perform some useful computation. The basic operators for performing arithmetic are
the same in many computer languages:
+ addition
- subtraction
* multiplication
/ division
% modulus (remainder)
Multiplication, division, and modulus all have higher precedence than addition and subtraction. The
term ``precedence'' refers to how ``tightly'' operators bind to their operands (that is, to the things
they operate on). In mathematics, multiplication has higher precedence than addition, so 1 + 2 * 3
is 7, not 9. In other words, 1 + 2 * 3 is equivalent to 1 + (2 * 3). C is the same way.
If Else Statement:
An if statement can be followed by an optional else statement, which executes when the boolean expression
is false.
Hardware Setup
The Arduino environment has been designed to be easy to use for beginners who have no software or
electronics experience. With Arduino, you can build objects that can respond to and/or control light,
sound, touch, and movement. Arduino has been used to create an amazing variety of things, including
musical instruments, robots, light sculptures, games, interactive furniture, and even interactive
Page | 26
Introduction to Computing Lab Manual
clothing. Arduino is used in many educational programs around the world, particularly by designers
and artists who want to easily create prototypes but do not need a deep understanding of the technical
details behind their creations. Because it is designed to be used by nontechnical people, the software
includes plenty of example code to demonstrate how to use the Arduino board’s various facilities.
Plug the board in to a USB port on your computer and check that the green LED power indicator on
the board illuminates. Standard Arduino boards (Uno, Duemilanove, and Mega) have a green LED
power indicator located near the reset switch. A yellow LED near the center of the board (labeled “Pin
13 LED” in Figure 1) should flash on and off when the board is powered up (boards come from the
factory preloaded with software to flash the LED as a simple check that the board is working). Arduino
board is shown in Figure 2.
Figure 1
Page | 27
Introduction to Computing Lab Manual
Software Setup
Use the Arduino IDE to create, open, and modify sketches that define what the board will do. You
can use buttons along the top of the IDE to perform these actions (shown in Figure 3), or you can use
the menus or keyboard shortcuts (shown in Figure 3). The Sketch Editor area is where you view and
edit code for a sketch. It supports common text-editing keys such as Ctrl-F for find, Ctrl-Z for undo,
Ctrl-C to copy highlighted text, and Ctrl-V to paste highlighted text. Figure 4 shows how to load the
Blink sketch (the sketch that comes preloaded on a new Arduino board). After you’ve started the IDE,
go to the File→Examples menu and select 1. Basics→Blink, as shown in Figure 4. The code for
blinking the built-in LED will be displayed in the Sketch Editor window (refer to Figure 4). Before
the code can be sent to the board, it needs to be converted into instructions that can be read and
executed by the Arduino controller chip; this is called compiling. To do this, click the compile button
(the top-left button with a tick inside), or select Sketch Verify/Compile. You should see a message
that reads “Compiling sketch...” and a progress bar in the message area below the text-editing window.
After a second or two, a message that reads “Done Compiling” will appear. The black console area
will contain the following additional message: Binary sketch size: 1026 bytes (of a 32256-byte
maximum) The exact message may differ depending on your board and Arduino version; it is telling
you the size of the sketch and the maximum size that your board can accept.
Figure 3
Page | 28
Introduction to Computing Lab Manual
Figure 4
Exerxise-1(5 points)
Suppose ‘x’, ‘y’, and ‘z’ are int variables and ‘w’ and‘t’ are double variables. What value is
assigned to each of these variables after the last statement executes?
x = 17;
y = 15;
x = x + y / 4;
z = x % 3 + 4;
w = 17 / 3 + 6.5;
t = x / 4.0 + 15 % 4 - 3.5;
First solve on paper. Then write a C++ code to verify your answer.
Write a program, which only takes a 4-digit number as a parameter and display the number in a
reverse order. For example, if the user enters the value 1234, your program must display 4321 on
the console window.
Write an Arduino code which will tell the user whether a number entered by the user is Even or Odd.
Reading and Writing will be done on Arduino Serial Monitor.
Page | 29
Introduction to Computing Lab Manual
Hint: See the examples on serial communication that are present in Arduino IDE
Write an Arduino code which will turn the output LED on for the number of seconds entered by a
user from serial monitor.
Hint: See the examples and learn how to add delay
Write a program in C++ that take input of three integer’s numbers from the user using Arduino
Serial Monitor. If 1st number is largest, blink right most LED for 1 seconds. If 2nd number is largest,
blink middle LED for 2 seconds. If 3rd number was largest, blink left most LED for 3 seconds.
Write an Arduino code in which user can set the number of times an output LED is going to blink.
If user enters 1 then LED will blink for 1 time, if user enters 5 then LED will blink for 5 times and
if user enters 10 then LED will blink for 10 times. Make sure your program is generic and not hard
coded. Use only “if-else” statements and some variables to count the number of iterations. Add
blinking delay of 0.5 seconds.
Pulse Width Modulation (also called Pulse Duration Modulation) is a method of regulating
the output voltage by varying the width, but not the height, of a train of pulses that drives a power
switch. By continuing this voltage on/off cycle with a varying duty cycle, the LED Brightness can
be varied. The waveforms in Figure-1 help to explain the way in which this method of control
operates. In each case the signal has maximum and minimum voltages of 5 V and 0V.
In waveform 1a, the signal has an ON Time-OFF Time ratio of 1:1. With the signal at 5V
for 50% of the time, the average voltage is 2.5V, so the LED will glow with half of its full
brightness.
In waveform 1b, the signal has a ON Time-OFF Time ratio of 3:1, which means that the
output is at 5V for 75% of the time. This clearly gives an average output voltage of 5x0.75=
3.75V.
In waveform 1c, the signal has a ON Time-OFF Time ratio of 1:3, giving an output signal
that is 5V for just 25% of the time. The average output voltage of this signal is just
5x0.25=1.25V.
𝑽 𝜶 𝑰 𝜶 𝑩𝒓𝒊𝒈𝒉𝒏𝒆𝒔𝒔 𝒐𝒇 𝑳𝑬𝑫
• So by varying the Voltage, we can control the brightness of LED. The desired voltage can be
generated by varying the mark-space ratio(ON/OFF Time) of the signal over the full range, it is
possible to obtain any desired average output voltage from 0V to 5V. (shown below in Figure 5)
Page | 30
Introduction to Computing Lab Manual
Figure 5
Write an Arduino Code to Control the brightness of Pin 13 LED using PWM. Generate a PWM at
10 kHz Frequency with Variable Duty Cycle entered by the user on Arduino Serial Monitor.
Note: You are not allowed to use AnalogWrite() Command
Page | 31
Introduction to Computing Lab Manual
Experiment No. 05
Control Structures: Nested If-else statement and Switch statement
OBJECTIVE:
To implement nested “if else” statements.
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the condition
is determined to be true, and optionally, other statements to be executed if the condition is determined
to be false.
Following is the general from of a typical decision making structure found in most of the programming
languages:
C++ programming language provides following types of decision making statements as shown in
table1
Table 1
Statement Description
nested if statements You can use one if or else if statement inside another if or else
if statement(s).
If Else Statement:
An if statement can be followed by an optional else statement, which executes when the boolean
expression is false.
Switch:
Switch case statements are a substitute for long if statements that compare a variable to several
values The basic format for using switch case is outlined below. The value of the variable given into
switch is compared to the value following each of the cases, and when one value matches the value
of the variable, the computer continues executing the program from that point.
Syntax:
switch(variable){
case value1 :
statement(s);
break;//optional case
value2 :
statement(s);
break;//optional
Page | 33
Introduction to Computing Lab Manual
The condition of a switch statement is a value. The case says that if it has the value of whatever is
after that case then do whatever follows the colon. The break is used to break out of the case
statements. Break is a keyword that breaks out of the code block, usually surrounded by braces,
which it is in. In this case, break prevents the program from falling through and executing the code in
all the other case statements. An important thing to note about the switch statement is that the case
values may only be constant integral expressions. Sadly, it isn't legal to use case like this:
The default case is optional, but it is wise to include it as it handles any unexpected cases. Switch
statements serves as a simple way to write long if statements when the requirements are met. Often it
can be used to process input from a user.
In a right triangle, the square of the length of one side is equal to the sum of the squares of the
lengths of the other two sides.
Write a program that prompts the user to enter the lengths of three sides of a triangle and then outputs
a message indicating whether the triangle is a right triangle.
Page | 34
Introduction to Computing Lab Manual
Post lab:
a. The roots of the quadratic equation 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0, are given by the following formula:
−𝑏 ± √𝑏 2 − 4𝑎𝑐
2𝑎
Write a program that prompts the user to input the value of ‘a’ (the coefficient of 𝑥 2 ), ‘b’ (the
coefficient of 𝑥), and ‘c’ (the constant term) and outputs the type of roots of the equation.
Case 1: 𝑏 2 − 4𝑎𝑐 = 0 Single repeated roots
b. Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for upto 100 calls.
Page | 35
Introduction to Computing Lab Manual
Experiment No. 06
Control Structures (Basic For Loop & While Loop)
OBJECTIVE:
To be able to understand the working of loops.
Repetition Statements
Repetition statements are called loops, and are used to repeat the same code multiple times in
succession.The number of repetitions is based on criteria defined in the loop structure, usually a
true/false expression.
The three loop structures in C++ are:
while loops
for loops
Three types of loops are not actually needed, but having the different forms is convenient
For Loop:
The for loop is most convenient with counting loops -- i.e. loops that are based on a counting
variable, usually a known number of iterations
Remember that the statement can be a single statement or a compound statement (block), so an
alternate way to write the format might be:
for (initialCondition; testExpression; iterativeStatement)
{
statement1;
statement2;
// ...
statementN;
}
Page | 36
Introduction to Computing Lab Manual
How it works
The initialCondition runs once, at the start of the loop
The testExpression is checked. (This is just like the expression in a while loop). If it's
false, quit. If it's true, then:
Run the loop body
Run the iterativeStatement
Go back to the testExpression step and repeat
These statements can be used to alter the flow of control in loops, although they are not
specifically needed. (Any loop can be made to exit by writing an appropriate test
expression).
break: This causes immediate exit from any loop (as well as from switch blocks)
continue: When used in a loop, this statement causes the current loop iteration to end, but
the loop then moves on to the next step.
o In a while or do-while loop, the rest of the loop body is skipped, and execution
moves on to the test condition
o In a for loop, the rest of the loop body is skipped, and execution moves on to
the iterative statement
Age is 16 or 18
Program (a):
#include <iostream>
using namespace std;
int main()
{
for (int count=1; count <= 5 ; count++)
{
int count = 1;
cout << count << "\n";
}
return 0;
}
Page | 37
Introduction to Computing Lab Manual
Program (b):
#include <iostream>
using namespace std;
int main()
{
int count = 1;
while (count <= 5)
{
int count = 1;
cout << count << "\n";
count++;
}
return 0;
}
Exercise –3 (5 points)
According to legend, the island of Manhattan was purchased from the native Indian population in
1626 for $24. Assuming this money was invested in a Dutch bank paying 5% simple interest per
year, construct a table showing how much money the native population would have at the end of each
50-year period, starting in 1626 and ending 400 years later. Write C++ code to calculate simple
interest and use for loop structure to solve this exercise.
u(0)=3
u(1)=2
u(n)=n*u(n-1)+(n+1)*u(n-2)+n
the program should generate the first n elements of the series generated by the above equation.
Page | 38
Introduction to Computing Lab Manual
Note: The material used for preparing this lab exercise has been taken from publicly available
material provided by Towson University and Oxford University.
Post Lab
Determine the pattern followed by the series below:
1, 2, 3, 5, 8, 13, 21, 34, …
Write a program that takes a number ‘n’ and prints first ‘n’ numbers of this series. For example, if
user enters 6, your program should display
1, 2, 3, 5, 8, 13
Page | 39
Introduction to Computing Lab Manual
Experiment No.07
Nested Control Structures
OBJECTIVE:
To be able to understand the working of nested control structures.
Exercise –1 (5 points)
Write a program that uses nested for – loops to print first 10 entries of tables of 1 to 10. For
example the first 10 entries of tables of 1 to 5 are given below in figures 1 & 2.
Page | 40
Introduction to Computing Lab Manual
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal
to the number itself. For example, 371 is an Armstrong number since 3^3 + 7^3 + 1^3 = 371.Write
a program to find all Armstrong number in the range of 0 and 999.
Post Lab
Write a program to calculate the place value of digit in an integer.
For example, if the user inputs an integer “6918” and you want to determine the place value of 6,
the output would be “Thousands”. You can include a check for whether that specific digit is present
or not. Your program should work for a maximum place value of “thousands”.
*Units; tens; hundreds; thousands.
Page | 41
Introduction to Computing Lab Manual
Experiment No.08
C++ Functions
OBJECTIVE:
To understand how to use pre-defined functions
To understand how to define your own functions
To get familiar with value returning functions
In C++, a function is a group of statements that is given a name, and which can be called from
some point of the program. The most common syntax to define a function is:
Where:
- ‘type’ is the type of the value returned by the function.
- ‘name’ is the identifier by which the function can be called.
- ‘parameters’ (as many as needed): Each parameter consists of a type followed by an identifier,
with each parameter being separated from the next by a comma. Each parameter looks very
much like a regular variable declaration (for example: int x), and in fact acts within the function
as a regular variable which is local to the function. The purpose of parameters is to allow passing
arguments to the function from the location where it is called from.
- ‘statements’ is the function's body. It is a block of statements surrounded by braces { } that
specify what the function actually does.
Page | 42
Introduction to Computing Lab Manual
Exercise –1 (5 points)
Write a program that will find the area and volume of sphere.
Data type for all variable should be double
double area (doubleradius): function that will take radius as input and return the area.
double volume (doubleradius): takes radius as input argument and return the volume of
sphere.
𝐴𝑟𝑒𝑎 = 4 𝜋 𝑟2
4
𝑉𝑜𝑙𝑢𝑚𝑒 = 𝜋 𝑟 3
3
Write a main function that will take radius from the user and display the area and volume, don’t
display the area and volume in the function.
Exercise –2 (5 points)
Write a void function calculateRoots( ) that takes three input parameters ‘a’, ‘b’, ‘c’; computes two
roots and display them on console. You may use pre-defined functions for taking square and square
root. Following expression calculates roots of a quadratic equation.
−𝑏 ± √𝑏2 − 4𝑎𝑐
2𝑎
Write a main( ) to test your function. Take values of ‘a’, ‘b’, ‘c’ from user.
This program solve quadratic equation only for this condition.
𝑏2 − 4𝑎𝑐 > 0
Exercise –3 (5 points)
Write a function that takes a four-digit number as input in a single variable from user and returns
the sum of its four digits. If user enters 2345, then output of program should be: 14
The input from user should be taken in main and then passed to the function as its
parameter. The output from function should be displayed on console in main.
Prototype should be void four_digit_number(int number)
Exercise –4 (10 points)
Write a function that determines the median of three input numbers. The median is the middle
number when the three numbers are arranged in order. However, the user can input the values in any
order, so your program must determine which value is between the other two. For example, if the
user enters:
41.52; 27.18; 96.03
Page | 43
Introduction to Computing Lab Manual
Exercise –5 (10 points)
The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385.The square of the
sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025.Hence the difference between
the square of the sum of the first ten natural numbers and the sum of the squares of first ten natural
numbers is 3025 − 385 = 2640.
Find the difference between the square of the sum of the first ten natural numbers and the sum of
the squares of first ten natural numbers
Post Lab
Write a program that takes as input five numbers and find the mean (average) and standard
deviation of the numbers.
Mean Function: write a function that takes 5 input arguments and return the means.
Standard Deviation Function: Write a function that will return the standard deviation.
If the numbers are x1, x2, x3, x4, and x5, then mean “x” and standard deviation “s” is given as:
(𝑥1 − 𝑥)2 + (𝑥2 − 𝑥)2 + (𝑥3 − 𝑥)2 + (𝑥4 − 𝑥)2 + (𝑥5 − 𝑥)2
𝑠= √
5
𝑥1 + 𝑥2 + 𝑥3 + 𝑥4 + 𝑥5
𝑥=
5
Page | 44
Introduction to Computing Lab Manual
Experiment No.09
Value and Reference parameters in Functions
OBJECTIVE:
To get an understanding of reference parameters
To learn the difference between value and reference parameters
A void function with value parameters are declared by enclosing the list of types for the parameter list in the
parentheses.
Example: A function that prints out a user specified number of horizontal lines is declared as:
Function Activation: To activate a void function with value parameters, we specify the name of the function
and provide the actual arguments enclosed in parentheses. The order and types of the list of arguments should
correspond exactly to those of the formal parameters declared in the function prototype. The arguments can be
constants, expressions, variables, or even function calls themselves. If an argument is a variable, at the time of
function activation, the variable must have a value.
Example:
PrintLines(8);
or
numOfLines = 5;
PrintLines(numOfLines);
We need to design software for an ATM machine. An ATM card is used for money withdrawal. The
systems needs following information of a card:
Page | 45
Introduction to Computing Lab Manual
Card Number
Initial balance
Type of card. (gold and silver)
InputCardDetails( .. ): This function should prompt the user to enter relevant details of ATM Card. Decide
the prototype yourself. Remember that variables must be declared in main only. The output from function
should be displayed on console through main.
Write the main and test your program.
WithdrawMoney(..): This function should take all the details of cards as input and ask the user the
amount he/she wants to withdraw. Following rules should be observed:
Your program should keep displaying the menu after each function call unless user wants to exit.
Algorithm of main program is given below. Convert it into C++ to test your functions accordingly
In the previous exercise add the functionality of balance enquiry or transfer money to other bank. For
this add the following functions:
BalanceInquiry(..): This function generates a message that displays card #, and current balance.
TransferMoney(..): This function should ask the user the account number to which amount has to be
transferred. It should keep a check on the balance before transferring any amount.
Your program should keep displaying the menu after each function call unless user wants to exit.
Algorithm of main program is given below. Convert it into C++ to test your functions accordingly
Page | 46
Introduction to Computing Lab Manual
Generate an inquiry about the balance
Transfer some amount
Generate an inquiry about the balance
Post Lab
Write the value of the variables in the boxes provided in Table 1.
Code – 1
# include <iostream.h>
int counter = 0;
int function1(int x, int& y)
{
counter = counter +5;
x = x*100;
y = x*10;
return x*y;
}
int function2(int& x,int& y,int &z)
{
counter = counter * 10;
x = y*z;
y = x*y;
z = z*z;
return x+y+z;
}
Table 1
Counter Result x y z
void main()
{
int x=10,y=100,z=1000;
int Result = 1;
counter++;
Result = function1(x,y);
x=1;y=2;z=3;
Result =function2(x,y,z);
}
Page | 47
Introduction to Computing Lab Manual
int Area1(int& height,int& width)
{
int a = height*width;
height = height/10;
width = width/2;
GlobalVariable1 = GlobalVariable1*10;
GlobalVariable2 = GlobalVariable2*100;
return a;
}
Table 2
area = Area(Length,Width);
area = Area(Length,Width);
area = Area1(Width,Length);
area = Area1(Length,Width);
}
Page | 48
Introduction to Computing Lab Manual
Experiment No.10
Introduction to 1-D Arrays using Arduino
OBJECTIVE
The main objective is to learn how to use arrays and loops to save and generate the filtered sensor
values
Photo resistors, also known as light dependent resistors (LDR), are light sensitive devices most often
used to indicate the presence or absence of light, or to measure the light intensity. In the dark, their
resistance is very high, sometimes up to 1MΩ, but when the LDR sensor is exposed to light, the
resistance drops dramatically, even down to a few ohms, depending on the light intensity. LDRs
have a sensitivity that varies with the wavelength of the light applied and are nonlinear devices.
They are used in many applications but are sometimes made obsolete by other devices such as
photodiodes and phototransistors. Some countries have banned LDRs made of lead or cadmium over
environmental safety concerns. A sample shown in Figure 1.
Figure 1
Schematic Diagram:
Page | 49
Introduction to Computing Lab Manual
In order to use an LDR as an analog light sensor, we need to add a resistor in series with the LDR in
order to vary the voltage with respect to light. Independent points of LDR and resistor will have a
direct connection with 5V and ground while the common point of these two components will be
attached with the analog pin of Arduino. Sample shown in Figure 2
Figure 2
Problem 1:
Read the analog values of the light sensor and display them on serial monitor.
Hint: See the examples of analog reading
Problem 2:
In the problem 1 you have observed that sensor value is not stable even if the light condition is
constant. So, in order to make it stable, apply noise filter on 20 sensor values and produce a stable
sensor value.
Hint: In noise filter, we record 20 sensor values in an array at a delay of 20ms, sort them in
ascending/descending order, discard first four and last four values and then take the average of
remaining values. The averaged value will be the stable one.
Problem 3:
Write a program that searches an array for a "key value" entered by Arduino Serial Monitor and
returns the array's index for that element and blink the LED array Index times with the delay of 500
millisecond. If the element is not found, LED should not blink.
Problem 4:
Now use the stable value of Problem 2 and compare this stable value K with array
[0,100,200,300,400,500,600,700,1000]. By using the below lookup table 1, convert this value into
binary and show this binary number on LEDs.1 represents the ON signal (LED which is to be glow)
and 0 represent the OFF Signal (LED which will remain off).
Page | 50
Introduction to Computing Lab Manual
Table 1
Problem 5(Optional):
Read the analog values of the light sensor and apply median filter. Now control the brightness of
LED using PWM with the help of stable LDR value. If the room is dark, the LED will glow at full
brightness. If the room has medium light intensity (300 to 600), generate PWM with 50 % duty
cycle. And if room has enough light intensity, generate PWM at 10 % duty Cycle. The frequency of
PWM will be 10 kHz
Page | 51
Introduction to Computing Lab Manual
Experiment No.11
File Handling
OBJECTIVE:
Things that will be covered in today’s lab:
To be able to understand the working of files and functions.
char i; Step#3
Using the variable declared in step 2, open
in_stream>>i; the file from which you want to read data.
cout<<i<<" ";
in_stream.close();
Step#4
return 0;
Just like you use cin to read data from
}
console, the ifstream variable is used exactly
the same way. This statement will read first
character from file. We can read integers or
any other data type too.
Step#5
After reading data from file, this statement is
used for closing the file.
Page | 52
Introduction to Computing Lab Manual
Step#4
Just like you use cout to write data on
console, the ofstream variable is used exactly
the same way. This statement will write value
of ain the beginning of file. We can read
integers or any other data type too
Step#5
After writing data to file, this statement is
used for closing the file
Example Codes
(A) Following code reads all integers from a file and displays on screen. Create a file
with name “myfile.txt” Enter some integers in it separated by space and save it in
the same folder in which you have saved your cpp file.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ifstream a;
a.open(“myfile.txt”);
int x;
Page | 53
Introduction to Computing Lab Manual
while(!a.eof())
{
a>>x;
cout<<x;
}
a.close();
}
(B) Following code reads all integers from a file and writes in another file. Use myfile.txt
of PART – A.
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ifstream in;
in.open(“myfile.txt”);
ofstream out;
out.open(“output_file.txt”);
int x;
while(!in.eof())
{
in>>x;
out<<x;
}
in.close();
out.close();
}
1 1 1 1
2 2 4 8
3 3 9 27
4 4 16 64
5 5 25 125
6 6 36 216
7 7 49 343
Page | 54
Introduction to Computing Lab Manual
2 3 2
10 9 8
4 5 7
2 1 0
3 3 5
………………
Exercise 3:
Write a program that reads data from a file”File_a.txt”, stores the data in an array, takes the square
of the data and then saves it in an output file”File_b.txt”. For example as in Figure 1
Post Lab
The file named fact_data.txt contains integers in each line. Write a program that reads each integer
and then finds and displays the factorial of that integer as well as write it in a file named
fact_out.txt in a new line. Factorial should be found using a function named factorial.
fact_data.txt fact_out.txt
1 1
2 2
3 6
4 24
Page | 56
Introduction to Computing Lab Manual
Experiment No.12
Character Arrays and Arrays with Functions
OBJECTIVE:
To be able to work with character arrays.
To be able to understand the working of arrays with functions.
String is a sequence of characters that is treated as a single data item and terminated by null character
‘\0’. Remember that C language does not support strings as a data type. A string is actually one-
dimensional array of characters in C language. These are often used to create meaningful and readable
programs.
For example: The string "hello world" contains 12 characters including '\0' character which is
automatically added by the compiler at the end of the string.
Remember that when you initialize a character array by listings all its characters separately then you
must supply the ‘\0’ character explicitly.Some examples of illegal initialization of character array are,
C++ does not allow to pass an entire array as an argument to a function. However, You can pass a
pointer to an array by specifying the array's name without an index.
If you want to pass a single-dimension array as an argument in a function, you would have to declare
function formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be received.
Way-1
Formal parameters as a pointer as follows:
void myFunction(int*param)
{
\\ Function definition
}
Way-2
Page | 57
Introduction to Computing Lab Manual
Formal parameters as a sized array as follows:
void myFunction(int param[10])
{
\\ Function definition
}
Way-3
Formal parameters as an unsized array as follows:
void myFunction(int param[])
{
\\ Function definition
}
Now, consider the following function, which will take an array as an argument along with another argument and
based on the passed arguments, it will return average of the numbers passed through the array as follows:
return avg;
}
#include<iostream>
usingnamespace std;
// function declaration:
double getAverage(int arr[],int size);
int main ()
{
// an int array with 5 elements.
int balance[5]={1000,2,3,17,50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance,5);
// output the returned value
cout <<"Average value is: "<< avg << endl;
return0;
}
When the above code is compiled together and executed, it produces the following result:
As you can see, the length of the array doesn't matter as far as the function is concerned because C++ performs
no bounds checking for the formal parameters.
Write a C++ program that asks the user to enter a phrase and then a single letter. The program should
then report how many times that letter occurred in the phrase, displaying the letter with double quotes
Page | 58
Introduction to Computing Lab Manual
around it. An example is shown below where the user searched for lower-case "r". Your program
should use functions appropriately.
Example:
Input:
Phrase: Programming requires effort and perseverance.
letter : r
Output:
The letter "r" occurred 6 times.
Write a program that will find the number of vowels in the string.
Define a function that must take the whole string from the main and print the number of vowels
appears in the string.
Example:
You are required to write a program which will take input from user in two integer arrays. The program
should compare both arrays for checking if both arrays are totally identical (Exactly same). Write a
boolean function which return true if arrays are totally identical otherwise return false. Example of two
identical (Exactly same) arrays:
Array1 Array2
1 1
2 2
3 3
5 5
7 7
9 9
Main function:
Declare and initialize two integer Arrays;
IsIdenticalArrays(Array1,Array2);
Output if arrays are equal or not;
Page | 59
Introduction to Computing Lab Manual
Write a function PickLarger( ) which compares the corresponding elements of array, picks the larger
element among them and saves the larger element in the output array.
Output:
Output Array: 8 2 1 5 11 10 3 5
Post Lab
Encryption can be very useful method for protecting sensitive data from intruders. Data is converted
into meaningless form by the usage of a given key and it is converted back to original form by utilizing
the key again when required. You need to design an encryption\decryption application.
Example:
Inputs:
Text: hello world , Key: 3
Outputs:
Encrypted text: khoor zruog , Decrypted text: hello world
Note:
1. Use only character arrays.
2. String Library functions are not allowed.
3. Make separate functions for encryption and decryption and write down the main function as
well to make the code interactive.
4. Usage of temporary arrays is prohibited. Both encryption and decryption should be performed
on original array.
Page | 60
Introduction to Computing Lab Manual
Project:
A detailed project description will be given to students in last 2/3 weeks of semester.
Page | 61
Introduction to Computing Lab Manual
Appendix A
Lab Evaluation Criteria
Notice:
Copying and plagiarism of lab reports is a serious academic misconduct. First instance of
copying may entail ZERO in that experiment. Second instance of copying may be reported to
DC. This may result in awarding FAIL in the lab course.
Page | 62
Introduction to Computing Lab Manual
Appendix B:
Safety around Electricity
In all the Electrical Engineering (EE) labs, with an aim to prevent any unforeseen accidents during
conduct of lab experiments, following preventive measures and safe practices shall be adopted:
Remember that the voltage of the electricity and the available electrical current in EE labs
has enough power to cause death/injury by electrocution. It is around 50V/10 mA that the
“cannot let go” level is reached. “The key to survival is to decrease our exposure to energized
circuits.”
If a person touches an energized bare wire or faulty equipment while grounded, electricity
will instantly pass through the body to the ground, causing a harmful, potentially fatal, shock.
Each circuit must be protected by a fuse or circuit breaker that will blow or “trip” when its
safe carrying capacity is surpassed. If a fuse blows or circuit breaker trips repeatedly while in
normal use (not overloaded), check for shorts and other faults in the line or devices. Do not
resume use until the trouble is fixed.
It is hazardous to overload electrical circuits by using extension cords and multi-plug outlets.
Use extension cords only when necessary and make sure they are heavy enough for the job.
Avoid creating an “octopus” by inserting several plugs into a multi-plug outlet connected to
a single wall outlet. Extension cords should ONLY be used on a temporary basis in situations
where fixed wiring is not feasible.
Dimmed lights, reduced output from heaters and poor monitor pictures are all symptoms of
an overloaded circuit. Keep the total load at any one time safely below maximum capacity.
If wires are exposed, they may cause a shock to a person who comes into contact with them.
Cords should not be hung on nails, run over or wrapped around objects, knotted or twisted.
This may break the wire or insulation. Short circuits are usually caused by bare wires
touching due to breakdown of insulation. Electrical tape or any other kind of tape is not
adequate for insulation!
Electrical cords should be examined visually before use for external defects such as: Fraying
(worn out) and exposed wiring, loose parts, deformed or missing parts, damage to outer jacket
or insulation, evidence of internal damage such as pinched or crushed outer jacket. If any
defects are found the electric cords should be removed from service immediately.
Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
Plug your heavy current consuming or any other large appliances into an outlet that is not
shared with other appliances. Do not tamper with fuses as this is a potential fire hazard. Do
not overload circuits as this may cause the wires to heat and ignite insulation or other
combustibles.
Keep lab equipment properly cleaned and maintained.
Ensure lamps are free from contact with flammable material. Always use lights bulbs with
the recommended wattage for your lamp and equipment.
Be aware of the odor of burning plastic or wire.
Page | 63
Introduction to Computing Lab Manual
ALWAYS follow the manufacturer recommendations when using or installing new lab
equipment. Wiring installations should always be made by a licensed electrician or other
qualified person. All electrical lab equipment should have the label of a testing laboratory.
Be aware of missing ground prong and outlet cover, pinched wires, damaged casings on
electrical outlets.
Inform Lab engineer / Lab assistant of any failure of safety preventive measures and safe
practices as soon you notice it. Be alert and proceed with caution at all times in the
laboratory.
Conduct yourself in a responsible manner at all times in the EE Labs.
Follow all written and verbal instructions carefully. If you do not understand a direction or
part of a procedure, ASK YOUR LAB ENGINEER / LAB ASSISTANT BEFORE
PROCEEDING WITH THE ACTIVITY.
Never work alone in the laboratory. No student may work in EE Labs without the presence of
the Lab engineer / Lab assistant.
Perform only those experiments authorized by your teacher. Carefully follow all instructions,
both written and oral. Unauthorized experiments are not allowed.
Be prepared for your work in the EE Labs. Read all procedures thoroughly before entering
the laboratory. Never fool around in the laboratory. Horseplay, practical jokes, and pranks
are dangerous and prohibited.
Always work in a well-ventilated area.
Observe good housekeeping practices. Work areas should be kept clean and tidy at all times.
Experiments must be personally monitored at all times. Do not wander around the room,
distract other students, startle other students or interfere with the laboratory experiments of
others.
Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or baggy
clothing are a hazard in the laboratory. Long hair must be tied back, and dangling jewelry
and baggy clothing must be secured. Shoes must completely cover the foot.
Know the locations and operating procedures of all safety equipment including fire
extinguisher. Know what to do if there is a fire during a lab period; “Turn off equipment, if
possible and exit EE lab immediately.”
Page | 64
Introduction to Computing Lab Manual
Appendix C:
Guidelines on preparing Lab Reports
Each student will maintain a lab notebook for each lab course. He will write a report for each
experiment he performs in his notebook. A format has been developed for writing these lab reports.
Problem Statement:
Write clearly the problem statement of each question.
Code:
#include<iostream>
usingnamespacestd;
intmain()
{
inti,temp,d,revrs=0;
}
if(revrs==i)
cout<<i<<" is palindorme";
else
cout<<i<<" is not palindrome";
}}
Output:
Screen shots of the output for various inputs are shown in Figure 1:
Page | 65