0% found this document useful (0 votes)
54 views30 pages

All Virtual Programming Lab (VPL) Exercises

The document describes a lab exercise on feature multiplicity in C++. It provides examples of conditional operators and if-else statements, as well as array initialization, to demonstrate multiple ways to accomplish operations in C++. The lab asks students to identify two other such examples and write programs to highlight feature multiplicity in C++.

Uploaded by

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

All Virtual Programming Lab (VPL) Exercises

The document describes a lab exercise on feature multiplicity in C++. It provides examples of conditional operators and if-else statements, as well as array initialization, to demonstrate multiple ways to accomplish operations in C++. The lab asks students to identify two other such examples and write programs to highlight feature multiplicity in C++.

Uploaded by

Majid Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

CS508 Virtual Programming Labs (VPLs)

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:

Conditional Operator and if – else statement:

int main()
{
int a = 5;
int b = 8;

a < b ? std::cout << "a is smaller" : std::cout << "a is greater ";
}

The above operation can also be accomplished using if – else statements:

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

int myArray[] = {1, 2, 3, 4};

//this can also be accomplished as


//int myArray[] {1, 2, 3, 4}; // both are equivalent
}

Mechanism to Conduct Lab:

Compile and run C++ code online at this link: http://cpp.sh/

Students and teacher communicate through Skype/Adobe Connect


Lab No. 2
Title: Comparison of Writ-ability and Readability of C++ and FORTRAN

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:

Area of triangle in C++:

#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 programs generate exactly same results.

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.

Mechanism to Conduct Lab:

C++ code can be compiled and run online at this link: http://cpp.sh/

Compile FORTRAN code online at this link: http://rextester.com/l/fortran_online_compiler

Students and teacher communicate through Skype/Adobe Connect


Lab No. 3
Title: Exploring SNOBOL4’s basic constructs and order of evaluation of expressions

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.

OUTPUT = "What is your name?"


Username = INPUT
Username "J" :S(LOVE)
Username "K" :S(HATE)
MEHO OUTPUT = "Hi" :(END)
LOVE OUTPUT = "How nice to meet you" :(END)
HATE OUTPUT = "Oh. It's you"

END

Solution:

Sample output when J is entered:

What is your Name?


How nice to meet you

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:

Output will be: -89.4

Mechanism to Conduct Lab:

Compile and run SNOBOL code online at this link: https://tio.run/#snobol4

Students and teacher communicate through Skype/Adobe Connect


Lab No. 4

Title: String concatenation and replacement functions in SNOBOL4

Problem:

Write complete code in SNOBOL that will perform following tasks:

1) Declare a variable having your First Name as its value.


2) Use string concatenation to append your Last Name with your First Name.
3) By using string replacement operation, replace your Last Name with your Student ID and show
the resultant output on the screen.
4) Calculate length of the string and show it on the screen.

Solution:

FIRST = 'Umair'
FULL = FIRST 'Mujahid'
FULL 'Mujahid' = 'bc120200001'
OUTPUT = FULL
LENGTH = SIZE(FULL)
OUTPUT = LENGTH
END

Mechanism to Conduct Lab:

Compile and run SNOBOL code online at this link: https://tio.run/#snobol4

Students and teacher communicate through Skype/Adobe Connect


Lab No. 5

Title: Declaring, initializing and accessing elements of an array in ADA

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:

with GNAT.IO; use GNAT.IO;


procedure Arr1 is
A: array(1..5) of Integer;
I: Integer;
begin
for I in 1..5 loop
Put("> ");
Get(A(I));
end loop;

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;

Mechanism to Conduct Lab:

Compile and run ADA code online at this link: https://tio.run/#ada-gnat

Students and teacher communicate through Skype/Adobe Connect


Lab No. 6

Title: Procedure declaration and calling mechanism in ADA

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:

with Ada.Text_IO, Ada.Integer_Text_IO;


use Ada.Text_IO, Ada.Integer_Text_IO;

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:

This is the heading for this little program.

This is line number 1 of this program.


This is line number 2 of this program.
This is line number 3 of this program.
This is line number 4 of this program.
This is line number 5 of this program.
This is line number 6 of this program.
This is line number 7 of this program.

This is the end of this little program.

Mechanism to Conduct Lab:

Compile and run ADA code online at this link: https://tio.run/#ada-gnat

Students and teacher communicate through Skype/Adobe Connect


Lab No. 7
Title: LISP functions and calling mechanism

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

(print (diffsqrt 2 3))

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:

(defun factorial (N)

(if (= N 1)
1
(* N (factorial (- N 1)))))

(print (factorial 5))

Mechanism to Conduct Lab:

Compile and run LISP code online at this link: https://tio.run/#clisp

Students and teacher communicate through Skype/Adobe Connect


Lab No. 8
Title: Converting given facts into PROLOG clauses and queries

Problem:

Convert the following facts into PROLOG clauses:

• Mary likes food


• Mary likes water
• John likes water
• John likes Mary
• Tom chases Jerry
• Dog chases Tom
• Tom eats Jerry
• Jerry eats Cheese

After writing above clauses, run the following queries:

• Does Mary like food?


• Does John like water?
• Does Tom like Jerry?
• Does Jerry like water?
• Does Jerry eat cheese?

Solution:

PROLOG clauses will be:

likes(mary,food).
likes(mary,water).
likes(john,water).
likes(john,mary).
chases(Tom,Jerry).
chases(Dog,Tom).
eats(Tom,Jerry).
eats(Jerry,Cheese).

PROLOG queries will be:

?-likes(mary,food).
?-likes(john,wine).
?-likes(Tom,Jerry).
?-likes(Jerry,water).
?-eats(Jerry,cheese).
Mechanism to Conduct Lab:

Compile and run ADA code online at this link: http://travispayton.com/Projects/compilers/prolog/

NOTE: In PROLOG editor, you’ve to first enter facts, one by one, (phase of loading database with facts)
and then write individual queries.

Students and teacher communicate through Skype/Adobe Connect.


Lab No. 9

Title: String manipulation in Java

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.*;

public class Palindrome


{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);

System.out.println("Enter a string or a number to check if it is a


palindrome");
original = in.nextLine();
int length = original.length();

for ( int i = length - 1; i >= 0; i-- )


reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

Mechanism to Conduct Lab:

Compile and run Java code online at this link: https://www.compilejava.net/

Students and teacher communicate through Skype/Adobe Connect


Lab No. 10
Title: Exploring multithreading concept in Java

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:

class ThreadClass extends Thread {


private Thread t;
private String threadName;

ThreadClass( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 5; i > 0; i--) {
System.out.println("Thread: " + threadName);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " Interrupted.");
}
System.out.println("Thread " + threadName + " Exiting.");
}

public void start () {


System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


ThreadClass T1 = new ThreadClass( "T1");
T1.start();

ThreadClass T2 = new ThreadClass( "T2");


T2.start();
}
}

Mechanism to Conduct Lab:

Compile and run Java code online at this link: https://www.compilejava.net/

Students and teacher communicate through Skype/Adobe Connect


Lab No. 11
Title: Classes, properties, and functions in C#

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 {

int basic, ta, da, hra;

public Salary() {
da = 9000;
hra = 6000;
}

public void getdata() {

Console.Write("Enter basic salary : ");


basic = int.Parse(Console.ReadLine());
Console.Write("Enter travelling allowance : ");
ta = int.Parse(Console.ReadLine());
}

public void showdata() {

Console.WriteLine("Basic salary : " + basic);


Console.WriteLine("Dearness allowance : " + da);
Console.WriteLine("Housing rent allowance : " + hra);
Console.WriteLine("Travelling allowance : " + ta);
Console.WriteLine("Gross Salary : " + (basic + da + hra + ta));
}
}

class Program {

static void Main(string[] args) {


Salary s = new Salary();
s.getdata();
s.showdata();
}
}

Mechanism to Conduct Lab:


C# code can be compiled and run on Microsoft Visual Studio (any version):
https://visualstudio.microsoft.com/
Students and teacher communicate through Skype/Adobe Connect.
Lab No. 12
Title: Variables, functions and associative arrays in PHP

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"];

// checks on input fields


if($lowerValue < 2)
$lowerValueError = "Lower value must be 2 or greater";

if(($upperValue < 0) || ($upperValue < $lowerValue))


$upperValueError = "Value must be greater than lower";

if(empty($lowerValue))
$lowerValueError = "This field is required";

if(empty($upperValue))
$upperValueError = "This field is required";

//if input fields are validated then calculate prime numbers


if(($lowerValueError == "") && ($upperValueError == ""))
primeNumberCalculator($lowerValue, $upperValue);
}

function primeNumberCalculator($lowerValue, $upperValue) {


$number = intval($lowerValue);
$limit = intval($upperValue);
global $primeNumbers;

while($number <= $limit) {


$divisorCount = 0;

for($i = 1; $i <= $number; $i++) {


if(($number % $i) == 0)
$divisorCount++;
}
if($divisorCount < 3) {
$primeNumbers[] = $number;
}
$number++;
}
}
?>

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

Mechanism to Conduct Lab:

The best way to run PHP program is to install any PHP package, for example, XAMPP server
(https://www.apachefriends.org/index.html)

Code can also be compiled and run online at: http://sandbox.onlinephpfunctions.com/

Students and teacher communicate through Skype/Adobe Connect


Lab No. 13

Title: JavaScript’s basic validation techniques

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:

• Password and Confirm Password fields must be similar


• No field should be blank
• Email must be in a correct format
• All errors should be displayed next to their text fields (where error occurs) in Red color

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>

Mechanism to Conduct Lab:

Code can be compiled and run online at: https://js.do/

Students and teacher communicate through Skype/Adobe Connect


Lab No. 14
Title: Static Binding and Dynamic Binding in Java

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{

private void eat() {


System.out.println("Cat is eating...");
}

public static void main(String args[]) {


Cat c1 = new Cat();
c1.eat();
}
}

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

class Cog extends Animal{


void eat(){
System.out.println("Cat is eating...");
}

public static void main(String args[]){


Animal a = new Cat();
a.eat();
}
}

Mechanism to Conduct Lab:

Compile and run Java code online at this link: https://www.compilejava.net/

Students and teacher communicate through Skype/Adobe Connect.


Lab No. 15
Title: Operator precedence, order of evaluation, and looping structures in C++, FORTRAN, and Python

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 g = d + e-- + f++;


cout << g << endl << endl;

int i = 0;
int j = 3;
int k = 5;
int l = i + j-- + --k;
cout << l << endl << endl;
}

Solution:

Output will be:


8
15
98
6
7
Problem 2:

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;

for ( i = 0; i < 4; i++ )


a[i] = 0;

for ( i = 0; i < 4; i++ )


cout << a[i] << '\n';

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

end program arrayProg

Loop in Python:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
Solution:

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.

Mechanism to Conduct Lab:

Compile and run C++ code online at this link: http://cpp.sh/

Compile FORTRAN code online at this link: http://rextester.com/l/fortran_online_compiler

Compile and run Python code at this link: https://www.onlinegdb.com/online_python_compiler

Students and teacher communicate through Skype/Adobe Connect.


Lab No. 16

Title: Call by value, call by reference, and decision structures in C++

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;

void mysteryFunction1(int num1, int num2);


void mysteryFunction2(int& num1, int& num2);

int main() {
int i = 10, j = 20;

mysteryFunction1(i, j);
cout << i << " " << j << endl;

mysteryFunction2(i, j);
cout << i << " " << j << endl;
}

void mysteryFunction1(int num1, int num2) {


int temp = num1;
num1 = num2;
num2 = temp;
}

void mysteryFunction2(int& num1, int& num2) {


int temp = num1;
num1 = num2;
num2 = temp;
}

Solution:

Output will be:

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 2: cout << "Number is 2";


break;

case 3:
case 4:
case 5:
case 6:
case 7:
case 8: cout << "Number is between 3 and 8";
break;

default: cout << "Number is greater than 8";


break;
}

Solution:

Compiler will not generate any error because fall-through in case statements is allowed in C++.

When user enters 3, output will be: Number is between 3 and 8


When user enters 12, output will be: Number is greater than 8
Mechanism to Conduct Lab:

Compile and run C++ code online at this link: http://cpp.sh/

Students and teacher communicate through Skype/Adobe Connect.

The End

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy