Sunteți pe pagina 1din 77

Computer Programming Department of Computer Engineering Wajiha Javed

LAB MANUAL
Computer Programming

CE-112

Air University
Islamabad

Prepared by: Engr. Wajiha Javed

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #01:

Introduction to C++

Lab Objective:

a. To learn how to write algorithms in order to solve difficult problems


b. To learn what does the compiler do
c. To learn how to write a C++ program
d. To learn how to take input and how to output data using C++.

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:

Let us look at the various parts of the above program −

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

Some rules for printing,

Description Command Output


Printing double quotes (“) cout<<”Hello \”World\””; Hello “World”
Printing back slash ( \ ) cout<<”Hello \\World”; Hello \ World
Printing tab space cout<<”Hello \t World”; Hello World
jump to new line cout<<”Hello \nWorld”; Hello
World
jump to new line cout<<”Hello” Hello

4
Computer Programming Department of Computer Engineering Wajiha Javed

cout<<endl<<”World”; World

Arithmetic Operations:

Description Operator Answer


Addition cout<<5+2 7
Subtraction cout<<5-2 3
Multiplication cout<<5*2 10
Integer Division cout<<5/2 2
Modulus ( remainder ) cout<<5%2; 1
Division including float Cout<<5.0/2 2.5

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

Variable type (Data type) How do define in C++


Integer int w;
Decimal float x;
A Single Character char y;
Boolean bool z;

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:

1. Write a program that displays the following output on screen


Danny asked, “Are you alright?”
Harry replied.”I’m fine”

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

1. What is the role of header file iostream.h?


2. If we print “Enter an Integer” but cin in a variable of float data type, will it cause any
error?
3. What is the only function all C++ programs must contain?

7
Computer Programming Department of Computer Engineering Wajiha Javed

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #02:

Fundamentals of Programming

Lab Objective:

Learn how to create variables and use them.

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.

Standard output (cout)

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

cout<< "Output sentence”; // prints Output sentence on screen


cout<< 120; // prints number 120 on screen
cout<< x; // prints the value of x on screen

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<< "Hello"; // prints Hello


cout<< Hello; // prints the content of variable Hello

Multiple insertion operations (<<) may be chained in a single statement:

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:

I am 24 years old and my zipcode is 90064

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:

cout<< "This is a sentence."; This is a sentence.This is another sentence.


cout<< "This is another sentence.";

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:

cout<< "First sentence.\n"; First sentence


cout<< "Second sentence.\nThird sentence."; Second sentence
Third sentence

Alternatively, the endl manipulator can also be used to break lines. For example:

cout<< "First sentence." <<endl; First sentence


cout<< "Second sentence." <<endl; Second sentence

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.

Standard input (cin)

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.

#include <iostream> Please enter an integer value: 702


usingnamespacestd; The value you entered is 702 and its double is 1404.

int main ()
{
inti;
cout<<"Please enter an integer value: ";
cin>>i;

11
Computer Programming Department of Computer Engineering Wajiha Javed

cout<<"The value you entered is "<<i;


cout<<" and its double is "<<i*2 <<".\n";
return 0;
}

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;

This is equivalent to:

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.

2. Write a C program to calculate the distance between the two points.


Note: x1, y1, x2, y2 are all double values.

Think?

1. Where a cin does stops during extraction of data?


2. Which is used to get the input during run time?

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #03:

Control Statement and if…else in C++

Lab Objective:

Learn how to use if in programming.

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.

How if statement works?

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

How if...else statement works?

Flowchart of if...else

C++ Nested if...else


The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.

Syntax of Nested if...else

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.

4. Find largest number among 3 numbers input by the users?

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #04:

Nested if/else And Switch

Lab Objective:

Understand nesting of if else along with switch.

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.

Syntax : C++ Nested If

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.

Example : Nested If-else


#include <iostream>
usingnamespacestd;

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.

3.Write a C++ program to create Simple Calculator 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

Name of Student: _________________________________ Section: _____________________


21
Computer Programming Department of Computer Engineering Wajiha Javed

Student’s Signature: _______________________________Date: ________________________


Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #05:

FOR Loops in C++

Lab Objective:

To have better understanding regarding loops.

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 −

for ( init; condition; increment )


{
statement(s);
}

22
Computer Programming Department of Computer Engineering Wajiha Javed

Figure 1: the loop’s logic.

Example
int main (){

23
Computer Programming Department of Computer Engineering Wajiha Javed

Output:

Other Forms of the Update Expression:

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:

And here is a loop that counts backward from 10 down to 0:

Defining a Variable in the for Loop’s Initialization Expression:

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.

Using Multiple Statements in the Initialization and Update


Expressions:
It is possible to execute more than one statement in the initialization expression and the update
expression. When using multiple statements in either of these expressions, simply separate the
statements with commas. For example

Omitting the for Loop’s Expressions:

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:

1. C++ program to Print Table of any Number.

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

4. Program to print half pyramid using *

*
* *
* * *
* * * *
* * * * *

27
Computer Programming Department of Computer Engineering Wajiha Javed

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #06:

While and Do.. While Loops in C++

Lab Objective:

To have better understanding regarding loops.

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:

We can make this loop finite by adding a line as shown below

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:

1. Program to print all natural numbers from 1 to n using while loop.

2. Program to print all even numbers between i to n using while loop.

3. Program to Generate Fibonacci Sequence up to a Certain Number. The Fibonacci


sequence is a series of numbers where a number is found by adding up the two numbers
before it. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so
forth using while loop

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #07:

ARRAYS in C++

Lab Objective:

To practice arrays and to get better understanding of how to use them.

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:

int foo [5] = { 16, 2, 77, 40, 12071 };


This statement declares an array that can be represented like this:

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:

int bar [5] = { 10, 20, 30 };


Will create an array like this:

The initializer can even have no values, just the braces:

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

Accessing the values of an array:

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:

foo [2] = 75;


and, for example, the following copies the value of the third element of foo to a variable called x:

x = foo[2];
Therefore, the expression foo[2] is itself a variable of type int.

Examples:the following examples displays the sum of elements of array.

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

Implicit Array Sizing:

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:

double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

Printing the Contents of an Array:

Suppose we have the following array definition:

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 :

cout<< numbers <<endl; //Wrong!


When this statement executes, cout will display the array’s memory address, not the array’s
contents. You must use a loop to display the contents of each of the array’s elements, as follows.
for (int count = 0; count < SIZE; count++)
cout<< numbers[count] <<endl;

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.

4. Take 20 integer inputs from user and print the following:


number of positive numbers

number of negative numbers

number of odd numbers

number of even numbers

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

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.

Initializing Two-Dimensional Arrays

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 −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

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:

1. C++ Program to display all elements of an initialized two dimensional array.

2. Add Two Matrices using Multi-dimensional Arrays from user

3. Find Transpose of a Matrix

39
Computer Programming Department of Computer Engineering Wajiha Javed

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB #09:

FUNCTIONS

Lab Objective:

To have better understanding regarding functions.

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

Defining and Calling Functions:

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:

1. Return type: A function can send a value to the part of the


program that executed it. The return type is the data type of the
value that is sent from the function.
2. Name: You should give each function a descriptive name. In
general, the same rules that apply to variable names also apply to
function names.
3. Parameter list: The program can send data into a function. The
parameter list is a list of variables that hold the values being
passed to the function.
4. Body: The body of a function is the set of statements that perform
the function’s operation. They are enclosed in a set of braces.

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 Header void displayMessage()


Function Call displayMessage();

Functions may also be called in a hierarchical, or layered, fashion.

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

Sending Data into a Function:

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:

result = pow(2.0, 4.0);

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)

{ cout<< "The value is " <<num<<endl; }

The return Statement and Returning a Value from a Function :

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.

Examples:The following example demonstrates a function with a parameter.

Example OUTPUT

44
Computer Programming Department of Computer Engineering Wajiha Javed

I am passing several values to displayValue.


The value is 5
The value is 10
The value is 2
The value is 16

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.

5. Write a function which converts an uppercase letter 'A'{'Z' to the corresponding


lowercase letter. If the parameter is not a letter it must be returned unchanged. Write
a main program which calls the function.

46
Computer Programming Department of Computer Engineering Wajiha Javed

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB 10:

File Handling in C++

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;

Opening of the file:

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:

This program uses an fstream object to write data to a file.

Example OUTPUT

48
Computer Programming Department of Computer Engineering Wajiha Javed

Example:

This program uses an fstream object to read data from a file.

Example OUTPUT

49
Computer Programming Department of Computer Engineering Wajiha Javed

The getline Function

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

The three arguments in this statement are explained as follows:

 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

Checking for a File’s Existence

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:

1. Write a C++ program to write number 1 to 100 in a data file NOTES.TXT

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.

The function should display the output as 3.

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

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.

Why Stack Overflow error occurs in recursion?


If the base case is not reached or not defined, then the stack overflow problem may arise.

How memory is allocated to different function calls in recursion?


When any function is called from main(), the memory is allocated to it on the stack. A recursive
function calls itself, the memory for a called function is allocated on top of memory allocated to
calling function and different copy of local variables is created for each function call. When the
base case is reached, the function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB : 12

Pointers in C++

Lab Objective:

To have better understanding regarding pointers.

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.

If var is a variable then, &var gives the address of that 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.

The 0x in the beginning represents the address is in hexadecimal form.

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

How to declare a pointer?


int *p

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.

Reference operator (&) and Deference operator (*)


Reference operator (&) as discussed above gives the address of a variable.To get the value
stored in the memory address, we use the dereference operator (*).

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:

Following Program to demonstrate the working of pointer

Example OUTPUT
int main() { ;
int *pc, c;

c = 5;

cout<<"Address of c (&c): "<<&c <<endl;

cout<<"Value of c (c): "<< c <<endl<<endl;

pc = &c; // Pointer pc holds the memory address of


variable c

cout<<"Address that pointer pc holds(pc):"<<pc<<endl;

59
Computer Programming Department of Computer Engineering Wajiha Javed

cout<<"Content of the address pointer pc holds (*pc): "<<


*pc <<endl<<endl;

c = 11; // The content inside memory address &c is


changed from 5 to 11.

cout<<"Address pointer pc holds (pc):"<<pc<<endl;

cout<<"Content of the address pointer pc holds (*pc): "<<


*pc <<endl<<endl;

*pc = 2;

cout<<"Address of c (&c): "<<&c <<endl;

cout<<"Value of c (c): "<< c <<endl<<endl;

return0;}

The “void” type pointer:


void * p;

The pointer variable “p” can hold the memory address of variable of any data type.

Pointers and Arrays:

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;

Common mistakes when working with pointers


Suppose, you want pointer pc to point to the address of c. Then,

1. int c, *pc;

2. pc=c; /* Wrong! pc is address whereas, c is not an address. */

3. *pc=&c; /* Wrong! *pc is the value pointed by address whereas,


%amp;c is an address. */

4. pc=&c; /* Correct! pc is an address and, %amp;pc is also an address. */

5. *pc=c; /* Correct! *pc is the value pointed by address and, c is also a


value. */

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.

Example:Passing by reference without pointers


Example OUTPUT

61
Computer Programming Department of Computer Engineering Wajiha Javed

Before swapping
a=1
b=2
After swapping
a=2
b=1

Example:Passing by reference with pointers


Example OUTPUT

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

Input the second number : 6


Expected Output :6 is the maximum number.

4. Write a program to convert kilogram to grams by passing pointers as arguments to the


function.

63
Computer Programming Department of Computer Engineering Wajiha Javed

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

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.

Arduino IDE to Code


ESP32 Microcontroller

MATLAB to Visualize
Results

USB COM PORT

Figure 0-1 Block Diagram Representing the Serial Communication

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

for(int row=0; row<=rows-1; row++) { // Count rows


for(int col=0; col<=cols-1; col++) {
Serial.print(Arr[row][col]);
Serial.print(" ");
}
Serial.println();
}
}

void loop() {
// leave empty for now
}

Figure 0-2 Arduino Code for 4x4 Binary Image to be Printed on Serial Port

Read /Export using Tera Term

0 1 1 1
0 0 0 0
1 0 1 0
0 0 0 0
Figure 0-3 Output on Serial Port

Display Image – MATLAB

67
Computer Programming Department of Computer Engineering Wajiha Javed

Figure 0-4 Image in Matlab

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

for(int row=0; row<=rows-1; row++) { // Count rows


for(int column=0; column<=coulmns-1; column++) {
Serial.print(Arr[row][column]);
Serial.print(" ");
}
Serial.println();
}
}

void loop() {
// leave empty for now
}

69
Computer Programming Department of Computer Engineering Wajiha Javed

Figure 0-5 Arduino Code for 16x16 Binary Image


0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0
0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0
0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0
0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Figure 0-6 16x16 Binary Image on Serial Port

Figure 0-7 16 x 16 Binary Image visualized in MATLAB

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

for(int row=0; row<=rows-1; row++) { // Count rows


for(int column=0; column<=coulmns-1; column++) {
Serial.print(Arr[row][column]);
Serial.print(" ");
}
Serial.println();
}
}

void loop() {
// leave empty for now
}

Figure 0-8 16x16 Grayscale Image code in Arduino IDE

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

Figure 0-9 16 x 16 Grayscale Image on Serial Port of ESP32

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.

Figure 0-10 16 x 16 Grayscale Image in MATLAB

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

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

LAB 14:

Intro to Arduino IDE - Hardware , Configuration /


Installation

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

Figure 0-1 Basic 2-Dimensional Array

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

Figure 0-2 Basic 4x4 Grayscale Image


int myArray[4][4] = {{236, 189, 189, 0},
{236, 80, 189, 189},
{236, 0, 189, 80},
{236, 189, 189, 80} };

Figure 0-3 4x4 Array for a Grayscale Image

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

// Two nested loops allow us to visit every spot in a 2D array.


// For every column I, visit every row J.
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
myArray[i][j] = 0;
}
}

Figure 0-4 Code to Generate 10 x10 Array

Resources

Lab Tasks

1. Write a C++ code to generate a 4* 4 binary.

75
Computer Programming Department of Computer Engineering Wajiha Javed

2. Write a C++ code to generate a 16*16 grayscale image.


3. Write a code to generate 200x200 grayscale image resembling to following image.
Hint: Rand is a c++ command which can be accessed by including cstlib (C Standard
General Utilities Library)
v1 = rand() % 255; //v1 in the range of 0-255

76
Computer Programming Department of Computer Engineering Wajiha Javed

Name of Student: _________________________________ Section: _____________________


Student’s Signature: _______________________________Date: ________________________
Name of Instructor: _______________________________ Instructor’s Signature: __________

OPEN ENDED LAB

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

S-ar putea să vă placă și