Lab Session 06: Objective
Lab Session 06: Objective
Lab Session 06
Objective:
To get familiar with the Algorithms and Flowchart
Introduction
Computational thinking involves applying a set of problem solving skills and techniques that
are used by computer programmers to write programs. Computational thinking is not thinking
about computers or even thinking like a computer. Computer scientists use logical reasoning
to work out exactly what a program or computer will do. Computational thinking involves
thinking about a problem in a logical way, and enabling a computer to solve it. Two
important techniques used in computational thinking are:
1. Decomposition: This is breaking any given task or problem into simple logical steps
or parts.
2. Abstraction: This is the process of taking away or removing characteristics from
something in order to reduce it to something simpler to understand. In computer
science, abstraction is often used for managing the complexity of computer systems.
There will often be more than one solution to the same problem, but you always need to
create ordered steps to achieve any of these solutions. We know there can often be many
answers to the same problem, but we need to determine what makes the best solution and it
would lead to the best algorithm. The first sets of criteria we need to consider are:
We could have lots of solutions to our problem and each can satisfies these two criteria.
Therefore, the next step is to determine which of our solutions is ‘best’. There are generally
two criteria used to determine whether one computer algorithm is ‘better’ than another. These
are:
the space requirements (i.e. how much memory is needed to complete the task)
the time requirements (i.e. how much time will it take to complete the task).
Algorithm:
Algorithms are at the very heart of computer science. An algorithm is simply a set of steps
that defines how a task is performed. For example, there are algorithms for cooking (called
recipes), for finding your way through a strange city (directions), and for operating washing
machines (manuals) even for playing music (sheet music). An algorithm must be clear, finite
and effective. The simplest form of algorithm is step-form algorithm (like a to-do list).
1
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
An algorithm has input data, and is expected to produce output data after carrying out a
process which is the actions taken to achieve the required outcome. You need to understand
this input–process–output model.
Storage
Feedback
In solving any problem, first you define the problem, then you define what the solution
must be, and finally you work on the transformation (process) to achieve the desired solution.
FEEDBACK occurs when outputs of a system are fed back as inputs that form a circuit
or loop. Programmers even plan out their code using these headings.
Algorithm development involves the following steps to carry out. We can proceed to
correct solution of a particular problem by adopting the following strategy.
Step 1: Investigation
2
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Sequences:
To solve a problem there must be a sequence. A sequential algorithm is an algorithm that is
executed sequentially, one step at a time from start to finish. It does this without any other
processes executing. Most standard computer algorithms are sequential.
Example: Say we want to input two numbers add them together and show the answer on
the screen.
Start
Input first number. # input stage
Input second number # input stage
Add first and second number together and
# process stage
Store as total
Output total # output stage
End
For your programming to work correctly all the commands have to be there and they need to
be in the correct sequence. Sequencing is extremely important in programming.
3
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Example: We want to make a cup of tea using tea bags and a kettle.
First Refinement
These steps are probably not detailed enough to make tea. We therefore refine each
step into a sequence of further simpler steps:
It might be refine to
It might be refine to
It might be refined to
4
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Second Refinement
Some of the refined steps may be further refined. For example Step 2 can be refine as
It might be refined to
Exercise 1: Write a algorithm to find the sum and average of three numbers
5
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Flow Chart
Flow chart is the pictorial representation of an algorithm. It is a way of visually
presenting the flow of data, the operations performed within the system and the sequence in
which they are performed. The flowchart is similar to the layout plan of a building. As we
know a designer draws a layout plan before starting construction on a building. Similarly, a
programmer prefers to draw a flowchart prior to writing a computer program. As in the case
of drawing of a layout plan, the flowchart is drawn according to defined rules.
Symbols of Flowchart
Flowcharts are usually drawn using some standard symbol however other special
symbols can also be developed when required. The standard symbols which are frequently
used in flowcharting are shown below
Symbols Purpose
Start / End of a
flowchart
Processing
Input / Output
Decision
Making
Connector
Off-page / On-
page connector
Flow Lines
Pre-defined
Process
Preparation
Remarks
6
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
f. Only one flow line is used in conjunction with terminal symbol. Ensure the flowchart
has a logical start and end
g. Write comments within Remarks symbol. We can use the remarks annotation) symbol
to describe steps more clearly.
h. If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. The intersection of flow lines should be avoided to make it
more effective and clear
i. It is useful to test the validity of the flowchart by passing through it with a simple test
data.
Example: Draw the flowchart to add two numbers. Example: Draw the Flowchart to check entered number is Even or
Start Start
Number A Number B
Take N
Sum = A + B Sum
Display N is even
End
Odd Even
End
Exercise 3: Draw a flowchart to check either the student is passed or fail by entering
the percentage of the student. (Passing percentage is 50%)
7
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Advantages
Exercise 4:ofDraw
Flowcharts
a flowchart to evaluate algebraic expression (ax+b)/(ax-b).
(i) It is a convenient method of communication.
(ii) With the help of a flowchart, the logic of an algorithm can be described more
effectively.
(iii) As flowcharts are part of the design document, hence maintenance of
operational programs becomes easy.
(iv) The flowcharts act as a guide for the program development. Therefore, they help the
programmer to put efforts more efficiently on the underlying problem.
(v) The flowchart helps in debugging process.
(vi) Flowcharts are one of the good way of documenting programs.
Limitations of Flowcharts
8
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Basic Control Structure of Flowchart:
1. Sequence:
Statement A
Statement B
2. Selection
Condition
Statement C
F T
Statement(s) Statement(s)
Condition
F
T
Statement(s)
3. Repetition
Condition P?
F
T
Statement(s)
9
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Example: Draw the flowchart to find the largest among three different numbers entered by user.
Example: Draw the flow chart to find the factorial of a given integer using non-recursive function.
10
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Exercise 5: Check whether given number is Armstrong Number or Not. Write Algorithm
for it and Draw Flowchart to represent the process.
11
Programming Fundamentals Faculty of Engineering
Department of Civil Engineering Lahore Leads University
Open Ended Lab Tasks:
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Lab Session 07
Objective:
To understand the programming basic structure and debugging concepts.
Introduction
The format of writing program in C++ is called its structure. The basic structure of C++
program is very flexible. It increases the power of language. It consists of the following parts:
• Preprocessor directive
• Main function
• Program body
Preprocessor Directive:
Preprocessor directive is an instruction given to the compiler before the execution of actual
program. Preprocessor directive is also known as compiler directive. It is part of C++
compiler. The preprocessor directives start with hash symbol #. These directives are written
at the start of program. The preprocessor directive is used in C++ to include header files in
the program.
Include preprocessor directive is used to include header files in the program. The syntax of
using this directive is as follow:
#include<iostream>
The above statement tells the compiler to include the file iostream in the source program
before compiling it.
Header Files:
Header files are collection of standard library functions to perform different tasks. There are
many header file for different purpose. Each header files contain different types of predefined
functions. Many header files can be included in one program. The header file must be
included in the program before calling any of its functions in the program. The name of
header file is written in angle brackets or double quotes.
Syntax: #include<header_file_name> #include”header_file_name”
Example: #include<iostream> #include”math.h”
The word “iostream” stands for input/output stream. This header file contain the definitions
of built-in input and output functions. A header file math.h is used in programs to use
predefined mathematical functions.
Namespace:
All the elements of the standard C++ library are declared within what is called a namespace,
the namespace with the name std. So in order to access its functionality we declare with this
expression that we will be using these entities. This line is very frequent in C++ programs
that use the standard library.
Syntax: using namespace std;
1
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Main Function:
The main function is the point by where all C++ programs start their execution,
independently of its location within the source code. It is essential that all C++ programs
have a main function. If a program does not contain main function, it can be compiled but
cannot be executed. The body of the main function enclosed in braces { }. What is contained
within these braces is what the function does when it is executed.
Syntax: int main ( )
{
body of main function
}
The curly brace { is called opening brace and } is called closing brace. These braces are
also known as delimiters.
Program Body:
Program body consists of C++ statements. The statements of the program are written in curly
braces. Each statement in C++ language is terminated by semicolon. A statement in C++ is an
instruction for the computer to perform a task. Computer perform these instructions one by
one in same sequence in which these instructions are written. The following example explains
the basic structure of C++ program.
cout<<“Hello World”;
This statement performs the only action that generates a visible effect in our program. cout
represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen).
The cout is used with the insertion operator (<<). Anything written after the insertion
operator is displayed on the screen. Notice that the statement ends with a semicolon character
(;). This character is used to mark the end of the statement and in fact it must be included at
the end of all expression statements in all C++ programs (one of the most common syntax
errors is indeed to forget to include some semicolon after a statement).
Comments:
Program comments are explanatory statements that you can include in the C++ code. These
comments help anyone reading the source code.
1
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Hello World!
You can also do mathematical operations using cout statements like above. You can also do
all the mathematical operation using single cout statement like this:
cout<<10/10<<endl<<10*10<<endl<<10+10<<endl<<10-10<<endl;
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Exercise 1:
Output of program:
Exercise 2:
Hello, Ahmad! on Saturday, you need to study 4.5 hours for the
exam.
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Escape Sequences
Escape Sequence causes the program to escape from the normal interpretation of a string, so
that the next character is recognized as having a special meaning. The back slash “\”
character is called the Escape Character”. The escape sequence includes the following:
\a => alarm, beep
\b => back space
\n => new line
\r => carriage return
\t => tab
\\ => back slash
\“ => double quotations
\‘ => single quotations
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Exercise 3:
Write a program that display following Output:
Output
***
* *
* *
* *
* *
*
*** *
Output
1 2 345 6
2 3 45 6
3 4 56
4 5 6
5 6
6
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Some important Definitions:
Exercise 1:
Write a program that display following output:
CCCCCCCCC CC ++ ++
CC CC CC ++ ++
CCCCCCCCC++++++++++++++++ ++++++++++++++++
++++++++++++++++ ++++++++++++++++
++ ++
++ ++
Exercise 2:
Write a program that computers the table of 5 and display it.
5x1=5
5x2=
.
.
.
.
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Lab Session 08
Objective:
To understand variables, data types and operators in programming.
Introduction
A computer acts on some data according to the instructions specified in a program and
produces the output. Memory of a computer is the area where data and programs are stored.
A computer memory is made up of registers and cells which are capable of holding
information in the form of binary digits 0 and 1 (bits). Data is stored in the memory at
physical memory locations. These locations are known as the memory address. It is very
difficult for humans to remember the memory addresses in numbers like 46735, so instead we
name a memory address by a variable.
“A variable is a named memory location that stores a value. It stores program’s data and its
computational results during execution. The value of a variable may change during the
execution of program. However, the name of variable cannot be changed.
In the above examples, int, float, char and double are keywords that indicate data types and
words marks, average, grade and salary are variable names.
Many variables of same data type can also be declared in single line. In this case, each
variable is separated by comma as follows:
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Data Types
Every variable in C++ can store a value. However, the type of value which the variable can
store has to be specified by the programmer. C++ supports the following inbuilt data types:
int (to store integer values), float (to store decimal values) and char (to store characters),
bool (to store Boolean value either 0 or 1) and etc.
A. Integer:
Integer (int) variables are used to store integer values like 34, 68704 etc. To declare a
variable of type integer, type keyword int followed by the name of the variable. You can give
any name to a variable but there are certain constraints, they are specified in Identifiers
section. For example, the statement
int sum; declares that sum is a variable of type int. You can assign a value to it now or later.
In order to assign values along with declaration use the assignment operator (=).
int sum = 25;
Assigns value 25 to variable sum. There are three types of integer variables in C++, short, int
and long int. All of them store values of type integer but the size of values they can store
increases from short to long int. This is because of the size occupied by them in memory of
the computer. The size which they can take is dependent on type of computer and varies.
More is the size, more the value they can hold. For example, int variable has 2 or 4 bytes
reserved in memory so it can hold 232= 65536 values. Variables can be signed or unsigned
depending they store only positive values or both positive and negative values. And short,
variable has 2 bytes. Long int variable has 4 bytes.
B. Float:
To store decimal values, you use float data type. Floating point data types comes in
three sizes, namely float, double and long double. The difference is in the length of value and
amount of precision which they can take and it increases from float to long double. For
example, statement
float average = 2.34;
Declares a variable average which is of type float and has the initial value 2.34
There are three types of integer variables in C++, float, double and long double. All of them
store values of type integer but the size of values they can store increases from float to long
double. This is because of the size occupied by them in memory of the computer. The size
which they can take is dependent on type of computer and varies. More is the size, more the
value they can hold.
C. Character:
A variable of type char stores one character. It size of a variable of type char is typically 1
byte. The statement
char name = 'c';
Declares a variable of type char (can hold characters) and has the initial values as character c.
Note that value has to be under single quotes.
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
D. Boolean:
A variable of type bool can store either value true or false and is mostly used in
comparisons and logical operations. When converted to integer, true is any non-zero value
and false corresponds to zero.
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Rules of declaring a Variable:
The variable name must be meaningful and readable. It helps the user to understand the
purpose of the variable. For example, a variable to store the marks of student should be
Marks. If a variable consists of multiple words, first letter of each word should be capitalized
to increase readability. A variable MyPhoneNo is more readable than myphoneno.
Example: sub1 _test full_name Integer
Exercise 1:
Indicate whether each of the following is a valid or invalid name for an identifier / variable
name. If invalid, explain why the name can't be used.
Average
thisIsALongName
howLongIsTooLong?
3rd
float
lengthInSqFt
cin
Short
1Floar
street_number
average-score
_ADDRESS
Ali Ahmad
$cost
My.School
Constant:
Constant is a quantity that cannot be changed during program execution. In C++, you can use
a named constant to instruct a program to mark those memory locations in which data is
fixed.
Named Constants: A memory location whose content is not allowed to change during
program execution.
Syntax: const dataType identifier = value;
12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Example: const float CONVERSION = 2.54;
const char blank = ‘ ’;
const double PI = 3.14159265;
In C++, const is a reserve word for constants. The constant is declared by specifying its data
type and name. The constant must be initialized with some value.
Exercise 2:
For each of the identifiers below, select a meaningful identifier name that adheres to the
naming conventions described above.
a. A variable that could contain a test score.
c. A memory location that could be used to keep the initial letter of your name.
e. Declare the variable QUARTER to be a constant which contains the value 25 and the
variable age and weight to be integer variables and the variable length to be a float variable.
Now that we have created some variables, we would like to store values in them. We do that
with an assignment statement.
Exercise 3:
Write valid C++ assignment statements for the following mathematical expressions:
a) A = 0.5 b h
b) E = J(J + 1)h
c) Place the sum of the values in t1, t2, and t3 into the variable sum.
13
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Declaration of Variable of Data Type (Integer)
#include <iostream>
using namespace
std; int main()
{ int length;
length = 7; \\Assigning a Fixed Value to Variable
cout<<"The Length is: ";
cout<<length;
cout<<"\n\n";
}
What is the difference of float data type from integer data type?
#include <iostream>
using namespace
std; int main()
{ int a, b, c;
float d, e, f;
a=d=10;
b=e=3;
c=a/b;
f=a/b;
cout<<"Answer is (int): ";
cout<<c;
cout<<"\n\n";
cout<<"Answer is (float): "<<f; cout<<"\n\
n";
}
The output of integers this program is 3, but actually 10/3 = 3.33333, but whenever fraction
comes the int variable always takes the lower value like 10/6=1.66667 but the int variable
will not convert it to 2 it will take the lower value i.e. 1 and excludes the fraction. In float
variables actual answer with fractional part is saved.
13
Programming Fundamentals Faculty of
Department of Civil Engineering Lahore
Exercise 4:
Find errors in the following statements and correct them.
const int n;
char c = “ABC”;
float a b c;
const double = 123.45678;
int = 35;
long, population = 1234567;
float aver = 45.43.
char grade = B;
Exercise 5:
// This program will output the circumference and area of the circle with a given radius.
// PLACE YOUR NAME HERE
#include <iostream>
using namespace std;
const double PI = 3.14;
const double RADIUS = 5.4;
int main()
{
area // definition of area of circle
float circumference; // definition of
circumference circumference = 2 * PI * RADIUS; // computes
circumference area = ; // computes area
/* Fill in the code for the cout statement that will
output (with description) */
// the circumference
/* Fill in the code for the cout statement that will
output (with description) */
// the area of the circle
return 0;
}
Operators
An operator is a symbol that tells the compiler to perform a specific mathematical or logical
manipulation. C++ has four general classes of operators: arithmetic, bitwise, relational, and
logical.
C++ also has several additional operators that handle certain special situations.
1. Arithmetic
C++ defines the following arithmetic operators:
Operator Meaning
+ Addition
- Subtraction (also Unary minus)
* Multiplication
13
Programming Fundamentals Faculty of
Department of Civil Engineering Lahore
/ Division
% Modulus
++ Increment
-- Decrement
The operators +, –, *, and / all work the same way in C++ as they do in algebra. These can be
applied to any built-in numeric data type. They can also be applied to values of type char.
The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
Therefore,
Highest ++ , - -
- (unary minus)
*/%
Lowest + -
Relational refers to the relationships that values can have with one another, and
logical refers to the ways in which true and false values can be connected together. Since the
relational operators produce true or false results, they often work with the logical operators.
In C++, not equal to is represented by != and equal to is represented by the double equal sign,
= =.
Relational Operators
Operator Meaning
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to
== Equal to
!= Not equal to
Logical Operators
Operator Meaning
&& AND
|| OR
! NOT
13
Programming Fundamentals Faculty of
Department of Civil Engineering Lahore
The following table shows the relative precedence of the relational and logical operators.
Highest !
> >= < <=
= = !=
&&
Lowest | |
Exercise 6:
For the following questions assume the following declarations:
int i = 1, j = 2, k = 3; float x = 1, y = 2, z = 3;
Exercise 7:
Which of the following in valid or invalid assignment expression:
x = 30;
a = 9 = 3;
10 = x;
x = y = 12;
x %=5;
x = 6\4;
13
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Exercise 8:
Consider the following code and answer the questions:
int a = 3, b = 4;
++a *= b++;
cout << a << endl;
Built in Functions:
The type of functions that is available as a part of language is known as build–in function or
library function. These functions are ready–made programs. These functions are stored in
different header files. Build–in functions make programming faster and easier. These can be
accessed in programs by including the header files in which these functions are defined.
Math Functions
The header file math.h contains the build–in function that are used to perform arithmetic
calculations. Some important function defined are as follow:
Absolute: cout<<abs (-8)<<”\n”; means that it will give modulus of value given i.e. +ive
value
Exponent: cout<<exp (6)<<”\n”;
Power: cout<<pow (2, 9)<<"\n"; means that 2 raise to power 9 i.e. 2^9.
Square Root: cout<<sqrt (16)<<”\n”;
13
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Character Functions:
The header file ctype.h contains the functions that are used to find the types of different
values. The character functions are extremely useful for testing and transforming characters.
Upper Case: cout<<toupper(‘g’ ); Gives the letter in quotes in upper case like G
lower Case: cout<<tolower(‘J’ ); Gives the letter in quotes in lower case like j
ASCII: cout<<toascii(‘+’ ); Gives the letter’s ASCII code like 43
Exercise 9:
1. Write the equivalent mathematical expression for the following computer expressions:
a) pow (a / b * c + pow(1 / a, 2 / b ), b - c)
2. Write the equivalent computer expression for the following mathematical expression:
𝑎 + 3𝑏17
𝑎 8 (1 + 2𝑏)3/4
Standard Input:
The term standard input refers to the input given via keyboard. C++ uses stream object to get
standard input. The word cin stands for console input. C++ handles standard input by
applying the extraction operator or get from operator (>>) with cin stream. The operator must
be followed by a variable. The variable is used to store the input data.
Syntax: cin >> var_name;
Example: cin >> x; cin >> radius;
The above line will get a value from keyboard and store it in variable x and radius
respectively. One statement can use multiple extraction operators to get multiple values.
cin >> a >> b >> c;
13
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Write a program that adds two floating point numbers and show the result on screen
#include<iostream>
using namespace
std; int main ()
{
float var1, var2, res;
cout<<”Enter first
number:”; cin>>var1;
cout<<”\nEnter second number:”;
cin>>var2;
res = var1 +
var2;
cout<<endl;
cout<<”\n”<<var1<<” + ”<<var2<<” = ”<<res;
Write a program that input radius of sphere from user. Calculate its volume and surface
area using formulas
#include<iostream>
#include<math.h>
using namespace
std; int main ()
{
float rad;
double s_a,
vol;
const double PI =
3.1415; cout<<”Enter
Radius:”; cin>>rad;
s_a = 4*PI*pow(rad,2);
vol =
4/3*PI*pow(rad,3);
cout<<endl; cout<<”\
nRadius = ”<<rad;
cout<<”\nSurface Area =
”<<s_a; cout<<”\nVolume =
13
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Exercise 10:
Write a program where the user enters a value with a fraction. Display the fraction
only.Ended
Open For example
LabifTask:
the user gives 5.28, you should display 0.28.
I. Write a program where the user gives a 3 digit integer number. Find the number by
adding the digits of the given number. For example, if the user gives 528, you should
display 5+2+8=15.
II. Write a program that inputs age in years and convert it into days and months and
display them.
III. Write a program that takes a number and display its ASCII code.
IV. Write a program to enter a letter and display the next two letters.
V. Write a program to find out the area of triangle when three sides a, b and c of
triangle are input from keyboard. Formula for the area of triangle is:
13