You are on page 1of 114

LAB

MANUAL
Course: IT-102-Computer Programming

Institute of Information Technology

Learning Procedure
1) Stage J (Journey inside-out the concept)
2) Stage a1 (Apply the learned)
3) Stage v (Verify the accuracy)
4) Stage a2 (Assess your work)

1
Table of Contents

Lab # Topics Covered Page #

Lab # 01 Introduction to Flowcharting using Raptor


Basic Flowcharting symbols and their use
Lab # 02 Selection and Iteration Symbols in Raptor and their usage
Lab # 03 Visual Studio Installation
First Program in C++
Lab # 04 if-else structure, nested if statements

Lab # 05 for loop, nested for loops

Lab Sessional 1

Lab # 06 while and do-while loops

Lab # 07 Methods

Lab # 08 Arrays (1-D & 2-D)


Passing arrays to methods
Lab # 09 Strings

Lab # 10 Methods Overloading


Recursion
Lab Sessional 2

Lab # 11 File handling I

Lab # 12 File handling II

Lab # 13 Test cases

Terminal Examination

IT-102-Computer Programming 2
LAB # 01

Statement Purpose:
The objective of this lab is to make student familiar with basic programming concepts
using flowcharting techniques.

Activity Outcomes:
This lab teaches you the following topics:
 An introduction to Raptor/Visio Tool
 Basic flowchart Symbols
 Creating, Running and Saving flowcharts in Raptor/Visio

IT-102-Computer Programming 3
1) StageJ(Journey)

Introduction:
Make yourself familiar with the Raptor/Visio Tool

1.1 Understand the symbols for Input, Process and Output


1.2 Placing symbols and saving your first flowchart
1.3 Running the flowchart and getting the output in console

Making program flowcharts is a powerful technique for logic building and


learning syntax free programming. Using Raptor/Visio, a GUI based drag
and drop tool you can easily test your logic building skill, just drape your
logic with the syntax of any programming language and claim yourself to
be a programmer.

IT-102-Computer Programming 4
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Create flowchart for “Hello World”

Solution:

Launch Raptor/Visio , you will see two set of windows, the main working
pane and the console window.

The main window is where you can drag and drop symbols and test your logic
while the console window gives you output and some basic information
regarding the last execution done.

The start and end symbols are placed by default.

IT-102-Computer Programming 5
Task 1.1: Hello World and it's Execution

➜ Pick the output symbol from symbols pane and drag it in between the start
and end symbol, the application might ask you to save your work, give it a
meaningful name like HelloWorld and it
will be saved with rap extension.

➜ Single click inside the output symbol to


select it.
➜ Double click inside the output symbol
and you will see a popup window asking
what you want to output.

➜ In the output popup window type (with


double quotes) “Hello World”.

➜ You can optionally change the speed of


execution using the scrolling pointer
given immediately after the buttons
toolbar.

IT-102-Computer Programming 6
Activity 2:
Flowchart for calculating Area of Circle

Solution:
The formula to calculate area of circle is
Area = 3.1415 * radius * radius
It's clear that the only variable in the above formula is “radius” of the circle, this means
we require it as an input from user to get a meaningful answer of the expression.

➜ Select the New option from File menu



Place the Input Symbol from the list of symbols.

Place the Assignment Symbol just below the Input Symbol.

Finally place an Output Symbol after the Assignment and just
before the End Symbol.

➜ Double click on the input symbol and tell the


Raptor/Visio the message you want to display
in the Prompt section and the variable name in
which you want to store the input from the
user.

➜ Double click the Assignment Symbol and


introduce a new variable named “area” in the Set
field and the formula for expression in the “to”
field.

➜ Double click the Output Symbol and tell the


Raptor/Visio what you want to display as output,
the literal message in double quotes concatenated
with the plus symbol and the variable whose value
you want to display.

"The Area of Circle with Radius " + radius + " is


" + area

➜ Execute the flow chart, give the required input for “radius” and verify the output.

IT-102-Computer Programming 7
IT-102-Computer Programming 8
Activity 3:
Update Activity 2 to calculate Perimeter of Circle (2*3.1415*radius) along with Area

3) Stage v (verify)

Home Activities:
1. Create a flowchart that prompts the user to enter two points (x1, y1) and (x2, y2) and
displays their distance between them. The formula for computing the distance is
sqrt((x2 - x1)2 + (y2 - y1)2). Note that you can use the built-in method sqrt(x) for
calculating square root of a given number.

2. Given an airplane’s acceleration a and take-off speed v, you can compute the minimum
runway length needed for an airplane to take off using the following formula:
length = (v * v)/(2*a)
Draw a flowchart that prompts the user to enter v in meters/second and the acceleration a in
meters/second squared and displays the minimum runway length.

4) Stagea2(assess)
Lab Assignment and Viva voce

IT-102-Computer Programming 9
LAB # 02

Statement Purpose:
The objective of this lab is to make student understand the basic concepts of selection
and looping using flowcharting technique in Raptor/Visio .

Activity Outcomes:
This lab teaches you the following topics:
 At the end of this lab student will know how to develop logic of a program
 Students will get clear understanding of two important Problem-Solving techniques which
are:
o Selection
o Iteration or Looping

Instructor Note:
As pre-lab activity, the concepts from Chapter 3 and Chapter 5 are covered from the
book (Program Design with C++ by Walter Savitch).

Although it’s too early to go in to the details of selection and looping in second lab but a
quick overview and concept of both can be introduced so that students can practice the
two important options given in the Raptor/Visio ’s symbol list.

IT-102-Computer Programming 10
1) StageJ(Journey)

Introduction
Selection
Selection means selecting a set of statements for execution under a certain condition, the condition
should a logical test involving logical and relational operators, e.g. display A/B only when B is not
equal to zero, means we have to test B for the specific value of zero.

Raptor uses the symbol

for selection type statements .

the diamond symbol represents the logical test and YES branch
means execution path when condition evaluates to be true, obviously NO side branch represents
execution path when the condition evaluates to be false.

Iteration or Looping
Iteration means repetition i.e. to repeat a set of statements a certain number of times or to repeat
the statements until a specific condition is met, e.g. if the user enters a negative value for his age
then ask him to enter the age repeatedly until he enters a value greater than zero.

Raptor uses the symbol

for looping.

IT-102-Computer Programming 11
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Draw a flowchart that tells user whether the Integer entered is Even or Odd Number,
use % symbol to test the remainder value.

Solution:

IT-102-Computer Programming 12
Activity 2:
Draw a flowchart to accept two values from user and display the larger one.

Solution:

IT-102-Computer Programming 13
Activity 3:
Draw a flowchart for a program that reads two numbers and displays the number series
from first to last number.

IT-102-Computer Programming 14
3) Stagev(verify)

Home Activities:
1. Draw a flow chart to calculate the Sum of series from Starting to Ending Number, the
increment per cycle is also entered by the user.
2. Construct flow chart to Calculate Factorial of a Number entered by the user.

4) Stagea2(assess)
Lab Assignment and Viva voce

IT-102-Computer Programming 15
LAB # 03

Statement Purpose:
This lab covers the following topics:

• Install Visual Studio


• Getting Started with Visual Studio
• Creating a Project
• Compiling a Project
• Running a Program
• Forcing a Program to Terminate

Activity Outcomes:
This lab teaches you the following topics:
 Installing Studio
 Create first C++ program

IT-102-Computer Programming 16
1) StageJ(Journey)

Introduction
This tutorial is for students who are currently taking a C++ course using Visual
Studio with “Program Design with C++”.

This brief tutorial will help you to become familiar with Visual Studio.
Specifically, you will learn how to create projects, create programs, compile, run, and
debug programs.

IT-102-Computer Programming 17
2) Stage a1 (apply)
Lab Activities:
Activity 1:Install Visual Studio

Get visual studio from IT Lab supervisor

IT-102-Computer Programming 18
Activity 2:Getting Started with Visual Studio

Figure 1
The Visual Studio main window is the command center for the IDE.

The Visual Studio main window contains menus, toolbars, project pane, files pane, runtime pane,
navigator pane, and other panes.

1.1 Workspaces
A workspace is a collection of windows that are pertinent to performing certain types of
operations, such as editing, execution, output, or debugging. The workspace windows can be
displayed from the Window menu.

IT-102-Computer Programming 19
Activity 3:Creating a Project
A project contains information about programs and their dependent files, and it also stores and
maintains the properties of the IDE. To create and run a program, you have to first create a project.

Here are the steps to create a demo project:

1. Choose File, New Project to display the New Project dialog box, as shown in Figure
2.

2. Select Visual C++ Win32 and Win32 Console Application.

3. Enter name and location of project. Press ok and move to next dialog

4. Click Finish to create the project. The new project is displayed, as shown in Figure 4.

Figure 2
The New Project dialog box enables you to specify a project type.

IT-102-Computer Programming 20
Figure 4

A new demo project is created.

IT-102-Computer Programming 21
Activity 5: Compiling a Project

Activity 6:Running a Program

Activity 7:Forcing a Program to Terminate

IT-102-Computer Programming 22
3) Stagev(verify)

Home Activities:
1. Every student is required to make installation on his / her personal computer before
next lab.

4) Stagea2(assess)
Lab Assignment and Viva voce

IT-102-Computer Programming 23
LAB # 04

Statement Purpose:
This lab will give you practical implementation of different types of Conditional Statements (if-
else and switch).

Activity Outcomes:
This lab teaches you the following topics:

 Use of indentation
 Use of simple if statement
 Use of if-else statement
 Use of nested-if statement
 Use of switch statement

Instructor Note:
As pre-lab activity, read Chapter 3 from the book (Program Design with C++ by Walter Savitch), and
also as given by your theory instructor.

IT-102-Computer Programming 24
1) Stage J (Journey)

Introduction:
if statement is used to perform logical operation. In order to perform decision making, we need
to check certain condition(s) before processing. C++ supports if statement for doing so. There
are various formats of if statement including if-else and if-ellse-if.

Apart from if statement, C++ also supports switch statement. switch statement is used to select
one of the various options.

The basic and shortest form of if statement is as below:

if (condition)
statement;

If the condition is true in above case then the statement written after the if statement will be
executed otherwise the given statement will be simple ignored. If there are more than one
statements to be executed when the condition is true then we need to write those statements in
a pair of curly brackets as below.

if (condition)
{
statement1;
statement2;


}

If the condition is true then the specified block of statements written within a pair of curly
brackets will be executed. It is important to note that the block is specified by the use of a pair of
curly brackets.

We can also write the else block associated with the if statement as below.

if (condition)
statement1;
else
statement2;

The else part of if statement is always optional but if is written then will be executed only if the
condition written after the if statement is false. In above case if the condition is true then
statement1 will be executed and statement2 will be ignored. On the other hand, if the
condition written after the if statement is false then statement2 will be executed and
statement1 will be ignored.

We can also write more than one statements in the if block or in the else block as shown below.

IT-102-Computer Programming 25
if (condition)
{
statement1;
statement2;


}
else
{
statement3;
statement4;


}

If we are required to test a number of conditions and want to execute one of the many blocks of
statements, then we can use multi-way if-else statements as below.

if (condition1)
{
statement1;
statement2;


}
else if (condition2)
{
statement3;
statement4;


}
else if (condition3)
{
statement5;
statement6;


}
else
{
statement7;
statement8;
}

In the above case only one of the written blocks will be executed depending on the condition to
be true. If none of the conditions is true then the block written after the last else will be
executed. If we have not written the last block then nothing will be executed if all the conditions
are false.

C++ supports another statement as alternative of the above case, called switch statement as
discussed below.

IT-102-Computer Programming 26
switch statement
The syntax of switch statement is as below.

switch (variable/expression)
{
case value1:
statement1;
statement2;


break;

case value2:
statement3;
statement4;


break;
case value3:
statement5;
statement6;


break;
default:
statement7;
statement8;


break;
}

In switch statement, only one of the case block can be executed depending on the value of the
variable or expression written after the switch statement. Every case block will have a unique
value and will be executed if the value hold by the switch variable (or expression) matches that
case value. The break statement is important to write in each case block. It takes control out of
the switch statement. If break statement is not written in any case block then the following
case block will be executed until break statement is found or the last statement written in the
switch statement is executed. The default block is optional and will be only executed if none of
the case value is equal to the value contained of the switch variable (or expression).

2) Stage a1 (apply)
Lab Activities:
Activity 1:
Let us take an integer from user as input and check whether the given value is even or
not.

Solution:

IT-102-Computer Programming 27
A. Create a new C++ Project using an appropriate IDE and type the following code.
B. Run the code.

You will get the following output.

Activity 2:
Let us modify the code to take an integer from user as input and check whether the
given value is even or odd. If the given value is not even then it means that it will be odd.
So here we need to use if-else statement an demonstrated below.

Solution:
A. Create a new C++ Project using an appropriate IDE and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 28
You will get the following output.

IT-102-Computer Programming 29
Activity 3:
Let us modify the above code in order to apply nested if structure. Sometimes we need
to use an if statement within the block of another if to find the solution of the problem.
The following code example illustrates that how nested if can be used in C++.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cout<<"Enter a First Value: ";
cin >> a;
cout<<"Enter a Second Value: ";
cin >> b;

if ( a > b )
{
cout<<a<<" is greater.";
}
else if ( a < b )
{
cout<<a<<" is greater.";
}
else
{
cout<<a<<"Both values are equal.";
}
}

You will get the following output.

Activity 4:
The code written in activity 3 can also be written as multi-way if-else statement and is
in fact a preferred way of writing multiple if-else statements in order to make the code
more readable.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.
IT-102-Computer Programming 30
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cout<<"Enter a First Value: ";
cin >> a;
cout<<"Enter a Second Value: ";
cin >> b;

if ( a > b )
{
cout<<a<<" is greater.";
}
else if ( a < b )
{
cout<<a<<" is greater.";
}
else
{
cout<<a<<"Both values are equal.";
}
}

You will get the following output.

Activity 5:
In this activity, you will be using multi-level if-else statement. You are required to accept
two integer values from user and calculate their addition, subtraction, multiplication
and division depending on the given choice.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 31
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cout<<"Enter a First Value: ";
cin >> a;
cout<<"Enter a Second Value: ";
cin >> b;

cout<<"Select your choice: "<<endl;


cout<<"1: Add"<<endl;
cout<<"2: Subtract"<<endl;
cout<<"3: Multiply"<<endl;
cout<<"4: Divide"<<endl;
cout<<"Enter Your Choice: ";
int choice;
cin >> choice;
if( choice == 1 )
{
cout<<a<<" + "<< b <<" = "<<(a+b);
}
else if( choice == 2 )
{
cout<<a<<" - "<< b <<" = "<<(a-b);
}
else if( choice == 3 )
{
cout<<a<<" * "<< b <<" = "<<(a*b);
}
else if( choice == 4 )
{
cout<<a<<" / "<< b <<" = "<<((double)a/b);
}
else
{
cout<<"Invalid choice...";
}
return 0;
}

You will get the following output.

Activity 6:
In this activity, you will rewrite the above code by using switch statement instead of
using multi-level if-else statement. You are required to accept two integer values from
user and calculate their addition, subtraction, multiplication and division depending on
the given choice.
IT-102-Computer Programming 32
Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cout<<"Enter a First Value: ";
cin >> a;
cout<<"Enter a Second Value: ";
cin >> b;

cout<<"Select your choice: "<<endl;


cout<<"1: Add"<<endl;
cout<<"2: Subtract"<<endl;
cout<<"3: Multiply"<<endl;
cout<<"4: Divide"<<endl;
cout<<"Enter Your Choice: ";
int choice;
cin >> choice;
switch( choice == 1 )
{
case 1:
cout<<a<<" + "<< b <<" = "<<(a+b);
break;
case 2:
cout<<a<<" - "<< b <<" = "<<(a-b);
break;
case 3:
cout<<a<<" * "<< b <<" = "<<(a*b);
break;
case 4:
cout<<a<<" / "<< b <<" = "<<((double)a/b);
break;
default:
cout<<"Invalid choice...";
}
return 0;
}

You will get the following output.

IT-102-Computer Programming 33
IT-102-Computer Programming 34
3) Stage v (verify)
Home Activities:
Activity 1:
Write a C++ code to accept marks of a student from 1-100 and display the grade
according to the following formula.

Grade F if marks are less than 50


Grade E if marks are between 50 to 60
Grade D if marks are between 61 to 70
Grade C if marks are between 71 to 80
Grade B if marks are between 81 to 90
Grade A if marks are between 91 to 100

Activity 2:
Write a C++ code to accept temperature value from user (in centigrade) and display an
appropriate message as below.

FREEZING if temperature in less than 0


COLD if temperature is between 0 to 15
WARM if temperature is between 16 to 30
HOT if temperature is between 31 to 40
VERY HOT if temperature is greater than 40

4) Stage a2 (assess)
Assignment:
For this student will submit Lab Assignment before the deadline.

IT-102-Computer Programming 35
LAB # 05

Statement Purpose:
This lab will give you practical implementation of different types of for loops including
nested for loops.

Activity Outcomes:
This lab teaches you the following topics:

 for loop
 nested for loop
 Use of break statement in for loop

Instructor Note:
As pre-lab activity, read Chapter 4 from the book (Introduction to Java Programming, Brief Version-
Prentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor.

IT-102-Computer Programming 36
1) Stage J (Journey)

Introduction:

Loops are one of the basic structures of a programming language. Loops are performed
to repeat a step or steps for a certain number of times. Java offers a number of loop
statements. One of them is for loop. This lab session covers the for loop.

for loop
for loop is probably the most commonly used loop in Java. It is preferred to use in
situations when the number of iterations are known in advance, i.e. we already know
that how many times the loop will be repeated.

The syntax of for loop is as below.

for(exp1;exp2;exp3)
statement;
or

for(exp1;exp2;exp3)
{
statement1;
statement2;
statement3;


}

Where,

exp1 is called initialization. Here we initialize the variable to be used to control the
loop iterations.
exp2 is a condition. Loop will continue to iterate as long as this condition is true.
exp3 is an increment or decrement statement. It will increment or decrement the loop
variable initialized in exp1.

IT-102-Computer Programming 37
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Calculate the sum of all the values between 0-10 using for loop.

Solution:
C. Create a new Java and type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int sum=0l;
for(int i=1; i<=10; i++)
{
sum = sum + i;
}
cout<<"Sum: "<<sum<<endl;

return 0;
}

You will get the following output.

Activity 2:
Accept an integer values from user and display its numeric table.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

IT-102-Computer Programming 38
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cout<<"Enter a value: ";
cin>>n;
for(int i=1; i<=10; i++)
{
int p = n * i;
cout<<i<<" * "<<n<<" = "<<p<<endl;
}
return 0;
}

You will get the following output.

Activity 3:
Accept an integer values from user and display its factorial.

Solution:
C. Create a new C++ Project type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cout<<"Enter a value: ";
cin>>n;
int f=1;
for(int i=1; i<=n; i++)
{
f = f * i;
}
cout<<"Factorial of Number: "<<f<<endl;
IT-102-Computer Programming 39
return 0;
}

You will get the following output.

Activity 4:
Write a C++ code to accept an integer value from user and check that whether it is
prime or not. In this activity, you will also learn the use of break statement in for loop.
break statement is used in for loop to terminate the for loop immediately and the next
iterations will not be performed as they may not be required further.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cout<<"Enter a value: ";
cin>>n;
bool prime=true;
for(int i=2; i<n/2; i++)
{
int r = i % 2;

IT-102-Computer Programming 40
if( r == 0)
{
Prime = false;
Break;
}
}

if (prime == true)
cout<<”The given value is prime”<<endl;
else
cout<<”The given value is not prime”<<endl;

return 0;
}

You will get the following output.

IT-102-Computer Programming 41
Activity 5:
In this activity, you will learn the use of nested for statements. If we use a for statement
within the body of another for statement then it is called nested for statements. You
are required to write a C++ Project to display all the prime numbers between 100 to
200.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{

For(int n=100; n<=200; n++)


{
bool prime=true;
for(int i=2; i<n/2; i++)
{
int r = i % 2;
if( r == 0)
{
Prime = false;
Break;
}
}

if (prime == true)
cout<<n<<endl;
}
IT-102-Computer Programming 42
return 0;
}
You will get the following output.

3) Stage v (verify)
Home Activities:
Activity 1:
Write a C++ code to accept 10 integer values from user and display sum of positive values.

Activity 2:
Write a C++ Project to generate the following output.

IT-102-Computer Programming 43
Activity 3:
Write a C++ program that prompts the user to enter two positive integers and find their
greatest common divisor as below.

Activity 4:
Fibonacci series is that when you add the previous two numbers the next number is
formed. You have to start from 0 and 1.
E.g. 0+1=1 → 1+1=2 → 1+2=3 → 2+3=5 → 3+5=8 → 5+8=13

So the series becomes


0 1 1 2 3 5 8 13 21 34 55 ……………………………………

Steps: You have to take an input number that shows how many terms to be displayed.
Then use loops for displaying the Fibonacci series up to that term e.g. input no is =6 the
output should be
011235

IT-102-Computer Programming 44
4) Stage a2 (assess)
Assignment:
For this student will submit Lab Assignment before the deadline.

IT-102-Computer Programming 45
LAB # 06

Statement Purpose:
This lab will give you practical implementation of while and do-while loops.

Activity Outcomes:
This lab teaches you the following topics:

 while loop
 do-while loop

Instructor Note:
As pre-lab activity, read Chapter 4 from the book (Introduction to Java Programming, Brief Version-
Prentice Hall (2012) By Y. Daniel Liang), and also as given by your theory instructor.

IT-102-Computer Programming 46
1) Stage J (Journey)

Introduction:

C++ provides different types of loop statements including while and do-while
statements. Although these loop statements can be used as alternatives of for loop but
are preferred to be used when the number of iterations are not known in advance.

while loop
This is also called as pre-test loop where a condition is tested first before the body of the
loop is executed. The body of the loop is executed as long as the condition followed by
the while statement remains true. The syntax of while loop is as below.

while (condition)
{
statement1;
statement2;
...
...
}

As you can see in the above syntax, a condition is followed by the while statement. This
condition must remain true for the execution of the loop. As long as the condition will
remain true, the loop will be iterated and will stop when the condition becomes false.

do-while loop

This is also called post-test loop where the condition is tested once the body of the loop
is executed. If the condition is true then the body of the loop is executed again and this
process continues until the condition becomes false. It means that the body of the loop
will be executed at least once whether the condition is true or false as the body is
executed first and then the condition is checked. The syntax of do-while loop is as
below.

do
{
statement1;
statement2;
...
...
}while (condition);

IT-102-Computer Programming 47
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Calculate the sum of all the values between 0-10 using while loop,

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
int sum=0,i=1;
while(i<=10)
{
sum+=i;
i++;
}
cout << "Sum=" << sum << endl;
system("pause");
return 0;
}

You will get the following output.

Activity 2:
Repeat the above code by accepting 5 integer values from user and display the sum of
given values.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 48
#include "stdafx.h"
#include<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
int num;
int sum=0;
int i=1;
while(i<=5)
{
cin >> num;
sum+=num;
i++;
}
cout << "Sum of given values is:" << sum << endl;
system("pause");
return 0;
}

You will get the following output.

Activity 3:
Rewrite the above code to keep accepting integer values from user until 0 is entered.
Display sum of the given values.

Solution:
A. Create a C++ Project file and type the following code.
B. Run the code by pressing F5.

int _tmain(int argc, _TCHAR* argv[])


{
int num;
cin >> num;
int sum=num;
while(num!=0)
{
cin >> num;
sum+=num;
}
cout << "Sum of given values is:" << sum << endl;
system("pause");
}

You will get the following output.

IT-102-Computer Programming 49
Activity 4:
Rewrite the above code using do-while loop.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
int num;
int sum=0;
do
{
cin >> num;
sum+=num;
}while(num!=0);
cout << "Sum of given values is:" << sum << endl;
system("pause");
return 0;
}

You will get the following output.

IT-102-Computer Programming 50
Activity 5:
Write a C++ program to accept two integer values from user and calculate their
addition, subtraction, multiplication and division depending on the given choice. Keep
accepting the values until a choice related to quit the process is selected.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
int choice;
int a,b;
string ch;
do{
cout << "input the first number :\n";
cin >> a;
cout << "Enter the second number :\n";
cin >> b;
cout << "Select Your Choice\n";
cout << "l: Add" << endl << "2: Subtract" << endl << "3: Multiply " << endl << "4:
Divide" << endl;
cout << "Enter your choice? ";
cin >> choice;
if(choice==1)
cout << a << "+" << "b=" << a+b << endl;
else if(choice==2)
cout << a << "-" << "b=" << a-b << endl;
else if(choice==3)
cout << a << "*" << "b=" << a*b << endl;
else if(choice==4)
cout << a << "/" << "b=" << a/b << endl;
cout << "Do you want to continue?" << endl;
cin >> ch;
}while (ch=="Y" || ch=="y" || ch=="Yes" || ch=="YES");
cout << "Program is ended\n";
system("pause");
return 0;
}

You will get the following output.

IT-102-Computer Programming 51
3) Stage v (verify)
Home Activities:
Activity 1:
Write a C++ program that prompts the user to enter an answer for a question on
addition of two single digits and let the user repeatedly enter a new answer until it is
correct as below.

Activity 2:
Guessing Numbers---The problem is to guess what number a computer has in mind. You
will write a program that randomly generates an integer between 0 and 100, inclusive.
The program prompts the user to enter a number continuously until the number
matches the randomly generated number. For each user input, the program tells the
user whether the input is too low or too high, so the user can make the next guess
intelligently. Here is a sample run:

IT-102-Computer Programming 52
Activity 3:
Write a C++ Project to keep accepting integer values from user until a prime number
is entered.

Activity 4:
Write a C++ Project to keep accepting marks and names of students until a negative
number is entered against marks. Display name of the student having maximum marks.

4) Stage a2 (assess)
Assignment:
For this student will submit Lab Assignment before the deadline.

IT-102-Computer Programming 53
LAB # 07

Statement Purpose:
This lab will give you practical implementation of different types of user-defined methods.

Activity Outcomes:
This lab teaches you the following topics:

 How to define own methods


 How to use user-defined methods
 Passing different types of arguments

Instructor Note:
As pre-lab activity, read Chapter 5 from the book also as given by your theory instructor.

IT-102-Computer Programming 54
1) Stage J (Journey)

Introduction:

It is usually a better approach to divide a large code in small methods. A method is a


small piece of code used to perform a specific purpose. Methods are defined first then
called whenever needed. A program may have as many methods as required. Similarly a
method may be called as many times as required.

How to Define Methods


Functions are defined as below.

returnType methodName(dataType par1, dataType par2, ...)


{
statement1;
statement2;
...
return value;
}

A method may or may not return a value. If a method does not return a value then the
return type must be void otherwise you need to return the data type of the value to be
returned.

A method must have an appropriate name and a pair of parenthesis. In parenthesis, you
need to mention that whether a method will accept or not any parameters. If a method
is not accepting any parameter then the parenthesis must be left blank otherwise you
need to mention the name and type of parameters to be accepted.

A method must return a value if the return type is not void.

How to Call A Function

Once a method is defined then it can be called by using its name and providing values to
the parameters. The following activities demonstrate that how methods are defined and
called in Java.

IT-102-Computer Programming 55
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Define a method to accept an integer value and return its factorial.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
using namespace std;

long factorial(int n)
{
long f=1;
for(int i=n; i>0; i--)
f=f*i;
return f;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter an integer value";
int value;
cin>>value;
long fact=factorial(value);
cout<<"Factorial of "<<value<< " is "<<fact<<endl;
system("pause");
return 0;
}

You will get the following output.

Activity 2:
Write a function to accept 2 integer values from user and return their sum.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 56
#include "stdafx.h"
#include<iostream>
using namespace std;

long sum(int x, int y)


{
int s=x+y;
return s;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter an integer value";
int a;
cin>>a;
cout<<"Enter another integer value";
int b;
cin>>b;
cout<<"Sum of given values is "<<sum(a,b)<<endl;
system("pause");
return 0;
}

You will get the following output.

Activity 3:
Define a function to accept an integer value from user and check that whether the given
value is prime number or not. If the given value is a prime number then it will return
true otherwise false.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 57
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
bool isPrime ( int x)
{
bool prime=true;
int r;
for (int i=2;i<x/2;i++)
{
r=x%i;
if (r==0)
{
prime=false;
break;
}
}
return prime;
}

int _tmain(int argc, _TCHAR* argv[])


{
int num;
cout << "Enter an integer va1ue\n";
cin >> num;
if(isPrime(num)==true)
cout << "The given number is Prime\n";
else
cout << "The given number is not Prime\n";
system("pause");
return 0;
}

You will get the following output.

Activity 4:
Define a function to accept an integer value and display its numeric table.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 58
#include "stdafx.h"
#include<iostream>
using namespace std;

void table(int n)
{
for(int i=1; i<=10;i++)
{

cout<<i<<" * "<<n<<" = "<<(i*n)<<endl;


}
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter an integer value";
int a;
cin>>a;
table(a);
system("pause");
return 0;
}

You will get the following output.

Activity 5:
Write a C++ Project to find the sum of integers from 1 to 10, from 11 to 20, and from 21
to 30, respectively.

Solution:
A. Create a new C++ Project and type the following code.
B. Run the code by pressing F5.

IT-102-Computer Programming 59
#include "stdafx.h"
#include<iostream>
using namespace std;

int sum(int a, int b)


{
int result = 0;
for(int i=a; i<=b; i++)
{
result+=i;
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Sum from 1 to 10 is "<<sum(1,10)<<endl;
cout<<"Sum from 1 to 10 is "<<sum(11,20)<<endl;
cout<<"Sum from 1 to 10 is "<<sum(11,30)<<endl;
system("pause");
return 0;
}

You will get the following output.

3) Stage v (verify)
Home Activities:
Activity 1:
Write a method to accept an integer ‘n’ and display ‘n’ elements of Fibonacci series.

Activity 2:
Write a method to accept three integer values and return the largest value.

IT-102-Computer Programming 60
Activity 3:
Write a method to accept marks of a student (between 0-100) and return the grade
according to the following criteria.

0 - 49 F
50 – 60 E
61 – 70 D
71 – 80 C
81 – 90 B
91 – 100 A

4) Stage a2 (assess)
Assignment:
For this student will submit Lab Assignment before the deadline.

IT-102-Computer Programming 61
IT-102-Computer Programming 62
LAB # 08

Statement Purpose:
In this lab, students will know about the basic concepts of Array data structure,
storing different types of data in arrays, creating arrays of integers, double, Strings and
passing arrays to the methods.

Activity Outcomes:
This lab teaches you the following topics:
 Create Arrays
 Accessing indexes/location of variables in arrays
 Accessing maximum, minimum numbers in arrays
 Different array’s operation
 Passing arrays to methods

Instructor Note:
As pre-lab activity, read Chapter 7 and 8 from the book (Introduction to JAVA
Programming, Liang, Y.D., 10th Edition (2015), Prentice Hall), and also as given by your
theory instructor.

IT-102-Computer Programming 63
1) StageJ(Journey)

Introduction
Often you will have to store a large number of values during the execution of a program.

Suppose, for instance, that you need to read 100 numbers, compute their average, and
findout how many numbers are above the average. Your program first reads the
numbers andcomputes their average, then compares each number with the average to
determine whetherit is above the average. In order to accomplish this task, the numbers
must all be stored invariables. You have to declare 100 variables and repeatedly write
almost identical code100 times. Writing a program this way would be impractical. So,
how do you solve thisproblem?

An efficient, organized approach is needed. C++ and most other high-level languages
providea data structure, the array, which stores a fixed-size sequential collection of
elements ofthe same type. In the present case, you can store all 100 numbers into an
array and access themthrough a single array variable.

Array is a data structure that represents a collection of the same types of data.

The array elements are accessed through the index. The array indices are 0-based, i.e., it
starts from 0 to arrayRefVar.length-1.

• Declaring arrays:

elementType[] arrayRefVar;

The elementType can be any data type, and all elements in the array will have the same
data type. For example, the following code declares a variable myList that references an
array of double elements.

double[] myList;
• Creating arrays:

arrayRefVar = new elementType[arraySize];

IT-102-Computer Programming 64
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Create a menu driven program, with the following functionalities: (Note: all of the
functionalities should be created in a single program with following menu options)

1. Input elements in array. (details of this functionality is given in Step a)


2. Search element and its location. (details of this functionality is given in
Step b)
3. Find largest and smallest value in the array. (details of this
functionality is given in Step c)
4. Copy data. (details of this functionality is given in Step d)

a) Input 10 elements in the array and display the array. (Note: this should
call two methods Input(int Array[ ] ) and display(int A[ ]) )
b) Search element is in the array then print “Element found” along with
its location. (Note: this should call two methods Input(int Array[ ]) and
search(intsearchkey, int Array[ ]). You should call the same Input() method that
is called in step a )
c) Find the largest and the smallest element in array. Then place largest
element on 0th index and smallest element on the last index 9th. (Note: this
should call three methods previously used Input(int Array[]) , Largest(int
Array[]) and Smallest (int Array[])

d) Copy the contents of one array into another.(Note: this should call two
methods Input(int Array[]) and copydata(int Array[], intcopiedArray[]).

Solution:

IT-102-Computer Programming 65
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

void Input(int Array[])


{
for(int i=0;i<10;i++)
{
cout<<" A[" <<i<<"] = ";
cin>>Array[i];
}
}
void display(int A[])
{
for(int j=0;j<10;j++)
{
cout<<" A["<<j<<"] = "<<A[j]<<endl;
}
}

void search(int Array[],int x)


{
int flag=0;
for(int j=0;j<10;j++)
{
if(Array[j]==x)
{
cout<<"Element Found A["<<j<<"] "<<Array[j]<<endl;
flag++;
}
}
if(flag==0)
{
cout<<"Element not found";
}
}

void largest(int Array[])


{
int k=Array[0];
for(int i=0;i<10;i++)
{
if(Array[i]>=k)
{
k=Array[i];
}
}
cout<<" Largest Value find in Array "<<k<<endl;
}

void smallest(int Array[])


{
int k=Array[0];
IT-102-Computer Programming 66
for(int i=0;i<10;i++)
{
if(Array[i]<=k)
{
k=Array[i];
}
}
cout<<" Smallest Value find in Array "<<k<<endl;
}
void copy(int Array[],int copied[])
{
for(int j=0;j<10;j++)
{
copied[j]=Array[j];
}
for(int k=0;k<10;k++)
{
cout<<" New copied array is B["<<k<<"] "<<copied[k]<<endl;
}
}
int main()
{
int input;
cout<<" Enter a number to choose menu : "<<endl;
cout<<" 1 : For input and display the Array\n";
cout<<" 2 : For searching element in an Array\n";
cout<<" 3 : For largest and Smallest element in the Array\n";
cout<<" 4 : For copy data to another Array\n";
cin>>input;
switch(input)
{
case 1:
{
int a1[10];
Input(a1);
display(a1);
break;
}
case 2:
{
int a1[10];
Input(a1);
int searchkey=0;
cout<<"Enter number for search\n";
cin>>searchkey;
search(a1,searchkey);
break;
}
case 3:
{
int a1[10];
Input(a1);
largest(a1);
smallest(a1);
break;
}
IT-102-Computer Programming 67
case 4:
{
int a1[10];
Input(a1);
int copied[10];
copy(a1,copied);
break;
}
}
system("pause");
return 0;
}

You will get the following output.

Activity 2:
Write a program which takes 50 characters as input in array and counts the occurrences
of each character.

E.g. A occurs 2 times


Y occurs 1 time
E occurs 1 time
O occurs 2 times
K occurs 1 time
@ occurs 1 time
……. So on…

Solution:

IT-102-Computer Programming 68
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;


int main()
{
char characters[10];
int counter=0;
for(int i=0;i<10;i++)
{
cout<<" A[" <<i<<"] = ";
cin>>characters[i];
}
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(characters[i]==characters[j])
{
counter++;
}
}
cout<<characters[i]<<" occurs "<<counter<<" times"<<endl;
counter=0;
}
system("pause");
return 0;
}

You will get the following output.

Activity 3:
Write a program to insert elements in 2D array. Then print the array in matrix form.

IT-102-Computer Programming 69
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;


int main()
{
int matrix[4][4];
for(int row=0;row<4;row++)
{
for(int col=0;col<4;col++)
{
cin>>matrix[row][col];
}
}
for(int row=0;row<4;row++)
{
for(int col=0;col<4;col++)
{
cout<<matrix[row][col]<<" ";
}
cout<<endl;
}
system("pause");
return 0;
}

You will get the following output.

Activity 4:
Write a program that reads two 2-D arrays of 3X3 each and Swap their values and then
print both matrices.

IT-102-Computer Programming 70
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;


int main()
{
int A[3][3];
int B[3][3];
int temp=0;
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
cout<<" A["<<row<<"]"<<"["<<col<<"] = ";
cin>>A[row][col];
}
}
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
cout<<" B["<<row<<"]"<<"["<<col<<"] = ";
cin>>B[row][col];
}
}
cout<<"This is Matrix A Before swapping\n";
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
cout<<A[row][col]<<" ";
}
cout<<endl;
}
cout<<"This is Matrix B Before swapping\n";
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
cout<<B[row][col]<<" ";
}
cout<<endl;
}
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
temp=A[row][col];
A[row][col]=B[row][col];
B[row][col]=temp;
}
cout<<endl;
}
cout<<"This is Matrix A After swapping\n";
for(int row=0;row<3;row++)
IT-102-Computer Programming 71
{
for(int col=0;col<3;col++)
{
cout<<A[row][col]<<" ";
}
cout<<endl;
}
cout<<"This is Matrix B After swapping\n";
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
cout<<B[row][col]<<" ";
}
cout<<endl;
}
system("pause");
return 0;
}

You will get the following output.

Activity 5:
Program below will show the difference between passing a primitive datatype value and
an array reference variable to a method.The program contains two methods for
swapping elements in an array. The first method,named swap, fails to swap two int
arguments. The second method, named swapFirst-TwoInArray, successfully swaps the
first two elements in the array argument.

IT-102-Computer Programming 72
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;


void swap(int n1,int n2)
{
int temp=n1;
n1=n2;
n2=temp;
}
void swapfirsttwoinArray(int Array[])
{
int temp=Array[0];
Array[0]=Array[1];
Array[1]=temp;
}
int main()
{
int a[]={1,2};
cout<<"Before invoking Swap\n";
cout<<"Array is {"<<a[0]<<","<<a[1]<<"}"<<endl;
swap(a[0],a[1]);
cout<<"After invoking Swap\n";
cout<<"Array is {"<<a[0]<<","<<a[1]<<"}"<<endl;

cout<<"Before invoking SwapFirstTwoInArray\n";


cout<<"Array is {"<<a[0]<<","<<a[1]<<"}"<<endl;
swapfirsttwoinArray(a);
cout<<"After invoking SwapFirstTwoInArray\n";
cout<<"Array is {"<<a[0]<<","<<a[1]<<"}"<<endl;
system("pause");
return 0;
}
You will get the following output.

IT-102-Computer Programming 73
3) Stagev(verify)

Home Activities:
1. Forty students were asked to rate the quality of food in the student cafeteria, on a scale of
1 to 10 (1 means awful and 10 means excellent). Place the forty responses in an integer
array and summarize the results of the poll.

2. Write a program which performs the following tasks:


• initialize an integer array of 10 elements in main( )
• Pass the entire array to a function modify( )
• In modify( ) multiply each element of array by 3
• return the control to main( ) and print the new array elements in main( )

3. Write a program to copy the contents of one array into another in the reverse order.

4) Stagea2(assess)
Lab Assignment and Viva voce

LAB # 09

Statement Purpose:
This lab will teach you about strings in C++. How strings are defined and used C++?

Activity Outcomes:
This lab teaches you the following topics:

 How to define strings


 How to use strings in problem solving
 Using predefined string methods

IT-102-Computer Programming 74
 Passing strings to methods

Instructor Note:
As pre-lab activity, read Chapter 9 from the book and also as given by your theory instructor.

IT-102-Computer Programming 75
1) Stage J (Journey)

Introduction:

Strings, which are widely used in C++ Project ming, are a sequence of characters. In the
C++ Project ming language, strings are objects. The C++ platform provides the String
class to create and manipulate strings. String literals are collection of characters
enclosed in double quotation marks. In many programming assignments, you will be
required to accept or process alphabetic or alphanumeric data. For this purpose you
may use strings to get the required results.

The String Class


C++ provides a built-in String class which provides a number of useful methods which
may be used to process strings.

Constructing a String

Strings can be constructed in a number of ways as below.

String s=new String(“COMSATS”);

Or

String s=”COMSATS”

We may also take strings as input from user at runtime. For this purpose we may use
getline methods.

Concatenating Strings

Anything added with a string is called string concatenation. For example if we add “abc”
with “xyz”, then the result will be “abcxyz”. Similarly if we add “street” with a mu,eric
integer 1 then the result will be “street1” as below.

“street”+1 will result “street1”.

Strings can also be concatenated by using built-in concat() method as below.

“string1”.concat(“string2”)

IT-102-Computer Programming 76
String Built-in Methods

Strings class has a number of useful methods. Some of them are as below.

“string1”.equals(“string2”)
returns true if “string1” and “string2” have same value otherwise
false

“string1”.equalsIgnoreCase(“string2”)
returns true if “string1” and “string2” have same value otherwise
false ignoring the case

“string1”.compareTo(“string2”)
Returns o, positive or negative integer value depending on that
whether string1 is equal to, greater than or less than string2.

“string1”.compareToIgnaoreCase(“string2”)
Returns 0, positive or negative integer value depending on that
whether string1 is equal to, greater than or less than string2
ignoring case.

“string”.length()
Returns length of the string.

“string”.charAt(index)
Returns the character at specified index.

“string”.concat(“string2”)
Concatenates the two strings.

“Pakistan”.substring(0,3)
Returns a 3-charcter long substring starting at index 0.

“Pakistan”.indexOf(“k”)
Returns index of “k” in “Pakistan”, i.e. 2. If the string to find is not
present in the string then returns a negative integer.

“Pakistan”.lastIndexOf(“a”)
Returns last index of “a” in “Pakistan”, i.e. 6 in this example.

IT-102-Computer Programming 77
2) Stage a1 (apply)
Lab Activities:
Activity 1:
Write a C++ Project to accept two strings from user and check that whether they are
same or not.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
cout<<"Enter a String : ";
string s1;
cin>>s1;
cout<<"Enter another String : ";
string s2;
cin>>s2;
if(s1==s2)
cout<<"Both Strings are same\n";
else
cout<<"Both Strings are different\n";
system("pause");
return 0;
}

You will get the following output.

Here is another output if the strings are different.

If strings are same but one is given in lowercase and the other in uppercase, then the
output will be as below.

IT-102-Computer Programming 78
Activity 2:
Rewrite the last code to accept two strings from user and compare with each other
ignoring case.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;


int main()
{
cout<<"Enter a String : ";
string s1;
cin>>s1;
cout<<"Enter another String : ";
string s2;
cin>>s2;
int n=s1.compare(s2);
if(n<0)
{
cout<<s1<<"<"<<s2<<endl;
}
else if(n>0)
{
cout<<s1<<">"<<s2<<endl;
}
else
{
cout<<s1<<"="<<s2<<endl;
}
system("pause");
return 0;
}

You will get the following output.

Activity 3:
Write a java program to accept two strings from user and display the smaller string.
Kindly note that smaller does not mean here that it will have less number of characters
in it but you need to compare the strings on the basis of ASCII character. For example,

IT-102-Computer Programming 79
“ahsan” is less than “zia” as ASCII code of “a” is less than that of “z”.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;


int main()
{
cout<<"Enter a String : ";
string s1;
cin>>s1;
cout<<"Enter another String : ";
string s2;
cin>>s2;
int n=s1.compare(s2);
if(n<0)
{
cout<<s1<<"<"<<s2<<endl;
}
else if(n>0)
{
cout<<s1<<">"<<s2<<endl;
}
else
{
cout<<s1<<"="<<s2<<endl;
}
system("pause");
return 0;
}

You will get the following output.

Activity 4:
Write a C++ Project to accept names of 5 students and sort in ascending order.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

IT-102-Computer Programming 80
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
void sort(string Array[])
{
string s="";
for(int i=0;i<5;i++)
{
s=Array[i];
int n=0;
for(int j=i+1;j<5;j++)
{
int n=s.compare(Array[j]);
if(n>0)
{
string temp=Array[i];
Array[i]=Array[j];
Array[j]=temp;
s=Array[i];
}
}
}
}
int main()
{
string students[5];
cout<<"Enter name of 5 students"<<endl;
for(int i=0;i<5;i++)
{
getline(cin,students[i]);
}
sort(students);
cout<<"Sorted names are....\n";
for(int i=0;i<5;i++)
{
cout<<students[i]<<endl;
}
system("pause");
return 0;
}

You will get the following output.

IT-102-Computer Programming 81
Activity 5:
Write C++ Project to accept names of 5 students from user in an array. Pass this array
to a method. The method will sort the names in descending order.

Solution:
C. Create a new C++ Project and type the following code.
D. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
void sort(string Array[])
{
string s="";
for(int i=0;i<5;i++)
{
s=Array[i];
int n=0;
for(int j=i+1;j<5;j++)
{
int n=s.compare(Array[j]);
if(n<0)
{
string temp=Array[i];
Array[i]=Array[j];
Array[j]=temp;
s=Array[i];
}
}
}
}
int main()
{
string students[5];
cout<<"Enter name of 5 students"<<endl;
for(int i=0;i<5;i++)
{
getline(cin,students[i]);
}
sort(students);
cout<<"Sorted names are....\n";
for(int i=0;i<5;i++)
{
cout<<students[i]<<endl;
}
system("pause");
return 0;
}

IT-102-Computer Programming 82
You will get the following output.

3) Stage v (verify)
Home Activities:
Activity 1:
Write a C++ Project to accept names and marks of 10 students. Display names of
student having maximum marks.

Activity 2:
Write a C++ Project to accept names and marks of 10 students. Sort this data
according to names in ascending order.

Activity 3:
Write a C++ Function to accept marks of a student between 0-100 and return the grade
according to the following criteria.

0 - 49 F
50 – 60 E
61 – 70 D
71 – 80 C
81 – 90 B
91 – 100 A

IT-102-Computer Programming 83
4) Stage a2 (assess)
Assignment:
For this student will submit Lab Assignment before the deadline.

IT-102-Computer Programming 84
LAB # 10

Statement Purpose:
This lab will give you practical implementation of method overloading and recursion.

Activity Outcomes:
This lab teaches you the following topics:

 Methods overloading
 Recursion

Instructor Note:
As pre-lab activity, read Chapters 5 and 20 from the book and also as given by your theory
instructor.

IT-102-Computer Programming 85
1) Stage J (Journey)

Introduction:

Methods overloading means to define more than one methods having same name but
different signatures in the same class. It enables us to use the same method’s name
multiple time in the same class. The functionality of each method may be different. It is
important to note that the return type of the method has nothing to do with
overloading. The return type may be kept same or different but the number or type of
parameters must be different to implement methods overloading.

Sometimes it may be required that a method should call itself to solve a particular
problem. If this happens then this is called recursion.

Methods Overloading
The important points in methods overloading are as below.

1. All the methods involved in overloading must be defined in the same class.
2. Names of all the methods must be same.
3. Number of parameters should be different.
4. If number of parameters are same then data type of at least on of them should be
different from other methods.
5. Names of parameters do no matter in methods overloading
6. Return type of methods may be same or different as return type is also not
considered in methods overloading

Recursion

In recursion, a method calls itself. If a method starts calling itself then a kind of loop
starts to happen. You must write some statements to break this loop so recursion stops.

2) Stage a1 (apply)
Lab Activities:
Activity 1:
Write a C++ Project to have two methods of same name called sum. One of them should
accept two integer values and return their sum. The other sum method should accept
three integer values and return their sum.

IT-102-Computer Programming 86
Solution:
E. Create a new C++ Project and type the following code.
F. Run the code by pressing F5.

#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

int sum(int a, int b)


{
return (a+b);
}
int sum(int a, int b, int c)
{
return (a+b+c);
}

int _tmain(int argc, _TCHAR* argv[])


{
cout<<"Enter an integer value ";
int x;
cin>>x;
cout<<"Enter another integer value ";
int y;
cin>>y;
cout<<"Sum of given values is "<<sum(x,y)<<endl;
system("pause");
return 0;
}

You will get the following output.

Here is the modified to code call the method having three parameters.

IT-102-Computer Programming 87
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

int sum(int a, int b){


return (a+b);
}
int sum(int a, int b, int c){
return (a+b+c);
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter an integer value ";
int x;
cin>>x;
cout<<"Enter another integer value ";
int y;
cin>>y;
cout<<"Enter another integer value ";
int z;
cin>>z;
cout<<"Sum of given values is "<<sum(x,y,z)<<endl;
system("pause");
return 0;
}

The output will be as below.

Activity 2:
Write two methods having name sum. One of them will add two integer values and the
other will add two double values.

Solution:
E. Create a new C++ Project and type the following code.
F. Run the code by pressing F5.

IT-102-Computer Programming 88
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

int sum(int a, int b){


return (a+b);
}
double sum(double a, double b){
return (a+b);
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter an floating point value ";
double x;
cin>>x;
cout<<"Enter another floating point value ";
double y;
cin>>y;
cout<<"Sum of given values is "<<sum(x,y)<<endl;
system("pause");
return 0;
}

You will get the following output.

Activity 3:
Write two methods having name max. One of them will accept an array of integers and
return maximum value. The other will accept an array of strings and return thr string
having maximum number of characters in it.

Solution:
E. Create a new C++ Project and type the following code.
F. Run the code by pressing F5.

IT-102-Computer Programming 89
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;
int max(int a[])
{
int m=a[0];
for(int i=1;i<7;i++)
{
if(a[i]>m)
{
m=a[i];
}
}
return m;
}

string max(string s[])


{
string m=s[0];
for(int i=1;i<5;i++)
{
if(s[i].length()>m.length())
{
m=s[i];
}
}
return m;
}

int main()
{
int a[]={11,2,9,22,6,8,3};
cout<<"Maximum value is : "<<max(a)<<endl;
string names[5];
names[0]="Muzaffar";
names[1]="Iqbal";
names[2]="Zafar";
names[3]="Farooqi";
names[4]="Ali";
cout<<"Name having maximum characters is : "<<max(names)<<endl;
system("pause");
return 0;
}

You will get the following output.

IT-102-Computer Programming 90
Activity 4:
Write a method to find factorial of an integer using recursion.

Solution:
E. Create a new C++ Project and type the following code.
F. Run the code by pressing F5.

IT-102-Computer Programming 91
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

long factorial(int n){


if(n==0)
return 1;
else
return (n*factorial(n-1));
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter an integer value ";
double x;
cin>>x;
cout<<"factorial of given number is "<<factorial(x)<<endl;
system("pause");
return 0;
}

You will get the following output.

Activity 5:
Write a C++ Project to display Fibonacci series by using a recursive method.

Solution:
E. Create a new C++ Project and type the following code.
F. Run the code by pressing F5.

IT-102-Computer Programming 92
#include "stdafx.h"
#include<iostream>
#include<string>

using namespace std;

int fib(int x)
{
if((x==1)||(x==0))
{
return(x);
}
else
{
return(fib(x-1)+fib(x-2));
}
}

int main()
{
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x)
{
cout << " " << fib(i);
i++;
}
system("pause");
return 0;
}

You will get the following output.

3) Stage v (verify)
Home Activities:
Activity 1:
Write the following overloaded methods and use them in a C++ Project . int

multiply(int a, int b)
double multiply(double x, double y)
float multiply(float a, float b)
IT-102-Computer Programming 93
Activity 2:
Write two overloaded methods having name sort. One of them will accept an array of
strings and sort them in descending order. The other will accept an array of integer
values and will sort them in descending order.

Activity 3:
Write a recursive method to build tower of Hanoi.

4) Stage a2 (assess)
Assignment:
For this student will submit Lab Assignment before the deadline.

IT-102-Computer Programming 94
LAB # 11

Statement Purpose:
In this lab you will experiment with the C++ Input/Output components by implementing two
programs that read input from a file and write output to a file.

The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in C++. All these streams represent an input source and an output destination. The stream in
the <iostream> library.

Activity Outcomes:
Student will be able to:

1. Describe the concept of an I/O stream


2. Explain the difference between text files and binary files
3. Save data
4. Read data

Instructor Note:
“Problem Solving and Programming with C++”, Savitch, W., 6th Edition (2012), Addison-

Wesley

IT-102-Computer Programming 95
1) Stage J (Journey)

Introduction
The character input and output shown so far has used the pre-defined “standard” streams
System.in and System.out. Obviously in many real applications it is necessary to access named
files. In many programming languages there is a logical (and practical) distinction made between
files that will contain text and those while will be used to hold binary information. Files
processed as binary are thought of as sequences of 8- bit bytes, while ones containing text
model sequences of characters.

Java uses names typically based on the word Stream for binary access, and Reader and Writer
for text. So when you read the documentation expect to find two broadly parallel sets of
mechanisms, one for each style of access.

2) Stage a1 (apply)
Lab Activities:
Activity 1: Create a program in C++ using stream to read input

Solution:
#include "stdafx.h"
#include<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
cout<<"Enter Characters, 'q' to quit.\n";
char ch;
try
{
do
{
ch =(char) cin.get();
cout<<ch;
}
while(ch != 'q');
}catch(const exception& e)
{

cout<<"Exception Occured";
}
system("pause");
return 0;
}

IT-102-Computer Programming 96
Activity 2:
Write a java program to demonstrate InputStream and OutputStream

Solution:
#include "stdafx.h"
#include<iostream>
#include<exception>
#include <fstream>
using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}

cout<<"File created successfully."<<endl;


//write text into file
file<<"ABCD.";
//closing the file
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);

if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}

//read untill end of file is not found.


char ch; //to read single character
cout<<"File content: ";

while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}

file.close(); //close file

return 0;
}

IT-102-Computer Programming 97
Activity 3:
#include<iostream>
#include<dirent.h>
using namespace std;
int main()
{
struct dirent *d;
DIR *dr;
dr = opendir(".");
if(dr!=NULL)
{
cout<<"List of Files & Folders:-\n";
for(d=readdir(dr); d!=NULL; d=readdir(dr))
{
cout<<d->d_name<<endl;
}
closedir(dr);
}
else
cout<<"\nError Occurred!";
cout<<endl;
return 0;
}

// convert.cpp : Defines the entry point for the console application.


//

#include "stdafx.h"
#include <iostream>
using namespace std;

// function to compare two paths


void pathCompare(string p1, string p2)
{

// stores compared value 0 or >0 or <0


const int res = p1.compare(p2);
if (res == 0)
cout << p1 << " is equal to " << p2;
else
cout << p1 << " is different to " << p2<<endl;

// Driver code
int main()
{
string p1 = "/a/b/c";
string p2 = "/a/b/";
string p3 = "/a/b";
string p4 = "/a/b";
string p5 = "/a/b";
string p6 = "/a/b.";
pathCompare(p1, p2); // function call
IT-102-Computer Programming 98
pathCompare(p3, p4); // function call
pathCompare(p5, p6); // function call
system("pause");
return 0;
}
A C++ program to show that a method called to read characters, and that it
returns the integer -1 at end of file.

Solution:
Activity 3:
Write a C++ program by using list( ) method provided by File object to list
down all the files and directories available in a directory.

Solution:

IT-102-Computer Programming 99
Activity 4:
Write a C++ program to compare paths of two files?

Solution:
#include<iostream>
#include<fstream>
using namespace std;

// Driver code
int main()
{
// fstream is Stream class to both
// read and write from/to files.
// file is object of fstream class
fstream file;

// opening file "Gfg.txt"


// in out(write) mode
// ios::out Open for output operations.
file.open("Gfg.txt",ios::out);

// If no file is created, then


// show the error message.
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}

cout<<"File created successfully.";

// closing the file.


// The reason you need to call close()
// at the end of the loop is that trying
// to open a new file without closing the
// first file will fail.
file.close();

return 0;
}

Activity 5:
Write a java program to create a new file?

Solution:
#include<fstream>
#include<iostream>
using namespace std;

IT-102-Computer Programming 100


int main()
{
ifstream in_file("a.txt", ios::binary);
in_file.seekg(0, ios::end);
int file_size = in_file.tellg();
cout<<"Size of the file is"<<" "<< file_size<<" "<<"bytes";
}

Activity 6:
Write a C++ program to create a new file (another way)?

Solution:
#include<iostream>
#include<fstream>
using namespace std;

// Driver code
int main()
{
// fstream is Stream class to both
// read and write from/to files.
// file is object of fstream class
fstream file;

// opening file "Gfg.txt"


// in out(write) mode
// ios::out Open for output operations.
file.open("Gfg.txt",ios::out);

// If no file is created, then


// show the error message.
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}

cout<<"File created successfully.";

// closing the file.


// The reason you need to call close()
// at the end of the loop is that trying
// to open a new file without closing the
// first file will fail.
file.close();

return 0;
}

IT-102-Computer Programming 101


Activity 7:
Write a C++ program to get last modification date of a file?

Solution:

Stage v (verify)

Home Activities:
Activity 1: Write a C++program to create a file in a specified directory?
Activity 2: Write a C++program to check a file exist or not?
3) Stage a2 (assess)
Assignment:
1) Write a C++ program to make a file read-only?
2) Write a C++ program to rename a file?

LAB # 12

Statement Purpose:

IT-102-Computer Programming 102


In this lab you will experiment with the Java Input/Output components by implementing two
programs that read input from a file and write output to a file.

The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination. The
stream in the java.io package supports many data such as primitives, object, localized
characters, etc.

Activity Outcomes:
Student will be able to:
1) Describe the concept of an I/O stream
2) Explain the difference between text files and binary files
3) Save data
4) Read data

Instructor Note:
Problem Solving and Programming using C++, Savitch, W., 6th Edition (2012), Addison-
Wesley

1) Stage J (Journey)

IT-102-Computer Programming 103


2) Stage a1 (apply)
Lab Activities:
Activity 1:
Write a C++ program to get a files size in bytes?

Solution:
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream in_file("a.txt", ios::binary);
in_file.seekg(0, ios::end);
int file_size = in_file.tellg();
cout<<"Size of the file is"<<" "<< file_size<<" "<<"bytes";
}

Activity 2:
Write a C++ program to get a files size in bytes?

Solution:
// C++ program to create a temporary file
// read and write to a temporary file.
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

// Driver code
int main()
{
// Creating a file pointer which
// points to the temporary file
// created by tmpfile() method
FILE* fp = tmpfile();

// Content to be written in temporary file


char write[] = "Welcome to QAU";

// If file pointer is NULL there is


// error in creating the file
if (fp == NULL)
{
perror("Error creating temporary file");
exit(1);
}
IT-102-Computer Programming 104
// Writing in temporary file the content
fputs(write, fp);
rewind(fp);

// Reading content from temporary file


// and displaying it
char read[100];
fgets(read, sizeof(read), fp);
cout << read;

// Closing the file. Temporary file will


// also be deleted here
fclose(fp);

return 0;
}

Activity 3:
Write a C++ program to change the last modification time of a file?

Solution:
// C++ program to demonstrate appending of
// a string using ofstream
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ofstream of;
fstream f;

// opening file using ofstream


of.open("Geeks for Geeks.txt", ios::app);
if (!of)
cout << "No such file found";
else {
of << " String";
cout << "Data appended successfully\n";
of.close();
string word;

// opening file using fstream


f.open("Geeks for Geeks.txt");
while (f >> word) {
cout << word << " ";
}
f.close();
}
return 0;
}

IT-102-Computer Programming 105


Activity 4:
Write a C++ program to create a temporary file?

Solution:

IT-102-Computer Programming 106


Activity 5:
Write a C++ program to append a string in an existing file?

Solution:

IT-102-Computer Programming 107


3) Stage v (verify)
Home Activities:
Activity 1: Write a C++ program to copy one file into another file?
Activity 2: Write a C++ program to delete a file?
4) Stage a2 (assess)
Assignment:
1) Write a C++ program to read a file?
2) Write a C++ program to write into a file?

LAB # 13

Statement Purpose:
An exception is an object that signals the occurrence of an unusual event during the execution
of a program. The process of creating this object that is generated an exception is called
throwing an exception.

IT-102-Computer Programming 108


Activity Outcomes:
1) Describe the notation of exception handling
2) React correctly when certain exceptions occur
3) Use C++ exception-handling facilities effectively in classes and programs

Instructor Note:
Problem Solving and Programming with C++, Savitch, W., 6th Edition (2012), Addison-

Wesley.

1) Stage J (Journey)

Introduction
Unit testing can be done in two ways − manual testing and automated testing.

IT-102-Computer Programming 109


Manual Testing

1. Executing a test cases manually without any tool support is known as manual testing.
2. Time-consuming and tedious − Since test cases are executed by human resources, it is very
slow and tedious.
3. Huge investment in human resources − As test cases need to be executed manually, more
testers are required in manual testing.
4. Less reliable − Manual testing is less reliable, as it has to account for human errors.
5. Non-programmable − No programming can be done to write sophisticated tests to fetch
hidden information.

Automated Testing

6. Taking tool support and executing the test cases by using an automation tool is known as
automation testing.
7. Fast − Automation runs test cases significantly faster than human resources.
8. Less investment in human resources − Test cases are executed using automation tools, so
less number of testers are required in automation testing.
9. More reliable − Automation tests are precise and reliable.
10. Programmable − Testers can program sophisticated tests to bring out hidden information.

A Unit Test Case is a part of code, which ensures that another part of code (method) works as
expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit
test framework for C++ Project ming language.

A formal written unit test case is characterized by a known input and an expected output, which is
worked out before the test is executed. The known input should test a precondition and the
expected output should test a post-condition.

There must be at least two unit test cases for each requirement − one positive test and one negative
test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases
as positive and negative.

2) Stage a1 (apply)
Lab Activities:
Activity 1:

Write a C++ program that catches arithmetic exception.

IT-102-Computer Programming 110


Solution:
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;
int main()
{
int num1,num2;
try
{
num1=0;
num2=62/num1;
cout<<"Try block message\n";
}
catch(runtime_error& e)
{
cout<<"Error: Don't divide a number by zero\n"<<e.what();
}
cout<<"After try-catch block in C++";
system("pause");
return 0;
}

Activity 2:
A C++ program for an array declared with 2 elements. Then the code tries to
access the 3rd element of the array which throws an exception.

Solution:
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;
int main()
{
try
{
int a[2];
cout<<"Access element three :" + a[3]<<endl;
}
catch(...)
{
cout<<"Exception thrown :"<<endl<<"Array index out of range";
}
cout<<"Out of the block\n";
system("pause");
return 0;
}

Activity 3:
IT-102-Computer Programming 111
C++ Project to access the index in an array that is not present in it.

Solution:

Activity 4:
C++ Project for multiple try catch blocks.

Solution:
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;
int main()
{
try
{
int a[7];
a[4]=30/0;
cout<<"First print statement in try block";
}
catch(std::exception e)
{
cout<<"Warning: ArithmeticException";
}
catch(std::exception e)
{
cout<<"Warning: ArrayIndexOutOfBoundsException";
}
catch(std::exception e)
{
cout<<"Warning: Some Other exception";
}
cout<<"Out of try-catch block...";

system("pause");
return 0;
}

Activity 5:
C++ Project for nested try loops

Solution:
#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdexcept>
using namespace std;
int main()
IT-102-Computer Programming 112
{
try
{
int arr[]={5,0,1,2};
try
{
int x=arr[3]/arr[1];
}
catch(std::exception e)
{
cout<<"divide by zero";
}
arr[4]=3;
}
catch(std::exception e)
{
cout<<"array index out of bound exception";
}

system("pause");
return 0;
}

3) Stage v (verify)
Home Activities:

IT-102-Computer Programming 113


Activity 1: Create your own exception sub class simply by extending
java Exception class. You can define a constructor for your Exception sub
class (not compulsory) and you can override the toString() function to
display your customized message on catch.

4) Stage a2 (assess)
Assignment:
Write a statement that will throw an exception of type Exception if the value
of the String variable named status is “bad”. The string recovered by
getMessage should be “Exception thrown: Bad Status.” You need not write
the try block and catch block.

IT-102-Computer Programming 114

You might also like