0% found this document useful (0 votes)
72 views

Lab Session 06: Objective

The document discusses algorithms and flowcharts. It defines algorithms as a set of steps to solve a problem and introduces common techniques used in computational thinking like decomposition and abstraction. It also discusses developing algorithms through investigation, creating a preliminary algorithm, and refining it. Examples are provided of sequential algorithms to calculate area of a circle and make a cup of tea by breaking processes down into detailed steps. Finally, exercises are given to write algorithms to find the sum and average of three numbers.

Uploaded by

Kashif Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Lab Session 06: Objective

The document discusses algorithms and flowcharts. It defines algorithms as a set of steps to solve a problem and introduces common techniques used in computational thinking like decomposition and abstraction. It also discusses developing algorithms through investigation, creating a preliminary algorithm, and refining it. Examples are provided of sequential algorithms to calculate area of a circle and make a cup of tea by breaking processes down into detailed steps. Finally, exercises are given to write algorithms to find the sum and average of three numbers.

Uploaded by

Kashif Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Programming Fundamentals Faculty of Engineering

Department of Civil Engineering Lahore Leads University

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:

 does the solution work?


 does the solution complete its task in a finite amount of time (within set boundaries)

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

A scientific description of an algorithm would be:

‘a series of unambiguous steps to complete a given task in a finite amount of time.’

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.

Input – Process – Output Model:

Input Processing Output

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.

Strategy for Developing Algorithm

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

 Identify the processes.


 Identify the major decisions.
 Identify the repetitions.
 Identify the variables.

Step 2: Preliminary Algorithm

 Devise a high-level (general) algorithm.


 Step through the algorithm. Does this "walk-through" reveal any major problems? If
it does then correct the problems.

Step 3: Refining the Algorithm

 Incorporate any refinements indicated in step 2.


 Group together processes where appropriate.
 Group together variables where appropriate.
 Test the algorithm again by stepping through it.

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.

Input Process Output


Two numbers Add the first number to the second The new number

We could write this as the following sequence:

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

WhyExample: The algorithm


are sequences inputs radius from the user and calculates the area of
so important?
In computer circle. ( Hint: Area
programming you= have
3.14 xtoradius
correctx sequence
radius) of the commands. Look at an
example to show how careful you need to be. If you write down your friend’s address it may
1. Start
look like this:
2. Input radius in R
John Smiith
You 3. Areathat
know = 3.14
this *isRthe
*Rorder that you should write an address, but
4. the
this is Print Area
exact opposite of the way that the postal system works. There 22 tfolly
5. End of John Smiths. There may be hundreds of Holly Roads,
are millions
ROAD
many of them with a number 22. The postal system needs to know the
address in the logical task order, meaning the order that you carry out tfempton
finding the address. London

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.

 Water  An electric kettle is filled  Tea presented in


 Tea bags with water cup
 Boiling water  Tea bags are place in the
 Milk tea pot
 Sugar  The boiling water is
poured into the tea pot and
the tea brews
 Milk is added to the cup
 Sugar is added to he cup
 The “brewed” tea is
poured into a cup

First Refinement

These steps are probably not detailed enough to make tea. We therefore refine each
step into a sequence of further simpler steps:

Step1. Boil water

It might be refine to

i. Fill kettle with enough water.


ii. Switch on kettle.
iii. Wait until water is boiled.
iv. Switch off kettle.

Step2. Put tea leaves in pot

It might be refine to

i. Open box of tea.


ii. Extract one spoonful of tea leaves.
iii. Put spoonful into pot.
iv. Close box of tea.

Step 5. Pour tea into cup

It might be refined to

i. Pour tea from pot into cup until cup is full.

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

Step 1. Fill kettle with water

It might be refined to

i. Putt kettle under tap.


ii. Turn on tap.
iii. Wait until kettle is full.
iv. Turn off tap.

Exercise 1: Write a algorithm to find the sum and average of three numbers

Exercise 2: Write a algorithm to find the of first fifty natural 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

Guidelines for Drawing a Flowchart

a. In drawing a flowchart, all necessary requirements should be listed in a logical order.


b. The flowchart should be clear, neat and easy to follow. There should not be any
ambiguity in understanding the flowchart.
c. The usual direction of the flowchart is from top to bottom or left to right.
d. Only one flow line should come out from a process symbol.
e. Only one flow line must enter a decision symbol, but two flow lines, one of
each possible answer, must leave it.

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

i. It is difficult to draw flowcharts for complex problems


ii. If alterations are required, the flowchart is to be redrawn.
iii. Showing many branches and looping in flowchart is difficult.
iv. Manual tracing is needed to check correctness of flowchart drawn on paper.

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:

1. Algorithm to find the sum of individual digits of positive integer.


2. Algorithm to check whether given number is perfect number or Not.
3. Flowchart to find the roots of a quadratic equation.
4. Flowchart to find both the largest and smallest number in a list of 15 integers.

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

First Program in C++ Source Code

//my first program in C++ #include <iostream>


using namespace std; int main ()
{
cout << "Hello World!";
} Output

Hello World!

// my first program in C++


This is a comment line. All lines beginning with two slash signs (//) are considered comments

//my second program in C++ #include <iostream>


using namespace std;

int main () Output


{ cout << 10+10<<endl; 20
cout<<10*10<<endl; 100
cout<<10-10<<endl; 0
cout<<10/10<<endl; 1
}

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;

Output of above cout statement

12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Exercise 1:
Output of program:

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


{
cout<<(1+8/2+((1*4)+ (5*4))/4); cout<<((1+1+1+1)/2+(1+1+1)/3);
cout<<(5*5+5/5+6); cout<<(((3+4)+ (7*4))/5); Output
cout<<((3*6*7*2)+ 12/2); cout<<5-3*4%(6-1);
cout<<(8*4*2+6)/2+4;
}

Exercise 2:

Write a C++ program that displays the following as output:

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

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


{
cout<<”*”; cout<<”\n”; cout<<”**”<<”\n”; cout<<”***\n”; cout<<”****”;
}
Output
*
**
***
****
*****

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


{
cout<<”*********”; cout<<”\n”; cout<<”*”<<”\t”<<”*\n”; cout<<”*\t*\n”;
} Output
*********
* *
* *
* *
*********

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:

Bug: An error in a program.


Syntax: The structure of a program.
Syntax Error: An error in a program that makes it impossible to parse (and therefore
impossible to compile).
Run-Time Error: An error in a program that makes it fails at run-time.
Logical Error: An error in a program that makes it does something other than what the
programmer intended.
Debugging: The process of finding and removing any of the three kinds of errors.

Open Ended Lab Task:

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.

Declaring a variable in C++:


A program can have as many variables as needed; all variables must be declared before they
are used in the program. A variable can be declared anywhere in the program before its use.
“When you create a new variable, you have to declare what type it is and then the name of
that variable. The compiler uses data type to determine how much memory is needed for
each variable. Different types require different amount of memory. Once a variable is
declared, its data type cannot be changed during program execution. However, the value of
variable can be changed during execution.

Syntax: data_type variable_name;

Example: int marks; float average; char grade; double salary;

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:

int a, b, c; float yel, red, blu; char grade, section;

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.

bool choice = false; \\ it displays 0 it could also be wrtiten as bool choice = 0;


bool choice = true; \\ it displays 1 it could also be written as bool choice = 1;

Name Description Size* Range*


char single character 1 byte signed: -128 (27) to 127 (27 - 1)
unsigned: 0 to 255 (28 - 1)
short int short integer 2 bytes signed:
(short) -32768 (215) to 32767 (215 - 1)
unsigned:
0 to 65535 (216 - 1)
int integer 4 bytes signed: -2147483648 (231) to
2147483647 (231 - 1)
unsigned:
0 to 4294967295 (232 - 1)
long int long integer 4 bytes signed: -2147483648 (231) to
(long) 2147483647 (231 - 1)
unsigned:
0 to 4294967295 (232 - 1)
bool boolean value. it can take 1 byte ture or false
only one of two values, true
or false (1,0)
float floating point numbers 4 bytes -
±3.4 x 10 38 to ±3.4 x 10+38
(~ 7 digits)
double double precision floating 8 bytes -308
±1.7 x 10 to ±1.7 x 10+308
point number (~ 15 digits)
long double long double precision 8 bytes -308
±1.7 x 10 to ±1.7 x 10+308
floating point number (~ 15 digits)
wchar_t wide character 2 or 4 1 wide character
bytes

12
Programming Faculty of
Department of Civil Engineering Lahore Leads University
Rules of declaring a Variable:

1. Variables may include letters, numbers and underscore ( _ ).


2. The first character of variable must be a letter or underscore ( _ ). The variables
9minite, #home and ?weight are invalid.
3. Blank spaces are not allowed in variable names. The variable my car and your var
are invalid.
4. Both upper and lower cases are allowed.
5. Special symbols cannot be used as variable name. The variable roll#, hello! and
detail: are invalid.
6. Reserve words ( keywords) cannot be used as variable name. The names int, void,
cout and main are invalid.
7. A variable can be declared only for one data type.

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.

b. A constant that could contain the number of minutes in an hour.

c. A memory location that could be used to keep the initial letter of your name.

d. A variable that can save your class average marks.

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.

Assignment Operator (=)

Now that we have created some variables, we would like to store values in them. We do that
with an assignment statement.

char a; \\Declaring a variable of character type.


a = ‘H’; \\Assigning a character value to the character variable.

 When you declare a variable, you create a named storage location.


 When you make an assignment to a variable, you give it a value.

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

Calculate the Area of the Box


#include <iostream>
using namespace
std; int main()
{ int length;
int width;
length=7;
width=5;
cout<<"The area is: ";
cout<<length*width;
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.

2. Increment & Decrement (++ and - -)

The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
Therefore,

x = x + 1; is the same as x++;


x = x -1; is the same as --x;
Both the increment and decrement operators can either precede (prefix) or follow (postfix)
the operand.
For example, x = x + 1; can be written as ++x; // prefix form or as x++; // postfix form.
In this example, there is no difference whether the increment is applied as a prefix or a
postfix.

The precedence of the arithmetic operators is shown here:

Highest ++ , - -
- (unary minus)
*/%
Lowest + -

3. Relational & Logical Operators

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;

a. Parenthesize this expression and write its value: i + j == k;

b. Parenthesize this expression and write its value: k – i < y > x;

c. Parenthesize this expression and write its value: z – x + 1 != j + k – 2 * i;

Compound Assignment Statement:


An assignment statement that assigns a value to many variables. The assignment operator
(=) is used in this statement. The statement A = B = 23; assigns the value 23 to both
variables A and B.
Compound Assignment Operators:
These are the operators that combine assignment operator with arithmetic operators.
These are used to perform mathematical operations more easily.
Syntax: variable_name ar_op = value;

variable_name: The variable to assign the value;


ar_op: Any arithmetic operator with assignment operator
value: can be constant, variable, expression

Example: N += 45; This statement is equivalent to N = N+ 45;

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;

a. What is the output of the above code?

b. What is the output if we replace “++a *= b++” by “++a *= ++b”?

c. The elementary operations executed by “a = b++” can be written as “a = b; b = b + 1;”. Write


down the elementary operations executed by “++a *= b++” and “++a *= ++b” in correct
order using only three elementary operations: +, * and =.

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

Logarithm & Trigonometric Functions:


Natural Algorithm: cout<< log (3)<<”\n”; Gives the natural logarithm of 3.
Sine: cout<< sin (45) <<”\n”; Gives the Sine value of 45 degrees in radians.
Cosine: cout<<cos (45) <<”\n”; Gives the cosine value of 45 degrees in radians.
Tangent: cout<<sin (45) <<”\n”; Gives the Tangent value of 45 degrees in radians.
Inverse of Sine: cout<<asin (0.5) <<”\n”; Gives the inverse sine of 30 degrees in radians.
Inverse of Cosine: cout<<acos (0.5) <<”\n”; Gives the inverse cosine of 30 degrees in
radians.
Inverse of Tangent: cout<<atan (1) <<”\n”; Gives the inverse tangent of 30 degrees
in radians.
Hyperbolic Sine: cout<<sinh (60) <<”\n”; Gives the hyperbolic sine of 60 degrees in
radians.
Hyperbolic Cosine: cout<<cosh (60) <<”\n”; Gives the hyperbolic cosine of 60
degrees in radians.
Hyperbolic Tangent: cout<<tanh (60) <<”\n”; Gives the hyperbolic tangent of 60
degrees in radians.

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)

b) pow (a - b / c + pow(1 / a + 1, 2 / 3 * b), a + b)

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:

𝐴𝑟𝑒𝑎 = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)


where
𝑎+ 𝑏+ 𝑐
𝑠=
2

13

You might also like