Вы находитесь на странице: 1из 63

EL-116 – INTRODUCTION TO

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

Date: August 30, 2014

Last Updated by: Mr. Muhammad Waheed Faraz, Ms. Sara Kiran & Mr. Umar Bashir

Date: August 19, 2019

Approved by the HoD: Dr. S.M Sajid


Date : August 19, 2019

Page | 4
Introduction to Computing Lab Manual

Table of Contents
Sr. Description Pg.
No. No.
1 List of Equipment 06

2 Experiment No. 01: Introduction to Scratch 07

3 Experiment No. 02: Game making using Scratch 16

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

8 Experiment No. 07: Nested Control Structures 40

9 Experiment No. 08: C++ Functions 42

10 Experiment No. 09: Value and Reference parameters in Functions 45

11 Experiment No. 10: Introduction to 1-D Arrays using Arduino 49

12 Experiment No. 11: File Handling 52

13 Experiment No. 12: Character Arrays and Arrays with Functions 57

14 Project 61

15 Appendix A: Lab Evaluation Criteria 62

16 Appendix B: Safety around Electricity 63

17 Appendix C: Guidelines on preparing Lab Reports 65

Page | 5
Introduction to Computing Lab Manual

List of Equipment
Sr. No. Description

1 Workstations (PCs)

2 Visual Studio 2012 C++ (software)

Page | 6
Introduction to Computing Lab Manual

Experiment No. 01
Introduction to Scratch

OBJECTIVE:

Get familiar with the scratch environment


To be able to write pseudo-codes for simple tasks
To be able to solve a problem from computing perspective

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

How to use Scratch:

Go Online to Scratch. http://scratch.mit.edu.


Look at the Scratch video tutorials. You can go to YouTube and search Scratch
tutorial, or you can go to Video tutorials instead to learn the basics.
Download other people's projects to your Scratch computer program, look at how they
set it up, and see what you can learn.

Problem 1: Introduction to various tabs of scratch

For reference Website: http://scratch.mit.edu/

Page | 7
Introduction to Computing Lab Manual

Things to know before getting started:


INPUT:Input is the value entered by user that goes into the program and is used within. In
scratch we can get input through the control ‘ask’ under ‘Sensing’
tab.
OUTPUT:Output is the value given out by a program after some computation. In scratch we can
show output by the control ‘say’ under Looks tab.

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

CONTROL OPERATORS: (depicted in Figure 4)


These operators control the program flow based on some logics.
If blocks are used to test conditions. If the condition is true then control enters
in the if block otherwise statements are skipped.

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

Step:3 In place of ‘what’s your name?’ in ask block


type in ‘Hi! I am 7 years old. How old are you?’
Shown in Figure 7.

Figure 7

Step:4 Go to the tab ‘Data’ click on the button


‘Make a Variable’. A dialogue box will appear
on the screen. You can type appropriate variable
name like input_age in textbox. We want to
store user age in this variable as depicted in
Figure 8.
Figure 8

Step:5 When you click ‘ok’ you will see the icon
of that variable along with other options.
(shown in Figure 9)

Figure 9

Step:6 Drag the block and


join it with as
shown in Figure 10.

Page | 9
Figure 10
Introduction to Computing Lab Manual

Step:7 The ask block stores the input to by default


variable ‘answer’. Click ‘Sensing’ under scripts tab
and locate answer. We want to get the value of
answer in the created variable input_age.
(shown in Figure 11)

Figure 11

Step:8 Drag the answer block and merge it


in set block as shown in figure 12

Figure 12

Step:9 Under control tab, drag if-then block as


shown in figure 13.

Figure 11

Step:10 Under operations tab drag ‘less than


control block’ in sprite editor. (Figure 14)

Figure 12

Suppose sprite age is 7. Now compare user input age


with 7. As we know if the user age is less than sprite
age which is 7 then the user is younger than sprite.
Go to the data tab again and merge input_age variable
in ‘less than control block’. At the end you will have
something similar to figure 15
Figure 13

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 .

Step:11 Now merge the less than block in the


if- then block like in figure 16.

Page | 10

Figure 14
Introduction to Computing Lab Manual

After merging if-then block, looks like in the figure 16.


Step:12 From the looks tab drag say block to the editor.

Step:13 Type in the say block ‘You are


younger to me!’ in place of Hello & merge say
block in the if-then block as in figure 17. Now
if the user input age is less than sprite age
which is 7 then ‘You are younger to me!’
output will be shown.
Figure 15

Step:14 Drag another if-then block from control


tab. Drag equal block from operators tab (Figure
18).
Figure 16

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.

Drag ‘say’ block under ‘Looks’ tab and type in


‘You are of my age!’ in place of hello and then
merge the say block in if-then block as shown
in Figure 19.

Figure 19

Step:16 Repeat step 14 & 15 but this time with


the ‘greater than’ block under operators. Type in
the say block ‘You are elder than me’. At the end
you will have third if-then block as in Figure 20.

Figure 20
Step:17 Merge all if-then block.

Step:18 Merge remaining two blocks together as


in Figure 21.
Page | 11

Figure 17
Introduction to Computing Lab Manual

Step:19 Go to the events tab and drag ‘when space


key pressed block’ to the editor. Merge it with the
other block, shown in Figure 22.

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.

Step:2 Test all the inputs and test your age


comparison with the age of sprite. Enjoy running the
code by pressing space character 
 Figure 19

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

Step:3 Change default repetitions from 10 to 3. Shown in Figure 26.

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.

Problem 1: Create a Scratch project


Follow the following steps to do interesting and fun things with scratch. Implement these and
observe the outcome:
1. Rainbow Fish: Learn to change the color of your sprite
Shown in figure 29.

2. Whirling Butterfly: Learn to change your sprite’s


graphic effects by moving your mouse.
As shown in Figure 29.

Figure 29

3. Beat It : Learn to move your sprite to a drum beat (figure


30)

Figure 30

4. Haunted Scratch: Learn to add your own


background and create a dialog for a story
as shown in Figure 31.

Figure 31 Page | 14
Introduction to Computing Lab Manual

Problem 3: Create a random walk

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:

& to give you:

combine this with move 10 steps)

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.

Problem 4: Create a simple animation

Create a simple animation in which a sprite of your choice walks in a line and bounces along the
edges. You can use:

and and some loop command. Make sure the animation


stops when some criterion (e.g., space bar pressed or mouse clicked) is met.

Now you can extend the animation to do something interesting like walk the sprite in a circle or a
rectangle.

Problem 5: Make your sprite move in circle

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

Design any game on scratch.

Page | 15
Introduction to Computing Lab Manual

Experiment No. 02
Making game using Scratch

OBJECTIVE:

To be able to write pseudo-codes for game using scratch.

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

STEP-4: Catch it (Catch sprite 1 using sprite 2) shown in Figure 4

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:

 To be able to use Visual Studio for compiling simple C++ Programs.


 To be able to understand I/O environment in C++
 To get familiar with data types
 To be able to understand and solve a programming problem using C++ arithmetic
expressions.

Section – 1: Microsoft Visual Studio tutorial

1) Start menu->Microsoft Visual Studio 2012->Visual C++ Development Settings->


Start Visual Studio as depicted in Figure 1

Figure 1

2) Microsoft Visual Studio->File->New->Project (shown in Figure 2,3 & 4)

Page | 19
Introduction to Computing Lab Manual

Enter Project Name


You may change Location from

Figure 2

Figure 3

Page | 20
Introduction to Computing Lab Manual

Figure 4

3) Creating a CPP file:


Right click on Source Folder-> Add->New Item then following window will be opened as shown
in Figure 5

1
2

3 Write your filename here

Figure 5

Page | 21
Introduction to Computing Lab Manual

4) Type following in code window. It will look like in the figure 6.

#include <iostream>
using namespace std;
void main()
{
cout<<”hello world”;
}

Paste your code here

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

Basic Data Types:

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 - 2 (10 points)


Declare three variables (A,B,C) of type int in C++. Take input from console in each
variable. Now write code such that following is displayed on screen:
A B C
[A]*2 [B]*2 [C]*2
[A]+3 [B]+2 [C]+2

Exercise - 3 (5 points)
Write a code in C++ to display following on console:
*
**
***
****

Exercise - 4 (10 points)


Write a C++ program that displays a table of 15 entries that contains square and cube of
numbers. An excerpt from table is shown.

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

b. Print RC circuit on the console window. Sample is given below in Figure 8.

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.

Syntax: The syntax of an if...else statement in C++ is:


if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else
block of code will be executed.

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

Figure 2. Basic Arduino board

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.

Exercise –2(10 points)

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.

Exercise –3(10 points)

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

Exercise –4(10 points)

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

Exercise –5(10 points)

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.

Exercise –6(10 points)

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(PWM)

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

Exercise –7(10 points) [Optional]

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

if statement An if statement consists of a boolean expression followed by


one or more statements.

if...else statement An if statement can be followed by an optional else statement,


which executes when the boolean expression is false.

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.

Syntax: The syntax of an if...else statement in C++ is:


if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else
block of code will be executed.
Page | 32
Introduction to Computing Lab Manual

If Else if Else Statements:


An if statement can be followed by an optional else if...else statement, which is very useful to test
various

conditions using single if...else if statement.


When using if , else if , else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax: The syntax of an if...else if...else statement in C++ is:


if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
elseif( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
elseif( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}

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

// you can have any number of case statements.


default://Optional
statement(s);
}

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.

Exercise - 1(5 points)

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.

Exercise - 2(10 points)


Any year is input by the user. Write a program to determine whether the year is a leap year or not.
How to determine whether a year is a leap year
To determine whether a year is a leap year, follow these steps:

1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.


2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
4. The year is a leap year (it has 366 days).
5. The year is not a leap year (it has 365 days).

Exercise –3(10 points)


Write a program in C++ using if else operator to find the grade of a student. The program should
prompt the user to enter marks.
The details are as follows:

marks >= 90 Grade A


marks >= 75 Grade B
marks >= 60 Grade C
marks >= 45 Grade D
else Grade F

Exercise –4(10 points)


Write a C++ program to design a calculator. The program should take 2 integers ‘a’ and ‘b’ and an
operator ‘ch’ of your choice. For example,

Page | 34
Introduction to Computing Lab Manual

if a=2 and b=3 and ch=+, then output would be a+b=5

if a=2 and b=3 and ch=*, then output would be a*b=6

Your calculator should be able to perform all the operations below:


1. If ch = ‘+’ then calculate add = a + b and display the addition result.
2. If ch= ‘- ‘then calculate sub = a – b and display the subtraction result.
3. If ch= ‘*’ then calculate mul = a * b and display the multiplication result.
4. If ch= ‘/’ then calculate div = a / b and display the division result.
5. If ch=’%’ then calculate mod = a % b and display the modulus result.
6. Otherwise display invalid operator

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

Case 2:𝑏 2 − 4𝑎𝑐 > 0 Two real roots

Case 3:𝑏 2 − 4𝑎𝑐 < 0 Two Complex roots

b. Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for upto 100 calls.

 Plus Rs. 0.60 per call for next 50 calls.


 Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 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

while and do-while loops: Format of while loop:


// while loop format
while (expression)
{
statement1;
statement2;
// ...
statementN;
}
How they work:
The expression is a test condition that is evaluated to decide whether the loop should repeat or not.
 true means run the loop body again.
 false means quit.
The while and do/while loops both follow the same basic flowchart -- the only exception is that:
 In a while loop, the expression is tested first
 In a do/while loop, the loop "body" is executed first.

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

Special statements: break and continue

 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

Exercise –1 (10 points)


Write a C++ relational expression for each:

 TaxRate is over 25% and Income is less than $2000

 LabTime is not equal to 0 minutes and LabTime is greater then 90 minutes

 Temperature is less than or equal to 75 or Humidity is less than 70%.

 Age is over 21 and Age is less than 25

 Age is 16 or 18

Exercise –2 (10 points)


For loops can always be re-written as while loops, and vice-versa. Are the following two programs
equivalent, and what is their output? Explain your answer, and run the programs to check.

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

Exercise –4 (10 points)


Write a C ++ program that calculates the sum and factorial of the integers for each integer from
1 to n. Where n is a positive integer that you enter.
 You are required to only use while loop structure in this question.
 Your program should produce the output below. Use setw to set the field widths for each
column. (Hint: The positive integer is used to control a loop.)
integer sum factorial
===============================
1 1 1
2 3 2
3 6 6
4 10 24
5 15 120
6 21 720
7 28 5040

Exercise –5 (10 points)


Write a C++ program that asks the user to type an integer N and compute u(N) defined as:

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

For example, if the user enters:

N=3 N=4 N=5


Output =3,2,15 Output=3,2,15,56 Output=3,2,15,56,303

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.

Exercise –2 (10 points)


Write a C++ program that takes 2 integers (i) a starting number and (ii) the number of elements in
last row. Then print the data in form of a lower triangular matrix. For example (shown in table 2), if:
Table 2

Starting number=10 Starting number=1 Starting number=20


Elements in last row=3 Elements in last row=4 Elements in last row=2
10 1 20
11 12 2 3 21 22
13 14 15 4 5 6
7 8 9 10

Page | 40
Introduction to Computing Lab Manual

Exercise –3 (10 points)


Design and write a C++ program that takes as input an integer larger than 1 and calculates the sum
of the squares from 1 to that integer. The output should be the value of the squares and the sum,
properly labelled on the screen.
For example, if the integer equals “4”, your program would display:
1
4
9
16
Sum=30

Exercise –4 (10 points)

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

Functions allow to structure programs in segments of code to perform individual tasks.

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:

type name ( parameter1, parameter2, ...) { statements }

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.

Let's have a look at an example:


// function example
#include <iostream>
usingnamespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout <<"The result is "<< z;
}
This program is divided in two functions: addition and main. Remember that no matter the order
in which they are defined, a C++ program always starts by calling main. In fact, main is the only
function called automatically, and the code in any other function is only executed if its function
is called from main (directly or indirectly).

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

Then the program would output:


The median of 41.52, 27.18 and 96.03 is 41.52

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

Functions with Value Parameters


Function Declaration: A value parameter is used to pass information into a function to be processed. Remember
the general form for a function declaration:

type function-name (formal parameter type list);

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:

// Purpose: Print out a number of lines


// Precondition: numOfLines has a value assigned.
// Postcondition: the number of lines are printed.
void PrintLines(int);

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

Void Functions with Reference Parameters


Function Declaration: The second type of parameter in C++ is called a reference parameter. These parameters
are used to send back a value (output), or both to send in and out values (input and output) from functions.
Reference parameters have the ampersand (&) following their type identifier in the function prototype and
function heading.
Example: A function that reads and returns (output) the length and width of a rectangle entered by the user,
is declared as:

// Purpose: Read and return the length and width of a rectangle


// Postcondition: the values of the two arguements are read
void GetData(int& length, int& width);
Exercise – 1 (10 points)

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.

Exercise – 2 (10 points)


In the previous exercise add the with draw money functionality.

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:

 For Silver card: Money to be withdrawn cannot be more than 10000.


 For Gold card: Money to be withdrawn cannot be more than 25000.

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

 Declare all required variables in main


 Get input of a card from user
 Display the menu
 Withdraw some amount

Exercise – 3 (10 points)

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

 Declare all required variables in main


 Get input of a card from user
 Display the menu
 Withdraw some amount

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

Code - 2 . Write answers in table 2


#include <iostream.h>
int GlobalVariable1 =100;
int GlobalVariable2 = 10;
int Area(int height,int width)
{
height = 2+width;
width = 5+height;
int a = height*width;
GlobalVariable1++;
GlobalVariable2++;
return a;
}

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

GlobalVaraible1 GlobalVariable2 Width Length Area


void main()
{
int Width = 10;
int Length = 20;
int area = 0;

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

Introduction About LDR

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

Binary LEDs Status


K Numbers
0<K <100 000 all LEDs off
100<K<200 001 Glow right most led.
200<K<300 010 Glow the middle LED
Glow the two right most
300<K<400 011 LEDs.
400<K<500 100 Glow the left most led.
Glow the right and left most
500<K<600 101 LEDs
600<K<700 110 Glow the two left most LEDs.
700<K<1000 111 Glow All LEDs.

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.

Reading data from file


Step#1
#include<fstream>
fstream library is included in order to
#include<iostream>
read/write from/to file.
using namespace std;

int main() Step#2


{ In order to read from file, a variable is
ifstreamin_stream; declared of type ifstream (Input stream).
in_stream.open("infile.txt");

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.

Using built in function of fstream


class
To read file till end: eof() is a function already defined in
while(!in_stream.eof()) fstream class. It returns 0 if file handle has
{ not reached to end of file
in_stream>>i;
//do any required processing on data
}

Page | 52
Introduction to Computing Lab Manual

Writing data to file


Step#1
#include<fstream>
fstream library is included in order to
#include<iostream>
using namespace std; read/write from/to file

int main() Step#2


{ In order to write data to file, a variable is
Ofstream o_stream; declared of type ofstream (output stream)
o_stream.open("ofile.txt");
int a = 10;
Step#3
o_stream<<”Hello World”; Using the variable declared in step 2, open
o_stream<<a; the file to which you want to write data. If file
does not exist then a new file with name
“ofile” is created. If a file exists already then
o_stream.close(); previous data is removed.
return 0;
}

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

Exercise 1: (10 points)


Modify the code B in Exercise - 1 such that it reads all integers from an input file and writes the
number, square of that number and cube of that number separated by tab to an output file.
Sample input and output files are given below. Use pow function of cmath library.

Input file Output file

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

Write your code and output here:

Exercise 2: (10 points)


File “quiz_result.txt” stores the result of three quizzes for 20 students. The format of the file is
shown below. The first column in the file lists the marks of first quiz, second columns lists the
marks of second quiz and third column is for third quiz. Write a program, which reads the marks
of all the quizzes for each student, and calculate and display the total marks obtained by each
student.
quiz_result.txt

2 3 2
10 9 8
4 5 7
2 1 0
3 3 5
………………

Write your code and output here:

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

File_a.txt Array1 File_b.txt


4 4 16
9 9 81
7 7 49
2 2 4
Figure 21

Now run your program on 10 numbers.


Page | 55
Introduction to Computing Lab Manual

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 and Character array

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.

Declaring and Initializing a string variables

There are different ways to initialize a character array variable.


char name[10]="StudyTonight"; //valid character array initialization

char name[10]={'L','e','s','s','o','n','s','\0'};//valid initialization

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,

char ch[3]="hell"; //Illegal


char str[4];
str="hell"; //Illegal

Arrays with Functions:

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:

double getAverage(int arr[],int size)


{
int i, sum =0;
double avg;
for(i =0; i < size;++i)
sum += arr[i];
avg =double(sum)/ size;

return avg;
}

Now, let us call the above function as follows:

#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:

Average value is:214.44

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.

Exercise –1 (10 points)

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.

Exercise –2 (10 points)

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:

Input: hard work is a key to success.


Output: 8

Exercise –3 (10 points)

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:

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

Exercise – 4 (10 points)

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.

Sample Input and Output:


Input:
Array 1: 1 2 1 5 9 1 3 5
Array 2: 8 2 1 0 11 10 3 4

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.

 Write a C++ code for the above problem

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

Labs with projects


1. Experiments and their report 50%
a. Experiment 60%
b. Lab report 40%

2. Quizzes (3-4) 15%


3. Final evaluation 35%
a. ProjectImplementation 60%
b. Project report and quiz 40%

Labs without projects


1. Experiments and their report 50%
a. Experiment 60%
b. Lab report 40%
2. Quizzes (3-4) 20%
3. Final Evaluation 30%
i. Experiment 60%
ii. Lab report, pre and post
experiment quiz 40%

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.

Sample Lab Report for Programming Labs

Problem Statement:
Write clearly the problem statement of each question.

Code:
#include<iostream>

usingnamespacestd;
intmain()
{
inti,temp,d,revrs=0;

cout<<"enter the number to check :";


cin>>i;
temp=i;
while(temp>0)
{
d=temp%10;
temp/=10;
revrs=revrs*10+d;

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

Fig.1. Screen shot of the output

Learning Outcome: What have you learned in this lab

Page | 65

Вам также может понравиться