All Virtual Programming Lab (VPL) Exercises
All Virtual Programming Lab (VPL) Exercises
Lab No. 1
Title: Feature multiplicity in C++
Problem:
Feature Multiplicity of a programming language means that the language has more than one way to
accomplish a particular operation. In handouts, we’ve discussed incrementing a variable in four different
ways.
Can you enlist any two other operations that can be accomplished in different ways? Take C/C++ as an
example language and write programs to highlight feature multiplicity in C/C++ (other than
increment/decrement operations).
Solution:
Example 1:
int main()
{
int a = 5;
int b = 8;
a < b ? std::cout << "a is smaller" : std::cout << "a is greater ";
}
int main(){
int a = 5;
int b = 8;
if(a < b)
std::cout << “a is smaller”;
else
std::cout << “a is greater”;
}
Example 2:
Universal Initialization of arrays in C++
int main() {
Problem:
Write a program in C++ to calculate area of a triangle when length of three sides is given. Use Heron’s
formula as given below:
𝐴 = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)
𝑎+𝑏+𝑐
𝑠=
2
After compiling and executing, compare your C++ code with given FORTRAN code which performs
similar function. Compare your final result by taking example lengths in both cases. Are results exactly
similar in both cases? Which code, in your opinion, has better (1) Writ-ability (2) Readability?
Solution:
#include<iostream>
#include<math.h>
using namespace std
int main() {
float a = 5;
float b = 5;
float c = 5;
float s, area;
s = (a + b + c) / 2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"Area of Triangle= "<< area << endl;
return 0;
}
Area of triangle in FORTRAN:
PROGRAM Triangle
IMPLICIT NONE
REAL :: a = 5
REAL :: b = 5
REAL :: c = 5
REAL :: s
REAL :: Area
s = (a + b + c) / 2.0
Area = SQRT(s*(s-a)*(s-b)*(s-c))
WRITE(*,*) "Triangle area = ", Area
END PROGRAM Triangle
Solution:
Both C++ and FORTRAN have same writ-ability but readability in C++ is better than FORTRAN. Note that
in FORTRAN there is no semicolon at the end of the statements which may cause some confusion while
reading.
C++ code can be compiled and run online at this link: http://cpp.sh/
Problem 1:
SNOBOL is an early attempt to develop a language specifically for string manipulation. This language has
a number of design problems including poor readability, poor writ-ability, very bad choice of operators,
and GOTO statement for control flow. Our goal for teaching you a nearly 50 years old language is to
appreciate how much important design considerations should be and what really is a “bad-designed”
language.
Write the following SNOBOL code, execute it, and observe the output. Be very careful while writing code
in the editor window because any extra space-character will ruin the program. Observe the output and
try to trace out code’s control flow.
END
Solution:
Problem 2:
One of the awkward design features of SNOBOL is that you can mix and match numeric and string values
in a single expression to design some logic that is difficult to understand. For example, write the
following code in editor, run it, and try to figure out how this output is generated. Again, take special
care of space characters while writing the code.
z = '20'
x = 5 * -z + '10.6'
OUTPUT = x
END
Solution:
Problem:
Solution:
FIRST = 'Umair'
FULL = FIRST 'Mujahid'
FULL 'Mujahid' = 'bc120200001'
OUTPUT = FULL
LENGTH = SIZE(FULL)
OUTPUT = LENGTH
END
Problem:
In this lab session we’ll look how arrays are implemented in ADA and how to access arrays elements
with loops. Write ADA program that will declare an array of length 5 of integer data type. Take input
from user to populate the array and then print the array in reverse order.
Solution:
Put("[");
for I in reverse A'Range loop
Put(A(I));
if I > A'First then
Put(' ');
end if;
end loop;
Put_Line("]");
end Arr1;
Problem:
In this lab session, we’ll see how procedures are declared in ADA, their calling mechanism, and the
concept of variable scope within procedures. Look at the following code and try to figure-out what will
be the output. After you’ve determined the output, write the code in editor, compile and run it, and
compare your answer with the actual output.
Solution:
procedure myprocedure is
Counter : INTEGER;
procedure Function_1 is
begin
Counter := 1;
Put("This is the heading for this little program.");
New_Line(2);
end Function_1;
procedure Function_2 is
begin
Put("This is line number");
Put(Counter, 2);
Put_Line(" of this program.");
Counter := Counter + 1;
end Function_2;
procedure Function_3 is
begin
New_Line;
Put_Line("This is the end of this little program.");
end Function_3;
begin
Function_1;
for Index in 1..7 loop
Function_2;
end loop;
Function_3;
end myprocedure;
Solution:
Output will be:
Problem 1:
Write a LISP function to compute difference of squares. That is, if x > y return x2 – y2 otherwise
return y2 – x2
Solution:
(defun diffsqr (x y)
(if(> x y)
(-(* x x) (* y y))
(-(* y y) (* x x))))
Problem 2:
Define a recursive function in LISP to calculate factorial of a number. After defining the function, pass 5
as a parameter and print the output.
Solution:
(if (= N 1)
1
(* N (factorial (- N 1)))))
Problem:
Solution:
likes(mary,food).
likes(mary,water).
likes(john,water).
likes(john,mary).
chases(Tom,Jerry).
chases(Dog,Tom).
eats(Tom,Jerry).
eats(Jerry,Cheese).
?-likes(mary,food).
?-likes(john,wine).
?-likes(Tom,Jerry).
?-likes(Jerry,water).
?-eats(Jerry,cheese).
Mechanism to Conduct Lab:
NOTE: In PROLOG editor, you’ve to first enter facts, one by one, (phase of loading database with facts)
and then write individual queries.
Problem:
Write a program in Java that will read a string of characters or numbers from the user and will
determine if the entered string (or number) is a Palindrome or not. [A palindrome is a string that reads
the same backwards as forwards. For example: ANA, 12321]
Solution:
import java.util.*;
Problem:
Create a Thread in Java by inheriting Thread class. Implement both methods of Thread class, start()
and run() in which you can add simple print statements. Use sleep() in run() to temporarily halt
the thread. In the main method, create two threads and start them by invoking start(). Observe the
output and see how interleaving of two threads are taking place.
Solution:
Problem:
Define a class ‘Salary’ in C# which will contain member variables Basic, TA, DA, HRA. Give appropriate
default values for DA and HRA in the constructor. Calculate the salary of employee and print it on the
screen.
Solution:
using System;
class Salary {
public Salary() {
da = 9000;
hra = 6000;
}
class Program {
Problem:
Write a complete PHP program that will print Prime Numbers from the given range. Lower value and
upper value (range of numbers) will be provided by the user using HTML forms.
[Note: You can use CSS to enhance the look of page. Also try to add certain validation checks while
taking input from user [for example: lower value must not be greater than upper value etc.]
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Prime Numbers Calculator</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><link
rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
alpha.6/css/bootstrap.min.css" integrity="sha384-
rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
crossorigin="anonymous">
</head>
<body>
<?php
$lowerValue = null;
$upperValue = null;
$lowerValueError = "";
$upperValueError = "";
$primeNumbers = array();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$lowerValue = $_POST["lowerValue"];
$upperValue = $_POST["upperValue"];
if(empty($lowerValue))
$lowerValueError = "This field is required";
if(empty($upperValue))
$upperValueError = "This field is required";
<div class="container">
<div class="page-header">
<h1>Prime Numbers Calculator</h1>
<br />
</div>
<form class="form-horizontal" method="POST"
action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label class="control-label col-sm-2">Lower Value:</label>
<div class="col-sm-4">
<input type="text" class="form-control"
name="lowerValue" value="<?php echo $lowerValue; ?>">
</div>
<div class="col-sm-6 form-control-static">
<?php echo "<p class='text-danger'>$lowerValueError</p>"; ?>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Upper Value:</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="upperValue"
value="<?php echo $upperValue; ?>">
</div>
<div class="col-sm-6 form-control-static">
<?php echo "<p class='text-danger'>$upperValueError</p>"; ?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">
Calculate Primes</button>
</div>
</div>
</form>
</div>
<div class="container">
<?php
if(!empty($primeNumbers)) {
echo "<h4> Prime Numbers between " . $lowerValue . " and " .
$upperValue . " are: <br /> </h4>";
foreach($primeNumbers as $value)
echo $value . " ";
}
?>
</div>
</body>
</html>
The best way to run PHP program is to install any PHP package, for example, XAMPP server
(https://www.apachefriends.org/index.html)
Problem:
Write a complete HTML code that will take input from user and then validate entered input using
JavaScript. Program will collect First Name, Last Name, Email, User ID and Password. Validation checks
will be as follows:
Solution:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
var divs = new Array();
divs[0] = "errFirst";
divs[1] = "errLast";
divs[2] = "errEmail";
divs[3] = "errUid";
divs[4] = "errPassword";
divs[5] = "errConfirm";
function validate()
{
var inputs = new Array();
inputs[0] = document.getElementById('first').value;
inputs[1] = document.getElementById('last').value;
inputs[2] = document.getElementById('email').value;
inputs[3] = document.getElementById('uid').value;
inputs[4] = document.getElementById('password').value;
inputs[5] = document.getElementById('confirm').value;
var errors = new Array();
errors[0] = "<span style='color:red'>Please enter your first name!</span>";
errors[1] = "<span style='color:red'>Please enter your last name!</span>";
errors[2] = "<span style='color:red'>Please enter your email!</span>";
errors[3] = "<span style='color:red'>Please enter your user id!</span>";
errors[4] = "<span style='color:red'>Please enter your password!</span>";
errors[5] = "<span style='color:red'>Please confirm your password!</span>";
for (i in inputs)
{
var errMessage = errors[i];
var div = divs[i];
if (inputs[i] == "")
document.getElementById(div).innerHTML = errMessage;
else if (i==2)
{
var atpos=inputs[i].indexOf("@");
var dotpos=inputs[i].lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=inputs[i].length)
document.getElementById('errEmail').innerHTML = "<span style='color: red'>
Enter a valid email address!</span>";
else
document.getElementById(div).innerHTML = "OK!";
}
else if (i==5)
{
var first = document.getElementById('password').value;
var second = document.getElementById('confirm').value;
if (second != first)
document.getElementById('errConfirm').innerHTML = "<span style='color: red'>
Your passwords don't match!</span>";
else
document.getElementById(div).innerHTML = "OK!";
}
else
document.getElementById(div).innerHTML = "OK!";
}
}
function finalValidate()
{
var count = 0;
for(i=0;i<6;i++)
{
var div = divs[i];
if(document.getElementById(div).innerHTML == "OK!")
count = count + 1;
}
if(count == 6)
document.getElementById("errFinal").innerHTML = "All data is correct";
}
</script>
</head>
<body>
<table id="table1">
<tr>
<td>First Name:</td>
<td><input type="text" id="first" onkeyup="validate();" /></td>
<td><div id="errFirst"></div></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="last" onkeyup="validate();"/></td>
<td><div id="errLast"></div></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" id="email" onkeyup="validate();"/></td>
<td><div id="errEmail"></div></td>
</tr>
<tr>
<td>User Id:</td>
<td><input type="text" id="uid" onkeyup="validate();"/></td>
<td><div id="errUid"></div></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="password" onkeyup="validate();"/></td>
<td><div id="errPassword"></div></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" id="confirm" onkeyup="validate();"/></td>
<td><div id="errConfirm"></div></td>
</tr>
<tr>
<td><input type="button" id="create" value="Create"
onclick="validate();finalValidate();"/></td>
<td><div id="errFinal"></div></td>
</tr>
</table>
</body>
</html>
Problem:
Write two separate Java programs that will highlight the difference between Static Binding and Dynamic
Binding. [Note: You can make any logic of your programs]
Solution:
There can be many solutions. One of them is provided below:
Static Binding: When type of object is determined at compile time, it is called static binding.
class Cat{
Dynamic Binding: When type of object is determined at run time, it is called dynamic binding.
class Animal{
void eat() {
System.out.println("animal is eating...");
}
}
Problem 1:
Try to determine the output of Print statements in the space provided below. After that, compile and
run the code and compare your answer with actual results.
#include <iostream>
using namespace std;
int main() {
int a = 0;
char c = 'b';
int d = 1;
int e = 1;
int f = 4;
int x = 10 - 3 % 8 + 6 / 4;
cout << x << endl << endl;
int y = 17 - 8 / 4 * 2 + 3 - ++a;
cout << y << endl << endl;
int z = c;
cout << z << endl << endl;
int i = 0;
int j = 3;
int k = 5;
int l = i + j-- + --k;
cout << l << endl << endl;
}
Solution:
Consider the following programs that are iterating on an array to print its elements. Compare these
codes and evaluate them in terms of readability and writ-ability.
Loop in C++:
#include<iostream>
using namespace std;
int main() {
int a[4];
int i;
Loop in FORTRAN:
program arrayProg
real :: numbers(5)
do i=1,5 !initializing
numbers(i) = i * 2.0
end do
do i = 1, 5 ! printing
Print *, numbers(i)
end do
Loop in Python:
As can be seen from given code, Python has far less lines than C++ and FORTRAN. Also these lines are
easily understandable. Hence it has higher writ-ability and readability as compared to other two
languages.
Problem 1:
Try to determine output of following program (C++). After that, run the code and compare your result.
[Hint: In one function, parameters are passed by value and in second function, parameters are passed
by reference]
#include<iostream>
using namespace std;
int main() {
int i = 10, j = 20;
mysteryFunction1(i, j);
cout << i << " " << j << endl;
mysteryFunction2(i, j);
cout << i << " " << j << endl;
}
Solution:
10 20
20 10
Problem 2:
Try to determine the output of following program if user enters (a) 3 and (b) 11.
After that run the code and compare your result. Some of the cases do not have any statement. Will
compiler generate syntax error?
#include <iostream>
using namespace std;
int main() {
int i;
cout << "Enter a number between 1 and 20" << endl;
cin >> i;
switch (i) {
case 1: cout << "Number is 1";
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8: cout << "Number is between 3 and 8";
break;
Solution:
Compiler will not generate any error because fall-through in case statements is allowed in C++.
The End