0% found this document useful (0 votes)
5 views

PF Lab manual

The CE1004 Lab Manual for Computer Programming for Engineering Applications at the National University of Technology outlines the course objectives, policies, and a detailed schedule of lab experiments focused on C++ programming. It emphasizes hands-on experience in programming fundamentals, including algorithms, flowcharts, and various programming concepts such as data types, control structures, and file handling. The manual also includes guidelines for lab conduct, report submissions, and ethical standards for students.

Uploaded by

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

PF Lab manual

The CE1004 Lab Manual for Computer Programming for Engineering Applications at the National University of Technology outlines the course objectives, policies, and a detailed schedule of lab experiments focused on C++ programming. It emphasizes hands-on experience in programming fundamentals, including algorithms, flowcharts, and various programming concepts such as data types, control structures, and file handling. The manual also includes guidelines for lab conduct, report submissions, and ethical standards for students.

Uploaded by

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

National University of Technology,

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

Title Computer Programming for Engineering Applications


Description
Created By Dr. Zulfiqar Ali
Date of
Creation
Maintained
By
Version No. Changes Updated Updating Status
Made By Date
v-1.0 Active
Foreword

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

Fundamentals of programming language and familiarization with programming


Week 02 environment using MS Visual studio.
• Print your name, favorite color, favorite song and favorite food.
• Use of Escape Sequences
• Input from the user and display it
Variables, Data types and Expressions

Familiarization with building blocks of C++ and conversion of


mathematical/engineering expressions into an equivalent C++ statements
• Read the values of x and y and print the results of the following expressions in
one line:

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)

Constants and Mathematical Functions


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

• Determine if the number is even or odd


• Reads in the coordinates of two points, computes the slope of the line through
Week 05 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.
• 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
Selection Structure

• Implementation of simple & scientific calculators using switch case statements


Week 06
•If cost price and selling price of an item is input through the keyboard, write a
program to determine whether the seller has made profit or incurred loss.
Program should determine and print how much profit or loss incurred in
percentage.
Repetition Structures

• Determine if number is prime


Week 07 • Generate all the prime numbers between 1 and n, where n is a value supplied
by the user.
• Print and sum all the numbers given as an input by the user. The program
should keep on executing till the user enters -999 (using while loop)
Week 08 Mid-Term

Week 09 Nested Loops

• Print the numbers in triangular form


1
1 2
12 3
123 4
• Sum of individual digits of a 3 digit number
• Performing simple bank transactions as many times as user wants (Applying
the concept of conditional break , while & do-while loops)
Functions
• Simple Calculator using Functions
Week 10 • Programs that use non-recursive functions
i. To find min of two numbers and print it
ii. To find max of two numbers and print it
Functions (Return Types)
Week 10
• Find the greatest common divisor of two given integers / LCM.
• Reads in n numbers and outputs their average and standard deviation.
• Reverse a given number
• Functions to:
i. Print Factorial of Number
ii. Print Fibonacci series
iii. Solve towers of Hanoi problem
Arrays, Multi-Dimensional Arrays

• Find the second largest integer in a list of integers.


• Count and display positive, negative, odd and even numbers in an array.
• Merge two sorted arrays into another array in a sorted order.
Week11
• Find the frequency of a particular number in a list of integers.
• Addition of two matrices
• Multiplication of two matrices

Strings

• Uses functions to perform the following operations:

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

• Display the contents of a file.

Week 14 • Copy the contents of one file to another.


• Reverse the first n characters in a file, where n is given by the user.
• Two files DATA1 and DATA2 contain sorted lists of integers. Write a program
to merge the contents of two files into a third file DATA i.e., the contents of the
first file followed by those of the second are put in the third file.
• Reads in numbers from a file and prints each number and its cosine to a second
file.

Week 15 Open Ended Lab & Revision

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.

An algorithm is a representation of a solution to a problem. If a problem can be defined as a


difference between a desired situation and the current situation in which one is, then a problem
solution is a procedure, or method, for transforming the current situation to the desired one. We
solve many such trivial problems every day without even thinking about it, for example making
breakfast, travelling to the workplace etc. But the solution to such problems requires little
intellectual effort and is relatively unimportant. However, the solution of a more interesting
problem of more importance usually involves stating the problem in an understandable form and
communicating the solution to others. In the case where a computer is part of the means of
solving the problem, a procedure, explicitly stating the steps leading to the solution, must be
transmitted to the computer. This concept of problem solution and communication makes the
study of algorithms important to computer science.

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.

"4 extra large eggs, beaten 1&1/2 C. stock


1/2 teaspoon salt 1 scallion, minced
1 C. small shrimp or lobster flakes 1 t. soy sauce
1 Tablespoon oil
1. Mix all the ingredients, except the oil, in a deep bowl.

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.

Symbol Name Function


Process Indicates any type of internal operation inside
the Processor or Memory

input/output Used for any Input / Output (I/O) operation.


Indicates that the computer is to obtain data
or output results

Decision Used to ask a question that can


be answered in a binary format (Yes/No,
True/False)

Connector Allows the flowchart to be drawn without


intersecting lines or without a reverse flow.

Predefined Process Used to invoke a subroutine or an


interrupt program.

Terminal Indicates the starting or ending of


the program, process, or interrupt
program.

Flow Lines Shows direction of flow.

Generally, there are many standard flowcharting symbols.


General Rules for flowcharting

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.

Note all circumstances actually dealt with.


• Test the flow chart by trying to follow the chart to perform the process charted. If there
is a problem performing the operation as charted, note any differences and modify the
chart to correct. A better approach would be to have someone unfamiliar with the
process try to follow the flow chart and note questions or problems found.
• Include mental steps in the process such as decisions. These steps are sometimes
left out because of familiarity with the process, however, represent sources of
problems due to a possible lack of information used to make the decision can be
inadequate or incorrect if performed by a different person.

Examples of Algorithms and Flowcharts

Example 1. Design an algorithm and the corresponding flowchart for adding the test
scores as given below:

26, 49, 98, 87, 62, 75


a) Algorithm

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

b) The corresponding flowchart is as follows:


The algorithm and the flowchart above illustrate the steps for solving the problem of adding
six testscores. Where one testscore is added to sum at a time. Both the algorithm and
flowchart should always have a Start step at the beginning of the algorithm or flowchart
and at least one stop step at the end, or anywhere in the algorithm or flowchart. Since we
want the sum of six testscore, then we should have a container for the resulting sum. In
this example, the container is called sum and we make sure that sum should start with a
zero value by step 2.
Example 2: The problem with this algorithm is that, some of the steps appear more than once,
i.e. step 5 get second number, step 7, get third number, etc. One could shorten the algorithm
or flowchart as follows:

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

Create your app project


Visual Studio uses projects to organize the code for an app, and solutions to organize your projects.
A project contains all the options, configurations, and rules used to build your apps, and manages the
relationship between all the project's files and any external files. To create your app, first, you'll create
a new project and solution.
1. In Visual Studio, open the File menu and choose New > Project to open the Create a new
Project dialog. Select the Console App template, and then choose Next.
2. In the Configure your new project dialog, enter HelloWorld in the Project name edit box.
Choose Create to create the project.

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.

Add a source code file


In Solution Explorer, select the HelloWorld project. On the menu bar, choose Project, Add New Item
to open the Add New Item dialog.

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

std::cout << "Hello, world!" << std::endl;


return 0;

The code should look like this in the editor window:

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.

Make your project a console app issues


If you don't see Linker listed under Configuration Properties, choose Cancel to close the Property
Pages dialog and then make sure that the HelloWorld project is selected in Solution Explorer, not the
solution or another file or folder, before you try again.

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.

Add a source code file issues


It's okay if you give the source code file a different name. However, don't add more than one source code
file that contains the same code to your project.

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.

Add code to the source file issues


If you accidentally closed the source code file editor window, to open it again, double-click on
HelloWorld.cpp in the Solution Explorer window.
Case is significant in C++ code.
Instructions

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

Compile a Lab Report by filling in the solution/answer part and submit.

This lab is graded. Min marks: 0. Max marks: 10.


Lab Tasks

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.

Lab Task 02:

Consider the following program:

#include <iostream>

using namespace std;

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 \”.

Lab Task 03:

Given the following program:

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

-------- Computer Science is Fun----

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

/*Program to evaluate expression


i. (x + y) / (x - y)
ii. (x + y)(x - y) */
int x, y;
float rslt1, rslt2;

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.

/* Program to evaluate expression ((a + b / c * d - e) * (f - g)). */

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;

cout << endl << "Enter the radius: ";


cin >> r;

area = 4 * pi * r * r;
vol = 4 / 3 * pi * r * r;

cout << endl << "Area of Sphere: " << area;


cout << endl << "Volume of Sphere: " << vol;
cout << endl;
}
LAB – 04
Selection Structures
Lab Objectives:

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

Logical operators ( !, & & , j j )


The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its
right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically,
it returns the opposite Boolean value of evaluating its operand.
For example:

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

Figure1: the structure of the if statement

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)

Based on this information, you have to decide three things:


- Is he a batsman? If yes, then should he be playing in Tests or in ODIs?
- If not a batsman, is he a bowler? If yes, then should he be playing in Tests or in
ODIs?
- If he is both, then should he be playing in Tests or in ODIs?

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.

A player should be categorized as a Batsman,

If his batting average is greater than or equal to 45 AND his bowling average is greater than or equal
to 60.

A player should be categorized as a Bowler (regardless of his type),

If his bowling average is less than or equal to 30 AND his batting average is less than 20.

A player should be categorized as an All-rounder

If his batting average is greater than or equal to 40 AND his bowling average is less than or equal to
30.

Now, a Batsman should play in a Test side,


If his batting average is greater than or equal to 50 AND his strike rate is less than or equal to 70. If
this is not the case then he should play in ODIs.

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,

1. your program must handle all exceptional cases


2. your program must be properly commented

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:

Teach student the structure of the switch statement.


• How to convert between if/else and switch statement
Background:
Switch Statement
Value

• Integer value or variable or expression


• Char value or variable
• Bool value or variable
Case statement

• 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

• Explain the basics of 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.
Pre-lab:
1. Study Deitel’s book (how to program C++) control structures.
2. Explain which of the following for loops are valid and which are invalid and why.
3. Convert the following for loop to while loop.
4. Convert the following while loop to for loop.
5. Analyze the following for loops in the table and state whether
a. They compile
b. They run
c. They print out a line
d. They print out more than one line Answer yes or no to each.
for (j = 1; j <= 10; j++);
for (j = 1; j < 11; ++j);
for (j = 1; j <= 10; j++)
cout<<“Hello\ cout<<“Hello\n”;
for (j = 1; j <= 10; j++);
cout<<“Hello\ cout<<“Hello\n”;
for (j = 1, j <= 10, j++)
cout<<“Hello\ cout<<“Hello\n”;
Lab Task 1
Write a complete C++ program that allows the user the ability to enter an integer in the range of
some lower bound (minimum 2) to some upper bound (maximum 100), inclusive. After asking
the user for this integer, you are to print out whether the value entered is even or odd, prime or
not, and finally the sum of the digits.
Be sure that you validate that the user’s input is a number between 2 and 100 (inclusive)!

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

After performing this lab, the students should be able to

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

The syntaxes of these two loop structures are as follows:

for (initialize loop variables; loop terminator; loop variable update)


{
Statements in the block or one statement
}
Not all three components of the for loop are necessary, in fact for ( ; ; ) is a valid statement.
The loop variable update can be increments of loop variable(s) or decrements; there can be
more than one loop variable in the same for loop separated by comma (,) and there can also
be nested for loops of for loop inside for loop etc.
When there is only one statement in the block, the enclosing braces{} can be omitted.

The following are a few valid for loop statements


The loop structure can be used to do the following problems encountered often in the first
programming course (usually considered challenging for the students new to programming):
LAB 08 & 09
Functions

Lab Objectives:

After completing this lab, the students should be able to


• Explain the concepts of functions.
• use common math functions available in the C++ Standard Library.
• Explain what a function prototype is and how that is different from the function definition.
• Convert the code processing in the main function to a function called from the main function.
• Create functions with multiple parameters.
• The mechanisms for passing information between functions and returning results.

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

In this task, you need to do the following:


• Write a function named displayMessage() that takes user name as input in character array and
then shows greetings
• Now take the name input in main() and pass the name as an argument to displayMessage()
function
• Change the displayMessage() method such that it returns the number of characters after
displaying the greetings
Lab Task 02
Write a function power that takes two parameters a and b. And it returns the power as ab.
Lab Task 03
Write a function that inputs two integers in main() function and passes the integers to a function by
reference. The function swaps the value. The main() function should display the values before and after
swapping.
Temp= Variable A;
Variable A= Variable B; Variable B= Temp
Lab Task 04
Write a function that takes an integer n as parameter and returns the sum of its digits. For example, the
program should display 9 if the user enters 135.
Lab Task 05
Write a function that takes an array of integers and size of that array as argument and returns the mode,
which is the maximum value occurred in the array.
Lab Task 06
Define a function named ’perfect’ that determines if parameter number is a perfect number. Call this
function multiple times in main() to determine and print all the perfect numbers between 1 and 1000.
Note: An integer number is said to be "perfect number" if its factors, including 1(but not the number
itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
Lab Task 07
The Fibonacci Sequence is the series of numbers such that the next number is found by adding up the
two numbers before it. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Define a function that returns the nth term of a Fibonacci series.
e.g if n=7 then function should return 8
LAB 10
Array
Lab Objectives:
Students would learn how to

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:

1. Declare an integer array of size 5 and print its values.

2. Now take 5 values from user as input and store them in this array

3. Print all the values of array in reverse order

Note: You are not allowed to use any loop.:

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:

• declare a character array of size 20

• ask user to enter a sentence and store it in this array

• Display number of upper case and lower-case letters

• Print frequency of each vowel in the input

• Capitalize first letter of each word


National University of Technology,
Islamabad
CE1004 Computer Programming for Engineering
Applications
Instructor Name: Dr. Zulfiqar Ali Program: Civil
Engineering

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

Passing Arrays as Function Parameters


In C++, arrays are always passed by reference by default. Whenever an array is passed as a parameter,
its base address is sent to the called function. Generally, functions that work with arrays require 2 items of
information as actual parameters: the beginning address of the array (in memory), and the number of
elements to process in the array.

For example (Function PrintArray):

void PrintArray(int Array[], int ArraySize)


{
for (int i = 0; i <= ArraySize - 1; i++)
cout << "array[" << i << "] = "<<Array[i] << endl;
}

Declare and manipulate Two-dimensional arrays


Two-dimensional arrays store a tabular arrangement of values accessed by two indexes, for example
matrix[i][j], where i is the row index and j is the column index.
To declare and initialize a two-dimensional array, Use the following syntax below.
DataType ArrayName [row][column];
The example below shows the declaring two-dimensional array b
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };

Lab Task 01
In this task, you need to do the following:

• Declare a character array of size 20

• Ask user to enter a sentence and store it in this array

• Display number of upper case and lower case letters

• Print frequency of each letter in the input

• Convert uppercase letters to lowercase and vise versa

• Capitalize first letter of each word

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

Lab Objectives: Pointers


In this lab students will learn:

• 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 Task 02:


What will be the output of the following code?
#include<iostream>
using namespace std;
void main()
{
int nNumber;
int *pPointer;
nNumber = 15;
pPointer = &nNumber;
cout<<"nNumber: "<<nNumber
<<"\npPointer: "<<pPointer
<<"\n*pPointer: "<<*pPointer
<<"\n&nNumber: "<<&nNumber
<<"\n&pPointer: "<<&pPointer
<<"\n&*&*pPointer: "<<&*&*pPointer
<<"\n*&*&*pPointer: "<<*&*&*pPointer<<endl;
}

Lab Task 03:


Write a c++ program that use pointers to swap two integer values.
National University of Technology,
Islamabad
CE1004 Computer Programming for Engineering
Applications
Instructor Name: Dr. Zulfiqar Ali Program: Civil
Engineering

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:

string testString = "This is a string.";


Often, we use strings as output, and coutworks exactly like one would expect:

cout << testString << endl;


will print the same result as

cout << "This is a string." << endl;

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.

string str1 = "hello";


string str2 = str1; // makes a new copy
str1[0] = 'y'; // changes str1, but not str2
Passing and returning strings from functions clones the string. If you change a string
parameter within a function, changes are not seen in the calling function unless you have
specifically passed the string by reference (e.g. using that & trick we learned about in the
Queen Safety example.)

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

Oh, it's you, Neal

Enter your name (or 'quit' to exit): Julie

Hi, Julie! Welcome back!

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.

Obtaining a C-style char *from a string


Remember, a C++ string is not the same thing as a C-style string (which is merely a char *
pointer to a sequence of characters terminated by a null character '\0'). Although old-style C
char*strings and C++ strings can co-exist in a program, almost all our use will be of C++ strings,
since they have a much richer set of operations and are less error-prone to work with. I say
"almost always" because in a few unavoidable situations, we are forced to use old-style C
strings, most notably when working with file streams. We can convert a C++ string to the old-
style representation using the .c_str() member function. One use we will see of this is to get a
char*to pass to the iostream::open function.
Example Program:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

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

// process the file


fs.close();
return 0;
}

The CS106 Library: strlib.h


In addition to the standard library support for strings, there are a few extensions that the
CS106 libraries provide. To use these functions, the strlib.h library must be #included.

integerToString, realToString, stringToInteger, stringToReal: Often your programs will need


to convert a string to a number or vice versa. These functions do just that, with the 'integer'
functions operating on int and the 'real' functions on double.
Example program:
#include <string>
#include <iostream>
using namespace std;

#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

The new string is 45.

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;

string lowerOrangeFruit = toLowerCase(orangeFruit);

cout << "Do " << appleFruit << " come before " << lowerOrangeFruit << "? "; cout <<
(appleFruit < lowerOrangeFruit ? "Yes!" : "Nope ... ") << endl; return 0;
}

Output:
Do apples come before ORANGES? Nope....

Do apples come before oranges? Yes!

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 Task 01:


Create an empty text file using c++ program and set its location
#include<fstream.h>
int main()
{
fstream file_op("c:\\test_file.txt",ios::in);
file_op.close() ;
return 0;
}
Lab Task 02:
Assign value to an empty text file using c++ program
#include<fstream.h>
int main()
{
ofstream file_op("c:\\test_file.txt",ios::in);
int x=5;
file_op <<x;
file_op.close ();
}
Lab Task 03:
Read value from empty text file using c++ program
#include<fstream.h>
int main()
{
fstream file_op("c:\\test_file.txt",ios::in);
int x;
file_op >>x;
cout<<x;
file_op.close ();
return 0;
}

Lab Task 04:


Create a program for writing records of 10 students in a text file Students.txt. Store Roll
no, First name, Last name, Department and Section of student. Name of file: Student.txt

123 Asad Ali CS A

321 Abbas Khan AI C


342 Bilal Haider CSDF B

Lab Task 05:


Now write another program that take positive integer N and reads first N number of records
of students in a text file Students.txt. Program must read roll no, first name, last name,
department and section of student. Program must display the information read from the file.
Annex A

Computer Systems and Programming (LAB 01)

Registration Number Name

Instructor’s Name Instructor’s


Date
Signature

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:

<Insert your code in this box>

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

CLOs Learning Taxonomy


Description PLO
Domain Level
CLO 1 Build logic of a program, design an algorithm and Cognitive 2,3 PLO 5
make a flow chart to represent the solution of
problem.
CLO 2 Design and Implement the solution of problem Cognitive 4,5 PLO 5
using loops, arrays, functions, structures.

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy