Documente Academic
Documente Profesional
Documente Cultură
LAB MANUAL
Computer Programming
CE-112
Air University
Islamabad
1
Computer Programming Department of Computer Engineering Wajiha Javed
AIR UNIVERSITY
Faculty of Engineering
Department of Computer Engineering
Lab Information
Lab Schedule
Experiment CLO’s
No. Experiment Title
1 Introduction to Programming CLO1
2 Introduction to C++ Environment and Variables CLO1
3 If…Else in C++ CLO2
4 Switches in C++ CLO2
5 For Loop in C++ CLO2
6 While….Do While Controls in C++ CLO2
7 Arrays in C++ CLO2
Lab Mid
8 Multidimensional Arrays in C++ CLO2
9 User defined Functions in C++ CLO2
10 File Handling in C++ CLO2
11 Recursion in C++ CLO2
12 Pointers in C++ CLO2
13 Intro to Arduino IDE - Hardware , Configuration / Installation CLO2
14 Open Ended Lab CLO2
Lab Final
2
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #01:
Introduction to C++
Lab Objective:
Lab Description:
Computer is organized in different units in which the basic units are input, output,
memory and CPU. Input unit provide data and instructions to the CPU. Memory stores the data
and instructions; CPU executes the instructions and pass the results of the execution to the
output.
Algorithm is a well-define and ordered set of instructions which lead to a solution within finite
number of steps.
Compiler is a program that translates high-level language to machine language and
creates an executable file.
C++ program has one function main () by default without which the program will not
execute as the execution starts from the first instruction of the main function.
3
Computer Programming Department of Computer Engineering Wajiha Javed
In C++ taking input from user and printing output on display of computer is done by including a
header file in the C++ code called iostream.h which notifies the preprocessor to include the
input/output stream contents.
Example:
The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is needed..
This contains pre-defined input/output functions that we can use in our program.
The line using namespace std; tells the compiler to use the std namespace. Namespaces
are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
The line intmain() is the main function where program execution begins.
The next line cout<< "Hello World"; causes the message "Hello World" to be displayed
on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0 to
the calling process.
4
Computer Programming Department of Computer Engineering Wajiha Javed
cout<<endl<<”World”; World
Arithmetic Operations:
Variables:
Variables are used to store data inside them.The name of a variable can be composed of letters,
digits, and the underscore character. It must begin with either a letter or an underscore. Upper
and lowercase letters are distinct because C++ is case-sensitive
5
Computer Programming Department of Computer Engineering Wajiha Javed
Assignment operator:
Solve expression on right side and assign the result in variable of left side. For example.
#include<iostream>
using namespace std;
void main ()
{
int x, y;
cout<<”Enter a number: ”
cin>>x;
y = x*x;
cout<<“The square of “ << x << “ is: “ << y;
}
LAB TASKS:
2. Write a program in C++ that takes input from user and display message on screen?
6
Computer Programming Department of Computer Engineering Wajiha Javed
THINK!!
7
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #02:
Fundamentals of Programming
Lab Objective:
Lab Description:
A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++
is case-sensitive
TYPE DESCRIPTION
Char Stores either value true or false.
Int Typically a single octet (one byte). This is an
integer type.
Float The most natural size of integer for the
8
Computer Programming Department of Computer Engineering Wajiha Javed
machine.
Double A single-precision floating point value.
Void A double-precision floating point value.
Bool Represents the absence of type.
On most program environments, the standard output by default is the screen, and the C++ stream
object defined to access it is cout.
For formatted output operations, cout is used together with the insertion operator, which is
written as << (i.e., two "less than" signs).
The << operator inserts the data that follows it into the stream that precedes it. In the examples
above, it inserted the literal string Output sentence, the number 120, and the value of
variable x into the standard output stream cout. Notice that the sentence in the first statement is
enclosed in double quotes (") because it is a string literal, while in the last one, x is not. The
double quoting is what makes the difference; when the text is enclosed between them, the text is
printed literally; when they are not, the text is interpreted as the identifier of a variable, and its
value is printed instead. For example, these two sentences have very different results:
cout<< "This " << " is a " << "single C++ statement";
9
Computer Programming Department of Computer Engineering Wajiha Javed
This last statement would print the text This is a single C++ statement. Chaining insertions is
especially useful to mix literals and variables in a single statement:
cout<< "I am " << age << " years old and my zipcode is " <<zipcode;
Assuming the age variable contains the value 24 and the zipcode variable contains 90064, the
output of the previous statement would be:
What cout does not do automatically is add line breaks at the end, unless instructed to do so. For
example, take the following two statements inserting into cout:
The output would be in a single line, without any line breaks in between as above.
To insert a line break, a new-line character shall be inserted at the exact position the line should
be broken. In C++, a new-line character can be specified as \n (i.e., a backslash character
followed by a lowercase n). For example:
Alternatively, the endl manipulator can also be used to break lines. For example:
The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it
10
Computer Programming Department of Computer Engineering Wajiha Javed
also has an additional behavior: the stream's buffer (if any) is flushed, which means that the
output is requested to be physically written to the device, if it wasn't already. This affects
mainly fully buffered streams, and cout is (generally) not a fully bufferedstream. Still, it is
generally a good idea to use endl only when flushing the stream would be a feature and '\n' when
it would not. Bear in mind that a flushing operation incurs a certain overhead, and on some
devices it may produce a delay.
In most program environments, the standard input by default is the keyboard, and the C++
stream object defined to access it is cin.
For formatted input operations, cin is used together with the extraction operator, which is written
as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the
extracted data is stored. For example:
int age;
cin>> age;
The first statement declares a variable of type int called age, and the second extracts from cin a
value to be stored in it. This operation makes the program wait for input from cin; generally, this
means that the program will wait for the user to enter some sequence with the keyboard. In this
case, note that the characters introduced using the keyboard are only transmitted to the program
when the ENTER (or RETURN) key is pressed. Once the statement with the extraction operation
on cin is reached, the program will wait for as long as needed until some input is introduced.
The extraction operation on cin uses the type of the variable after the >> operator to determine
how it interprets the characters read from the input; if it is an integer, the format expected is a
series of digits, if a string a sequence of characters, etc.
int main ()
{
inti;
cout<<"Please enter an integer value: ";
cin>>i;
11
Computer Programming Department of Computer Engineering Wajiha Javed
As you can see, extracting from cin seems to make the task of getting input from the standard
input pretty simple and straightforward. But this method also has a big drawback. What happens
in the example above if the user enters something else that cannot be interpreted as an integer?
Well, in this case, the extraction operation fails. And this, by default, lets the program continue
without setting a value for variable i, producing undetermined results if the value of iis used
later.
This is very poor program behavior. Most programs are expected to behave in an expected
manner no matter what the user types, handling invalid values appropriately. Only very simple
programs should rely on values extracted directly from cin without further checking. A little later
we will see how stringstreams can be used to have better control over user input.
Extractions on cin can also be chained to request more than one datum in a single statement:
cin>> a >> b;
cin>> a;
cin>> b;
In both cases, the user is expected to introduce two values, one for variable a, and another for
variable b. Any kind of space is used to separate two consecutive input operations; this may
either be a space, a tab, or a new-line character.
12
Computer Programming Department of Computer Engineering Wajiha Javed
LAB TASKS:
1. Take two integers as input from the user apply arithmetic operations on them (+,-,*,/) as
print them on screen.
Think?
13
Computer Programming Department of Computer Engineering Wajiha Javed
a)cout
b)cin
c)coi
d) none of the mentioned
14
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #03:
Lab Objective:
Lab Description:
To specify the conditions under which a statement or group of statements should be executed.
if (testExpression)
// statements
15
Computer Programming Department of Computer Engineering Wajiha Javed
The if statement evaluates the test expression inside parenthesis.If test expression is evaluated
to true, statements inside the body of if is executed.If test expression is evaluated to false,
statements inside the body of if is skipped.
Flowchart of if Statement
if...else
The if else executes the codes inside the body of if statement if the test expression is true and
skips the codes inside the body of else.If the test expression is false, it executes the codes inside
the body of else statement and skips the codes inside the body of if.
16
Computer Programming Department of Computer Engineering Wajiha Javed
Flowchart of if...else
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
17
Computer Programming Department of Computer Engineering Wajiha Javed
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is
true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
LAB TASKS:
1. Write a program to check whether a number is positive, negative or zero. If the user
enters negative number print number entered is positive otherwise print number is
negative.
2. Input : Marks
Process: If Marks is greater than and equal to 75, score will be A.
If Marks is less than 75 and greater than and equal to 60, score will be B.
If Marks is less than 60 and greater than and equal to 45, score will be C.
If Marks is less than 30, Score will be D
Output: Print the score of the student.
3. Any integer is input by the user. Write a program to find out whether it is an odd number
or even number.
5. Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for upto 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
6. Write a program to check whether a triangle is valid or not, when the three angles of the
triangle are entered by the user. A triangle is valid if the sum of all the three angles is
equal to 180 degrees
18
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #04:
Lab Objective:
Lab Description:
Nested If:
In C++ we can use if statement in another else block or we can also include if block in another if
block.
if(boolean_expression1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression2)
{
// Executes when the boolean expression 2 is true
}
19
Computer Programming Department of Computer Engineering Wajiha Javed
Example : Nested If
We can nest else if…else in the similar way as you have nested if statement.
intmain()
{
int marks =55;
if( marks >=80){
cout<<"U are 1st class !!";
}
else{
if( marks >=60){
cout<<"U are 2nd class !!";
}
20
Computer Programming Department of Computer Engineering Wajiha Javed
else{
if( marks >=40){
cout<<"U are 3rd class !!";
}
else{
cout<<"U are fail !!";
}
}
}
return0;
}
Switch case
switch...case is a branching statement used to perform action based on available choices, instead
of making decisions based on conditions. Using switch...case you can write more clean and
optimal code than if...else statement. switch...case only works with integer, character and
enumeration constants.
LAB TASKS
1.Write a C++ program print total number of days in a month number entered by user using
switch case.
2.Write a C++ program to check whether an alphabet is vowel or consonant using switch case.
4. Wrtite a C++ code using switch that takes int number from 1-9 and print its English .
1->one
2->two
LAB #05:
Lab Objective:
Lab Description:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
The syntax of a for loop in C++ is −
22
Computer Programming Department of Computer Engineering Wajiha Javed
Example
int main (){
23
Computer Programming Department of Computer Engineering Wajiha Javed
Output:
You are not limited to using increment statements in the update expression. Here is a loop that
displays all the even numbers from 2 through 100 by adding 2 to its counter:
24
Computer Programming Department of Computer Engineering Wajiha Javed
Not only may the counter variable be initialized in the initialization expression, it may be defined
there as well. The following code shows an example.
The initialization expression may be omitted from inside the for loop’s parentheses if it has
already been performed or no initialization is needed. Here is an example
Nested Loops:
A loop that is inside another loop is called a nested loop. A clock is a good example of
something that works like a nested loop. The second hand, minute hand, and hour hand all spin
around the face of the clock. Each time the hour hand increments, the minute hand increments 60
times. Each time the minute hand increments, the second hand increments 60 times. Here is a
25
Computer Programming Department of Computer Engineering Wajiha Javed
program segment with a for loop that partially simulates a digital clock. It displays the seconds
from 0 to 59:
Example
Output:
Implicit conversion
Implicit conversions are automatically performed when a value is copied to a compatible type.
For example
Short a= 2000;
Int b;
b=a;
Type casting
C++ is a strong-typed language. Many conversions, specially those that imply a different
interpretation of the value, require an explicit conversion, known in C++ as type-casting. There
exist two main syntaxes for generic type-casting: functional and c-like:
double x = 10.3;
int y;
y = int (x); // functional notation
26
Computer Programming Department of Computer Engineering Wajiha Javed
LAB TASKS:
The concept of generating table of any number is multiply particular number from 1 to 10.
num * 1
num * 2
num * 3
num * 4
num * 5
num * 6
num * 7
num * 8
num * 9
num * 10
2. Find Sum of digits. Add all the digits of any number, for example we take any number
like 358. Its sum of all digit is 3+5+8=16. Using For Loops.
3. Write a program in C which prints the numbers from 1 to 100. But, multiples of 3 should
be replaced with "Fizz", multiples of 5 should be replaced with "Buzz" and multiples of
both 3 and 5 should be replaced with "FizzBuzz"?
*
* *
* * *
* * * *
* * * * *
27
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #06:
Lab Objective:
Lab Description:
A loop is part of a program that repeats. The while loop has two important parts: (1) an
expression that is tested for a true or false value, and (2) a statement or block that is repeated as
long as the expression is true.
The while Loop Is a Pretest Loop ,which means it tests its expression before each iteration
whereas the do-while loop is a posttest loop, which means its expression is tested after each
iteration.
28
Computer Programming Department of Computer Engineering Wajiha Javed
Infinite Loops:
If a loop does not have a way of stopping, it is called an infinite loop. An infinite loop continues
to repeat until the program is interrupted. Here is an example of an infinite loop:
Examples:The following example averages a series of three test scores for a student. After the
average is displayed, it asks the user if he or she wants to average another set of test scores. The
program repeats as long as the user enters Y for yes.
Example OUTPUT
29
Computer Programming Department of Computer Engineering Wajiha Javed
LAB TASKS:
30
Computer Programming Department of Computer Engineering Wajiha Javed
4. Write a do-while loop that asks the user to enter two numbers. The numbers should be
added and the sum displayed. The user should be asked if he or she wishes to perform the
operation again. If so, the loop should repeat; otherwise it should terminate.
31
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #07:
ARRAYS in C++
Lab Objective:
Lab Description:
An array is a series of elements of the same type placed in contiguous memory locations that can
be individually referenced by adding an index to a unique identifier.
That means that, for example, five values of type int can be declared as an array without having
to declare 5 different variables (each with its own identifier). Instead, using an array, the
five int values are stored in contiguous memory locations, and all five can be accessed using the
same identifier, with the proper index.
For example, an array containing 5 integer values of type int called foo could be represented as:
where each blank panel represents an element of the array. In this case, these are values of
32
Computer Programming Department of Computer Engineering Wajiha Javed
type int. These elements are numbered from 0 to 4, being 0 the first and 4 the last; In C++, the
first element in an array is always numbered with a zero (not a one), no matter its length.
Initializing arrays:
By default, regular arrays of local scope (for example, those declared within a function) are left
uninitialized. This means that none of its elements are set to any particular value; their contents
are undetermined at the point the array is declared.
But the elements in an array can be explicitly initialized to specific values when it is declared, by
enclosing those initial values in braces {}. For example:
The number of values between braces {} shall not be greater than the number of elements in the
array. For example, in the example above, foo was declared having 5 elements (as specified by
the number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for
each element. If declared with less, the remaining elements are set to their default values (which
for fundamental types, means they are filled with zeroes). For example:
intbaz [5] = { };
This creates an array of five int values, each initialized with a value of zero:
33
Computer Programming Department of Computer Engineering Wajiha Javed
The values of any of the elements in an array can be accessed just like the value of a regular
variable of the same type. The syntax is:
name[index]
Following the previous examples in which foo had 5 elements and each of those elements was of
type int, the name which can be used to refer to each element is the following:
For example, the following statement stores the value 75 in the third element of foo:
x = foo[2];
Therefore, the expression foo[2] is itself a variable of type int.
Example OUTPUT
12206
The following example shows how to Find the Highest and Lowest Values in a Numeric Array
HIGHEST LOWEST
34
Computer Programming Department of Computer Engineering Wajiha Javed
It’s possible to define an array without specifying its size, as long as you provide an initialization
list. C++ automatically makes the array large enough to hold all the initialization values. For
example, the following definition creates an array with five elements:
onstint SIZE = 5; int numbers [SIZE] = {10, 20, 30, 40, 50};
You now know that an array’s name is seen as the array’s beginning memory address. This
explains why the following statement cannot be used to display the contents of array :
LAB TASKS:
1. Write a program that asks for the number of hours worked by six employees. It stores the
values in an array.
35
Computer Programming Department of Computer Engineering Wajiha Javed
2. Write a C++ program to swap first and last element of an integer 1-d array.
3. Take 10 integer inputs from user and store temperature in Celsius in it then convert the
temperature to Fahrenheit and store it in another array also display it.
number of 0.
5. Take an array of 10 elements. Split it into middle and store the elements in two different
arrays. E.g.-
INITIAL array:
36
Computer Programming Department of Computer Engineering Wajiha Javed
LAB : 8
Multi-Dimensional Array
Lab Objective:
To be able to declare a two-dimensional array.
To be able to perform fundamental operations on a two-dimensional array.
To be able to pass two-dimensional arrays as parameters.
To be able to view a two-dimensional array as an array of arrays.
Lab Description:
C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 .10 . 4 integer array −
intthreeD[5][10][4];
Two-Dimensional Arrays
37
Computer Programming Department of Computer Engineering Wajiha Javed
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional
integer array of size x,y, you would write something as follows −
typearrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y
number of columns. A 2-dimensional array a, which contains three rows and four columns can
be shown as below −
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Multidimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example −
38
Computer Programming Department of Computer Engineering Wajiha Javed
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and
column index of the array. For example −
intval = a[2][3];
Example:
Example OUTPUT
LAB TASKS:
39
Computer Programming Department of Computer Engineering Wajiha Javed
LAB #09:
FUNCTIONS
Lab Objective:
Lab Description:
A function is a collection of statements that performs a specific task. So far you have
experienced functions as you have created a function named main in every program you’ve
written. Functions are commonly used to break a problem down into small manageable pieces.
This approach is sometimes called divide and conquer because a large problem is divided into
several smaller problems that are easily solved.
This benefit of using functions is known as code reuse because you are writing the code to
perform a task once and then reusing it each time you need to perform the task
40
Computer Programming Department of Computer Engineering Wajiha Javed
A function call is a statement that causes a function to execute. A function definition contains the
statements that make up the function. When creating a function, you must write its definition. All
function definitions have the following parts:
Void Functions:
It isn’t necessary for all functions to return a value, however. Some functions simply perform
one or more statements, which follows terminate. These are called void functions. The display
Message function, which follows, is an example.
Calling a Function:
A function is executed when it is called. Function main is called automatically when a program
starts, but all other functions must be executed by function call statements. When a function is
called, the program branches to that function and executes the statements in its body
41
Computer Programming Department of Computer Engineering Wajiha Javed
Function prototype:
A function prototype eliminates the need to place a function definition before all calls to the
function. You must place either the function definition or either/the function prototype ahead of
all calls to the function. Otherwise the program will not compile.
42
Computer Programming Department of Computer Engineering Wajiha Javed
When a function is called, the program may send values into the function. Values that are sent
into a function are called arguments. In the following statement the function pow is being called
and two arguments, 2.0 and 4.0, are passed to it:
By using parameters, you can design your own functions that accept data this way. A parameter
is a special variable that holds a value being passed into a function. Here is the definition of a
function that uses a parameter:
voiddisplayValue(intnum)
The return statement causes a function to end immediately. A function may send a value back to
the part of the program that called the function this is known as returning a value. Here is an
example of a function that returns an int value:
However, we could have eliminated the result variable and returned the expression num1 +
num2, as shown in the following code:
43
Computer Programming Department of Computer Engineering Wajiha Javed
A function can also return a Boolean value instead of integer or double or character. The
following example shows that.
Example OUTPUT
44
Computer Programming Department of Computer Engineering Wajiha Javed
LAB TASKS:
45
Computer Programming Department of Computer Engineering Wajiha Javed
1. Write a function named timesTen. The function should have an integer parameter
named number. When timesTen is called, it should display the product of number
times ten. (Note: just write the function. Do not write a complete program.)
2. Write a function asks the user to enter the radius of the circle and then returns that
number as a double. Write another function that takes this radius as input and
returns the area of circle.
3. Write a function accepts an integer argument and tests it to be even or odd. The
function returns true if the argument is even or false if the argument is odd. The
return value should be bool. In main take a integer input from user and pass it to the
function.
4. Write a program with a function that takes two int parameters, adds them together,
then returns the sum. The program should ask the user for two numbers, then call
the function with the numbers as arguments, and tell the user the sum.
46
Computer Programming Department of Computer Engineering Wajiha Javed
LAB 10:
Objective:
Aim of this lab is to make students learn how to handle input and get output by reading a file in
C++
File:
A file is a collection of data that is usually stored on a computer’s disk. Data can be saved to
files and then later reused.The information/data stored under a specific name on a storage
device, is called a file.
ifstream : Input File Stream : This data type can be used only to read data from files into
memory.
ofstream Output File Stream : This data type can be used to create files and write data to
them.
fstream File Stream : his data type can be used to create files, write data to them, and
read data from them.
47
Computer Programming Department of Computer Engineering Wajiha Javed
Using the fstream Data Type You define an fstream object just as you define objects of other
data types. The following statement defines an fstream object named dataFile .
fstream dataFile;
As with ifstream and ofstream objects, you use an fstream object’s open function to open a
file. An fstream object’s open function requires two arguments, however. The first argument
is a string containing the name of the file. The second argument is a file access flag that
indicates the mode in which you wish to open the file. Here is an example.
dataFile.open("info.txt", ios::out);
The first argument in this function call is the name of the file, info.txt .The second argument is
the file access flag ios::out . This tells C++ to open the file in output mode. Output mode allows
data to be written to a file. The following statement uses the ios::in access flag to open a file in
input mode, which allows data to be read from the file.
dataFile.open("info.txt", ios::in);
NOTE: When used by itself, the ios::out flag causes the file’s contents to be deleted if
the file already exists. When used with the ios::in flag, however, the file’s existing contents
are preserved. If the file does not already exist, it will be created.
Example:
Example OUTPUT
48
Computer Programming Department of Computer Engineering Wajiha Javed
Example:
Example OUTPUT
49
Computer Programming Department of Computer Engineering Wajiha Javed
The problem with above Program can be solved by using the getline function. The function
reads a “line” of data, including whitespace characters. Here is an example of the function call:
getline(dataFile, str,'\n');
dataFile :
This is the name of the file stream object. It specifies the stream object
from which the data is to be read.
str:
This is the name of a string object. The data read from the file will be
stored here.
' \ n' :
This is a delimiter character of your choice. If this delimiter is
encountered, it will cause the function to stop reading. (This argument is
optional. If it’s left out, ' \ n' is the default.) The statement is an
instruction to read a line of characters from the file. The function will
read until it encounters a \n. The line of characters will be stored in the
str object.
Example:
This program demonstrate the working of getline.
50
Computer Programming Department of Computer Engineering Wajiha Javed
Example OUTPUT
Example:
This program uses an fstream object to write data to a file. The file is closed, and an end-of-file character is
automatically written. When the file is reopened, the new output is appended to the end of the file
Example OUTPUT
51
Computer Programming Department of Computer Engineering Wajiha Javed
Before Opening It Sometimes you want to determine whether a file already exists before
opening it for output. You can do this by first attempting to open the file for input. If the file
does not exist, the open operation will fail. In that case, you can create the file by opening it for
output. The following code gives an example.
Example OUTPUT
52
Computer Programming Department of Computer Engineering Wajiha Javed
LAB TASKS:
2. Write a function in C++ to count and display the number of lines not starting with
alphabet 'A' present in a text file "STORY.TXT".
Example:
If the file "STORY.TXT" contains the following lines,
The rose is red.
A girl is playing there.
There is a playground.
An aeroplane is in the sky.
Numbers are not allowed in the password.
3. Assuming that a text file named FIRST.TXT contains some text written into it, write a
function named vowelwords(), that reads the file FIRST.TXT and creates a new file
named SECOND.TXT, to contain only those words from the file FIRST.TXT which start
with a lowercase vowel (i.e., with 'a', 'e', 'i', 'o', 'u').
For example, if the file FIRST.TXT contains
Carry umbrella and overcoat when it rains
Then the file SECOND.TXT shall contain
umbrella and overcoat it
4. Write a user-defined function in C++ to read the content from a text file OUT.TXT, count
and display the number of alphabets present in it
53
Computer Programming Department of Computer Engineering Wajiha Javed
LAB 11:
Recursion in C++
Objectives:
To become familiar with the concept of recursion
To learn basic guidelines in writing recursive functions
To learn how recursion is implemented
To compare recursion and iteration
Description:
The process in which a function calls itself is known as recursion and the corresponding function
is called the recursive function. The popular example to understand the recursion is factorial
function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil
discuss what is base condition and why it is important.
In the following diagram. I have shown that how the factorial function is calling itself until the
function reaches to the base condition.
54
Computer Programming Department of Computer Engineering Wajiha Javed
The purpose of recursion is to divide the problem into smaller problems till the base condition
is reached.
55
Computer Programming Department of Computer Engineering Wajiha Javed
LAB TASKS:
1. Write a recursive function that computes sum of all numbers from 1 to n ,where n is
given as parameter?
2. Write a recursive function that finds and return a minimum element in an array, where
the array and its size are given as parameters?
3. Write a recursive function that computes and return the sum of all the elements in an
array where array and its size is given as parameters?
56
Computer Programming Department of Computer Engineering Wajiha Javed
LAB : 12
Pointers in C++
Lab Objective:
Lab Description:
Pointers are powerful features of C++ that differentiates it from other programming languages
like Java and Python.
Pointers are used in C++ program to access the memory and manipulate the address.
Address in C++
To understand pointers, you should first know how data is stored on the computer.
Each variable you create in your program is assigned a location in the computer's memory. The
value the variable stores is actually stored in the location assigned.
To know where the data is stored, C++ has an & operator. The & (reference) operator gives you
the address occupied by a variable.
Example:
57
Computer Programming Department of Computer Engineering Wajiha Javed
In the following example, you may not get the same result on your system.
Notice that first address differs from second by 4-bytes and second address differs from third
by 4-bytes.
This is because the size of integer (variable of type int) is 4 bytes in 64-bit system.
Example OUTPUT
Pointers Variables
C++ gives you the power to manipulate the data in the computer's memory directly. You can
assign and de-assign any space in the memory as you wish. This is done using Pointer variables.
Pointers variables are variables that points to a specific address in the memory pointed by
another variable.
58
Computer Programming Department of Computer Engineering Wajiha Javed
Or,
int* p
The statement above defines a pointer variable p. It holds the memory address.
The asterisk is a dereference operator which means pointer to.Here, pointer p is a pointer
to int, i.e., it is pointing to an integer value in the memory address.
For example: If a number variable is stored in the memory address 0x123, and it contains a
value 5.
The reference (&) operator gives value 0x123, while the dereference (*) operator gives the the
value 5.
The (*) sign used in the declaration of C++ pointer is not the dereference pointer. It is just a
similar notation that creates a pointer.
Example:
Example OUTPUT
int main() { ;
int *pc, c;
c = 5;
59
Computer Programming Department of Computer Engineering Wajiha Javed
*pc = 2;
return0;}
The pointer variable “p” can hold the memory address of variable of any data type.
There is a close relationship between pointers and arrays.when an array is declared the array
name is the starting address of the array. For example
int x[5];
int * p;
p=x;
A pointer to a pointer
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.
60
Computer Programming Department of Computer Engineering Wajiha Javed
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, following is the declaration to declare a
pointer to a pointer of type int as
int **var;
1. int c, *pc;
Call by Reference
You learned about passing arguments to a function. This method used is called passing by value
because the actual value is passed.
However, there is another way of passing an argument to a function, where the actual value of
the argument is not passed. Instead, only the reference to that value is passed.
61
Computer Programming Department of Computer Engineering Wajiha Javed
Before swapping
a=1
b=2
After swapping
a=2
b=1
Before swapping
a=1
b=2
After swapping
a=2
b=1
Lab Tasks:
1. Write a C++ program to accept five integer values in an array using pointer offset notation.
2. Write a C++ function to sort an array of ten integer values in ascending order.
3. Write a program in C++ to find the maximum number between two numbers using a
pointer.
Test Data :
Input the first number : 5
62
Computer Programming Department of Computer Engineering Wajiha Javed
63
Computer Programming Department of Computer Engineering Wajiha Javed
LAB 13:
Intro to Arduino IDE - Hardware , Configuration /
Installation
Objectives
Learn to use software development tools such as Arduino IDE, and Tera Term serial port
reader for the ESP32 microcontroller.
Learn to configure environment to start using a microcontroller.
Learn to upload a program to ESP32 microcontroller and visualize the results using
MATLAB.
Software Used
Arduino IDE
TeraTerm
MATLAB
Arduino IDE
The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text
editor for writing code, a message area, a text console, a toolbar with buttons for common
functions and a series of menus. It connects to the Arduino and Genuino hardware to upload
programs and communicate with them.
Tera Term
Tera Term (alternatively TeraTerm) is an open-source, free, software implemented, terminal
emulator (communications) program. It emulates different types of computer terminals. It
supports serial port connections.
64
Computer Programming Department of Computer Engineering Wajiha Javed
MATLAB
MATLAB® is a programming platform designed specifically for engineers and scientists. The
heart of MATLAB is the MATLAB language, a matrix-based language allowing the most natural
expression of computational mathematics. We’ll be using MATLAB only to visualize the results
(images/arrays) in this lab.
65
Computer Programming Department of Computer Engineering Wajiha Javed
Hardware Used
ESP32 Microcontroller
ESP32
ESP32 is a series of low-cost, low-power system on a chip microcontrollers with integrated Wi-
Fi and dual-mode Bluetooth.
MATLAB to Visualize
Results
We’ll refer to Installation_Manual.pdf to set up the Arduino IDE for ESP32 kit Figure 0-1 shows
basic serial communication, and then follow the steps mentioned below to write the code to
hardware and visualize the result.
1. Write a code in Arduino IDE Figure 0-2shows the basic architecture of the code.
2. Upload the code to ESP32 Kit.
3. Read the serial port of the ESP32 once the code has been successfully uploaded.
Figure 0-3 shows the serial output of the hardware.
4. Store this output printed 2D array as .csv file.
66
Computer Programming Department of Computer Engineering Wajiha Javed
5. Read this csv file in MATLAB using the image_read.m file provided to you.
Display the image. Figure 0-4 a 4x4 Binary Image Visualized in MATLAB.
4 x 4 Binary Image
Initially we’ll generate a 4x4 binary image and visualize the image once it has been processed by
hardware.
Code in Arduino IDE
void setup() {
int rows=4;
int cols=4;
Serial.begin(9600);
boolean Arr[rows][cols] = { { false, true, true, true },{ false, false, false,
false },{ true, false, true, false },{ false, false, false, false }};
void loop() {
// leave empty for now
}
Figure 0-2 Arduino Code for 4x4 Binary Image to be Printed on Serial Port
0 1 1 1
0 0 0 0
1 0 1 0
0 0 0 0
Figure 0-3 Output on Serial Port
67
Computer Programming Department of Computer Engineering Wajiha Javed
68
Computer Programming Department of Computer Engineering Wajiha Javed
16 x 16 Binary Image
Code in Arduino IDE
void setup() {
Serial.begin(9600);
int rows=16;
int coulmns=16;
boolean Arr[rows][coulmns] ={ { false, false, false, false, false, false, false,
false, false,false, false, false, false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, true, false, false,false, false,
false, false, false, false },
{ false, false, false, false, false, false, true, true, true, false,false, false,
false, false, false, false },
{ false, false, false, false, false, true, true, true, true, true, false, false,
false, false, false, false },
{ false, false, false, false, true, true, true, true, true, true, true, false,
false, false, false, false },
{ false, false, false, true, true, true, true, true, true, true, true, true,
false, false, false, false },
{ false, false, true, true, true, true, true, true, true, true, true, true,
true, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false },
{ false, false, false, false, false, false, false, false, false,false, false, false,
false, false, false, false }};
void loop() {
// leave empty for now
}
69
Computer Programming Department of Computer Engineering Wajiha Javed
70
Computer Programming Department of Computer Engineering Wajiha Javed
16 x 16 Grayscale Image
Code in Arduino IDE
#define rows 16
#define coulmns 16
void setup() {
Serial.begin(9600);
int Arr[rows][coulmns] ={ { 0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0},
{ 200, 200,200, 200,200, 200,200, 200,200, 200,200, 200,200, 200,200, 200},
{ 175, 175, 175, 175,175, 175,175, 175,175, 175,175, 175,175, 175,175, 175},
{ 150, 150, 150, 150,150, 150,150, 150,150, 150,150, 150,150, 150,150, 150},
{ 125, 125, 125, 125,125, 125, 125, 125,125, 125, 125, 125,125, 125, 125, 125},
{ 100, 100, 100, 100 , 100, 100, 100, 100 ,100, 100, 100, 100 ,100, 100, 100, 100 },
{ 100, 100, 100, 100 , 100, 100, 100, 100 ,100, 100, 100, 100 ,100, 100, 100, 100 },
{ 100, 100, 100, 100 , 100, 100, 100, 100 ,100, 100, 100, 100 ,100, 100, 100, 100 },
{ 100, 100, 100, 100 , 100, 100, 100, 100 ,100, 100, 100, 100 ,100, 100, 100, 100 },
{ 0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0},
{ 125, 125, 125, 125,125, 125, 125, 125,125, 125, 125, 125,125, 125, 125, 125},
{ 150, 150, 150, 150,150, 150,150, 150,150, 150,150, 150,150, 150,150, 150},
{ 175, 175, 175, 175,175, 175,175, 175,175, 175,175, 175,175, 175,175, 175},
{ 200, 200,200, 200,200, 200,200, 200,200, 200,200, 200,200, 200,200, 200},
{ 255, 255, 255, 255,255, 255,255, 255,255, 255,255, 255,255, 255,255, 255 },
{ 0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0,0, 0, 0, 0}};
void loop() {
// leave empty for now
}
The output generated upon reading the serial port of Arduino can be observed in Figure 0-9.
71
Computer Programming Department of Computer Engineering Wajiha Javed
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200
175 175 175 175 175 175 175 175 175 175 175 175 175 175 175 175
150 150 150 150 150 150 150 150 150 150 150 150 150 150 150 150
125 125 125 125 125 125 125 125 125 125 125 125 125 125 125 125
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
125 125 125 125 125 125 125 125 125 125 125 125 125 125 125 125
150 150 150 150 150 150 150 150 150 150 150 150 150 150 150 150
175 175 175 175 175 175 175 175 175 175 175 175 175 175 175 175
200 200 200 200 200 200 200 200 200 200 200 200 200 200 200 200
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Load csv file , and display image using image_read.m to get the image.m Figure 0-10 displays the
image grayscale image generated by the code in Figure 0-8.
72
Computer Programming Department of Computer Engineering Wajiha Javed
Resources
Installation_Manual
.pdf
Lab Tasks
1. Configure/install / Get familiarized with environment of Arduino IDE, Tera Term and
MATLAB
2. Configuration of ESP32 Kit.
3. Transfer/Process a 4*4 binary image using ESP32 Kit.
4. Edit grayscale.cpp file provided to you and upload the code using Arduino IDE to ESP32
Kit, finally read the output from serial port of ESP32 and visualize the Image.
73
Computer Programming Department of Computer Engineering Wajiha Javed
LAB 14:
Description:
An array keeps track of multiple pieces of information in linear order, a one-dimensional list.
However, the data associated with certain systems (a digital image, a board game, etc.) lives in
two dimensions. To visualize this data, we need a multi-dimensional data structure, that is, a
multi-dimensional array. A two-dimensional array is really nothing more than an array of arrays.
For our purposes, it is better to think of the two-dimensional array as a matrix. A matrix can be
thought of as a grid of numbers, arranged in rows and columns, kind of like a bingo board. We
might write the two-dimensional array out as follows to illustrate this point:
int myArray[4][4] = { {0, 1, 2, 3},
{3, 2, 1, 0},
{3, 5, 6, 1},
{3, 8, 3, 4} };
We can use this type of data structure to encode information about an image. For example,
grayscale image in Figure 0-2could be represented by the array in Figure 0-3:
74
Computer Programming Department of Computer Engineering Wajiha Javed
For a two-dimensional array, in order to reference every element, we must use two nested
loops. This gives us a counter variable for every column and every row in the matrix as
represented in Figure 0-4.
int cols = 10;
int rows = 10;
int myArray[cols][rows];
Resources
Lab Tasks
75
Computer Programming Department of Computer Engineering Wajiha Javed
76
Computer Programming Department of Computer Engineering Wajiha Javed
Using all the concepts studied during lab sessions and lectures think of your own design to solve the
given lab.
TASK:
Write a function named "reverse" that takes as its arguments the following:
(1) an array of floating point values;
(2) an integer that tells how many floating point values are in the array.
The function must reverse the order of the values in the array. Thus, for example, if the
array that's passed to the function looks like this:
5.8 | 2.6 | 9.0 | 3.4 | 7.1 then when the function returns, the array will have been
modified so that it looks like this:
7.1 | 3.4 | 9.0 | 2.6 | 5.8
The function should not return any value.
77