EE 163 Computers and Programming
EE 163 Computers and Programming
EE 163 Computers and Programming
LAB MANUAL
For the course
Instructor name:__________________________________
Student name:____________________________________
Roll no: Batch:___________________
Semester: Year:________________
LAB MANUAL
For the course
Approved By
____________________ ____________________
____________________ ___________________
____________________ ____________________
To be filled by lab technician
Roll No. Rubric Rubric Rubric Rubric Rubric Rubric OEL/PBL Final LAB Attendance Final weighted Score for
based based based based based based Rubric Rubric Percentage MIS System
Lab I Lab II Lab III Lab IV Lab V Lab VI Score Score [10(A)+10(B)+5(C)]/25
A B C Round to next higher
multiple of 5
Note: All Rubric Scores must be in the next higher multiple of 5 for correct entry in MIS system.
CONTENTS
Psychomotor / Cognitive Level: P4
CLO/PLO: 5/3
3 C++ Mathematics
8 Arrays in C/C++
Lab Session 1
Objective:
Installation process is simple. Run the executable file you just downloaded (or acquired from Computer
Lab). The installation Wizard will guide you through the whole process.
Once you run the setup file, the Wizard will get started.
You must agree with license terms to install and use Code::Blocks (read the terms provided and click I
Agree). Once you are agreed with the terms, the installation wizard will now prompt to choose the
components to install, check all components and click Next.
EE-163 Computers & Programming Lab Session 01
NED University of Engineering & Technology Department of Electrical Engineering
Now select the hard disk location to install the Code::Blocks (using default is recommended)
Once you click the install button the installation will take place. Upon successful installation you will get
the message.
Figure 6 Installation in process
EE-163 Computers & Programming Lab Session 01
NED University of Engineering & Technology Department of Electrical Engineering
• Open Code::Blocks
• Create a new empty file (shortcut Ctrl + Shift + N )
• Save the file as lab_01_code_01.cpp
• Beware about the format .cpp
EE-163 Computers & Programming Lab Session 01
NED University of Engineering & Technology Department of Electrical Engineering
lab01_code_01.cpp
#include<iostream>
using namespace std;
int main(void)
{
cout<<"Hello World";
return 0;
}
• Type the code as shown (don’t worry if you don’t understand it for now)
• After typing the code Go to BUILD>>BUILD and RUN (shortcut F9)
• If your program was successfully written, it will be executed otherwise you will get an error
To navigate through the directories, one can use cd command. A sample is shown in figure.
There are many useful commands for command prompt, following links are helpful to get started.
• http://www.digitalcitizen.life/command-prompt-how-use-basic-commands
• http://www.computerhope.com/overview.htm
EE-163 Computers & Programming Lab Session 01
NED University of Engineering & Technology Department of Electrical Engineering
• GuessNumber.exe is already written program, the program asks the user to guess a number (which is
in computer’s mind)
• The user will respond by typing and can do so, until correct number is guessed
• In the meanwhile for any wrong guess computer will give a hint
• Let’s try it
Exercise
Task 1:
Write a program to print text in following pattern,
Hello World
Hello World
Hello World
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
______________________________________________________________________________________
EE-163 Computers & Programming Lab Session 02
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 2
Objective:
Fundamental to any computer program is the data associated with its use. Based on the nature of data
it can be classified into various categories. Data types are important to understand, they define
proper use of an identifier and expression. In C++ data types can be categorized as following.
Numeric: This type contains the numbers including integers and floating point values. Following are the
example of numeric data
• 100
• 895
• -237
• 6.022140857 × 10 ^ 23
• 6.62607004 × 10 -34
• -1.60217662 × 10-19
Character: Character data includes the alpha numeric characters and special symbols (enclosed in single
quotes). Following are the examples
• ‘a’
• ‘F’
• ‘@’
• ‘%’
• ‘^’
EE-163 Computers & Programming Lab Session 02
NED University of Engineering & Technology Department of Electrical Engineering
Strings: Strings include all the text values (enclosed in double quotes). Following are the examples
• “Finland”
• “NED University”
• “PO Box No 341”
• “all along the watch tower”
lab_02_code_01.cpp
Following code can be used to check the memory requirements of various data types
#include<iostream>
using namespace std;
// sizeof() function calculates the Bytes
int main(void)
{
cout<<"Integer Bytes="<<sizeof(int);
cout<<"\nDouble Bytes="<<sizeof(double);
cout<<"\nCharacter Bytes="<<sizeof(char);
EE-163 Computers & Programming Lab Session 02
NED University of Engineering & Technology Department of Electrical Engineering
cout<<"\nBoolean Bytes="<<sizeof(bool);
return 0;
}
Variable Naming Rules: Following rules must be taken care while assigning a name to any variable.
lab02_code_03.cpp
#include<iostream>
using namespace std;
int main(void)
{
int Roll_No = 123, salary = 40000;
float CGPA = 3.2;
double pi = 3.1214, x = 0.012, y;
string enrolment_no = "ned/0145/14-15",name;
char section = 'D';
bool logical = 1;
cout<< "My Roll No:" <<Roll_No<<"\t Pi="<<CGPA;
cout<< endl<<"Value of y is:"<<y<<endl;
cout<< "Name:"<<name<< endl;
cout << "Enrolment:"<< enrolment_no;
return 0; }
2.3 Comments in a C++ Program
Program comments are explanatory statements that you can include in the C++ code that you write
and helps anyone reading it's source code. All programming languages allow for some form of
comments. C++ supports single-line and multi-line comments. All characters available inside any
comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example:
/* This is a comment */
main() {
cout << "Hello World"; // prints Hello World
return 0;
}
When the above code is compiled, it will ignore // prints Hello World and final executable will produce the
following result:
EE-163 Computers & Programming Lab Session 02
NED University of Engineering & Technology Department of Electrical Engineering
Within a /* and */ comment, // characters have no special meaning. Within a // comment, /* and */ have no
special meaning. Thus, you can "nest" one kind of comment within the other kind. For example:
/* Comment out printing of Hello World:
*/
int value;
cout<<“Please enter the value ”;
cin>>value;
cin>>cgpa;
cout<<endl<<endl;
//*****Printing Output*****
cout<<"\t My Profile"<<endl;
cout<<"Name:"<<name<<"\tRoll No:"
<<roll_no<<endl<<"Section:"
<<section<<"\tYear:"<<year<<
endl<<"Department:"<<
department<<"\tCGPA:"<<cgpa;
return 0;
}
Sequence Purpose
\n Next line
\r Carriage return
\t Horizontal tab
\b Backspace
\a Alert (beep)
\\ Print \
\’ Print ’
\” Print “
Taking help from your textbook and online resources, try to figure out the purpose of these escape
sequences and explain with the help of an example program.
Exercise
Task 1:
How to insert single line and multiline comments in a C++ program.
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
EE-163 Computers & Programming Lab Session 02
NED University of Engineering & Technology Department of Electrical Engineering
Task 2:
Variable Declarations can appear almost anywhere in the body of C++ function (T/F).
If true, then discuss the situation in which variable declaration must be done prior to some specific
task. Support you answer by giving example.
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
Task 3:
Calculate the maximum and minimum number that can be accommodated by int data type (calculate
range).
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
Task 4:
What do you mean by Variable Declaration and Variable Definition in C/C++?
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 02
NED University of Engineering & Technology Department of Electrical Engineering
Task 5:
Check the output of the following cout functions and write your comments.
1. cout << “I am a computer geek, \rits a \blie.”
2. cout <<"a"<<"\t"<<"b"<<"\t"<<"c"<<endl;
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 3
Objective:
C++ Mathematics
C++ can be used to perform basic mathematical operations. The following program can be used to
illustrate this.
Code 01
1. #include<iostream>
2. using namespace std;
3. int main()
4. {
5. int number1;
6. int number2;
7. int result;
8. cout<<"Please enter number1 & number2";
9. cin>>number1>>number2;
10. result = number1 + number2; // addition
11. result = number1 - number2; // subtraction
12. result = number1 * number2; // multiplication
13. result = number1 / number2; // division
14. result = number1 % number2; // remainder division
15. cout<<result;
16. return 0;
17. }
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
In the above program the variable number1 and number2 are called operands and they are
connected via different operators in expressions given on line numbers 10 through 14. Response of
each operation is stored in the variable result.
Keep in mind that modulus (%) operator is only defined for the data type integers
It is important to emphasis that result of the division is not as we expect in general. This is because
the data type of number1 and number2 is integer, an integer divided by an integer will give an
integer response, while truncating the decimal part of the value. This makes the order of precedence
of arithmetic operators very significant.
The following code will help you develop intuition of C++ Mathematics
Code 02
#include<iostream>
using namespace std;
int main(void)
{ // BMI Calculator
float weight_in_kg ,height_in_meter ,bmi;
cout<<"\t \t **Body mass index (BMI) calculator** \n";
cout<<"\t Calculates an index that indicates"<<
" healthy weight distribution\n";
cout<<"Enter your weight in Kgs: ";
cin>> weight_in_kg;
cout <<"\nEnter your height in meters: ";
cin>> height_in_meter;
bmi=weight_in_kg/(height_in_meter*height_in_meter);
cout<<"\nYour BMI value is:"<< bmi;
cout<<"\n\n \t\t Standard BMI Values for comparison \n";
cout<<"\n \t\t Less than 18.5 : Underweight";
cout<<"\n \t\t Between 18.5 and 24.9 : Normal";
cout<<"\n \t\t Between 25 and 29.9 : Overweight";
cout<<"\n \t\t Greater than 30 : Overweight";
return 0;
}
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Working with +, -, * and / is very obvious. Modulus operator (%) though needs some more
explanation. Modulus operator gives the value of remainder once an int is divided by other int. This
is very useful operator in C++. This can be very helpful in many programming situations. The
following code snippet will help develop more intuition about modulus operator.
In order to properly evaluate an expression such as 4 + 2 * 3, we must understand both what the
operators do, and the correct order to apply them. The order in which operators are evaluated in a
compound expression is called operator precedence. Using normal mathematical precedence rules
(which state that multiplication is resolved before addition), we know that the above expression should
evaluate as 4 + (2 * 3) to produce the value 10.
In C++, all operators are assigned a level of precedence. Those with the highest precedence are
evaluated first. You can see in the table below that multiplication and division have a higher
precedence than addition and subtraction. The compiler uses these levels to determine how to evaluate
expressions it encounters.
Thus, 4 + 2 * 3 evaluates as 4 + (2 * 3) because multiplication has a higher level of precedence than
addition.
If two operators with the same precedence level are adjacent to each other in an expression, the
associativity rules tell the compiler whether to evaluate the operators from left to right or from right
to left.
For example, in the expression 3 * 4 / 2, the multiplication and division operators are both precedence
level 5. Level 5 has an associativity of left to right, so the expression is resolved from left to right: (3
* 4) / 2 = 6.
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Following examples will help you to understand the idea of precedence and associativity
y = 5 / 2 * 5 + 3 * 5 + 7;
cout<<y;
y = 5 * 5 / 2 + 3 * 5 + 7;
cout<<y;
Code 03
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7.
8. int number1 = 74, number2 = 82, number3 = 88;
9. double average;
10. average = number1 + number2 + number3 / 3;
11. cout<<average;
12. return 0;
13. }
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Code 04
1. #include<iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7.
8. int number1 = 74, number2 = 82, number3 = 88;
9. double average;
10. average = (number1 + number2 + number3) / 3;
11. cout<<average;
12. return 0;
13. }
What did you observe from the output of the above two programs? Try to explain briefly.
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
__________________________________________________________
Incrementing (adding 1 to) and decrementing (subtracting 1 from) a variable are so common that they
have their own operators in C++. There are actually two versions of each operator, a prefix version
and a postfix version. Following table lists them
The prefix increment/decrement operators are very straightforward. The value of x is incremented or
decremented, and then x is evaluated.
For example
int x = 5;
int y = ++x; // x is now equal to 6, and 6 is assigned to y
The postfix increment/decrement operators are a little more tricky. The compiler makes a temporary
copy of x, increments or decrements the original x (not the copy), and then evaluates the temporary
copy of x. The temporary copy of x is then discarded.
int x = 5;
int y = x++; // x is now equal to 6, and 5 is assigned to y
Let’s examine how this last line works in more detail. First, the compiler makes a temporary copy of
x that starts with the same value as x (5). Then it increments the original x from 5 to 6. Then the
compiler evaluates the temporary copy, which evaluates to 5, and assigns that value to y. Then the
temporary copy is discarded.
Consequently, y ends up with the value of 5, and x ends up with the value 6. Here is another
example showing the difference between the prefix and postfix versions:
int x = 5, y = 5;
cout << x << " " << y << endl;
cout << ++x << " " << --y << endl; // prefix
cout << x << " " << y << endl;
cout << x++ << " " << y-- << endl; // postfix
cout << x << " " << y << endl;
5 5
6 4
6 4
6 4
7 3
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Compound assignment operators modify the current value of a variable by performing an operation
on it. They are equivalent to assigning the result of an operation to the first operand: Following table
summarizes the compound assignments
x -= 1000 x=x-1000
x *= 10 x=x*10
x /= 5 x=x/5
You are now familiar with the idea of precedence and associativity. It is now time to clarify one very
important aspects of C++ mathematics, how an expression or equation contacting mixed data types
e.g. int and float is evaluated. Consider the equation for example
tempf=tempc*(9/5)+32;
One may be disguised that there is nothing wrong with the above statement, but the way C++ handle
it is really important to consider. The literal 9 when divided by 5 will result in an int value whereas
the user might be expecting floating result. In that case the result will be incorrect. This can be
corrected by implementing the same expression with floating point literals, like
tempf=tempc*(9.0/5.0)+32;
tempf=tempc*(9.0/5)+32; or tempf=tempc*(9/5.0)+32;
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
C++ allows to temporarily change the type of a variable for one statement, this idea is called type
casting. The idea is explained in the following code.
Code 05
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main ()
7. {
8. float num1 = -9.5;
9. int num2 = 101;
10. cout<<(int)num1;
11. cout<<endl<<(float)num2/10;
12.
13. return 0;
14. }
Line number 10 will be processed by considering num1 as int and not its own type, similarly line 11
will be executed by considering num2 as floating point quantity and not int.
Some very useful and advanced mathematical functions are present in <cmath> library. Which can be
included in a program through preprocessor directive #include<cmath>. Following are the few functions
which are available in this library.
Code 06
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8.
9. const double pi = 3.141592;
10. double angle = pi/6;
11. cout<<endl<<"******** Calculating Trigonometric Ratios
********"<<endl;
12. cout<<endl<<"All calculations on Angle "<<angle<<"
Radians"<<endl;
13. cout<<endl<<"cos("<<angle<<") "<<"= "<<cos(angle)<<endl;
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Code 07
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8. double num = 10.3;
9. cout<<endl<<"exp("<<num<<") "<<"= "<<exp(num)<<endl;
10. cout<<endl<<"log("<<num<<") "<<"= "<<log(num)<<endl;
11. cout<<endl<<"log10("<<num<<") "<<"= "<<log10(num)<<endl;
12.
13. return 0;
14. }
Code 08
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8. double num1 = 10.3, num2 = 2.0;
9. cout<<endl<<"pow("<<num1<<","<<num2<<") "<<"=
"<<pow(num1,num2)<<endl;
10. cout<<endl<<"sqrt("<<num1<<") "<<"= "<<sqrt(num1)<<endl;
11. cout<<endl<<"cbrt("<<num1<<") "<<"= "<<cbrt(num1)<<endl;
12.
13. return 0;
14. }
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
Code 09
1. #include<iostream>
2. #include<cmath>
3.
4. using namespace std;
5.
6. int main()
7. {
8. double num1 = 2.3,num2 = 3.8,num3 = 5.5,num4 = -2.3,num5 = -3.8,num6 = -
5.5;
9. cout<<"value\tround\tfloor\tceil\ttrunc\n";
10. cout<<"-----\t-----\t-----\t----\t-----\n";
11. cout<<num1<<"\t"<<round(num1)<<"\t"<<floor(num1)<<"\t"<<ceil(num1)<<
"\t"<<trunc(num1)<<"\n";
12. cout<<num2<<"\t"<<round(num2)<<"\t"<<floor(num2)<<"\t"<<ceil(num2)<<
"\t"<<trunc(num2)<<"\n";
13. cout<<num3<<"\t"<<round(num3)<<"\t"<<floor(num3)<<"\t"<<ceil(num3)<<
"\t"<<trunc(num3)<<"\n";
14. cout<<num4<<"\t"<<round(num4)<<"\t"<<floor(num4)<<"\t"<<ceil(num4)<<
"\t"<<trunc(num4)<<"\n";
15. cout<<num5<<"\t"<<round(num5)<<"\t"<<floor(num5)<<"\t"<<ceil(num5)<<
"\t"<<trunc(num5)<<"\n";
16. cout<<num6<<"\t"<<round(num6)<<"\t"<<floor(num6)<<"\t"<<ceil(num6)<<
"\t"<<trunc(num6)<<"\n";
17.
18. return 0;
19. }
20.
Exercise
1. Using compound assignment operators, write a program that generates the following output:
x = 2.5 y = 10
x = 25.0 y = 15
x = 250.0 y = 20
x = 2500.0 y = 25
Initialize x as float with value of 2.5 and y as int with value 10. In each successive stage, use
*= operator for x and += operator for y to achieve the desired values.
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
___________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
___________________________________________________________________________________
2. Write a program that asks the user to enter the length of base and perpendicular of a right angle
triangle. Then it determines the length of hypotenuse, angle between base and hypotenuse and
angle between hypotenuse and perpendicular. Also find the sine and cosine values of these
angles. (For hint refer to basic trigonometry from any mathematics book)
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
__________________________________________________________________________________
EE-163 Computers & Programming Lab Session 03
NED University of Engineering & Technology Department of Electrical Engineering
3.Write a program that asks the user to enter coefficients a, b and c of the stand ard quadratic equation:
ax2+bx+c=0
The program then should compute and display discriminant
|b2-4ac|
And the roots of equation
2
𝑥1 = −𝑏 + √𝑏 − 4𝑎𝑐⁄2𝑎
2
𝑥2 = −𝑏 − √𝑏 − 4𝑎𝑐⁄2𝑎
Finally, give opinion on how the program could be made more general to different input conditions
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
__________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
__________________________________________________________________________________
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 4
Objective:
The idea of decision making allows to control the flow of the program. So far, every program that we
have discussed was executed from start to end. Often it is required to control the flow of a program so
that a certain piece of code is only executed if a certain condition is met. The ability to control the
flow of a program, letting it make decisions on what code to execute, is valuable in programming. The
if statement allows to control if a program enters a section of code or not based on whether a given
condition is true or false. One of the important functions of the if statement is that it allows the program
to select an action based upon the user's input. For example, by using an if statement to check a user
entered password, your program can decide whether a user is allowed access to the program.
Decision making in programming is done in terms of testing an expression (logical or relational). The
result of the test is either TRUE or FALSE. A TRUE leads to the execution of a specified piece of
code, whereas a FALSE leads to two possibilities; either a piece of code is executed that is different
from the TRUE case or a branch takes place. An important note regarding decision making structures
is that they are not loops; they are executed only once.
Arithmetic operators are incapable of generating TRUE or FALSE. For this we need operators that
can result in YES and NO. In other words operators that can produce Boolean output. There are two
such operators in C++
i. Relational Operators
ii. Logical Operators
Code 01
#include<iostream>
using namespace std;
int main(void)
{
int num1=105, num2=34;
float pi=3.1412, x=123.5;
string password="abcd1234";
bool result=(num1>num2);
cout<<num1<<">"<<num2<<"\t1=true, 0=false";
cout<<"\nanswer="<<result<<endl;
cout<<pi<<"="<<x<<"\t1=true, 0=false";
cout<<"\nanswer="<<(pi==x)<<endl;
cout<<"Is the password correct?\t1=yes, 0=no";
cout<<"\nanswer="<<(password=="abcd1234");
return 0;
Logical operators
The logical operators apply logic functions (NOT, AND, and inclusive OR) to boolean arguments. These are
helpful to take decision based on multiple conditions. Following tables summarize these operators.
A B A&&B A||B
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
A !A
0 1
1 0
Code 02
#include<iostream>
using namespace std;
int main(void)
{
bool a=true, b=0, c=0, result;
result=(c||a);
cout<<"a AND b="<<(a&&b);
cout<<"\nc OR a="<<result;
cout<<"\nNOTa="<<(!a);
cout<<"\nNOTb="<<(!b);
cout<<"\nNOTc="<<(!c);
return 0;
}
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
Explain in few lines what you understood from the above program
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________
if (testExpression)
{
// statements
}
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. This can be demonstrated with the following flow-chart.
Code 03
#include<iostream>
using namespace std;
int main(void)
{ //Calculator Program
double operand1, operand2, result;
char operation;
cout<<"\t***Calculator Program***";
cout<<"\nEnter the desired expression"
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
}
cout<<"\n\nresult="<<result;
return 0;
}
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
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. The following flow chart and
program will help you understand the idea.
Code 04
#include<iostream>
using namespace std;
int main(void)
{
string stored_password="abcd1234";
string user_password;
cout<<"Enter password:";
getline(cin,user_password);
if(user_password==stored_password)
{
cout<<"\nAccess granted\n";
}
else
{
cout<<"\nAccess denied\n";
}
return 0;
}
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
Occasionally, programs need to decide between a set of given conditions to perform an operation. This
is called ‘Multiple Selection’. In our calculator program, we performed multiple selection by using
multiple if() statements. This is an improper method. Multiple selection can be perform by using if()
– else if () statement. Following example and flow chart will be helpful to understand.
Code 05
#include<iostream>
using namespace std;
int main(void)
{ //Calculator Program
double operand1, operand2, result;
char operation;
cout<<"\t***Calculator Program***";
cout<<"\nEnter the desired expression"
<<"with spaces<eg 12.6 + 4.32>";
cin>>operand1>>operation>>operand2;
if(operation=='+')
{
result=operand1+operand2;
}
else if(operation=='-')
{
result=operand1-operand2;
}
else if(operation=='*')
{
result=operand1*operand2;
}
else if(operation=='/')
{
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
result=operand1/operand2;
}
else
{
cout<<"\nInvalid Operator\n";
return 0;
}
cout<<"\n\nresult="<<result;
return 0;
}
Exercise
Task 1:
Write a program that asks user to enter 3 numbers and then finds the largest and smallest among them
and displays both largest and smallest number. This program can be written in many ways. Provide
at-least two methods.
Note: This program can be written using Multiple if() statements, Multiple if()-else statements or if()
else. And of course there are other methods also. This exercise is a test of your thinking abilities.
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
Task 2:
C++ provides an alternate approach for if () – else if () statements, that is switch () –
case statement. Use literature and internet resources to understand using it. Then write a calculator
program written in lab session using switch ()-case statements. If the user entered the operator other
than +,-,*,/ then program should print “Invalid Operator” on screen.
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
__________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
______________________________________________
EE-163 Computers & Programming Lab Session 04
NED University of Engineering & Technology Department of Electrical Engineering
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 05
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 05
Objective:
One of the very powerful control structures is Repetition Statements in C++. Repetition statements
allow to repeat a block of code until a certain condition is true. Repetition statements are commonly
referred as loops and they can be implemented with the following statements
i. for
ii. while
iii. do while
In this lab we shall discuss (i) whereas (ii & iii) will be discussed in the next. Loops are helpful when
a certain piece of code is required to be executed in a repeated manner. This can save a lot of precious
time and laborious efforts.
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. The syntax of a for loop in C++ is
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop. The init step is executed first, and only once. This step allows
you to declare and initialize any loop control variables. Next, the condition is evaluated. If it is true,
the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of
control jumps back up to the increment statement. This statement allows you to update any loop control
variables. The condition is now evaluated again. If it is true, the loop executes and the process repeats
EE-163 Computers & Programming Lab Session 05
NED University of Engineering & Technology Department of Electrical Engineering
itself (body of loop, then increment step, and then again condition). After the condition becomes false,
the for loop terminates. Following diagram explains the whole process.
Code 01
#include<iostream>
using namespace std;
int main(void)
{
int num;
for(int num=0;num<=10;num++)
{
cout<<"\n num = "<<num;
}
return 0;
}
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________
Code 02
#include<iostream>
using namespace std;
int main(void)
{ //Calculating Power (base^exponent)
int base,exponent,answer,counter;
cout<<"Enter a number(integer):";
cin>>base;
cout<<"Enter an exponent(integer):";
cin>>exponent;
answer=1;//running product variable
for(counter=exponent;counter>0;counter=counter-1)
{
answer=answer*base;
}
cout<<"\n"<<base<<" raised to power "<<exponent
<<" = "<<answer;
return 0;
}
Placing a loop inside the body of a loop is called nesting the loops. This idea is so useful to code
solutions for many real life computational problems. Following is the syntax of nested for loops
Code 03
#include<iostream>
using namespace std;
int main(void)
{ // 10x10 Grid of a character
int row,col;
char display_char;
cout<<"Enter a character for display:";
cin>>display_char;
cout<<endl<<endl;
for(row=1;row<=10;row++)
EE-163 Computers & Programming Lab Session 05
NED University of Engineering & Technology Department of Electrical Engineering
{
for(col=1;col<=10;col++)
{
cout<<display_char;
}
cout<<endl;
}
return 0;
}
Code 04
#include<iostream>
using namespace std;
int main()
{
for(int row = 1; row <= 5; ++row)
{
for(int col = 1; col <= 5; ++col)
{
cout<<row<<" * "<<col<<" = "
<<row * col<<"\t";
}
cout<<endl;
}
}
Exercise
Task 1:
Write a program to print following pattern using for loops (do not use if, if-else or any other decision
making statement).
a) *
***
*****
*******
b) 1
121
12321
1234321
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 05
NED University of Engineering & Technology Department of Electrical Engineering
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
EE-163 Computers & Programming Lab Session 05
NED University of Engineering & Technology Department of Electrical Engineering
Task 2:
Using for() loops, write a program that displays all possible combination of 6 bit binary number. (Hint:
You shall need 6 int variables for the six digits)
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 06
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 06
Objective:
Loops that do not have a pre-defined ending point and terminate when the termination condition has
arrived. Unlike exhaustive loops, the termination condition in these loops is provided by manipulations
within the loop. Sometimes, loop control may need to be based on the value of what we are processing.
In this case, we would sentinel-controlled repetition. Sentinel-controlled repetition is sometimes called
indefinite repetition because it is not known in advance how many times the loop will be executed. It
is a repetition procedure for solving a problem by using a sentinel value (also called a signal value, a
dummy value or a flag value) to indicate "end of data entry". The sentinel value itself is not a part of
the processed data. C++ provides while and do while statements for implementing sentinel loops.
Code 01
#include<iostream>
#include<conio2.h>
using namespace std;
int main(void)
{
char guess;
cout<<"Press any key from keyboard :";
cout<<"\n This program shall end only"
<<" when you press the secret key";
guess=getche();
while( guess!='x' )
{
cout<<"\n Wrong input, try another key:";
guess=getche();
}
cout<<"\nEureka! You have discovered it.";
getch();
return 0;
}
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________
EE-163 Computers & Programming Lab Session 06
NED University of Engineering & Technology Department of Electrical Engineering
Code 02
#include<iostream>
#include<iomanip>
#include<conio2.h>
using namespace std;
int main(void)
{
char option='y';
double num;
int counter;
cout<<"\t\t****Multiplication Tables****";
while( option!='n' )
{
cout<<"\n\nEnter a number:";
cin>>num;
for(counter=1;counter<=15;counter++)
{
cout<<left;
cout<<setw(10)<<num<<"*"<<right
<<setw(10)<<counter<<"="<<
setw(10)<<num*counter<<endl;
}
cout<<"\n\nDo you like to continue?(y or n):";
option=getche();
}
if(option=='n')
{
cout<<"Thanks for using this program";
}
getch();
return 0;
}
EE-163 Computers & Programming Lab Session 06
NED University of Engineering & Technology Department of Electrical Engineering
Exercise
Task 1:
Write a program that continuously asks user to enter an integer and displays the SUM of the current
input with all previous input. The program continuous to run until the SUM value is less than equal to
100. Use while() loop.
Sample Run:
Enter an integer: 12 [Enter]
Running Sum = 12
.
Sum exceeds 100. Program terminated.
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
__________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 06
NED University of Engineering & Technology Department of Electrical Engineering
________________________________________________________________________________________
______________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
EE-163 Computers & Programming Lab Session 06
NED University of Engineering & Technology Department of Electrical Engineering
Task 2:
Write a program that counts number of digits in an integer entered by the user. Use while() loop.
Sample Run:
Enter an integer: 123456 [Enter]
No. of digits = 6
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
________________________________________________________________________________________
_______________________________________________________________________________________
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 07
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 07
OBJECTIVES:
What is Algorithm?
In Programming, Algorithm is a set of well-defined instructions in sequence to solve a problem. An
algorithms should have a clear stopping point
To generate random numbers in a specific range, modulo operator is used. Let’s have a look!
Fibonacci Sequence:
Fibonacci Sequence is characterized by the fact that every number in it is a sum of two preceding ones.
1,1,2,3,5,8,….
#include<iostream>
using namespace std;
int main()
{
int n,counter;
char x;
int prev_term = 1,curr_term = 1,sum;
cout<<"Enter number of terms to generate: ";
cin>>n;
cout<<prev_term<<"
//Random ";
Number Generation
for(counter=1;
#include<iostream> counter<n; counter++)
{
#include<cstdlib>
if(counter%10
using namespace std; == 0)cout<<endl;
cout<<curr_term<<"
int main() ";
{ sum = prev_term + curr_term;
prev_term
for(int = curr_term;
i=0; i<10; i++)
{ curr_term = sum;
} cout<<rand()%100<<endl;
} }
}
GCD:
In mathematics, GCD of a two or more integers, is the largest positive integer that divides the number without
remainder.
There are three methods to calculate GCD:
1. Using Naïve Method
2. Euclid Slow Method
3. Euclid Fast Method
The Euclidean Algorithm is based on the principle that the GCD of two numbers doesn’t change if the
larger number is replaced by its difference with the smaller number. For example: GCD of 252 and
105 is 21 and the same number 21 is also the GCD of 105 and 147=252-105.
EE-163 Computers & Programming Lab Session 07
NED University of Engineering & Technology Department of Electrical Engineering
A more efficient version of the algorithm is to replace subtraction of larger and smaller number by
division of larger and smaller and replacing the number by remainder.
Bisection Method:
The bisection method in mathematics is a root-finding method that repeatedly bisects an interval and
then selects a subinterval in which a root must lie for further processing.
The method is applicable for numerically solving the equation f(x) = 0 for the real variable x,
where f is a continuous function defined on an interval [a, b] and where f(a) and f(b) have opposite
signs. In this case a and bare said to bracket a root since, by the intermediate value theorem, the
continuous function f must have at least one root in the interval (a, b).
EE-163 Computers & Programming Lab Session 07
NED University of Engineering & Technology Department of Electrical Engineering
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,x,N;
cout<<"Enter a number +ve number: ";
cin>>N;
a = 1.0; b = N;
x = 1.0;
while(fabs((x*x)-N)>0.0001)
{
c = 0.5*(a+b);
x = c;
if(x*x-N<0)
a = c;
else
b = c;
}
cout<<endl<<"Root is: "<<x;
}
Trapezoidal Integration:
In mathematics, and more specifically in numerical analysis, the trapezoidal rule (also known as the trapezoid
rule or trapezium rule) is a technique for approximating the definite integral.
𝑏
∫ 𝑓(𝑥)𝑑𝑥
𝑎
The trapezoidal rule works by approximating the region under the graph of the function f(x) as a trapezoid and
calculating its area.
The approximation the integral becomes,
𝑏 𝑁
ℎ
∫ 𝑓(𝑥)𝑑𝑥 = ∑ (𝑓(𝑥𝑘+1 ) + 𝑓(𝑥𝑘 ))
2
𝑎 𝑘=1
EE-163 Computers & Programming Lab Session 07
NED University of Engineering & Technology Department of Electrical Engineering
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double x,a,b,delta=0.0001,sum=0.0,fx1,fx2,deg_a,deg_b;
double pi = 3.14159265359;
int counter,counter_max;
cout<<"Enter x_min in degrees: ";
cin>>deg_a;
cout<<"Enter x_max in degrees: ";
cin>>deg_b;
a = deg_a*pi/180.0;
b = deg_b*pi/180.0;
counter_max = ((b-a)/delta);
x = a;
for(counter=1; counter<=counter_max; counter++)
{
fx1 = sin(x);
fx2 = sin(x+delta);
sum = sum + (fx1+fx2);
x = x + delta;
}
sum = 0.5*sum*delta;
cout<<"integral = "<<sum;
return 0;
}
Exercise:
𝑓(𝑥) = 𝑎𝑥 3 + 𝑏𝑥 2 + 𝑐𝑥 + 𝑑
Halley’s method for determining roots of polynomial is,
2𝑓(𝑥𝑛 )𝑓 ′ (𝑥𝑛 )
𝑥𝑛+1 = 𝑥𝑛 −
2𝑓 ′ (𝑥𝑛 )2 − 𝑓(𝑥𝑛 )𝑓 ′′ (𝑥𝑛 )
Q: Write an iterative algorithm to implement the following expansion (precision upto 0.0001)
∞
(−1)𝑛 2𝑛+1
sin(𝑥) = ∑ 𝑥
(2𝑛 + 1)!
𝑛=0
Deliverables:
C++ code containing the implementation of the above the algorithms.
Methodology:
Follow methods provided in the lab manual for implementing above algorithms.
1
Guidelines:
Understand the concept of Halley's Method and how it can be used to find the roots of
a polynomial
Write a plan for the program, including the algorithm and data structures needed.
Write the code for the program, using appropriate data types and functions to
implement the Halley's Method algorithm.
2
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 08
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 08
OBJECTIVES:
Arrays in C/C++.
➢ Understanding array as a sequential data structure
➢ Declaring and initializing arrays
➢ Using loops to manipulate/process arrays
➢ Working with 2D arrays
➢ Using functions to manipulate/process arrays
Array:
An array is the list of variables of a certain data type having a single name, define contiguously in the
memory.
In C/C++ an array is called a “subscripted variable” for obvious reasons. It is the very first step towards the
data structures.
An integer array of 5 elements would look like this in the memory. The memory locations occupied by the
array are numbered 0 to 4 while the array itself is the content of these locations.
Declaring an Array:
C++ has 5 basic variable data types. Since an array is a list of variables it can also be defined as any one of
them namely; integer, float, character, long and double.
Try the following program to understand array definition.
➢ int num[3];
➢ float temperature[7];
➢ char myname[25];
➢ unsigned int roll_num[270];
➢ double cgpa[100];
And this is allowed:
➢ const int size = 30;
➢ int arr[size];
Initializing an Array:
Initializing an array means declaring it and assigning some initial values to it. This can be done easily by the
following syntax shown in the program.
#define LIM 3
int main(void)
{
float num[LIM]={12.9, 9.0, 986.89}; // Declaration of an array
char ch[]={'a‘,'b‘,'c‘,'d'}; // Declaration of char array, no. of
// elements not assigned
cout<<"float array:”<<num[0]<<“,”<<num[1]<<“,”<<num[2];
cout<<"char array:“<<ch[0] <<“,”<<ch[1] <<“,”<<ch[2] <<“,”<<ch[3];
return 0;
}
➢ The syntax for initializing values is simply the use of parenthesis {} and putting the values in it.
➢ Even when the no. of elements is not defined, the compiler fixes it to a constant value that is equal to
the no. of elements actually present.
➢ Declaration does not require the no. of elements to be explicitly given since the compiler calculates it
automatically.
Practically speaking we exploit one special property of arrays to work with them. As the array index
– the number written inside the square bracket – is always going to be an integer value, we define a
separate integer variable and write it within the square bracket (example: num[index]). This empowers
us to manipulate the array by changing the index variable.
Once the index variable is defined, the best way to manipulate it through a loop. The following
example uses for() loops to perform operation on an array.
In the next example we will write a program that has a character array of 25 elements. Some of these
are used by the user to enter his/her name while others remain unused.
#define LIM 10
int main(void)
{
// variable definition
// 10 element float array, numbered 0 to 9
float num[LIM];
int index_count;// an integer variable to access different array
locations
getch();
return 0;
}
// Note:
// 1) A for() loop is feasible when we have to process all elements of
anarray.
// 2) We have used three loops for three tasks; input, processing, and
output.
// We could have done this through a single loop but we shall make our
// programs modular in this way.
EE-163 Computers & Programming Lab Session 08
NED University of Engineering & Technology Department of Electrical Engineering
int main(void)
{
const int MAX=100;
// Array/variable definition
char name[MAX];
int index;
int maxindex;
cout<<"\nEnter your name (press ESC to stop)\n";
// Taking input in array locations:
// index goes from 0 to unknown value
index=0;
name[index]=getche();
while( name[index]!=27 )
{
index++;
if(index==100)
{
cout<<"\nArray Overflow\n";
break;
}
name[index]=getche();
}
maxindex=index;
// Simple processing of name[] array, converting small into capital
case
// index goes upto maxindex less 1
for(index=0; index<maxindex; index++)
{
if((name[index]>=97)&&(name[index]<=122))
{
name[index]=name[index]-32;
}
}
cout<<"\nPrinting the processed array.\n";
for(index=0;index<maxindex; index++)
{
cout<<name[index];
}
return 0;
}
EE-163 Computers & Programming Lab Session 08
NED University of Engineering & Technology Department of Electrical Engineering
Representation of 2D Array:
A 2D relay, also called an array of arrays, is practically nothing but a two dimensional grid of numbers
or characters. Just like 1D array which has a max length, a 2D array has both max length and max
width.
#include<iostream>
#include<conio2.h>
using namespace std;
#define row 5
#define col 3
int main(void)
{
int i,j;
float num[row][col]; // a global array
cout<<"Enter elements of array:";
for(i=0;i<row;i++) // loop for scanning
{
for(j=0;j<col;j++)
{
cout<<"\nEnter location "<<i<<","<<j<<":";
cin>>num[i][j];
}
}
cout<<"\n \n";
for(i=0;i<row;i++) // loop for printing
{
for(j=0;j<col;j++)
{
cout<<"Location "<<i<<","<<j<<"="
<<num[i][j]<<"\t";
}
cout<<"\n";
}
getch();
return 0;
}
In the previous example, the array was manipulated with nested for() loops. This is ideal in the case
of arrays that need to be processed completely – all elements, first to last. But when we need only a
part of array which has some unused locations, we need nested while() loops.
In the next example we will write a program that has a 2D character array of 10x25 elements. Some
of these are used by the user to enter his/her name while others remain unused.
EE-163 Computers & Programming Lab Session 08
NED University of Engineering & Technology Department of Electrical Engineering
#include<iostream>
#include<conio2.h>
using namespace std;
#define row 10
#define col 25
int main(void)
{
static char names[row][col]; // static class is empty
int i,j,maxrow,maxcol;
char ch;
cout<<"Enter name of 10 students,press ESC to stop\n";
i=0;
ch=1;
while(ch!=27)
{ // 1st while start
j=0;
cout<<"\n Enter name "<< i+1<<":";
ch=getche();
while((ch!=13)&&(ch!=27))
{ // 2nd while starts
names[i][j]=ch;
j=j+1;
if(j==25)
{
cout<<"\n Too long name.";
i=i-1;
break;
}
ch=getche();
} // 2nd while ends
i=i+1;
if(i==10)
{
cout<<"\n No. of names exceeded";
break;
}
cout<<"\nPress ESC to stop, any other key to continue.";
} // 1st while ends
maxrow=i;
cout<<endl<<endl;
for(i=0;i<maxrow;i++) // loop for printing
{
for(j=0;j<col;j++)
{
cout<<names[i][j];
}
cout<<endl;
}
getch();
return 0;
}
EE-163 Computers & Programming Lab Session 08
NED University of Engineering & Technology Department of Electrical Engineering
➢ For the programs where you need to utilize the array completely, use for() loops – nothing
special.
➢ For the programs in which a part of array is used, we use while() loops.
✓ The total no. of rows and columns actually utilized by the array needs to be saved for
the future use in the program.
✓ while() loop needs a separate termination condition to avoid exceeding array limit.
#include<iostream>
#include<conio2.h>
using namespace std;
// Function Prototype
int bubblesort(float array[], int N, char order);
// array is the array to sort, N is the array size
// and order dictates ascending/descending sorting
int main(void)
{
float num[10]={10.1,2.0,34.5,4.6,-5.7,
6.2,77.0,18.8,9.4,0.0};
char option;
int index;
cout<<"\nPrinting the given array.\n\n";
for(index=0;index<10; index++)
cout<<num[index]<<endl;
cout<<"\nHow would you like to sort it?"<<
" press a for ascending d for";
option=getche();
bubblesort(num, 10, option); // Function Call
cout<<"\n\nPrinting the sorted array.\n\n";
for(index=0;index<10; index++)
cout<<num[index]<<endl;
getch();
return 0;
} // End of main()
Exercise:
Q1: Read in 20 numbers in an array, each of which is in between 10 and 100 – if the number is not in
this range, ask user to re-enter. As each number is read by the program, print it only if it is not a
duplicate of a number already read.
Q2: Write a simple database program that stores name, roll no., and cgpa in FE , all in separate arrays,
for 25 students. The program should be able to let the user enter records, display records and replace
any one of the records (switch()-case can be used to give these options to user). The program must
continue until ESC is pressed. [Note: A single ‘record’ means name, roll no., and cgpa of one student]..
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 09
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 09
OBJECTIVES:
Functions:
Function is a self-contained one piece of code with some inputs upon which it does processing and
returns the output.
Number of inputs in a function can be any value and any data-type. However, in a C/C++, function
can only return one output. This is handicap when writing functions required to generate multiple
outputs.
➢ Organization: As programs grow in complexity, having all the code live inside the main()
function becomes increasingly complicated. A function is almost like a mini-program that we
can write separately from the main program, without having to think about the rest of the
program while we write it. This allows us to divide complicated tasks into smaller, simpler
ones, and drastically reduces the overall complexity of our program.
➢ Reusability: Once a function is written, it can be called multiple times from within the program.
This avoids duplicated code and minimizes the probability of copy/paste errors. Functions can
also be shared with other programs, reducing the amount of code that has to be written from
scratch (and retested) each time.
➢ Testing: Because functions reduce code redundancy, there’s less code to test in the first place.
Also because functions are self-contained, once we’ve tested a function to ensure it works, we
don’t need to test it again unless we change it. This reduces the amount of code we have to test
at one time, making it much easier to find bugs (or avoid them in the first place).
EE-163 Computers & Programming Lab Session 09
NED University of Engineering & Technology Department of Electrical Engineering
➢ Extensibility: When we need to extend our program to handle a case it didn’t handle before,
functions allow us to make the change in one place and have that change take effect every time
the function is called.
➢ Abstraction: In order to use a function, you only need to know its name, inputs, outputs, and
where it lives. You don’t need to know how it works, or what other code it’s dependent upon
to use it. This is super-useful for making other people’s code accessible (such as everything in
the standard library).
//Function Prototype
int factorial(int);
int main(void)
{
int number,fact;
cout<<"Enter a positive number:";
cin>>number;
cout<<"\nFactorial of "<<number
<<" is "<<factorial(number);
return 0;
}
//Function Definition
int factorial(int num)
{
int counter, answer=1;
if(num<0 || num>15)
{
return 0; //indicates error
}
if(num==0)
{
return 1; //special case
}
for(counter=1;counter<=num;counter++)
{
answer=answer*counter;
}
return answer;
}
EE-163 Computers & Programming Lab Session 09
NED University of Engineering & Technology Department of Electrical Engineering
#include<iostream>
#include<conio2.h>
using namespace std;
int main(void)
{
getch();
cout<<"Testing void function delay()\n";
delay(1);
cout<<"This line is printed after delay value 1\n";
delay(2);
cout<<"This line is printed after delay value 2\n";
delay(5);
cout<<"This line is printed after delay value 5\n";
return 0;
}
}
}
EE-163 Computers & Programming Lab Session 09
NED University of Engineering & Technology Department of Electrical Engineering
#include<iostream>
#include<conio2.h>
#include<cmath>
using namespace std;
float root2;
// Global Variable: Can be seen and
// manipulated by all functions
int main(void)
{
float num1,num2,num3,root1;
cout<<"\t\tProgram for calculating roots"
<<" of Quadratic Equation\n\t\t"
<<" of the form ax^2+bx+c=0";
cout<<"\nEnter the 1st co-efficient a:";
cin>>num1;
cout<<"\nEnter the 2nd co-efficient b:";
cin>>num2;
cout<<"\nEnter the constant c:";
cin>>num3;
root1=quadroots(num1,num2,num3);
//Function Call: root1 is returned by quadroots()
cout<<"The roots are "<<root1<<","<<root2;
getch();
return 0;
}
int main(void)
{
float num1,num2,num3,r1,r2;;
cout<<"\t\tProgram for calculating roots of Quadratic Equation\n\t\t"
<<" of the form ax^2+bx+c=0";
cout<<"\nEnter the 1st co-efficient a:";
cin>>num1;
cout<<"\nEnter the 2nd co-efficient b:";
cin>>num2;
cout<<"\nEnter the constant c:";
cin>>num3;
quadroots(num1,num2,num3,r1,r2);
//Function Call: nothing is returned,
//root values come back via input arguments
//r1 and r2
cout<<"The roots are "<<r1<<","<<r2;
getch();
return 0;
}
Exercise:
Q1: Write program with a function that accepts 3 int type numbers and returns the smallest among
them. The function is called minimum().
Q2: Write a void function that generates a precise delay of 2 seconds whenever it is called. The
function should contain clock() function or time() function from ctime, for precise timing.
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 10
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 10
OBJECTIVES:
Recursion:
Recursion in Computer science is a method where the solution to a problem depends on a solution to
smaller instances of the same problem. The power of recursion evidently lies in the possibility of
defining infinite set of objects by a finite statement.
Recursive Functions:
Recursive function is the one that calls itself to repeat the code. Recursive function calls generally
work just like normal function calls. The most important difference with recursive function is you
must include a recursive termination condition, or they will run forever (actually, until the call stack
runs out of memory). A recursive termination condition is a condition that, when met, will cause the
recursive function to stop calling itself.
Recursive termination generally involves if statement.
Have a look at an examples on how recursion process can be used to convert decimal into binary and
to calculate factorial of a number.
Fabonacci sequence for nth number can be calculated using recursive functions.
//program to display nth fabonacci numbers
#include <iostream>
int fibonacci(int number)
{
if (number == 0)
return 0; // base case (termination condition)
if (number == 1)
return 1; // base case (termination condition)
return fibonacci(number-1) + fibonacci(number-2);
}
// And a main program to display the first 13 Fibonacci numbers
int main()
{
for (int count=0; count < 13; ++count)
std:: cout << fibonacci(count) << " ";
return 0;
}
EE-163 Computers & Programming Lab Session 10
NED University of Engineering & Technology Department of Electrical Engineering
Recursion vs Iteration:
One question that is often asked about recursive functions, “Why use a recursive function if the same
can be done through iteration (using for or while loops)?” It turns out that you can always solve the
recursive problem iteratively. However, for non-trivial problems, the recursive version is often much
simpler to write (and read).
Iterative functions (those using for or while loop) are always more efficient than recursive
counterparts. This is because every time you call a function there is some amount of overhead that
takes place in pushing and popping stack frames. Iterative functions avoid this overhead.
That’s not to say iterative functions are always a better choice. Sometimes the recursive
implementation of a function is so much cleaner and easier to follow that incurring a little extra
overhead is more than worth it for the benefit in maintainability, particularly if the algorithm doesn't
need to recurse too many times to find a solution.
In general, recursion is a good choice when most of the following are true:
However, if the recursive algorithm is simpler to implement, it may make sense to start recursively
and then optimize to an iterative algorithm later.
Exercise:
Q1: Write a recursive function to implement Newton Raphson Method algorithm to determine square
root of a number.
Q2: Write a recursive function to find Greatest Common Divisor of two numbers using Euclid
Remainder Algorithm.
Q4: Write a recursive function to implement the following expansion (precision upto 0.0001)
NED University of Engineering & Technology
Department of Electrical Engineering
Page 1 of 2
Psychomotor Domain Assessment Rubric for Laboratory (Level P3)
Extent of Achievement
Skill(s) to be assessed
0 1 2 3 4
Software Menu Unable to Little ability and Moderate ability Reasonable Demonstrates
Identification and understand understanding and understanding command over
Usage: and use of software understanding of of software software menu
Ability to operate software menu software menu menu usage with
software environment menu operation, operation, makes operation, frequent use of
under supervision, using makes many lesser mistakes makes no major advance menu
menus, shortcuts, mistake mistakes options
instructions etc.
15% 0 15 30 45 60
Detecting and Unable to Able to find Able to find error Able to find Able to find
Removing check and error messages messages in error messages error messages
Errors/Exceptions: detect error in software but software as well in software as in software
Detect common messages in no as understanding well as along with the
Errors/Exceptions and software understanding of detecting some understanding understanding
manipulate, under of detecting of those errors of detecting all to detect and
supervision, to rectify those errors and and their types of those errors rectify them
the Code their types and their types
10% 0 10 20 30 40
Duplicating given Unable to Little ability to Ability to Ability to Ability to
Code/Instructions: reproduce reproduce given reproduce given reproduce given reproduce given
Copying/Duplication of given piece of piece of code piece of code piece of code piece of code
given Code/Instructions code correctly correctly on correctly on correctly on correctly on
without syntax and on software software (major software with software with software with no
semantic errors from syntax and minor syntax and little to no syntax and
lab manual or slides semantic errors) semantic errors syntax and semantic errors
semantic errors
10% 0 10 20 30 40
Manipulating given Unable to Ability to Ability to Ability to Ability to
Code/Instructions understand understand understand understand understand
under guidance: and follow teacher’s teacher’s teacher’s teacher’s
Manipulate given teacher’s guidance guidance guidance guidance
Code/Instructions guidance to regarding regarding code regarding code regarding code
under supervision, in manipulate manipulation manipulation but manipulation manipulation
order to produce a code but could not lags behind in and follows and follows all
different result follow following majority of instructions
instructions successfully
10% 0 10 20 30 40
Page 2 of 2
EE-163 Computers & Programming Lab Session 11
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 11
OBJECTIVE:
Pointers:
A pointer is a variable that holds a memory address as its value. Pointers are typically seen as one of
the most confusing part of the C++ language, but are surprisingly simple when explained properly.
Before moving deeper into Pointers we need to understand two basic concept related to it.
#include <iostream>
int main()
{
int x = 5;
std::cout << x << '\n'; // print the value of variable x
std::cout << &x << '\n'; // print the memory address of variable x
return 0;
}
pretty straightforward.
Note: Although the address-of operator looks just like the bitwise-and operator, you can distinguish
them because the address-of operator is unary, whereas the bitwise-and operator is binary.
#include <iostream>
int main()
{
int x = 5;
std::cout << x << '\n'; // print the value of variable x
std::cout << &x << '\n'; // print the memory address of variable x
std::cout << *&x << '\n';// print the value at the memory address of variable x
return 0;
}
Note: Although the dereference operator looks just like the multiplication operator, you can distinguish
them because the dereference operator is unary, whereas the multiplication operator is binary.
EE-163 Computers & Programming Lab Session 11
NED University of Engineering & Technology Department of Electrical Engineering
Declaring a Pointer:
Pointer variables are declared just like normal variables, only with an asterisk between the data type
and the variable name.
For e.g:
int *iPtr; //a pointer to an integer value
double *dPtr; //a pointer to a double value
Note that the asterisk here is not a dereference. It is part of the pointer declaration syntax.
Syntactically, C++ will accept the asterisk next to the data type, next to the variable name, or even in
the middle.
However, when declaring multiple pointer variables, the asterisk has to be included with each variable.
If we get used to declare pointers with asterisk next to data type and we are declaring multiple
variables, then the first declared variable will be the pointer but the other will just be a plain variable.!
Have a look at this.
For this reason, when declaring pointers, it is recommended to put asterisk next to variable name.
Since pointers only hold addresses, when we assign a value to a pointer, that value has to be an address.
One of the most common things to do with pointers is have them hold the address of a different
variable.
To get the address of a variable, we use the address-of operator:
int value = 5;
int *ptr = &value; //initialize ptr with address of a variable value
The type of the pointer has to match the type of the variable being pointed to:
int iValue = 5;
double dValue = 7.0;
int *iPtr = &iValue; //ok
double *dPtr = &dValue; //ok
iPtr = &dValue; //wrong
dPtr = & iValue; //wrong
int *ptr = 5;
EE-163 Computers & Programming Lab Session 11
NED University of Engineering & Technology Department of Electrical Engineering
This is because pointers can only hold addresses, and integer literal 5 doesn’t have a memory address.
If you try this, the compiler will tell you it cannot convert an integer to an integer pointer.
Dereferencing Pointers:
Once we have a pointer variable pointing at something, the other common thing to do with it is
dereference the pointer to get the value of what it’s pointing at. A dereferenced pointer evaluates to
the contents of the address it is pointing to.
int value = 5;
cout << &value; //prints address of value
cout << value; //prints contents of value
int *ptr = &value //ptr points to a value
cout << ptr; //prints address held in ptr, which is &value
cout << *ptr; //dereference ptr (get the value that ptr is pointing to)
This is why pointers must have a type. Without a type, a pointer wouldn’t know how to interpret the
contents it was pointing to when it was dereferenced.
Following example calculates the average value of numbers stored in an array using pointer passed an
argument
EE-163 Computers & Programming Lab Session 11
NED University of Engineering & Technology Department of Electrical Engineering
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
returnexample
Following 0; calculates the average value of numbers stored in an array by using pointer passed as an
}argument.
return avg;
getSeconds( &sec );
}
// print the actual value
cout << "Number of seconds :" << sec << endl;
return 0;
}
Exercise:
Q1: Selection sort algorithm can be used to sort an array in ascending order. The first iteration of the
algorithm selects the smallest element in the array and swaps it with the first element. The second
iteration selects the second-smallest element (which is the smallest element of the remaining elements)
and swaps it with the second element. The algorithm continues until the last iteration selects the
second-largest element and swaps it with the second-to-last index, leaving the largest element in the
last index.
As an example, consider the array
34 56 4 10 77 51 93 30 5 52
A program that implements the selection sort first determines the smallest value (4) in the
array, which is contained in element 2. The program swaps the 4 with the value in element
0 (34), resulting in
4 56 34 10 77 51 93 30 5 52
The program then determines the smallest value of the remaining elements (all elements
except 4), which is 5, contained in element 8. The program swaps the 5 with the 56 in
element 1, resulting in
4 5 34 10 77 51 93 30 56 52
On the third iteration, the program determines the next smallest value, 10, and swaps it
with the value in element 2 (34).
4 5 10 34 77 51 93 30 56 52
The process continues until the array is fully sorted.
4 5 10 30 34 51 52 56 77 93
Using pass by reference feature of pointers, implement the selection sort algorithm.
Q.2 Explore all methods of viewing addresses of variables. Also explore address storing mechanisms
(pointer variables). Finally use this knowledge to access and manipulate arrays and call multiple
variables from functions using pointers.
EE-163 Computers & Programming Lab Session 12
NED University of Engineering & Technology Department of Electrical Engineering
Lab Session 12
OBJECTIVES:
Stream:
It refers to a sequence of bytes.
Text file:
It is a file that stores information in ASCII characters. In text files, each line of text is terminated with
a special character known as EOL (End of Line) character or delimiter character. When this EOL
character is read or written, certain internal translations take place.
Opening a File:
Opening File using constructor
ofstream outFile(“sample.txt”); //output only
ifstream inFile(“sample.txt”); //input only
Opening File using open()
ofstream outFile;
outFile.open(“sample.txt”);
ifstream inFile;
inFile.open(“sample.txt”);
Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that is used
if the file is opened without a second argument:
For fstream, the default value is only applied if the function is called without specifying any value for
the mode parameter. If the function is called with any value in that parameter the default mode is
overridden, not combined.
Closing a File:
outFile.close();
inFile.close();
int main()
{
ofstream fout;
fout.open("out.txt");
fout.close();
return 0;
}
EE-163 Computers & Programming Lab Session 12
NED University of Engineering & Technology Department of Electrical Engineering
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
Where, eof() function returns a true (non-zero) if end of the file is encountered while reading;
otherwise return false (zero). This while loop will continue to run as long as we reached the end of the
file.
get() function is used take a single character from text file and print it on console.
int main()
{
ifstream fin;
fin.open("out.txt");
int count = 0;
char ch;
while(!fin.eof())
{
fin.get(ch);
count++;
}
fin.close();
return 0;
}
EE-163 Computers & Programming Lab Session 12
NED University of Engineering & Technology Department of Electrical Engineering
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
fin.close();
fout.close();
return 0;
}
Q.1 Develop a simple text editor application with File, Edit and Fonts Menus. It should be able to create new
files, display previously stored text files, edit files and save any changes.