You are on page 1of 105

NATIONAL UNIVERSITY OF

TECHNOLOGY

Electrical Engineering Department

Instructor: Lec. Aneeqa Ramzan /


LE. Syed Muhammad Ali Zaidi

Lab Manual

Computer Programming
(EE-1004)

Name:
Semester: Registration No:
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programming Semester: III

List of Experiments

Week Experiments Covered

1 Setting up Code Blocks/DEV C++ IDE for programming in C++.

2 Implementing Data Types, Variables and Arithmetic Operations in a program.

3 Executing Control Structure Programs

4 Implementing Repetition Structure Programs

5 Implementing programs using 1- dimensional and 2 dimensional Arrays

6 Executing String and Pointers Program

7 Improving Code efficiency by writing programs with Functions

Mid Semester Exam

8 Open ended lab I

9 Executing Structure Programs

10 Implementing C++ programs using Classes

Improving C++ programs with the help of Encapsulation, Inheritance and


11
Polymorphism
12 Open Ended II

13 Imitating programs to understand File handling and Templates

14 Practicing Python Basics

15 Project

End Semester Exam


National University of Technology
Electrical Engineering Department

EE-1004: Computer Programming Semester: IV

Lab 01: Setting up Code Blocks/DEV C++ IDE for


programming in C++.
Learning Outcomes

 Brief understanding of different languages and their hierarchy.


 Familiarization with compilers and their relation to programing language.
 Introduction to the DEV C++ compiler.

Equipment required

 Computer/ DEV C++

Computer language and common types.

What is a computer language?

Humans need a medium to communicate with each other. This medium in general is termed as
language. The same concept applies when it comes to communication between a human and a
computer. Since the invention of computers, computer languages have been evolving and kept on
getting more user friendly, which, in turn, increased productivity. The first commercially available
language was FORTRAN. An American company IBM developed it in 1956.

What is a computer program?

A computer program is a collection of instructions that can be executed by a computer to perform a


specific task.

std::cout << "Hello World!";


Types of computer languages.

There are mainly three different languages with the help of which we can develop computer
programs.

 Machine Level language


 Assembly Level Language
 High Level Language

Computer can understand only the language of Digital Electronics. Digital Electronics deals with
presence and absence of voltages. Within the computer there are two logics can play their role? These
logics are –

 Positive Logic – Here presence of voltage will be denoted by 1 and absence of voltage will be
denoted by 0
 Negative Logic – Here presence of voltage will be denoted by 0 and absence of voltage will
be denoted by 1

However, computer can follow anyone of the logics at a time, not both the logics simultaneously. To
make the computer understand, a program can be written using only 0s and 1s. The data can also be
specified and represented using only 0s and 1s. Such a program is called Machine Language program.
Machine language was the first in the evolution of computer programming languages. Computer directly
understands a program written in the machine language. So as a result, machine language program
does not require any translator to convert from one form to another. In fact, even to this day, basically
computers understand only the 0s and 1s.

Assembly Level Language


After machine level language, the next level of development in the evolution of computer languages
was the Assembly Language. Machine level language uses only the binary language. But on the other
hand, assembly language uses mnemonics or symbolic instructions in place of a sequence of 0s and
1s. As example, we can consider that, to add register A and B in a particular computer, assembly
language uses the mnemonic ‘ADD B’ in place of 10001111. In assembly language, we use symbolic
names to denote addresses and data. A number of such examples are dealt with in the successive
chapters. Thus writing a program in assembly language has advantages over writing the same in a
machine language.

High Level Language


High level language is the next development in the evolution of computer languages. Examples of some
high-level languages are given below –

 Python
 Java
 C++
 C
High-level languages are like English-like language, with less words also known as keywords and fewer
ambiguities. Each high level language will have its own syntax and keywords. The meaning of the word
syntax is grammar.

Compiler vs interpreter.
We generally write a computer program using a high-level language. A high-level language is one that
is understandable by us, humans. This is called source code.
However, a computer does not understand high-level language. It only understands the program written
in 0's and 1's in binary, called the machine code.
To convert source code into machine code, we use either a compiler or an interpreter.
Both compilers and interpreters are used to convert a program written in a high-level language into
machine code understood by computers. However, there are differences between how an interpreter
and a compiler works.
Interpreter Compiler

Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.

Interpreters usually take less amount of Compilers usually take a large amount of
time to analyse the source code. time to analyse the source code.
However, the overall execution time is However, the overall execution time is
comparatively slower than compilers. comparatively faster than interpreters.

Generates intermediate object code


No intermediate object code is
which further requires linking, hence
generated, hence are memory efficient.
requires more memory.

Programming languages like JavaScript, Programming languages like C, C++, and


Python, and Ruby use interpreters. Java use compilers.

IDE

An IDE, or Integrated Development Environment, enables programmers to consolidate the different


aspects of writing a computer program.

IDEs increase programmer productivity by combining common activities of writing software into a
single application: editing source code, building executables, and debugging.

DEV C++
Dev-C++, developed by Bloodshed Software, is a fully featured graphical IDE (Integrated
Development Environment), which is able to create Windows or console-based C/C++ programs
using the MinGW compiler system

LAB TASK 1
Setup Dev C++ by following given steps.
1. Configure Dev-C++.
We need to modify one of the default settings to allow you to use the debugger with your programs.

 Go to the "Tools" menu and select "Compiler Options".


 In the "Settings" tab, click on "Linker" in the left panel, and change "Generate debugging
information" to "Yes":
 Click "OK".
 2. Create a new project.
A "project" can be considered as a container that is used to store all the elements that are
required to compile a program.

 Go to the "File" menu and select "New", "Project...".


 Choose "Empty Project" and make sure "C++ project" is selected.
Here you will also give your project a name. You can give your project any valid filename, but
keep in mind that the name of your project will also be the name of your final executable.
 Once you have entered a name for your project, click "OK".
 Dev-C++ will now ask you where to save your project.

3. Create/add source file(s).


You can add empty source files one of two ways:

 Go to the "File" menu and select "New Source File" (or just press CTRL+N) OR
 Go to the "Project" menu and select "New File".
Note that Dev-C++ will not ask for a filename for any new source file until you attempt to:
1. Compile
2. Save the project
3. Save the source file
4. Exit Dev-C++

You can add pre-existing source files one of two ways:

 Go to the "Project" menu and select "Add to Project" OR


 Right-click on the project name in the left-hand panel and select "Add to Project".

LAB TASK 2

Write a simple program and compile by following given steps.


SIMPLE PROGRAM
1. Compile.
Once you have entered all of your source code, you are ready to compile.

 Go to the "Execute" menu and select "Compile" (or just press CTRL+F9).

It is likely that you will get some kind of compiler or linker error the first time you attempt to
compile a project. Syntax errors will be displayed in the "Compiler" tab at the bottom of the
screen. You can double-click on any error to take you to the place in the source code where it
occurred. The "Linker" tab will flash if there are any linker errors. Linker errors are generally
the result of syntax errors not allowing one of the files to compile.

Once your project successfully compiles, the "Compile Progress" dialog box will have a status of
"Done". At this point, you may click "Close".

2. Execute.
You can now run your program.

 Go to the "Execute" menu, choose "Run".

LAB TAK 3

Download, install and set up Code: blocks IDE for C++.


Link is given below.
Go to https://www.bloodshed.net/. Click "Download the binary release". Select your operating platform (e.g.,
Windows 2000/XP/Vista/7). Download the installer with GCC Compiler, e.g., codeblocks-13.12mingw-
setup.exe (98 MB) (which includes MinGW's GNU GCC compiler and GNU GDB debugger).
OBSERVATIONS & DISCUSSION
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programming Semester: IV

Lab 02: Implementing Data Types, Variables and


Arithmetic Operations in a program.
Learning Outcomes

 Learning to write a basic program.


 Different types of variable and their role in writing a program.
 Introduction to different data types in C++ programing.

Equipment required

 Computer/ DEV C++

Program 1:

#INCLUDE <IOSTREAM>
USING NAMESPACE STD;

VOID MAIN()

{
COUT<<" EVERY AGE HAS A LANGUAGE OF ITS OWN”;

Preprocessor Directives:

 The instructions that are given to the compiler before the beginning of the actual program are
called preprocessor directives.
 The two lines that begin the FIRST program are directives. The first is a preprocessor directive,
and the second is a using directive. A preprocessor directive is an instruction to the compiler.
 The preprocessor directive #include tells the compiler to insert another file into your source file.

 A part of the compiler called the preprocessor deals with these directives before it begins the
real compilation process. The type file usually included by #include is called a header file
Header Files

 In the FIRST example, the preprocessor directive #include tells the compiler to add the source
file IOSTREAM to the FIRST.CPP source file before compiling.
 A header file is added if the function/object defined in it is to be used in the program.
 Header file is a C++ source file that contains definitions of library functions/objects.
 Header files are added in the program at the compilation of the program.

Main Function

 When you run a C++ program, the first statement executed will be at the beginning of a function
called main().
 The program may consist of many functions, classes, and other program elements, but on
startup, control always goes to main().
 If there is no function called main() in your program, an error will be signaled.
Program Statements

 The program statement is the fundamental unit of C++ programming. The statement in the
FIRST program is:

Cout<<"Every age has a language of its own\n";


 A semicolon signals the end of the statement.

Output using “cout”

 The statement: cout<<"Every age has a language of its own\n"; causes the phrase in quotation
marks to be displayed on the screen.
 The identifier cout pronounced (“C out”). The operator << is called the insertion or put to operator.
It directs the contents of the variable on its right to the object on its left.

Example 1

Example 2
Data types in C++
1. Integer
Int, short int, long int, unsigned int, unsigned long int

2. Floating Point
Float, long float

3. Double
Double, long double

4. Characters
Char

5. Boolean
Bool

Example 3
Example 4
#include <iostream>

using namespace std;

void main()

int n;

cout<<"Enter a number = “;

cin>>n;

cout<<"\n Number you entered is = "<<n;

Variables
A quantity whose value may change during execution of the program is called variable. It is represented
by a symbol or a name e.g. a,b etc.

Constants
A quantity whose value cannot change during execution of the program is called constant. e.g. const
pi=3.14

String Constants
A sequence of characters consisting of alphabets, digits or special characters enclosed in double
quotation marks is called string constant.
The phrase in quotation marks, “Every age has a language of its own\n”, is an example of a string
constant.

Character Constant
A single character enclosed in single quotation marks is called character constant. For example ‘a’, ‘/‘
represent character constants.
Tokens
Smallest textual element that has some meanings to the code is called token. Tokens: main, {,}, cout
etc.
Types of Tokens
 Keywords.
 Punctuators.
 Identifiers.

Keywords
Essential part of programming language is known as keywords. e.g. int , float , while , class etc.

Punctuators
Symbols used for grouping or separating code are known as punctuators.
“( )”,” {}”,”[]”, comma, semicolon, colon, period.

Identifiers
Program designed tokens used for naming variables, methods, classes, interfaces,
namespaces, labels are known as identifiers. e.g. x, abc, home etc.

Manipulators
Manipulators are operators that are used with insertion operator (<<) to control format of data.
The “endl” Manipulator
The “endl” stands for end of line. It is a predefined iostream manipulator.
Comment Syntax
Comments start with a double slash symbol (//) and terminate at the end of the line. (This is one of the
exceptions to the rule that the compiler ignores whitespace).
//define
//char variable
//as character

Alternative Comment Syntax


There’s a second comment style available in C++:

/*define char variable as character*/

/*define
char variable
as character*/

LAB TASK 1
Write a program that shows following Output

LAB TASK 2
Write a program that assign values to different variables at the time of declaration. Print the
assigned values on the computer screen. The output of the program should be like:

Operators
Operators are used in expressions to describe operations involving one or more operands.
Operators are symbols that perform operations on variables and values. For example, + is an operator
used for addition, while - is an operator used for subtraction.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,

a + b;

Here, the + operator is used to add two variables a and b . Similarly there are various other
Arithmetic operators in C++.

+ Addition Adds together two values

- Subtraction Subtracts one value from another

* Multiplication Multiplies two values

/ Division Divides one value by another

% Modulus Returns the division remainder

++ Increment Increases the value of a variable by 1

-- Decrement Decreases the value of a variable by 1

EXAMPLE 1
# include <iostream>
using namespace std;

int main() {
int a, b;
a = 7;
b = 2;

// printing the sum of a and b


cout << "a + b = " << (a + b) << endl;

// printing the difference of a and b


cout << "a - b = " << (a - b) << endl;

// printing the product of a and b


cout << "a * b = " << (a * b) << endl;

// printing the division of a by b


cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b


cout << "a % b = " << (a % b) << endl;

return 0;
}

LAB TASK 1

Write a simple program to use subtraction (-), multiplication (*), division (/), modulus (%),
increment (++) and decrement (--) operators.

2. Assignment Operators

In C++, assignment operators are used to assign values to variables.


Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

EXAMPLE 2

#include <iostream>
using namespace std;

int main() {
int a, b, temp;

// 2 is assigned to a
a = 2;

// 7 is assigned to b
b = 7;

// value of a is assigned to temp


temp = a; // temp will be 2
cout << "temp = " << temp << endl;

// assigning the sum of a and b to a


a += b; // a = a +b
cout << "a = " << a << endl;

return 0;
}

LAB TASK 2

Write a simple program and use following operators.


+=, -=, *=, /=, %=

3. C++ Relational Operators


A relational operator is used to check the relationship between two operands. For example,

// checks if a is greater than b


a > b;

Here, > is a relational operator. It checks if a is greater than b or not.


If the relation is true, it returns 1 whereas if the relation is false, it returns 0.

Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

EXAMPLE 3
#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;

result = (a == b); // false


cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;

LAB TASK 3
Use the following relational operators in a program.

1. != 2. > 3. < 4. >= 5. <=

4. C++ Logical Operators


Logical operators are used to check whether an expression is true or false. If the expression is true,
it returns 1 whereas if the expression is false, it returns 0.

Operator Example Meaning

Logical AND.
&& expression1 && expression2
True only if all the operands are true.

Logical OR.
|| expression1 || expression2
True if at least one of the operands is true.

Logical NOT.
! !expression
True only if the operand is false.

EXAMPLE 4

int main() {
bool result;

result = (3 != 5) && (3 < 5); // true


cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false


cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false


cout << "(3 == 5) && (3 > 5) is " << result << endl;
return 0;
}

LAB TASK 4

Write a simple program to perform logical OR and logical NOT operations.


LAB TASK 5

Write a program that calculates the area and circumference of the circle (use pi as a floating point
constant) with the output formatted in the following way:

LAB TASK 6

Write a program that performs all the arithmetic operations by using all arithmetic operators with the
output formatted in the following way:
OBSERVATIONS & DISCUSSION
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programming Semester: 3rd

Lab 03: Executing Control Structure Programs


Learning Outcomes

 Familiarization with conditional statements in C++


 Implementation of if – else statements
 Implementation of nested conditional statements
 Familiarization with switch statement

Conditional Statements
The conditional statements are used to execute a set of statements after testing a condition. The
conditional statements are also called selection statements.
The “if” Statement:
 The “if statement” evaluates a condition.
 If the given condition is true, the statement (or set of statements) following the “if statement” is
executed.
 If the given condition is false, the statement (or set of statements) following the “if statement” is
 Ignore and the control transfers to the next statement.

“If” Statement
EXAMPLE

“if-else” Statement

 In this statement, one condition and two blocks of statements are given.
 Either one of the two blocks of statements is executed after evaluating a condition.
 If the given condition is true, the first block of statements is executed.
If the given condition is false, the first block of statements is ignored and the second block following
the else is executed.

Syntax of “if-else” statement

If (condition)
Statement – 1;
else
Statement – 2;
EXAMPLE 2
Nested- if else statemente

Example 3
LAB TASK 1
Write a program to input two numbers and then find out whether these numbers are equal. The output
of the program should be like:

LAB TASK 2
Write a program to input a number from the key board and then print the message “It is an odd number”
if the given number is odd number.
Else print “It is an even number”. (A number is even it is divisible by 2). The output of the program
should be like:
LAB TASK 3
Write a program to enter a number from the user and print “Number is positive” if given number is
positive (greater than 0) and print “Number is negative” if number is negative (less than 0). The Output
will be like:

LAB TASK 4
Write a program to find the Largest of three decimal numbers. Take numbers from user.

LAB TASK 5
Write a program to calculate the net pay of the employee. Input the basic pay and calculate the net pay
as follow:
 House rent is 45% of the basic pay.
 Medical allowance is 2% of basic, if basic is greater than Rs. 5000. It is 5% of the basic pay if the
pay is less than Rs. 5000.
 Conveyance allowance is Rs. 960 if the basic pay is less than Rs. 5000. It is Rs. 500 if the basic
pay is more than Rs. 5000.
 Net pay is calculated by adding basic pay, medical allowance, conveyance allowance and house
rent.

The Output must be:


SWITCH statement

It is used when multiple choices are given and one choice to be selected. It is also used as a substitute
of “nested if-else” statements. It is used at the end of the statements in each case. The syntax of switch
is:

switch (expression)
{
case const-1:
Statements;
break;
case const-2:
Statements;
break;
case const-n:
Statements;
break;
default:
statements;
}

Example 2

#include <iostream.h>
int main()
{
int speed; //turntable speed
cout << "\nEnter 33, 45, or 78: ";
cin >> speed; //user enters speed
switch(speed) //selection based on speed
{
case 33: //user entered 33
cout << "LP album\n";
break;
case 45: //user entered 45
cout << "Single selection\n";
break;
case 78: //user entered 78
cout << "Obsolete format\n";
break;
}
return 0;
}

LAB TASK 6
Write a program in C++ to input marks obtained by a student in a subject. The total marks are 100. Find
out the grade of the student by using switch statement structure. The grade is:

 If marks are equal to or greater than 90, grade is A


 If marks are equal to or greater than 70 and less than 90, grade is B
 If marks are equal to or greater than 90 and less than 70, grade is C
 If marks are less than 50, grade is “F”.

The output of the program should be like:

LAB TASK 7
Write a program to perform simple arithmetic operations by using switch statement. The output of the
program should be like:

LAB TASK 8
Write a program to display different colors by using switch statement. Output should be like this:

MAIN MENU

R. for Red color


W. for White color
B. for Blue color
Y. for Yellow color
Please enter your choice: B
Color is Blue
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 04: Implementing Repetition Structure


Programs
Learning Outcomes
 Familiarization with loops and their syntax
 Understanding of Implementation of For and While loop in a program.
 Understanding Similarities and subtle differences between different loops(For, While,
Do While)
 Familiarization with the multidimensional property of nested loop.

LOOP STATEMENT
“For” Loop
 The for loop statement is used to execute a set of statements repeatedly for a fixed number of times.
It is also known as counter loop.
 It is used when you know, before entering the loop, how many times you want to execute the code.
 All its loop control elements are gathered in one place, while in the other loop constructions they
are scattered about the program.

Structure of “For” Loop

The general syntax of the for loop is:


for (initialization; condition; increment/decrement)
{ …………. }
It has the following parts:
 Test Expression (Condition)
 Increment or decrement (Increment/decrement expression)
 Body of the loop
Initialization Expression

The Initialization Expression

 In initialization part, the value in the variable (or a set of variables) is assigned when control
enters in the loop first time. New variable can also be declared and initialized in this part.
 The initialization expression is executed only once, when the loop first starts. It gives the loop
variable an initial value. For example:
for (int a=5; a<=10; a++)
The Test Expression

 In this part, the test condition is executed. The body of the loop executes as long as this condition
remains true.
 The test expression usually involves a relational operator. It is evaluated each time through the
loop, just before the body of the loop is executed.
 It determines whether the loop will be executed again. If the test expression is true, the loop is
executed one more time.
 If it’s false, the loop ends, and control passes to the statement following the loop.

Increment/Decrement Expression

 This portion changes the value of the loop variable, often by incrementing or decrementing it. It
is always executed at the end of the loop, after the body of the loop has been executed.
 Each time the body of the loop is executed, the value of the variable is increased or decreased.
 The use of this part is optional. If this part is not used then the control variable must be
incremented or decremented inside the body of the loop.

Body of “For” Loop

The statements under the “for” loop are the body of loop. If more than one statement is to be executed,
these are enclosed in braces. Multiple statements are delimited by braces.

#include<iostream.h>
void main()
{
int c;
for (c=1;c<=10;c++)
cout<<c<<endl;
}

Example 1

void main()
{
int tab,c,r;
cout<<"\n Enter the number = ";
cin>>tab;
for(c=1;c<=10;c++)
{
r=tab*c;
cout<<tab<<“*”<<c<<“=“<<r<<endl; } }
LAB TASK 1

Write a program that displays counting from 1 to 5 using for loop.

LAB TASK 2

Write a program using for loop that prints out the cubes of numbers from 1 to 10. The output of the
program should be like:

LAB TASK 3

Write a program to print odd numbers between 1 and 100 and also print sum of odd numbers.

LAB TASK 4

Write a program to calculate and display the sum of 1 to n in steps of s, where n and s are numeric-
type arguments input from the keyboard such that s denotes the step size between 1 and n. For
example, if n=21 and s=3 are passed, it will display the result of 1 4 7 10 13 16 19.

LOOP STATEMENT

The “While” Loop


It is used to execute a statement or a set of statements as long as the given condition remains true.
The syntax of while loop is:

while (condition)
Statement;

Example
#include <iostream.h>
main()
{
int n = 1;
while(n<=5)
{cout<< “Hello”<<endl;
n=n+1;
}
cout<< “Program Ends”;}

A while loop is a control flow statement that allows code to be executed repeatedly based on a
given Boolean condition. The while loop can be thought of as a repeating if statement.
Understanding of basic concept of while loop. The while construct allows for repetitive execution of a
list of commands, as long as the command controlling the while loop executes successfully (exit status
of zero).

LAB TASK 5

Write a program to calculate factorial of a number using while loop. The output of the program should
be like:

LAB TASK 6

Write a program to print natural numbers 1 to 20 in descending order. The output of the program should
be like:
LAB TASK 7

Write a program to find the sum of the following series.


1+1/2+1/3+…..1/45
The output of the program should be like:

LAB TASK 8

Write a program that converts a number into its equivalent binary number using while loop.
LOOP STATEMENT

The “do-while” Loop

The do-while is like while loop but in this loop the condition is tested after executing the statements of
the loop. In do-while loop, the body of the loop is executed at least once before the condition is tested.
The syntax is:

do
{
Statements;
}
while (condition)

Example

#include <iostream.h>
main()
{
int n = 1;
do
{
cout<<n<<endl;
n++;
}
while (n<=10);
}

In “do-while” loop, the body of the loop is executed at least once before the condition is tested. It is
repeatedly executed as long as the condition remains true.
If the given condition becomes false at any stage during the program execution, the loop terminates
and control shifts to the statement that comes immediately after the keyword “while”.
Understanding of basic concept of do-while loop. In “do-while” loop, the body of loop comes before the
test condition. The body of the loop is executed and then the condition is tested.

LAB TASK 9

Write a program to print in the descending order first twenty natural numbers on the computer screen
by using “do-while” loop.

LAB TASK 10

Write a program to compute and print the factorial of the given number using the “do-while” loop.

Nested for Loop


A loop nested inside another loop.

Example 2

LAB TASK 11

Write a program to display following output using “while” loop


OBSERVATIONS & DISCUSSION
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 05: Implementing programs using 1-


dimensional and 2 dimensional Arrays

Learning Outcomes

 Familiarization with the concept of 1 d and 2 d arrays.


 Understanding how an array is taken as user input.
 Understanding the simplicity an array provides in a code.

ARRAYS

Arrays are like structures in that they both group a number of items into a larger unit. But while a
structure usually groups items of different types, an array groups items of the same type. More
importantly, the items in a structure are accessed by name, while those in an array are accessed by
an index number.

Using an index number to specify an item allows easy access to a large number of items. Arrays exist
in almost every computer language. Arrays in C++ are similar to those in other languages, and
identical to those in C.

The use of arrays may allow us to simplify our processing. We can use arrays to help read and
analyze repetitive data with a minimum of coding. An array and a loop can make the program smaller.

It is learned that Arrays contain a number of data items of the same type. This type can be a simple
data type, a structure, or a class. The items in an array are called elements.
LAB TASK 1
Write a program to input value in an array. Find out the total number of even and odd values entered
in the array.

LAB TASK 2
Write an array to take an array from user and print it in reverse order.

2-d Array
In C++, we can create an array of an array, known as a multidimensional array. For example:

int x[3][4];

Here, x is a two-dimensional array. It can hold a maximum of 12 elements.


We can think of this array as a table with 3 rows and each row has 4 columns as shown below.

LAB TASK 3
Declare the following two-dimensional array of type integer:
1 2 3
2 4 6
3 5 -7
-1 4 8

Display only the negative value from the above two dim array.

LAB TASK 4
Write a program that allows the user to input a number of integers, and then stores them in a two
dimensional array of n*m dimension (n and m are also taken as input from user). The program should
first display the 2 d array as output and then display only the diagonal values of the 2 d array.

OBSERVATIONS & DISCUSSION


National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 06: Executing String and Pointers Program

Learning Objectives

 Familiarization with strings, using arrays and using string class


 Familiarization with the built in functions of strings in C++
 Introduction to the concept of pointers in C++
 To write basic programs of strings and pointers to have a solid base in programming.

STRINGS
The combination of characters is called a string. A string is a variable that stores a sequence of letters
or other characters, such as "Hello" or "May 10th is my birthday!". Just like the other data types, to
create a string we first declare it, then we can store a value in it.

Declaration using array of character


The declaration and definition of the string using an array of chars is similar to declaration and definition
of an array of any other data type:

Any string ends with a terminating null character '\0'. An array definition in such a way should
include null character '\0' as the last element. In above case the capacity of an array is 10 but we have
used only 8 of it. The remaining two chars of an array will not be defined.

String array can also be taken as input from the user demonstrated in the example below

Example
#include <iostream>
using namespace std;

int main()
{
char str[100];

cout << "Enter a string: ";


cin >> str;
cout << "You entered: " << str << endl;

cout << "\nEnter another string: ";


cin >> str;
cout << "You entered: "<<str<<endl;
cout<<str[3];
return 0;
}

Built in string functions

Operators Description Example

strcpy String copy Strcpy(s1,s2)

strcat Concatenation Strcat(s1,s2)

strlen String length Strlen(s1)

#include <iostream>
#include <cstring>
using namespace std;
int main() {

char name1[10] = "ahmed";


char name2[10] = "ibrahim";
char name3[10];

int len;
strcpy(name3, name1);
cout << "strcpy( name3, name1) : " << name3 << endl;
strcat(name1, name2);
cout << "strcat( name1, name2): " << name1 << endl;

len = strlen(name1);
cout << "strlen(name1) : " << len << endl;

return 0;
}

Using string class

In the C++ programming language, the string class is a standard representation for a string of text. This
class alleviates many of the problems introduced by c-style strings by putting the onus of memory
ownership on the string class rather than on the programmer.
The class provides some typical string operations like comparison, concatenation, find and replace,
and a function for obtaining substrings.
The combination/sequence of characters is called a string. (Array of chars)
To use strings, you must include an additional header file in the source code, the <string> library:

Example

// Include the string library


#include <string>

// Create a string variable


string greeting = "Hello";

User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered by a user:

Example

string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John


// Your name is: John

However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that
it can only display a single word (even if you type many words):

Example
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: John Doe


// Your name is: John

From the example above, you would expect the program to print "John Doe", but it only prints "John".

That's why, when working with strings, we often use the getline() function to read a line of text. It
takes cin as the first parameter, and the string variable as second:

String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:

To get the length of a string, use the length() function:

Access Strings

You can access the characters in a string by referring to its index number inside square
brackets [].

This example prints the first character in myString:

Example
string myString = "Hello";
cout << myString[0];
// Outputs H

Erase string

str.erase(1, 4); // Deletes 4 characters from index number 1

str.erase(1); // Deletes all characters except first one

str.erase(); // Deletes all characters


LAB TASK 1
Write a program to input data into a string. Delete a specific character from string. Print on the screen
the entered string and the string after deleting the character.

LAB TASK 2
Write a program that read a string and count the number of characters in it.

LAB TASK 3
Write a program to find whether a given string is palindrome or not. Use array string.

POINTERS
Pointers are much more commonly used in C++ (and C) than in many other languages (such as BASIC,
Pascal, and certainly Java, which has no pointers).

The idea behind pointers is not complicated. Here’s the first key concept: Every byte in the computer’s
memory has an address.

Addresses are numbers, just as they are for houses on a street. The numbers start at 0 and go up from
there—1, 2, 3, and so on. If you have 1MB of memory, the highest address is 1,048,575. (Of course
you probably have much more.)

Your program, when it is loaded into memory, occupies a certain range of these addresses. That means
that every variable and every function in your program starts at a particular address

Therefore pointers are used in many occasion when programming.


Pointers are used for:

 Accessing array elements


 Passing arguments to a function when the function needs to modify the original argument
 Passing arrays and strings to functions
 Obtaining memory from the system
Creating data structures such as linked lists

The Address-of Operator &


You can find the address occupied by a variable by using the address-of operator &. Here’s a short
program, that demonstrates how to do this:

Example
#include <iostream>
using namespace std;
int main()
{
int var1 = 11; //define and initialize
int var2 = 22; //three variables
int var3 = 33;
cout<<&var1 << endl //print the addresses
<<&var2 << endl //of these variables
<<&var3 << endl;
return 0;
}

This simple program defines three integer variables and initializes them to the values 11, 22, and 33.
It then prints out the addresses of these variables. The actual addresses occupied by the variables in
a program depend on many factors, such as the computer the program is running on, the size of the
operating system, and whether any other programs are currently in memory.

The << insertion operator interprets the addresses in hexadecimal arithmetic, as indicated by the prefix
0x before each number. This is the usual way to show memory addresses. If you aren’t familiar with
the hexadecimal number system, don’t worry. All you really need to know is that each variable starts at
a unique address.

However, you might note in the output above that each address differs from the next by exactly 4 bytes.
That’s because integers occupy 4 bytes of memory (assuming it’s a 16-bit system). If we had used
variables of type char, they would have adjacent addresses, since a char occupies 1 byte; and if we
had used type double, the addresses would have differed by 8 bytes.

Dereferencing

n the example from the previous page, we used the pointer variable to get the memory
address of a variable (used together with the & reference operator). However, you can also use the
pointer to get the value of the variable, by using the * operator (the dereference operator):

Example
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration

// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";

// Dereference: Output the value of food with the pointer (Pizza)


cout << *ptr << "\n";

The addresses appear in descending order because automatic variables are stored on the stack, which
grows downward in memory. If we had used external variables, they would have ascending addresses,
since external variables are stored on the heap, which grows upward.

Pointers are the most powerful feature of C & C++. These are used to create and manipulate data
structures such as linked lists, queues, stacks, trees etc. These are used in advance programming
techniques. They provide means by which functions can modify their calling arguments.

Pointers are variables that hold address values. The use of pointers can improve the efficiency of the
certain routines.
Modify the Pointer Value

You can also change the pointer's value. But note that this will also change the value of the original
variable:

Example
string food = "Pizza";
string* ptr = &food;

// Output the value of food (Pizza)


cout << food << "\n";

// Output the memory address of food (0x6dfed4)


cout << &food << "\n";

// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";

// Change the value of the pointer


*ptr = "Hamburger";

// Output the new value of the pointer (Hamburger)


cout << *ptr << "\n";

// Output the new value of the food variable (Hamburger)


cout << food << "\n";

NULL POINTER
NULL pointer the pointer that points nothing.

To initialize a pointer variable when the pointer variable is not assigned any valid memory address.

NULL pointer is an empty pointer.

int *Num = NULL;


cout<<“The value of Num : ”<<Num;

The value of Num : 0

POINTER TO POINTER

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer


contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the
address of the second pointer, which points to the location that contains the actual value as shown
below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name. For example, the following declaration declares a pointer to a
pointer of type int.

EXAMPLE

#include <iostream>
using namespace std;
int main () {

int var;
int *ptr;
int **pptr;

var = 3000;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

return 0;
}

LAB TASK 1

Simple Program for Add Two Numbers Using Pointer. Numbers must be taken as input from the user.

LAB TASK 2
Write a simple Program for Increment and Decrement Integer Using Pointer. Integer Values must be taken as
input from the use.
LAB TASK 3

Write a program to swap two values using pointers. The output of the program should be like:

LAB TASK 4
Write program to display values of integer array and use dereferencing to change array values using
pointers.

OBSERVATIONS & DISCUSSION


National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 07: Improving Code efficiency by writing


programs with Functions

Learning Outcomes

 Brief understanding of different languages and their hierarchy.


 Familiarization with compilers and their relation to programing language.
 Introduction to the DEV C++ compiler.

Description

A function groups a number of program statements into a unit and gives it a name. This unit can then
be invoked from other parts of the program. A function is a complete and independent program. It is
executed by main function or any other function of the program to perform its task.

Functions in C++ (and C) are similar to subroutines and procedures in various other languages.

Any sequence of instructions that appears in a program more than once is a candidate for being made
into a function. The function’s code is stored in only one place in memory, even though the function is
executed many times in the course of the program.
Figure: Flow of control to function

Simple Functions

Our first example demonstrates a simple function whose purpose is to print a line of 45 asterisks. The
example program generates a table, and lines of asterisks are used to make the table more readable.
Here’s the listing for TABLE:

// demonstrates simple function

#include<iostream>
using namespace std;

voidstarline(); //function declaration


// (prototype)
int main()
{
starline(); //call to function
cout<< “Data type Range” << endl;
starline(); //call to function

cout<< “char -128 to 127” << endl


<< “short -32,768 to 32,767” << endl
<< “int System dependent” << endl
<< “long -2,147,483,648 to 2,147,483,647” << endl;
starline(); //call to function
return 0;
}

//--------------------------------------------------------------
// starline()
// function definition

voidstarline()
for(int j=0; j&lt45; j++) //function body
cout<< ‘*’;
cout<< endl;
}
output from the program looks like this:

*********************************************
Data type Range
*********************************************

char -128 to 127


short -32,768 to 32,767
System dependent
double -2,147,483,648 to 2,147,483,647

Program consists of two functions: main() and starline(). You’ve already seen main() alone. What other
components are necessary to add a function to the program? functiondeclaration, the calls to the
function, and the function definition.

The Function Declaration


Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function
without telling the compiler about it. There are two ways to do this. The approach we show here is to
declare the function before it is called.

(The other approach is to define it before it’s called; we’ll examine that next.). In the TABLE program,
the function starline() is declared in the line

voidstarline();

The declaration tells the compiler that at some later point we plan to present a function called starline.
The keyword void specifies that the function has no return value, and the empty parentheses indicate
that it takes no arguments.

(You can also use the keyword void in parentheses to indicate that the functiontakes no arguments, as
is often done in C, but leaving them empty is the more common practice in C++.)

We’ll have more to say about arguments and return values soon. Notice that the function declaration is
terminated with a semicolon. It is a complete statement in itself. Function declarations are also called
prototypes, since they provide a model or blueprint for the function.

They tell the compiler, “a function that looks like this is coming up later in the program, so it’s all right if
you see references to it before you see the function itself.”

Calling the Function

The function is called (or invoked, or executed) three times from main(). Each of the three calls looks
like this:

starline();

This is all we need to call the function: the function name, followed by parentheses. The syntax of the
call is very similar to that of the declaration, except that the return type is not used. The call is terminated
by a semicolon.

Executing the call statement causes the function to execute; that is, control is transferred to the
function, the statements in the function definition (which we’ll examine in a moment) are executed, and
hen control returns to the statement following the function call.

The Function Definition

Finally, we come to the function itself, which is referred to as the function definition. The definition
contains the actual code for the function. Here’s the definition for starline ():

void starline() //declarator


{
for(int j=0; j&lt45; j++) //function body
cout<< ‘*’;
cout<< endl;
}

The definition consists of a line called the declarator, followed by the function body. The function body
is composed of the statements that make up the function, delimited by braces.
The declarator must agree with the declaration:

It must use the same function name, have the same argument types in the same order (if there are
arguments), and have the same return type.

Notice that the declarator is not terminated by a semicolon. Figure shows the syntax of the function
declaration, function call, and function definition.

When the function is called, control is transferred to the first statement in the function body. The other
statements in the function body are then executed, and when the closing brace is encountered, control
returns to the calling program.

Passing Arguments to Functions

An argument is a piece of data (an int value, for example) passed from a program to the function.
Arguments allow a function to operate with different values, or even to do different things, depending
on the requirements of the program calling it.

C++ allows programmers to divide their code up into chunks known as functions. A function with simple
description and a well-defined interface to outside world can be written and debugged without worrying
about the code that surrounds it.

Basic understanding of the concept of function. Using function we can structure our program in a more
modular way, accessing all the potential that structured programming can offer to us in C++.

LAB TASK 1

Write a program to pass two integer type numbers as arguments to the function body, compare the
numbers in the function body and print the greater number on the screen. The output of the program
should be like:

LAB TASK 2
Write a program that converts the kilograms into grams by using a function. The output of the program
should be like: Hint: 1 kilogram = 1000 grams.

LAB TASK 3

Write a program that creates four function calculator, so that it uses functions for each of the four
arithmetic operations. They can be fadd, fsub, fmul, and fdiv. Each of these functions should take three
arguments two of float type and one is of character type for the operator. The output of the program
should be like:
OBSERVATIONS & DISCUSSION
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 08: Open Ended Lab I


Problem Statement
Jamal is a CEO of a Company XYZ and wants to develop a forum, which stores the information of
Employees. He hires a computer programmer to write the simple porotype program. Initially for
testing purpose, he defines only three personal information variables (name, age, height).
For code to be more organized, mutable and readable, he demands the code to be written with
following instruction.
1. The three variables must be defined under one data type.
2. Two functions named “finput” and “display” must be defined, where, finput takes an input
for the three variable (name, age, height) and display function displays out the information
entered.
3. Pointer must be used as a passing argument to functions.
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 09: Executing Structure Programs in C++

Learning objectives

 Brief understanding of Structures and its syntax.


 Understanding how to define a structure.
 Understanding how to pass structure to a function and return of structure from a
function
 Familiarization with the array of structures

A STRUCT is a C++ data structure that can be used to store together elements of different data
types. In C++, a structure is a user-defined data type. The structure creates a data type for grouping
items of different data types under a single data type.

For example:

Suppose you need to store information about someone, their name, citizenship, and age. You can
create variables like name, citizenship, and age to store the data separately.

However, you may need to store information about many persons in the future. It means variables for
different individuals will be created. For example, name1, citizenship1, age1 etc. To avoid this, it's
better to create a struct.

Why to use a structures?

 Use a struct when you need to store elements of different data types under one data
type.

 C++ structs are a value type rather than being a reference type. Use a struct if you don't intend
to modify your data after creation

C++ Structure Initialization

To create a C++ structure, we use the struct keyword, followed by an identifier. The identifier
becomes the name of the struct. Here is the syntax for creation of a C++ struct:
Syntax:

struct struct_name
{
// struct members
};

In the above syntax, we have used the struct keyword. The struct_name is the name of the
structure.The struct members are added within curly braces. These members probably belong to
different data types.

For example:

struct Person
{
char name[30];
int citizenship;
int age;
}

In the above example, Person is a structure with three members. The members include name,
citizenship, and age. One member is of char data type, while the remaining 2 are integers when a
structure is created, memory is not allocated. Memory is only allocated after a variable is added to the
struct.

Creating Struct Instances

In the above example, we have created a struct named Person. We can create a struct variable as
follows:

Person p;

The p is a struct variable of type Person. We can use this variable to access the members of the
struct.

Accessing Struct Members

To access the struct members, we use the instance of the struct and the dot (.) operator. For
example, to access the member age of struct Person:

p.age = 27;

We have accessed the member age of struct Person using the struct's instance, p. We have then set
the value of the member age to 27.

#include <iostream>
using namespace std;
struct Person
{
int citizenship;
int age;
};
int main(void) {
struct Person p;
p.citizenship = 1;
p.age = 27;
cout << "Person citizenship: " << p.citizenship << endl;
cout << "Person age: " << p.age << endl;
return 0;
}
Struct as Function Argument

You can pass a struct to a function as an argument. This is done in the same way as passing a
normal argument. The struct variables can also be passed to a function. A good example is when you
need to display the values of struct members. Let's demonstrates this:

#include<iostream>
using namespace std;

struct Person
{
int citizenship;
int age;
};

void func(struct Person p);

int main()
{
struct Person p;

p.citizenship = 1;
p.age = 27;

func(p);
return 0;
}
void func(struct Person p)
{
cout << " Person citizenship: " << p.citizenship<<endl;
cout << " Person age: " << p.age;
}
Pointers to Structure and passing structure instance pointer to function

It is possible to create a pointer that points to a structure. It is similar to how pointers pointing to
native data types like int, float, double, etc are created. Note that a pointer in C++ will store a memory
location address.

Example
#include <iostream>
using namespace std;

struct Length
{
int meters;
float centimeters;
};
int main()
{ Length *ptr, l;
ptr = &l;

cout << "Enter meters: ";


cin >> (*ptr).meters;
cout << "Enter centimeters: ";
cin >> (*ptr).centimeters;
cout << "Length = " << (*ptr).meters << " meters " << (*ptr).centimeters << " centimeters";
return 0;
}

Example

This example demonstrates the use of pointers defined as an instance of a structure, passed to a
function.

#include<iostream>
using namespace std;
#include<cstring>

struct talha
{
int age;
string fullname;
float height;
};

void display(talha *x)


{
cout<<(*x).age<<endl;
cout<<(*x).height<<endl;
cout<<(*x).fullname;
}

int main()
{

talha *ptr,p;
ptr=&p;
(*ptr).age=29;
(*ptr).height=5.11;
(*ptr).fullname="talhaakmalahmed";
display(ptr);
cout<<(*ptr).age;

Array of structures

In programming, an array is a collection of elements of same data type. Structure is a user defined
data type. So, we make the array of Structures, to store the multiple records, where each structure is
stored on the specific index in array. Each structure is accessed through array index.

Example

#include<iostream>
using namespace std;
#include<cstring>
struct human
{
int age;
string fullname;
float height;
};

int main()
{

human arr[2];
arr[0].age=27;
arr[0].height=5.8;
arr[0].fullname="shahidafridi";

arr[1].age=28;
arr[1].height=5.9;
arr[1].fullname="shoib malik";

cout<<endl;
cout<<endl;

cout<<arr[0].age<<endl;
cout<<arr[0].height<<endl;
cout<<arr[0].fullname<<endl;

cout<<arr[1].age<<endl;
cout<<arr[1].height<<endl;
cout<<arr[1].fullname<<endl;

LAB TASK 1

Define an array of structure as arr[2]. User Input the members of structure on every index of array
and display the input on screen. Hint(use for loop).
Returning structure from a function

#include<iostream>
using namespace std;
struct Person // defining and declaring structure
{
string Name;
int Age;
float CGPA;
};

Person Input(Person y); // return type in not int or float but structure.

Person Input(Person y)
{
cout<<"Enter name :"<<endl;
cin>>y.Name;
cout<<"Enter age :"<<endl;
cin>>y.Age;
cout<<"Enter CGPA :"<<endl;
cin>>y.CGPA;
return y; // instance is returned by function to main function
}

int main()
{
Person P1; // creating instance of structure Person
P1 = Input(P1);

cout<<"Name:"<<P1.Name<<endl;
cout<<"Age : "<<P1.Age<<endl;
cout<<"CGPA : "<<P1.CGPA;
return 0;
}

LAB TASK 2

Define a structure having three members, one integer, one float and third variable to save their sum.
Pass the instance of structure to a function where it adds the two numbers and return its sum in the
main function to display.
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester:3rd

Lab 10: Implementing C++ programs using


Classes

Learning Objectives

 Brief understanding of basics of classes.


 Familiarization with class members and class instances/objects.
 Introduction to the access modifiers in OOP.

CLASSES
The classes are the most important feature of C++ that leads to Object Oriented programming. Class
is a user defined data type, which holds its own data members and member functions, which can be
accessed and used by creating instance of that class.
A class is a collection of data and functions. The data items and functions are defined within the class.
The functions are written to work upon data items and each function has a unique relationship with the
data items of the class. An object is said to be an instance of a class.

Classes are defined to create user-defined data types. Defining a class specifies its data members and
relationship between the data items through its functions.

Classes are used for flexible programming. It is an easy way for designing and organizing the program.
They are used to represent the real world entities that not only have data type properties but also
associated operations or functions.

Basic understanding of the class concept. A class is a specification or blueprint for a number of objects.
Objects consist of both data and function that operate on that data.
A member function is a function that is a member of a class. Member functions have access to an
object’s private data, while non–member functions do not.
Some important Conventions and Points regarding classes

1. Class name must start with an uppercase letter(Although this is not mandatory). If class name
is made of more than one word, then first letter of each word must be in uppercase. Example,
class Study, class StudyTonight etc
2. Classes contain, data members and member functions, and the access of these data members
and variable depends on the access specifiers (discussed in next section).
3. Class's member functions can be defined inside the class definition or outside the class
definition.
4. Class in C++ are similar to structures in C, the only difference being, class defaults to private
access control, where as structure defaults to public.
5. All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation,
Abstraction etc.
6. Objects of class holds separate copies of data members. We can create as many objects of a
class as we need.
7. Classes do posses more characteristics, like we can create abstract classes, immutable classes,
all this we will study later.

Objects of Classes
Class is mere a blueprint or a template. No storage is assigned when we define a class. Objects are
instances of class, which holds the data variables declared in class and the member functions work
on these class objects.
Each object has different data variables. Objects are initialised using special class functions
called Constructors. We will study about constructors later.
And whenever the object is out of its scope, another special class member function
called Destructor is called, to release the memory reserved by the object. C++ doesn't have
Automatic Garbage Collector like in JAVA, in C++ Destructor performs this task.

Access modifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,
1. public
2. private
3. protected
These access modifiers are used to set boundaries for availability of members of class be it data
members or member functions
Access modifiers in the program, are followed by a colon. You can use either one, two or all 3
modifiers in the same class to set different boundaries for different class members. They change the
boundary for all the declarations that follow them.

class Abc
{
int x;
void display()
{
// some statement
}
};

int main()
{
Abc obj; // Object of class Abc created
}

Public Access Modifier in C++


Public, means all the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. Hence there
are chances that they might change them. So the key members must not be declared public.

class PublicAccess
{
// public access modifier
public:
int x; // Data Member Declaration
void display(); // Member Function decaration
}

Private Access Modifier in C++


Private keyword, means that no one can access the class members declared private, outside that
class. If someone tries to access the private members of a class, they will get a compile time error.
By default class variables and member functions are private.

class PrivateAccess
{
// private access modifier
private:
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Protected Access Modifier in C++
Protected, is the last access specifier, and it is similar to private, it makes class member inaccessible
outside the class. But they can be accessed by any subclass of that class. (If class A is inherited by
class B, then class B is subclass of class A. We will learn about inheritance later.)

class ProtectedAccess
{
// protected access modifier
protected:
int x; // Data Member Declaration
void display(); // Member Function decaration
}

DEFINING CLASS AND CREATING OBJECTS


When we define any class, we are not defining any data, we just define a structure or a blueprint, as
to what the object of that class type will contain and what operations can be performed on that object.
Below is the syntax of class definition,

class ClassName
{
Access specifier:
Data members;
Member Functions()
{
// member function defintion
}
};

Here is an example, we have made a simple class named Student with appropriate members,
class Student
{
public:
int rollno;
string name;
};
So its clear from the syntax and example, class definition starts with the keyword "class" followed by
the class name. Then inside the curly braces comes the class body, that is data members and
member functions, whose access is bounded by access specifier. A class definition ends with a
semicolon, or with a list of object declarations.

Creating Instances

class Student
{
public:
int rollno;
string name;
}A,B;

Here A and B are the objects of class Student, declared with the class definition. We can also declare
objects separately, like we declare variable of primitive data types. In this case the data type is the
class name, and variable is the object.

int main()
{
// creating object of class Student
Student A;
Student B;
}

Accessing Public Data Members


Following is an example to show you how to initialize and use the public data members using the dot
(.) operator and the respective object of class.
class Student
{
public:
int rollno;
string name;
};

int main()
{
Student A;
Student B;
// setting values for A object
A.rollno=1;
A.name="Adam";

// setting values for B object


B.rollno=2;
B.name="Bella";

cout <<"Name and Roll no of A is: "<< A.name << "-" << A.rollno;
cout <<"Name and Roll no of B is: "<< B.name << "-" << B.rollno;
}

Member functions are the functions, which have their declaration inside the class definition and
works on the data members of the class. The definition of member functions can be inside or outside
the definition of class.
If the member function is defined inside the class definition it can be defined directly, but if its defined
outside the class, then we have to use the scope resolution :: operator along with class name
along with function name.
For example:
class Cube
{
public:
int side;
/*
Declaring function getVolume
with no argument and return type int.
*/
int getVolume();
};
If we define the function inside class then we don't not need to declare it first, we can directly define
the function.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};

Accessing Private Data Members


To access, use and initialize the private data member you need to create getter and setter functions,
to get and set the value of the data member.
The setter function will set the value passed as argument to the private data member, and the getter
function will return the value of the private data member to be used. Both getter and setter function
must be defined public.

Example :

class Student
{
private: // private data member
int rollno;

public:
// public function to get value of rollno - getter
int getRollno()
{
return rollno;
}
// public function to set value for rollno - setter
void setRollno(int i)
{
rollno=i;
}
};

int main()
{
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}

Calling Class Member Function in C++

Similar to accessing a data member in the class, we can also access the public member functions
through the class object using the dot operator (.).
Below we have a simple code example, where we are creating an object of the class Cube and
calling the member function getVolume():

int main()
{
Cube C1;
C1.side = 4; // setting side value
cout<< "Volume of cube C1 = "<< C1.getVolume();
}

LAB TASK 1
Write a program that use two classes. Calculate the factorial of a given number by using one class and
calculate the sum of three numbers by using the second class. Both the classes should have their
constructor functions.

LAB TASK 2
Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units by
creating a class named 'Triangle' with a function to print the area and perimeter.

OBSERVATIONS & DISCUSSION


National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester:3rd

Lab 11: Improving C++ programs with the help


of Encapsulation, Inheritance and
Polymorphism
Learning Objectives
 Understanding the concept of Inheritance and Multilevel Inheritance.
 Understanding how a constructor works in class Inheritance.
 Familiarization with Encapsulation and Polymorphism.

Understanding Inheritance
n C++, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:

 derived class (child) - the class that inherits from another class
 base class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

Simple class

#include<iostream>
#include<string>
using namespace std;

class inheritance
{
public:
string first;
string second;
int any;

};
int main()
{
inheritance obj1;

Simple Constructor in a class

#include<iostream>
#include<string>
using namespace std;

class Inheritance
{
public:
string first;
string second;
int any;
};
Inheritance()
{
}

int main()
{
inheritance obj1;

The constructor in a class is called automatically every time an instance of a class is created. Constructor can also be user
defined and may take arguments, depending upon the code.

Assigning values to class members using class object.

#include<iostream>
#include<string>
using namespace std;

class Inheritance
{
public:
string first;
string second;
int any;

};
int main()
{
Inheritance obj1;

obj1.first="Amjid";
cout<<obj1.first;

Objects are created to access the members of a class. Like in the example below an instance obj1 is created and is used
to access public members of class Inheritance.

Default Constructor’s Behavior when an instance is created

#include<iostream>
#include<string>
using namespace std;

class Inheritance
{
public:
string first;
string second;
int any;
Inheritance()
{
first="Amjid"
}

};
int main()
{
Inheritance obj1;

cout<<obj1.first;

}
Simple Function Inside a Class

#include<iostream>
#include<string>
using namespace std;
class Inheritance
{
public:
string first;
string second;
int any;
Inheritance()
{
func();
}

void func()
{
cout<<"This is a simple function inside class";
}
};
int main()
{
Inheritance obj1;
obj1.func();
}
}

Assigning values to Class Members by passing values and argument to constructor function

#include<iostream>
#include<string>
using namespace std;

class Inheritance
{
public:
string first;
string second;
int any;
Inheritance(string a, string b, int c)
{
first=a;
second=b;
any=c;
}

};
int main()
{
Inheritance obj1("Amjid","ali",7);
cout<<obj1.first<<endl;
cout<<obj1.second<<endl;
cout<<obj1.any<<endl;

Sub Class of Main/Base Class


#include<iostream>
#include<string>
using namespace std;
class Inheritance
{
public:
string first;
string second;
int any;
Inheritance(string a, string b, int c)
{
first=a;
second=b;
any=c;
}
};
class daughter: public Inheritance
{
public:
void func()
{
cout<<first<<endl;
cout<<second<<endl;
cout<<any<<endl;
}

int main()
{
Inheritance obj1("Amjid","ali",7);

cout<<obj1.first<<endl;
cout<<obj1.second<<endl;
cout<<obj1.any<<endl;

}
Assigning Values to Members of both Class using Constructors
#include<iostream>
#include<string>
using namespace std;
class Inheritance
{
public:
string first;
string second;
int any;
Inheritance(string a, string b, int c)
{
first=a;
second=b;
any=c;
}
};

class daughter: public Inheritance


{
public:
string middle;
void func()
{
cout<<first<<endl;
cout<<second<<endl;
cout<<any<<endl;
cout<<middle;
}
daughter(string x,string a, string b,int c ):Inheritance(a,b,c)
{
middle=x;
}
};
int main()
{
Inheritance obj1("Amjid","ali",7);

daughter obj2("khan","Amjid","ali",7);

obj2.func();
Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.

Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those
methods to perform different tasks. This allows us to perform a single action in different ways.

#include<iostream>
#include<string>
using namespace std;
class Inheritance
{
public:
string first;
string second;
int any;
Inheritance(string a, string b,int c )
{
first=a;
second=b;
any=c;
}
void display()
{
cout<<"display inheritance";
}
void func()
{
cout<<second<<endl;
cout<<second<<endl;
cout<<any<<endl;
}
};
class daughter: public Inheritance
{
public:
string middle;
void func()
{
cout<<first<<endl;
cout<<second<<endl;
cout<<any<<endl;
cout<<middle;
}

daughter(string x, string a, string b,int c ):inheritance(a,b,c)


{
middle;x;
}
};
int main()
{
inheritance obj1("Amjid","ali",7);
daughter obj2("Amjid","ali",7);

obj1.display();
obj2.func();
obj1.func();

Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must declare class variables/attributes as private (cannot be accessed from outside
the class). If you want others to read or modify the value of a private member, you can provide
public get and set methods.

#include<iostream>
#include<string>
using namespace std;

class inheritance
{
private:
string first;
string second;
int any;

public:
void set_private(string a)
{
first=a;
}

string get_private()
{
return first;
}
};

int main()
{

inheritance obj1;
obj1.set_private("rizwan");
cout<<obj1.get_private();

}
Multiple Inheritance
A class can also be derived from more than one base class, using a comma-separated list:

#include<iostream>
#include<string>
using namespace std;

class MyClass
{
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
class MyOtherClass {
public:
void myOtherFunction() {
cout << "Some content in another class." ;
}
};

class MyChildClass: public MyClass, public MyOtherClass { // Derived class

};

int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 12: Open Ended Lab II


Problem Statement
Consider the given specification which will perform the following operations.
1. Allows the user to enter the names (First and Last Name) of five candidates in an interview and the
numbers of votes received by each candidate for a job. There are total of 10 selectors in which majority
vote would determine the selected employee.
2. The program should output each candidate’s name, the number of votes received, and the percentage of
the total votes received by the candidate. Program should also output the name of selected employee.
3. Use Class and user defined constructor function to assign the values to members of class.
4. The salary of selected candidate should be kept private and printed out using setter and getter functions.
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 13: Imitating programs to understand File


handling and Templates
Learning Objectives
 Familiarization with the generic properties of Templates.
 Understanding the concept of Function Templates and Class Templates
 Familiarization with the Opening, reading and writing to a file in c++.

Templates in C++
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a
parameter so that we don’t need to write the same code for different data types. For example, a
software company may need sort() for different data types. Rather than writing and maintaining the
multiple codes, we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword
can always be replaced by keyword ‘class’.
How templates work?
Templates are expanded at compiler time. This is like macros. The difference is, compiler does type
checking before template expansion. The idea is simple, source code contains only function/class,
but compiled code may contain multiple copies of same function/class.

Function template works in a similar way as normal function, with slight difference. A single normal
function can only work with one set of data types, on the other hand a single function template can
work with different data types at once. In-case we need to perform identical operations on two or
more types of data, we use function overloading to create two functions with the required function
declaration.
Syntax
template <class T> or
template <typename T>

template <typename X>


X Function(X parameters)
{


}
Example
#include <iostream>
using namespace std;

// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}

int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char

return 0;
}

Class templates
We also have the possibility to write class templates, so that a class can have members that
use template parameters as types. Like function templates, we can also create class
templates for generic class operations. Normally, you would need to create a different class
for each data type or create different member variables and functions within a single class.

Syntax
template <class T>
template <typename T>

class Class_Name
{
public:
T var;
T method(T arg);
};

Example
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};

The class that we have just defined serves to store two elements of any valid type. For example, if we
wanted to declare an object of this class to store two integer values of type int with the values 115
and 36 we would write:

mypair<int> myobject (115, 36);


this same class would also be used to create an object to store any other type:
mypair<double> myfloats (3.0, 2.18);

The only member function in the previous class template has been defined inline within the class
declaration itself. In case that we define a function member outside the declaration of the class
template, we must always precede that definition with the template <...> prefix:
Example
template<Class T>
class Calculator
{
private: T a,b;
public:
Calculator(T x,T y)
{ a = x;
b = y;
}
T Add() { return a+b; }
T Sub () { return a-b; }
T Mul() { return a*b; }
T Div() { return a/b; }
};
int main()
{
Calculator<int> A(10,20);
Calculator<float> B(2.1,2.5);
cout<<A.Add();
Cout<<B.Add();
return 0;
}

Lab Task 1
Write a program to create a function template which calculates addition and subtraction between
 Two integers
 Two float values
 An integer and float value.

Lab Task 2
Write a program to create a class template to find greatest number between
 Three integers
 Three float values.
Files In C++
Files are named locations on disk to store related information. They are used to permanently store
data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile
(which loses its data when the computer is turned off), we use files for future use of the data by
permanently storing them.

In C++, a file is categorized as either text or binary.Text files are structured as a sequence of lines
much like a string can be thought of as a sequence of characters.Each line is terminated with a
special character, called the EOL or End of Line character.

The fstream library allows us to work with files. To use the fstream library, include both the
standard <iostream> and the <fstream> header file:

Example
#include <iostream>
#include <fstream>

There are three classes included in the fstream library, which are used to create, write or read files

Class Description

ofstream Creates and writes to file

ifsteam Reads from files

fstream A combination of ofstream and ifstream: creates, reads, and


writes to files

Opening a File
Before performing any operation on a file, you must first open it. If you need to write to the file, open it
using fstream or ofstream objects. If you only need to read from the file, open it using the ifstream
object.
The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in them.
The function takes this syntax:
open (file_name, mode);
 The file_name parameter denotes the name of the file to open.
 The mode parameter is optional. It can take any of the following values:
Value Description
ios:: app The Append mode. The output sent to the file is appended to it.
ios::ate It opens the file for the output then moves the read and write control to file's end.
ios::in It opens the file for a read.
ios::out It opens the file for a write.
ios::trunk If a file exists, the file elements should be truncated prior to its opening.

Create and Write To a File


To create a file, use either the ofstream or fstream class, and specify the name of the file.To write to the file,
use the insertion operator (<<).

Example
#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Create and open a text file
ofstream MyFile("filename.txt");

// Write to the file


MyFile << "Files can be tricky, but it is fun enough!";

// Close the file


MyFile.close();
}

Why do we close the file?


It is considered good practice, and it can clean up unnecessary memory space.

Read a File
To read from a file, use either the ifstream or fstream class, and the name of the file. Note that we
also use a while loop together with the getline() function (which belongs to the ifstream class) to read
the file line by line, and to print the content of the file:
Example

// Create a text string, which is used to output the text file


string myText;

// Read from the text file


ifstream MyReadFile("filename.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
// Output the text from the file
cout << myText;
}

// Close the file


MyReadFile.close();
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 14: Practicing Python Basics


Learning Objectives
 Understanding the syntax of python language
 Familiarization with different Variable types and data types in python.
 Familiarization with Conditional statements and repetitive structures in python.

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It


was created by Guido van Rossum during 1985- 1990. Python is a cross-platform programming language,
meaning, it runs on multiple platforms like Windows, MacOS, and Linux. Python is an interpreter language,
means it executes the code line by line. Python provides a Python Shell (also known as Python Interactive Shell)
which is used to execute a single Python command and get the result. Python Shell waits for the input command
from the user. As soon as the user enters the command, it executes it and displays the result.
It is free and open source. Following are important characteristics of python −
 It supports functional and structured programming methods as well as OOP.

 It can be used as a scripting language or can be compiled to byte-code for building large applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Variables:
During programming we need to store data. This data is stored in variables. Variables are locations in memory
for storing data. The memory is divided into blocks and there is a numerical address for each location of a
memory block. It is difficult for us to handle these numerical addresses in our programs. So we give a name to
these locations and these names are variables. In a programming language, variable has the following attributes.

 Name

 Type

 Size

 Value

Variable Selection Rule:


 Names can contain numbers and letters.
• Names cannot contain spaces.
• The underscore character _ is legal (e.g., my_count)
• The first character has to be a letter.
• Upper and lower case letters are different (e.g., Apples is not the same as apples).
• Words that are part of the Python language cannot be used.
Practice Task1: Simple pay calculator

Practice Task2: Program to Swap two numbers

Python Data Types:


Data types are the classification or categorization of data items. Data types represent a kind of value which
determines what operations can be performed on that data. Numeric, non-numeric and Boolean (true/false)
data are the most used data types. Python has the following standard or built-in data types:
Numeric:
A numeric value is any representation of data which has a numeric value. Python identifies three types of
numbers:
 Integer: Positive or negative whole numbers (without a fractional part)

 Float: Any real number with a floating point representation in which a fractional component is denoted
by a decimal symbol or scientific notation
 Complex number: A number with a real and imaginary component represented as x+yj. x and y are
floats and j is -1(square root of -1 called an imaginary number)

Sequence Type:
A sequence is an ordered collection of similar or different data types. Python has the following built-in
sequence data types:
 String: A string value is a collection of one or more characters put in single, double or triple quotes.

 List: A list object is an ordered collection of one or more data items, not necessarily of the same type,
put in square brackets.
 Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of the same
type, put in parentheses.

Dictionary:
A dictionary object is an unordered collection of data in a key:value pair form. A collection of such pairs is
enclosed in curly brackets. For example: {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}
Python has an in-built function type() to ascertain the data type of a certain value. Try and verify the data type
of different values in Python shell, as shown below.
Practice Task#3:

To get the input from the user, use the input command.
Practice Task#4:
Type Casting:
Convert one data type to another data type is called typecasting. Some situation, when you want to convert the
data type. For example, you want to add two number in which one existing value of a variable is an integer and
the second is a string. Then you need to use Python typecasting to convert string data type in integer before
adding.
There are some functions which used for Python type casting:
 int(): is used to specify integer literal. Â Construct an integer number from a string literal and Float.
 str(): is used to specify the string literal. Construct a string type from integer literal OR float literal.
 float(): is used to specify the float data types. Construct float literal from integer and string literal.

Practice Task # 5: How to add two number in which one variable has the string value and second has
integer?

Lab Task:
Write a python program in which ask user to enter two values and use the type conversion function to
convert these values in to int, float and string type.

Python Operators:
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

Assignment operators:
Assignment operators are used to assign values to variables:

Practice Task # 2: Assignment operators in Python


Comparison operators:

Comparison operators are used to compare values. It either returns True or False according to the condition.

Practice Task #3: Comparison operators in Python

Logical Operators:
Logical operators are used to combine conditional statements

Conditional Statements
Conditional statements allow user to make decision, based upon the result of a condition. These statements are
called decision-making statements or conditional statements. Python uses if keyword to implement decision
control. Python's syntax for executing a block conditionally is as below:
IF statement:
IF statement is used to execute the some lines of code, if a test condition is true otherwise if condition is
false, execute nothing.

The program evaluates the test expression and will execute statement(s) only if the text expression is True. If
the text expression is False, the statement(s) is not executed.

Practice Task #1

Output

IF-ELSE statement:
Along with if statement, the else condition can be optionally used to define an alternate block of statements to
be executed if the Boolean expression in if condition is not true.

Practice Task #2:


The output of the above program will be a print message “Positive or Zero”

Practice Task#3:

Nested IF statement:
A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement
inside another if statement.

Practice Task#4:

Output:

Practice Task#5:
Output:

EL-IF statement:
The el-if statement allows you to check multiple expressions for TRUE and execute a block of code as soon as
one of the conditions evaluates to TRUE.

Practice Task#6

Lab Task 1
Write down the Python program, in which ask user to enter the age of three people and find the
younger among them all.

Repetitive Structures
There are situations, when a block of code needs to be executed several number of times. In general, statements
are executed sequentially. The first statement is executed first, followed by second and so on. A loop statement
allows us to execute a statement or group of statements multiple times. Given below is the general form of a
loop statement in most of the programming languages.

WHILE LOOP:
Python uses the “while and for” keywords to constitute a conditional loop, by which repeated execution of a
block of statements is done until a Boolean expression is true. Here, you will learn about the while loop. The
following is the while loop syntax.
Python keyword while has a conditional expression followed by the “ : ” symbol to start a block with increased
indent. This block has statements to be executed repeatedly. Such a block is usually referred to as the body of
the loop. The body will keep executing till the condition remains true. If and when it turns out to be false, the
program will come out of the loop.
Practice Task#1

Output:

Practice Task#2:

Output:

Practice Task#3:
Output:

Infinite Loop:
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while
loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that
never ends. Such a loop is called an infinite loop.

Practice Task#4:

Output:

Nested While Loop


The syntax for a nested while loop statement in Python programming language is as follows:

For Loop
The while loops we have used so far are highly stylized. Each iterates over a sequence of integers. Python
provides a language mechanism, for loop, that can be used to simplify programs containing this kind of iteration.
Python's for keyword provides a more comprehensive mechanism to constitute a loop. The body of for loop is
executed for each member element in the sequence. Hence, it doesn't require explicit verification of Boolean
expression controlling the loop (as in the while loop).

To start with, variable x in for statement refers to the item at the 0 index in the sequence. The block of
statements with increased uniform indent after “ : “ symbol will be executed. Variable x now refers to the next
item and repeats the body of the loop till the sequence is exhausted.
Practice Task#5:
Output:

Nested for Loop:


If a loop (for loop or while loop) contains another loop in its body block, we say that the two loops are nested. If
the outer loop is designed to perform m iterations and the inner loop is designed to perform n repetitions, the
body block of the inner loop will get executed m X n times.

Practice Task#6:

Output:
Practice Task#7:

Output:

Practice Task#8:

Output:

Lab Task 2
Take 10 integers from keyboard using loop and print their average value on the screen.
Lab Task 3
Print multiplication table of 10, 50 and 100 using loop.
Lab Task 4
Print all elements of a list using for loop.
Lab Task 5
Use nested for loop to create the following patterns.

#####
####
###
National University of Technology
Electrical Engineering Department

EE-1004: Computer Programing Semester: 3rd

Lab 15: Project


Group wise project simulation in C++ syntax, project presentations and report submission.

You might also like