PF Lab manual
PF Lab manual
Islamabad
CE1004 Computer Programming for Engineering
Applications
Instructor Name: Dr. Zulfiqar Ali Program: Civil
Engineering
LAB MANUAL
CE1004
SEMSTER: 4th Credit Hours: ONE TIME: 48 CONTACT
HOURS
Version History
This is the Lab Manual for CE1004 Computer Programming for Engineering
Applications. This manual is intended for the Second Year Computer Science
Students.
The Lab course for Programming Fundamentals introduces the basic as well as
advance concepts of programming using C++ language. This lab helps the
students in understanding and having a hands-on-experience of a powerful,
portable and flexible structured programming language which is suitable for both
systems and applications programming. It is a robust language which contains a
rich set of built-in functions and operators to write any complex program. Each lab
session begins with a brief theory of the topic followed by series of practical
assignment(s)
Lab Objectives
Lab would enable the students to:
1. Develop modular, efficient and readable C++ programs with hands-on
experience.
2. Interpret good profound knowledge in C programming language and enable
them to build programs using operators, control structures, arrays, strings,
functions, pointers and structures to solve the real world problems.
3. Illustrate memory allocation to variables dynamically and perform operations
using files.
Lab Policy
Groups
Students will be formed into groups / syndicates of two on the first lab day. This pair
programming approach may vary depending upon the experiment nature. However, once
a student has signed up with a group in term project, he may not change groups without
prior approval of the instructor.
Lab Reports
Students will perform the Experiment/Practical in group(optional), and turn in individual
laboratory reports on the assigned date of deadline mentioned at the beginning of each
lab experiment detailed document. Your report should be self-contained, i.e. a computer
scientist should be able to perform the experiment and duplicate your results by reading
your report. DO NOT "adjust" your data to make them fit what you believe to be an
acceptable value. Plagiarism is strictly forbidden in individual reports. Those Students
who found in such activities will be awarded no credits plus re-submission will not be
entertained. For each Lab Task maintain screenshots of results along with all the program
files as a record in separate lab folder with name of student id or group id. Task
Screenshots should be shown along with program source code as evidence of task
implementation. In order to achieve the expected results do not “adjust” your actual results
instead explain the discrepancies.
Report Format
The report must be typewritten. The lab report format is provided in Annex A.
Requirements for Lab
Hardware
Computer Systems for each individual or One PC for two students
Software
Microsoft Visual Studio (Visual C++) – Latest Version
Lab Ethics
Students need to take care of following:
1. Maintenance of proper decorum is mandatory during lab.
2. No student is allowed to leave their seats during PHASE III of Lab Conduct Plan.
3. No student is allowed to leave without permission.
4. Attendance is mandatory. Lab report won’t be accepted if absent from lab.
5. Lab equipment must be taken care of. Any damage to lab resources will be dealt
with sternly.
6. PCs should be turned off and chairs need be arranged by each individual after lab
List of Experiments
Following is the lab schedule with week wise distribution and example set of problems
that would be provided to students
Lab Experiments (Schedule)
Introduction to Algorithm and Flow Charts
Detailed Hands on Session with Development of Algorithm and Flow Chart
Week 01
• Flowchart to take average of three number
• Algorithm and Flowchart to add five test scores
Familiarization with Visual Studio and Stream Insertion / Extraction Operator
Week 03 i. (x + y) / (x - y)
ii. (x + y)(x - y)
• Evaluate the arithmetic expression ((a + b / c * d - e) * (f - g)). Read the values
a, b, c, d, e, f, g from the standard input device.
• Computes and outputs the surface area and volume of a sphere with radius r (r
is given/taken from user as input)
•
Declare a constant PI with value 3.1416 and compute the area of circle with
Week 04 radius r taken from user as input
• Write a program to implement mathematical functions; power, sqrt, abs, sin,
round etc.
Selection Structures
Week 12 • Insert a sub string into a given main string from a given position.
• Delete n characters from a given position in a given string.
• Find a string within a sentence and replace it with another string.
• Reads a line of text and counts all occurrence of a particular character.
• Determine if the given string is a palindrome or not.
Pointers
• Concatenate two strings using pointers.
• Find the length of string using pointers.
Week 13 • Compare two strings using pointers.
• Copy a string from source to destination using pointers.
• Reverse a string using pointers.
(Open Ended Lab)
File Handling
End Semester
Week 16
National University of Technology,
Islamabad
CE1004 Computer Programming for Engineering
Applications
Instructor Name: Dr. Zulfiqar Ali Program: Civil
Engineering
LAB 01
Introduction to Algorithms and Flow Charts
Lab Objectives:
• Lab would introduce the concepts of algorithms and flow Chart
Algorithms
The term algorithm originally referred to any computation performed via a set of rules applied to
numbers written in decimal form. The word is derived from the phonetic pronunciation of the last
name of Abu Ja'far Mohammed ibn Musa al-Khowarizmi, who was an Arabic mathematician who
invented a set of rules for performing the four basic arithmetic operations (addition, subtraction,
multiplication and division) on decimal numbers.
Throughout history, man has thought of ever more elegant ways of reducing the amount of labour
needed to do things. A computer has immense potential for saving time/energy, as most
(computational) tasks that are repetitive or can be generalised can be done by a computer. For
a computer to perform a desired task, a method for carrying out some sequence of events,
resulting in accomplishing the task, must somehow be described to the computer. The algorithm
can be described on many levels because the algorithm is just the procedure of steps to take
and get the result. The language used to describe an algorithm to other people will be quite
different from that which is used by the computer, however the actual algorithm will in essence
be the same. An example of an algorithm people use would be a recipe to make a cake.
2. Put 1" water in wide pot, then place deep bowl of batter inside.
3. Cover pot tightly and steam 15 min.
4. Heat oil very hot and pour over custard.
5. Steam 5 more min. Serves 4 people"
This breaks down 'Making Chinese egg custard' into smaller steps. To make the product one
still needs to know how to execute each of the steps in the procedure and understand all of the
terms.
Definition:
A procedure is a finite sequence of well-defined instructions, each of which can be
mechanically carried out in a finite amount of time.
The procedure must break up the problem solution into parts that the recipient party can
understand and execute. In the case of a computer, the problem solution is usually in the form
of a program that encompasses the algorithm and explains to the computer a clearly defined
procedure for achieving the solution. The procedure must consist of smaller steps each of which
the computers understand. There may be no ambiguities in the translation of the procedure into
the necessary action to be taken. A program is then just a specific realisation of an algorithm,
which may be executed on a physical device.
A computer is essentially a physical device designed to carry out a collection of primitive actions.
A procedure is a sequence of instructions written in terms of which evoke a proper operation. To
make effective use of an algorithm on a computer one must not only find and understand a
solution to the problem but also convey the algorithm to the computer, giving the correct
sequence of understood commands that represent the same algorithm.
Definition:
An algorithm is procedure consisting of a finite set of unambiguous rules (instructions) which
specify a finite sequence of operations that provides the solution to a problem, or to a specific
class of problems for any allowable set of input quantities (if there are inputs). In other word, an
algorithm is a step-by-step procedure to solve a given problem
Alternatively, we can define an algorithm as a set or list of instructions for carrying out some
process step by step. A recipe in a cookbook is an excellent example of an algorithm. The recipe
includes the requirements for the cooking or ingredients and the method of cooking them until
you end up with a nice cooked dish.
In the same way, algorithms executed by a computer can combine millions of elementary steps,
such as additions and subtractions, into a complicated mathematical calculation. Also by means
of algorithms, a computer can control a manufacturing process or co-
ordinate the reservations of an airline as they are received from the ticket offices all over the
country. Algorithms for such large-scale processes are, of course, very complex, but they are
built up from pieces.
One of the obstacles to overcome in using a computer to solve your problems is that of
translating the idea of the algorithm to computer code (program). People cannot normally
understand the actual machine code that the computer needs to run a program, so programs
are written in a programming language such as C or Pascal, which is then converted into
machine code for the computer to run.
In the problem-solving phase of computer programming, you will be designing algorithms. This
means that you will have to be conscious of the strategies you use to solve problems in order to
apply them to programming problems. These algorithms can be designed though the use of
flowcharts or pseudocode.
Flowcharts
Flowcharting is a tool developed in the computer industry, for showing the steps involved in a
process. A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by
arrows - each shape represents a step in the process, and the arrows show the order in which
they occur. Flowcharting combines symbols and flowlines, to show figuratively the operation of
an algorithm.
In computing, there are dozens of different symbols used in flowcharting (there are even national
and international flowcharting symbol standards). In business process analysis, a couple of
symbols are sufficient. A box with text inside indicates a step in the process, while a diamond
with text represents a decision point. See the figure for an example.
If the flowchart is too messy to draw, try starting again, but leaving out all of the decision points
and concentrating on the simplest possible course. Then the session can go back and add the
decision points later. It may also be useful to start by drawing a high-level flowchart for
the whole organisation, with each box being a complete process that has to be filled out
later.
From this common understanding can come a number of things - process improvement ideas
will often arise spontaneously during a flowcharting session. And after the session, the facilitator
can also draw up a written procedure - a flowcharting session is a good way of documenting a
process.
Process improvement starts with an understanding of the process, and flowcharting is the first
step towards process understanding.
Flowcharting Symbols
There are 6 basic symbols commonly used in flowcharting of assembly language programs:
Terminal, Process, input/output, Decision, Connector and Predefined Process. This is not a
complete list of all the possible flowcharting symbols, it is the ones used most often in the
structure of Assembly language programming.
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry
points. The exit point for all flowchart symbols is on the bottom except for the
Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom
and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can
be shown as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs
or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Flowcharting uses symbols that have been in use for a number of years to represent the
type of operations and/or processes being performed. The standardised format provides
a common method for people to visualise problems together in the same manner. The use
of standardised symbols makes the flow charts easier to interpret, however, standardising
symbols is not as important as the sequence of activities that make up the process.
Flowcharting Tips
• Chart the process the way it is really occurring. Do not document the way a written
process or a manager thinks the process happens.
• People typically modify existing processes to enable a more efficient process. If the
desired or theoretical process is charted, problems with the existing process will not
be recognised and no improvements can be made.
Example 1. Design an algorithm and the corresponding flowchart for adding the test
scores as given below:
1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop
i. Start
ii. Sum = 0
iii. Get a value
iv. sum = sum + value
v. Go to step 3 to get next Value
vi. Output the sum
vii. Stop
This algorithm and its corresponding flowchart are a bit shorter than the first one. In this
algorithm, step 3 to 5 will be repeated, where a number is obtained and added to sum. Similarly
the flowchart indicates a flowline being drawn back to the previous step indicating that the
portion of the flowchart is being repeated. One problem indicates that these steps will be
repeated endlessly, resulting in an endless algorithm or flowchart. The algorithm needs to be
improved to eliminate this problem. In order to solve this problem, we need to add a last value
to the list of numbers given. This value should be unique so that, each time we get a value, we
test the value to see if we have reached the last value. In this way our algorithm will be a finite
algorithm which ends in a finite number of steps as shown below. There are many ways of
making the algorithm finite.
The new list of numbers will be 26, 49, 498, 9387, 48962, 1, -1. The value –1 is a unique
number since all other numbers are positive.
i. Start
ii. Sum = 0
iii. Get a value
iv. If the value is equal to –1, go to step 7
v. Add to sum ( sum = sum + value)
vi. Go to step 3 to get next Value
vii. Output the sum
viii. Stop
Corresponding flowchart
National University of Technology,
Islamabad
CE1004 Computer Programming for Engineering
Applications
Instructor Name: Dr. Zulfiqar Ali Program: Civil
Engineering
LAB 02
Familiarization with Visual Studio and Insertion / Extraction Operator
Lab Objectives:
Lab is focused towards:
• Familiarization with Programming Environment using Microsoft Visual Studio.
Requirements for Lab:
Hardware: Computer Systems for each individual
Software: Microsoft Visual Studio (Visual C++)
In-Lab Task:
Develop “Hello World” Console Application
Visual Studio creates a new project, ready for you to add and edit your source code. By default, the
Console App template fills in your source code with a "Hello World" app:
When the code looks like this in the editor, you're ready to go on to the next step and build your app.
In Visual Studio, open the File menu and choose New > Project to open the New Project dialog.
In the New Project dialog, select Installed, Visual C++ if it isn't selected already, and then choose
the
Empty Project template. In the Name field, enter HelloWorld. Choose OK to create the project.
Visual Studio creates a new, empty project, ready for you to specialize for the kind of app you want to
create and to add your source code files.
Make your project a console app
Visual Studio can create all kinds of apps and components for Windows and other platforms. The
Empty Project template isn't specific about what kind of app it creates. To create a console app, one
that runs in a console or command prompt window, you must tell Visual Studio to build your app to use
the console subsystem.
In Visual Studio, open the Project menu and choose Properties to open the HelloWorld Property
Pages dialog.
In the Property Pages dialog, under Configuration Properties, select Linker, System, and then
choose the edit box next to the Subsystem property. In the dropdown menu that appears, select
Console (/SUBSYSTEM:CONSOLE). Choose OK to save your changes.
Visual Studio now knows to build your project to run in a console window. Next, you'll add a source
code file and enter the code for your app.
In the Add New Item dialog, select Visual C++ under Installed if it isn't selected already. In the center
pane, select C++ file (.cpp). Change the Name to HelloWorld.cpp. Choose Add to close the dialog
and create the file.
Visual studio creates a new, empty source code file and opens it in an editor window, ready to enter
your source code.
Add code to the source file
1. Copy this code into the HelloWorld.cpp editor window.
#include <iostream>
int main()
When the code looks like this in the editor, you're ready to go on to the next step and build your app.
Create your app project issues
If the New Project dialog doesn't show a Visual C++ entry under Installed, your copy of Visual Studio
probably doesn't have the Desktop development with C++ workload installed. You can run the installer
right from the New Project dialog. Choose the Open Visual Studio Installer link to start the installer again.
If the User Account Control dialog requests permissions, choose Yes. In the installer, make sure the
Desktop development with C++ workload is checked, and choose OK to update your Visual Studio
installation.
If another project with the same name already exists, choose another name for your project, or delete the
existing project and try again. To delete an existing project, delete the solution folder (the folder that
contains the helloworld.sln file) in File Explorer.
The dropdown control does not appear in the SubSystem property edit box until you select the property.
You can select it by using the pointer, or you can press Tab to cycle through the dialog controls until
SubSystem is highlighted. Choose the dropdown control or press Alt+Down to open it.
If you added the wrong kind of file to your project, for example, a header file, delete it and try again. To
delete the file, select it in Solution Explorer and press the Delete key.
Having read the “Intro to Visual C++” document, you should now be able to use an IDE (Integrated
Development Environment) to write, compile and execute a C++ program. Using Visual C++ IDE,
complete the tasks below and save them on the computer. Insert the solution/answer in this document as
directed below. You must show the execution of below tasks, along with your completed Lab Report to
get your work graded. You must also submit this Lab Report.
Deliverables
Lab Task 1:
Create and execute Kernighan and Ritchie’s famous “hello, world” program:
#include <iostream>
using namespace std;
int main()
{
cout << “ your name \n”;
}
(i) Make changes to the program such that your first name and last name are printed on two separate lines.
#include <iostream>
int main()
{
cout << "Any intelligent fool,";
cout << "\n can make things bigger, more complex, \n and more violent.";
cout << "It takes a touch of genius -- \n and a lot of courage -- ";
cout << "to move in the opposite direction.";
cout <<"--Albert Einstein”;
}
(i) Make changes to the program such all the text is printed without any new line breaks.
(iii) Show quotation marks on Albert Einstein on the output screen, like “Albert Einstein” by using the
command \“ Albert Einstein \”.
#include <iostream>
using namespace std;
int main()
{
// your code here
cout << “Your code goes here \n”;
}
(i) write a program to display the following by changing indentation and line breaks:
Fun is life.
Life is precious.
(ii) Add comments in this program clearly identifying start of program, end of program and monitor
display statement. Comments are written on each line with the symbol // e.g.
// This is a comment.
National University of Technology,
Islamabad
CE1004 Computer Programming for Engineering
Applications
Instructor Name: Dr. Zulfiqar Ali Program: Civil
Engineering
LAB 03
Variables and constants, Data types and Expressions
Lab Objectives
• Familiarization with building blocks of C++ and conversion of mathematical/engineering expressions
into an equivalent C++ statements
• Input from the user and display it
Tasks
1) Read the values of x and y and print the results of the following expressions in one line:
a. (x + y) / (x - y)
b. (x + y)(x - y)
Evaluate and compare the expressions with and without parenthesis.
Source Code
int main()
x = 9;
y = 3;
rslt1 = (x + y) / (x - y);
rslt2 = (x + y) * (x - y);
cout << endl << "Resultant First Expression: with parenthesis: " << rslt1;
cout << endl << "Resultant Second Expression: with parenthesis: " << rslt2;
rslt1 = x + y / x - y;
rslt2 = x + y * x - y;
cout << endl << "Resultant First Expression: without parenthesis: " << rslt1;
cout << endl << "Resultant Second Expression: without parenthesis: " << rslt2;
cout << endl;
}
2) Evaluate the arithmetic expression ((a + b / c * d - e) * (f - g)). Read the values a, b, c, d, e, f, g
from the standard input device.
int a, b, c, d, e, f, g;
cout << "Enter the value of a , b , c, d, e, f, g";
cin >> a >> b >> c >> d >> e >> f >> g;
int exp = 0;
exp = ((a + b / c * d - e) * (f - g));
cout << endl << "Expression evlauates to: " << exp;
cout << endl;
}
3) Computes and outputs the surface area and volume of a sphere with radius r (r is given/taken from
user as input)
int main()
{
/* A = 4 * pi * r*r;
V = 4/3 pi*r*r* ; */
float pi = 3.14;
float r, area, vol;
area = 4 * pi * r * r;
vol = 4 / 3 * pi * r * r;
• Learn the student, how to use if/else selection statements, and use it to write and
execute a simple program.
• Applying the arithmetic operations with if/else selection statements, and use it to
write and execute a program.
• Convert arithmetic expression from scientific notation to C++ notation.
Background:
Relational and Comparison Operators
Two expressions can be compared using relational and equality operators. For example, to know if
two values are equal or if one is greater than the other. C++ supports six comparison operators ==,
!=, >, <, >=, <= . Comparison operators always use two operands and result of such an operation is
either true or false (i.e., a Boolean value 1 or 0).
The relational operators in C++ are:
operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less
than or
equal to
>= Greater than or
equal to
Examples:
It’s not just numeric constants that can be compared, but just any value, including variables.
Suppose that a=2, b=3 and c=6, then:
Note: The assignment operator (operator =, with one equal sign) is not the same as the equality
comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the
right-hand to the variable on its left, while the other (==) compares whether the values on both sides
of the operator are equal. Therefore, in the last expression ((b=2) == a), we first assigned the value
2 to b and then we compared it to a (that also stores the value 2), yielding true.
The logical operators & & and j j are used when evaluating two expressions to obtain a single
relational result. The operator & & corresponds to the Boolean logical operation AND, which yields
true if both its operands are true, and false otherwise. The following panel shows the result of
operator & & evaluating the expression a& & b:
The operator j j corresponds to the Boolean logical operation OR, which yields true if either of its
operands is true, thus being false only when both operands are false. Here are the possible results
of aj j b:
If Statement:
• Condition
• Expression can be either true or false
• Can be formed using equality or relational operators
• if statement
• If the condition is true, the body of the if statement executes
• If the condition is false, the body of the if statement does not execute
If (Condition )
{
Statement(s);
}
Pre-lab:
The student should know the structure of a simple C++ program, in that, any program may
be written according to the following format:
#include<iostream>
using namespace std;
void main()
{
//Program body
}
The student should know the keywords of simple C++.
Lab Task 1
Determine if number is prime
Lab Task 2
Reads in the coordinates of two points, computes the slope of the line through the two points, and
outputs the message "Negative slope", "Zero slope", "Positive slope" or "Infinite slope" depending
upon whether the slope is negative, zero, positive or infinite.
OR
A character is entered through keyboard. Write a C program to determine whether the character
entered is a capital letter, a small case letter, a digit or a special symbol using if-else and switch
case. The following table shows the range of ASCII values for various characters.
Characters ASCII values
A–Z 65 – 90
a–z 97 – 122
0–9 48 – 57
Special symbols 0 – 47, 58 – 64, 91 – 96, 123 – 127
Lab Task 3
You have to write a program to aid in the selection of a cricket team. Your program will take the
following information as input:
- Batting average (greater than or equal to 0)
- Bowling average (greater than or equal to 0)
- Type of Bowler (‘f’ for fast bowler and ‘s’ for spinner)
- Batting strike rate (greater than 0)
- Economy rate (greater than or equal to 0)
If the stats of a player are such that he can not be put into any of the above three categories, then
your program should state that the player should be part of the Reserves.
If his batting average is greater than or equal to 45 AND his bowling average is greater than or equal
to 60.
If his bowling average is less than or equal to 30 AND his batting average is less than 20.
If his batting average is greater than or equal to 40 AND his bowling average is less than or equal to
30.
In case of a Bowler,
If he is a spinner AND his average is between 20 and 30 (both inclusive) AND his economy rate is
less than or equal to 3 then he should play in a Test side – otherwise in ODIs.
If he is a fast bowler AND his average is between 20 and 30 (both inclusive) AND his economy rate
is less than or equal to 5 but greater than 3 then he should play in ODIs – otherwise in Tests.
For an All-rounder
If the batting average is greater than or equal to 40 AND the bowling average is less than or equal to
25 then he should be playing in Tests – otherwise in ODIs.
In addition,
Lab Task 4
A teacher would like his students to play a small game. The rules of the game require that the
students be divided into 4 groups (Red, Green, Blue and Purple) based on the following information
for each student:
1. The roll number of the student – not more than 3 digits long and ranging between 1 and 400
2. The score of the student the last time he played this game (scores will be between 0 and 100)
Your task is to write a program that automatically decides the new group of the student when the
above information is entered. Your program must take into consideration the following rules for
group assignment:
If Roll_no between And score between The assign this group
1 and 100 0 and 25 RED
26 and 50 GREEN
51 and 75 BLUE
76 and 100 PURPLE
101 and 200 0 and 25 GREEN
26 and 50 RED
51 and 75 PURPLE
76 and 100 BLUE
201 and 300 0 and 25 PURPLE
26 and 50 BLUE
51 and 75 RED
76 and 100 GREEN
301 and 400 0 and 25 BLUE
26 and 50 PURPLE
51 and 75 GREEN
76 and 100 RED
Note: The roll number and score entered by the user should not be out of their respective ranges. If
they are out of range, then the program should give an appropriate message and close down with
an appropriate ‘flag’.
Hint: There are four ways through which a student might end up in any one group – try to formulate
your conditions by keeping that in mind.
LAB 05
Selection Structures
Lab Objectives:
• If the value in the switch statement is equal to the value in one of the case statements,
the body of the case statement executes
• If the value in the switch statement doesn’t match any value of the case statements, the
body of the default statement executes
Figure 1 Switch Statement
Pre-lab:
The student should know the structure of a simple if statement:
If (Condition )
{
Statement(s);
}
Figure 2 The structure of the if statement
Lab Task 1
Implement of simple calculator using switch case statements. The program should ask the user
to input two operands and an operation, your program should print the result of performing the
required operation on the input operands as the following output suggests:
Enter operand 1: 5
Enter operand 2: 10
Enter operation: /
The result of 5/10 is 0.5
*Use Menu-Driven Programs
Lab Task 2
An aircraft system is designed which checks speeds and monitors various functions of the
aircraft during the flight. Warnings and errors are generated if any fault develops during the
flight. The system is coded in a manner that if 100 is entered as input it indicates “normal
speed range”, if 101 is entered it gives “over-speed warning” indicating that aircraft is over
speeding. If 88 is entered, it indicates “Low Oil Pressure” and if 187 is entered it indicates
“Engine Failure”. Use switch statement to implement this logic.
Lab Task 3
Write a program which allows the user to type his own ID. If the ID is valid it will ask him to enter
his password, if the password is correct the program will print the name of the user. Otherwise
the program will print Incorrect Password and if the ID does not exist , the program will print
Incorrect ID .
*Use Nested structure
LAB – 06
Repetition Structures
Lab Objectives:
Students should be able to
Lab Task 2
write a complete C++ program that implements a simple calculator. The operators are +, -, *,
and /. If the user types in ‘q’ or ‘Q’, then quit. If the user enters any other character, then repeat
the input message. Assume that the user is entering only integer values and that the output is
an integer. A correct solution to this problem uses only while and if statements.
Lab Task 3
Using while loop write a program that takes input from the user and keep taking an input till a
sentinel value -999 is entered. Program should print the max and minimum of all the values
entered.
LAB-07
Repetition Structures
• explain the basics of while and for loops and while loops
• apply the syntaxes of loop structures
• design programs using loop structures
• solve (hard) problems of repetitive nature using loop structures Background:
Loop structures called for loops and while loops are covered as some basic control
structures. The loop can be used to do repetitive calculations. Though human beings can do
calculation or processing or repetitive nature by hand, it is much slower and tedious for the
human being. Good and solid logic of loop structures can be used to solve such problems in
a very efficient way.
For example, in order to compute the sum of 1 + 2 + 3 + … + 100, we can do easily using the
following code:
int sum = 0;
for (int j = 1; j <= 100; j++)
sum += j;
There are two control structures used often: the for loop and the while loop (and do while as
a different way of while).
Lab Objectives:
Background:
The function is a good mechanism to encapsulate code used repeatedly in a program so that it can be
called from other parts of the code. A function does not use a keyword called function but instead the
programmer has to define function prototype before the main function and then define the function
again later.
A function has the following format:
type function_name (optional parameter list)
{
function code;
return value;
}
Return data type of function is in general the types of C++ variable types including int, double, char etc.
The function does some processing and the calculated value is returned using the return value.
In the main function or the other functions calling this function_name, the value returned is used like
the instruction:
calling_value = function_name (parameters);
A function does not need to always return a value. A function not returning a value can omit the return
statement and the function type is void in this case. Function prototype has the following format:
type function_name (list of variable types);
Examples are:
Example 1:
int compute_sum (int);
Example 2:
void tryout ();
Function prototypes differ from the function definitions in two places: there is no code (no {} with code
in between) and the variable names do not follow the types. A function prototype can return nothing, in
which case void is the type returned; also it may have no parameters at all like example 2 above.
The function prototype is declared before the main function with the function calls inside the main
function or the other functions calling this function. The function definitions are put after the main
function.
C++ Standard Library: is a collection of functions, which are written in the core language and part of
the C++ ISO Standard itself to provides several generic functions that utilize and manipulate these
containers, function objects, generic strings and streams (including interactive and file I/O), support for
some language features, and everyday functions for tasks such as finding the square root of a number.
Using sqrt requires <math.h> header file.
Pre-labs:
In order to do this lab, students should know how to write, compile, and run a C++ program, and
understand what functions are and how to invoke them. They should also be familiar with an editor.
Assessment tools:
The assessment is according to the student participation in the lab if the student solves the
exercise, (s)he will get the participation mark for this lab.
Consider the following code that computes the sum of 1 + 2 + 3 + .. + 100 by a for loop.
#include <iostream>
using namespace std;
int main ( )
{
int sum = 0;
for (int j = 1; j <= 100; j++)
sum += j;
cout << “The sum of 1 + 2 + 3 + .. + 100 is “ << sum <<
endl;
return 0;
}
This program shows how to compute a sum in a quick way. The program can be easily modified to
compute and display the sum of 1 + 2 + .. + n for a variable n (with n = 100 as above).Such code of (3
lines) computing the sum can be coded as one instruction in the main function compute_sum (n) with
the variable n as the parameter.
The function prototype is declared before the main function with the function calls inside the main
function or the other functions calling this function. The function definitions are put after the main
function as follow:
int compute_sum (int x)
{
int sum = 0;
for (int j = 1; j <= x; j++)
sum += j;
return x;
}
Lab Task 01
Use the array data structure to represent a set of related data items.
Declare arrays, initialize arrays and refer to the individual elements of arrays.
Background
Definition
Array: A collection of individual values, all of the same data type, stored in adjacent memory locations.
One Dimensional Array: An array with a single variable index. Using the array name together with an
integral valued index in square brackets refers to the individual values. The first array element always
has the subscript 0. The second array element has the subscript 1, etc.
The base address of an array is its beginning address in memory.
Declaring an Array: Use the following syntax below.
DataType ArrayName [ConstIntExpression];
The example below shows the declaration of an integer array of size 10 with element 0 - 9.
const int MAXSIZE = 10;
int array[MAXSIZE];
Arrays can be initialized during declaration by equating the array to a listing of the array's members in
brackets. For example
int array[MAXSIZE] = {2 , 4, 6, 8, 10, 12, 14, 16, 18, 20};
Lab Task 01
In this task you need to do the following:
2. Now take 5 values from user as input and store them in this array
Lab Task 02
Take 5 integer inputs from user and store them in an array. Again, ask user to give a
number. Now, tell user whether that number is present in array or not.
Lab Task 03
Take 11 floating point numbers from user and store them in an array. Now, compute and display
average of elements at first, middle and last positions.
Lab Task 04
Take 5 integer inputs from user and store them in an array. Now, copy all the elements in
another array but in reverse order.
Lab Task 05
Write a program to display largest and smallest elements of an Array.
Lab Task 06
Write a program to add the most significant digits of all the elements in 1D-Array.
Example:
Input: [321, 2345, 4, 876, 54]
Ouput: 3+2+4+8+5 = 22
Lab Task 07
Write a program that can swap the second largest and second smallest values in an array of size
10.
Lab Task 08
In this task, you need to do the following:
LAB 11
ARRAYS-II (MULTI-DIMENSIONAL ARRAYS)
Lab Objectives:
Students will learn how to:
• Pass arrays to functions.
• Declare and manipulate Two-dimensional arrays.
Background
Lab Task 01
In this task, you need to do the following:
Lab Task 02
Create an array of size 5x5 first fill the array with random values between 1 and 100, print it in straight
and reverse order. Now, fill that array from the user input and print it in straight and reverse order.
Lab Task 03
Write a program to add two matrix using multi-dimensional dimensional arrays.
Lab Task 04
Write a program to declare a 3x3 integer type array and store values by taking input from user and find
sum of lower triangular matrix.
Lab Task 05
Take an array of size 5x5 and initialize it with random numbers of range 1 to 10, now add all the elements
of the 2D array and display sum.
• Modify part a in such a way that you have to find individual sum of each row of the 2D array and
store corresponding result in 1D array i.e. sum of all the elements of row 0 should be stored in
1st element of 1D array, similarly sum of all elements of the second row of 2D array should be
stored at the second index of 1D array. Display the final sum array (i.e. 1D array). Think about
the size of 1D array yourself.
Example Array:
23531
45121
47320
21151
17890
Sum array:
13 23 18 21 3
• Perform sum of all the elements of the arrays whose row number and column number both are
odd. Display the final sum. it.
Example Array:
23531
45121
47320
21151
17890
Sum array: 13
Lab Task 06
You have to create two 2D arrays and do a matrix multiplication. E.g. If First array is of size 3x2
and 2nd one of 2X2.
Lab Task 07
Write a program to find a sub-string within different strings. If found display the starting positions.
(Using 2D-array)
Lab 12
• Memory concept of variables, pointers and how to use variable identifiers and pointers to refer to
the variable.
• Pointer variable declarations and initialization.
• Direct and indirect referencing a variable using the pointer operators.
• Using * and address (&) operators.
Background:
When declaring a variable, it is located at a specific location in memory, the memory address. The task of
locating variables is automatically performed by the operating system during runtime. In some cases we
need to know the address where the variable is being stored during runtime.
Variable which stores a reference to another variable is called a pointer. We can directly access the value
stored in the variable using a pointer which points to it.
FILE HANDLING
Syntax:
1. Pointer Declaration:
Syntax:
Pointer_type *Pointer_name;
Example:
int *Ptr1;
double *Ptr2;
2. Pointer initialization:
Syntax:
Pointer_name=NULL;
Pointer_name=&variable_name;
Example:
int *Ptr1, var;
Ptr1=&var;
Lab Task 01:
Write a c++ program that defines an integer variable var1 and a pointer Ptr that points to var1. Assign and
print value to var1, then assign and print a new value to var1 using Ptr.
Solution:
#include<iostream>
using namespace std;
void main()
{
int var1,*ptr;
ptr=&var1;
var1=10;
cout<<var1;
cout<<endl;
*ptr=20;
cout<<*ptr;
}
Lab 13
Strings
Lab Objectives:
Background
C++ Strings
One of the most useful data types supplied in the C++ libraries is the string. A string is a variable that
stores a sequence of letters or other characters, such as "Hello"or "May 10th is my birthday!".
Just like the other data types, to create a stringwe first declare it, then we can store a value
in it.
string testString;
testString = "This is a string.";
We can combine these two statements into one line:
In order to use the string data type, the C++ string header <string>must be included at the
top of the program. Also, you’ll need to include using namespace std; to make the short
name stringvisible instead of requiring the cumbersome std::string. (As a side note, std is a
C++ namespace for many pieces of functionality that are provided in standard C++ libraries.
For the purposes of this class, you won't need to otherwise know about namespaces.) Thus,
you would have the following #include's in your program in order to use the stringtype.
#include <string>
using namespace
std;
Basic Operations
Let’s go into specifics about the string manipulations you’ll be doing the most.
Counting the number of characters in a string. The length method returns the number
of characters in a string, including spaces and punctuation. Like many of the string
operations, length is a member function, and we invoke member functions using dot notation.
The string that is the receiver is to the left of the dot, the member function we are invoking is to
the right, (e.g. str.length()). In such an expression, we are requesting the length from the
variable str.
Example Program:
#include <string>
#include <iostream>
using namespace std;
int main() {
string small, large;
small = "I am short";
large = "I, friend, am a long and elaborate string indeed";
cout << "The short string is " << small.length()<< " characters." << endl;
cout << The long string is " << large.length()<< " characters." << endl; return 0;
}
output:
The short string is 10 characters.
The long string is 48 characters.
Accessing individual characters. Using square brackets, you can access individual
characters within a string as if it’s a char array. Positions within a string str are numbered
from 0 through str.length()-1. You can read and write to characters within a string using [].
Example Program:
output:
I am Q the omnipotent
ch = Q
Be careful not to access positions outside the bounds of the string. The square bracket
operator is not range-checked and thus reading from or writing to an out-of-bounds index
tends to produce difficult-to-track-down errors. There is an alternate member function
at(intindex)that retrieves the character at a position with the benefit of built-in range-
checking, but it’s used much less often.
Passing, returning, assigning strings. C++ strings are designed to behave like ordinary
primitive types with regard to assignment. Assigning one string to another makes a deep
copy of the character sequence.
Comparing two strings. You can compare two strings for equality using the == and !=
operators. Suppose you ask the user for his or her name. If the user is Julie, the program
prints a warm welcome. If the user is not Neal, the program prints the normal message.
Finally… if the user is Neal, it prints a less enthusiastic response.
Example program:
#include <string>
#include <iostream>
using namespace std;
int main() {
string myName = "Neal";
while (true) {
cout << "Enter your name (or 'quit' to exit): ";
string userName = getLine();
if (userName == "Julie") {
cout << "Hi, Julie!Welcome back!" << endl;
} else if (userName == "quit") {
// user is sick of entering names, so let's quit
cout << endl;
break;
} else if (userName != myName) {
// user did not enter quit, Julie, or Neal
cout << "Hello, " << userName << endl;
} else {
cout << "Oh, it’s you, " << myName << endl;
}
output:
Enter your name (or 'quit' to exit): Neal
You can use <, <=, >, and >=to compare strings as well. These operators compare strings
lexicographically, character by character and are case-sensitive. The following
comparisons all evaluate to true: "A"<"B","App" <"Apple", "help" > "hello", "Apple"
<"apple". The last one might be a bit confusing, but the ASCII value for 'A' is 65, and
comes before 'a', whose ASCII value is 97. So "Apple" comes before "apple" (or,
for that matter, any other word that starts with a lower-case letter).
Appending to a string: C++ strings are wondrous things. Suppose you have two strings, s1
and s2 and you want to create a new string of their concatenation. Conveniently, you can just
write s1 + s2, and you’ll get the result you’d expect. Similarly, if you want to append to the
end of string, you can use the +=operator. You can append either another string or a single
character to the end of a string.
Example Program:
#include <string>
#include <iostream>
using namespace std;
int main() {
string firstname = "Leland";
string lastname = " Stanford";
string fullname = firstname + lastname; // concat the two strings
fullname += ", Jr"; // append another string
fullname += '.'; // append a single char
cout << firstname << lastname << endl;
cout << fullname << endl;
}
output:
Leland Stanford
Leland Stanford, Jr.
More (Less Used) Operations
The string class has many more operations; we’ll show just a few of the more useful ones
below.
Searching within a string. The string member function find is used to search within a string
for a particular string or character. A sample usage such as str.find(key) searches the
receiver string strfor the key. The parameter keycan either be a string or a character. (We say
the find member function is overloaded to allow more than one usage). The return value is
either the starting position where the key was found or the constant string::nposwhich
indicates the key was not found.
Occasionally, you’ll want to control what part of the string is searched, such as to find a
second occurrence past the first. There is an optional second integer argument to find which
allows you to specify the starting position; when this argument is not given, 0 is assumed.
Thus, str.find(key, n)starts at position nwithin strand will attempt to find key from that point
on. The following code should make this slightly clearer:
Example Program:
output:
First we: 5
Second we: 8
Third we: 28
Extracting substrings. Sometimes you would like to create new strings by extracting portions
of a larger one. The substrmember function creates substrings from pieces of the receiver
string. You specify the starting position and the number of characters. For example,
str.substr(start, length) returns a new string consisting of the characters from strstarting at the
position startand continuing for lengthcharacters. Invoking this member function does not
change the receiver string, as it makes a new string with a copy of the characters specified.
Example program:
#include <string>
#include <iostream>
using namespace std;
int main() {
string oldSentence;
oldSentence = "The quick brown fox jumped WAY over the lazy dog"; int len
= oldSentence.length();
cout << "Original sentence: " << oldSentence << endl;
int found = oldSentence.find("WAY ");
string newSentence = oldSentence.substr(0, found);
cout << "Modified sentence: " << newSentence << endl;
newSentence += oldSentence.substr(found + 4);
cout << "Completed sentence: " << newSentence << endl;
Output:
Original sentence: The quick brown fox jumped WAY over the lazy dog
Modified sentence: The quick brown fox jumped
Completed sentence: The quick brown fox jumped over the lazy dog
There are a couple of special cases for substr(start, length). If startis negative, it will cause
a run-time error. If startis past the end of the string, it will return an empty string (e.g., ""). If
lengthis longer than the number of characters from the start position to the end of the string,
it truncates to the end of the string. If lengthis negative, then the behavior is undefined, so
make sure that length is always non-negative. If you leave off the second argument, the
number of characters from the starting position to the end of the receiver string is assumed.
Modifying a string by inserting and replacing. Finally, let’s cover two other useful member
functions that modify the receiver string. The first, str1.insert(start, str2), inserts str2 at position
start within str1, shifting the remaining characters of str1 over. The second, str1.replace(start,
length, str2), removes from str1 a total of length characters starting at the position start,
replacing them with a copy of str2. It is important to note that these member functions do modify
the receiver string.
Example Program:
#include <string>
#include <iostream>
using namespace std;
int main() {
string sentence = "CS106B sucks.";
cout << sentence << endl;
// Insert "kind of" at position 8 in sentence
sentence.insert(7, "kind of ");
cout << sentence << endl;
// Replace the 10 characters "kind of su" with the string "ro" in sentence
sentence.replace(7, 10, "ro");
cout << entence << endl;
}
output:
CS106B sucks.
CS106B kind of sucks.
CS106B rocks.
#include "console.h"
int main() {
ifstream fs;
string filename = "courseinfo.txt"; string
s;
// open function requires a C-style string, must convert! fs.open(filename.c_str());
if (fs.fail()) return -1; // could not open the file!
#include "genlib.h"
#include "strlib.h"
int main() {
string str1 = "5.6";
double num = stringToReal(str1); string
str2 = integerToString(45);
cout << "The original string is " << str1 << "." << endl; cout << "The
number is " << num << "." << endl;
cout << "The new string is " << str2 << "." << endl; return 0;
}
Output:
The original string is 5.6.
The number is 5.6
Any integer or real can be safely converted to a string. However, when converting in the
other direction, if you pass an improperly formatted string to convert to an integer or real, an
error is raised by the conversion functions.
topUpperCase, toLowerCase: These functions take a string, and return a new string with all
letters in lower or upper case respectively. These can be used to change two strings to a
uniform case before comparing to allow a case-insensitive comparison.
Example program:
#include <string>
#include <iostream>
using namespace
std;
#include "genlib.h"
#include "strlib.h"
int main() {
string appleFruit = "apples"; string
orangeFruit = "ORANGES";
cout << "Do " << appleFruit << " come before " << orangeFruit << "? "; cout <<
(appleFruit < orangeFruit ? "Yes!" : "Nope ... ") << endl;
cout << "Do " << appleFruit << " come before " << lowerOrangeFruit << "? "; cout <<
(appleFruit < lowerOrangeFruit ? "Yes!" : "Nope ... ") << endl; return 0;
}
Output:
Do apples come before ORANGES? Nope....
There are a few other functions within the strliblibrary (equalsIgnoreCase, startsWith,
endsWith, and trim) as well.
Lab 14
File Handling
Lab Objectives:
This lab would make students learn
;
• File I/O class fstream in C++ which is used for File Read/Write operations
• Use of file operations, use it to write and execute a simple program.
• Creation of a file using simple program.
• Writing in a file using simple program
• Reading from a file using simple program
• Implement all previous application using file stream
Background:
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Lab Objectives:
Provide Lab Objectives here
Requirements for Lab:
Hardware: Computer Systems for each individual
Software: Microsoft Visual Studio (Visual C++)
Annex A
Lab Tasks
Task 1:
< Task Statement >
Algorithm Steps/Procedure Followed/Program Flow Chart for Task 1
<Algorithm>
<Flow Chart>
Program Code:
Test Cases
<testcases goes here > E.g write a program that adds two integer numbers. In order to
test your program give two valid inputs and two invalid inputs. Each task must have
such test case table
Sample Input Sample Output
x=1, y=1 2
x=11212121212121212121212, 11212121212121212121213
y=1
x= , y= Error
x=1, y=4.5 Error
Output Screen
Annex A
Your screenshot/picture of output goes here
Task 2:
< Task Statement >
Similar format to be adapted as above.
Note: Each lab report is checked for plagiarism. Any student who involves in copying other
student program will be held accountable plus his marks for respective task will be
compromised. Without prior discussion from lab instructor late report will not be accepted.
If any issues are faced in labs duly consult lab instructor.
FONT: Arial
Heading Size: Arial – 12 points, Bold
Text Size: Arial – 12 points