Laboratory Manual
Programming Fundamental
C++
PROGRAMMING LANGUAGE
Compiled and tested by
Ms. Javeria Barkat
STUDENT’S INFORMATION
Name: RIZWAN HAIDER
Class: PROGRAMMING FUNDAMENTALS -LAB
Registration number: 10699
Semester: 2ND
Department: BSCS
Email:rizwanalpha99@gmail.com
Lab Session 1
Basic Concepts
Objective: To understand the basic concept and format of C++
language
Description:
In the C++ programming language, the C++ Standard Library is a
collection of classes and functions, which are written in the core
language. The library includes several header files. Most frequently used
header files are iostream, conio.h followed by preprocessor directives #include.
#include<iostream> abbreviated for input/ output stream
#include<conio.h> abbreviated for console input/ output
#include<cmath> for mathematical functionalities like power,
square root, cube root etc.
Note: .h extension is used with those header files that are included in
both C and C++.
Now, C++ has some collection of names referred to as the
namespace. This includes various names which are not used for other
purposes. For example cin, cout, basic input-output functions define in
std namespace. After including header files using namespace std is
added in global space in order to access various function in any program.
In different programs input is required to be entered from user at
rum time and output is generate don the monitor screen so for this two
functions are defined in namespace std that in Console input (cin),
Console output (cout)
After declaring all header files and standard namespace, program
will declare main function that is the gateway or the starting point of the
program. In C++ all functions carried ( ) parenthesis.
int main () In C++ main function has return type integer that
indicates an integer will return to end up the functionality of main
function and return a value to operating system.
Syntax of Program;
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
return 0;
}
Curly braces {} indicates the starting and ending of the program,
return 0; statement returns the 0 value that indicates normal termination
of program.
In main() function all the problem solving codes are written that
involve different data. For example if a program is taking personal
details from user to this program will includes name, mobile number,
address, gender etc. that indicates some data are of only characters like
name or some have numeric digits and alphabets like address.
Data Types
Data types indicates type of data as string, character, integer, float,
double, bool etc.
declaring a boolean variable which can only holds true or false value
bool b1 = true;
declaring a string value
string g= “Ali”;
string f= “6758”;
string y= “57.6”;
string d=“true”;
declaring a character value
char z= ‘b’;
char j= ‘4’;
declaring a decimal value
float h=25.2;
double u=612345.56;
declaring a integer value
int u=3;
Keywords:
Like C and other languages C++ also have some keywords that cannot
be used for variable names.
OPERATORS:
In C++ there are various types of operators including:
Arithmetic operators (+,-,*,/,%) where % is the modulus that returns
the remainder value between two integers.
Note: All operators can perform operations for both int or float except
modulus that accepts only integer opearands.
Relational Operators determines the relation between two inputs either
less than <, greater than >, equals to ==, less than and equals to <=,
greater than and equals to >= or not equals to !=.
Logical Operators are those that performs logical operations such as
AND(&&), OR(||), NOT(!)
Examples Task:
Write a program to print “hello world”?
Write a program to take two integer numbers from user and
print the result of sum of two numbers?
Write a program that do not take any inputs from user and print
the result of sum of two numbers where summation of two integers
will store in the variable result?
Write a program that multiply two float values in “cout” statement
with or without taking input from user? One case is done for you.
Another task is done by your self
Write a program to execute the expression a+b-c and print the
overall final result where a,b,c are the console integer input from
user?
Home Assignment
/* Done */
Print the output of these programs by taking screen shot from
screen and insert the picture after each question so that lab manual
will be maintained properly.
Laboratory Manual
Lab Session 2
Operators
Objective: Develop understanding of operators and cmath library
functions
Description:
Operators:
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators
and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Arithmetic Operators
There are following arithmetic operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then
Show Examples
Operato Description Example
r
+ Adds two operands A + B will give 30
- Subtracts second operand A - B will give -10
from the first
* Multiplies both operands A * B will give 200
/ Divides numerator by de- B / A will give 2
numerator
% Modulus Operator and B % A will give 0
remainder of after an
integer division
++ Increment operator, A++ will give 11
increases integer value by
one
-- Decrement operator, A-- will give 9
decreases integer value by
one
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Operato Description Example
r
== Checks if the values of two (A == B) is not true.
operands are equal or not, if
yes then condition becomes
true.
!= Checks if the values of two (A != B) is true.
operands are equal or not, if
values are not equal then
condition becomes true.
> Checks if the value of left (A > B) is not true.
operand is greater than the
value of right operand, if yes
then condition becomes true.
< Checks if the value of left (A < B) is true.
operand is less than the
value of right operand, if yes
then condition becomes true.
>= Checks if the value of left (A >= B) is not true.
operand is greater than or
equal to the value of right
operand, if yes then
condition becomes true.
<= Checks if the value of left (A <= B) is true.
operand is less than or equal
to the value of right
operand, if yes then
condition becomes true.
Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then −
Show Examples
Operato Description Example
r
&& Called Logical AND (A && B) is false.
operator. If both the
operands are non-zero, then
condition becomes true.
|| Called Logical OR (A || B) is true.
Operator. If any of the two
operands is non-zero, then
condition becomes true.
! Called Logical NOT !(A && B) is true.
Operator. Use to reverses
the logical state of its
operand. If a condition is
true, then Logical NOT
operator will make false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as
follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the
following table. Assume variable A holds 60 and variable B holds 13,
then −
Show Examples
Operato Description Example
r
& Binary AND Operator
(A & B) will give 12 which
copies a bit to the result if it
is 0000 1100
exists in both operands.
| Binary OR Operator copies (A | B) will give 61 which is
a bit if it exists in either 0011 1101
operand.
^ Binary XOR Operator
(A ^ B) will give 49 which
copies the bit if it is set in
is 0011 0001
one operand but not both.
~ Binary Ones Complement (~A ) will give -61 which is
Operator is unary and has 1100 0011 in 2's
the effect of 'flipping' bits. complement form due to a
signed binary number.
<< Binary Left Shift Operator.
The left operands value is
A << 2 will give 240 which
moved left by the number of
is 1111 0000
bits specified by the right
operand.
>> Binary Right Shift Operator. A >> 2 will give 15 which is
The left operands value is 0000 1111
moved right by the number
of bits specified by the right
operand.
Assignment Operators
There are following assignment operators supported by C++ language −
Show Examples
Operato Description Example
r
= Simple assignment operator,
C = A + B will assign
Assigns values from right side
value of A + B into C
operands to left side operand.
+= Add AND assignment
operator, It adds right operand C += A is equivalent to C
to the left operand and assign =C+A
the result to left operand.
-= Subtract AND assignment
operator, It subtracts right
C -= A is equivalent to C
operand from the left operand
=C–A
and assign the result to left
operand.
Example 1 Write a program that takes integer input from user and
apply all arithmetic operators along with post and pre increment?
Syntax:
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int a,b, result1, result2,result3, result4, result5, result6,result7;
cout<< "Enter first number ";
cin>>a;
cout<<"Enter second number ";
cin>>b;
result1=a+b;
result2=a-b;
result3=a*b;
result4=a/b;
result5=a%b;
result6= a++;
result7= ++a;
cout<<"The result of addition is"<<result1<<endl;
cout<<"The result of subtraction is"<<result2<<endl;
cout<<"The result of multiplication is"<<result3<<endl;
cout<<"The result of division is"<<result4<<endl;
cout<<"The result of modulus is"<<result5<<endl;
cout<<"The result of post increment is"<<a<<endl; // same as post
decrement
//print” a” instead of “result6” coz now a will be the incremented
variable
cout<<"The result of pre increment is"<<result7<<endl; // same as pre
decrement
//pre dec or inc work same
return 0;
}
output
EXTRA: EXAMPLES FOR PRE AND POST INC / DEC :
PRE: SAME PRE-DECREMENT
#include <iostream>
using namespace std;
int main()
{
int x = 10, a;
a = ++x;
cout << "Pre Increment Operation";
// Value of a will change
cout << "\na = " << a;
// Value of x change before execution of a=++x;
cout << "\nx = " << x;
return 0;
}
output
POST: SAME POST-DECREMENT
#include <iostream>
using namespace std;
int main()
{
int x , a;
cout<<"enter value ";
cin>>x;
a = x++;
cout << "Post Increment Operation";
// Value of a will not change
cout << "\na = " << a;
// Value of x change after execution of a=x++;
cout << "\nx = " << x;
return 0;
}
output
Example 2 Write a program that takes two integer input from user
and apply assignment operators?
Syntax:
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int a,b;
cout<< "Enter first number ";
cin>>a;
cout<<"Enter second number ";
cin>>b;
a+=b;
cout<<"The result is"<<a<<endl;
//SIMILARLY
b+=a;
cout<<"The result is"<<b<<endl;
return 0;}
PIC
The <cmath> header file declares a set of functions to perform
mathematical operations such as: sqrt() to calculate square root, log() to
find natural logarithm of a number etc. Some of the frequently used
functions of this library are mentioned as under;
Square root : used to calculate the square root of the given argument
double sqrt(double x)
Cube root: used to calculate the cube root of the given argument
double cbrt(double x)
Power: determines the power for given exponent
double pow(double base, double exponent);
Absolute: returns the absolute value of integer value
int x = -5;
int a = abs(x);
Sine angle: Use to calculate the sine value of given angle
double sin (double x); //same as cos angle tangent angle
Round off: The round() function in C++ returns the integral value that is
nearest to the argument, with halfway cases rounded away from zero
double round(double x);
Logarithm returns logarithmic value of given argument
double log10 (double x);
The floor() function in C++ returns the largest possible integer value
which is less than or equal to the given argument.
double floor(double x);
The ceil() function in C++ returns the smallest possible integer value
which is greater than or equal to the given argument.
double ceil(double x);
Task:
1. Write a program to take integer input from user, store it in a
variable named as num1 and apply post increment (num1 ++), pre
increment (++num1), post decrement (num1 --) and pre decrement
(num1--). Display each result in a new line with a tack of previous
value before applying each increment or decrement.
2. Write a program that does not take input from user and
calculates 65^4+√ 625+pi? Where pi is a constant value of 3.142
should be declare as constant.
3. Write a program that takes a value of angle from user and
determines the sine value of it where result will add with the
logarithmic value of another argument taken from user and display
the final result only.
TASK ( CODE AND PIC )
1. SOLUTION:
Code
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num1,a;
cout<<"enter number"<<endl;
cin>>num1;
a = ++num1;
cout << "Pre Increment Operation";
// Value of a will change
cout << "\na = " << a;
// Value of num1 change before execution of a=++num1;
cout << "\nnum1 = " << num1<<endl;
//now post inc
a = num1++;
cout << "Post Increment Operation";
// Value of a will not change
cout << "\na = " << a;
// Value of num1 change after execution of a=num1++;
cout << "\nnum1 = " << num1<<endl;
//now pre decrement
a = --num1;
cout << "Pre Decrement Operation";
// Value of a will change
cout << "\na = " << a;
// Value of num1 change before execution of a=--num1;
cout << "\nnum1 = " << num1<<endl;
//now post decrement
a = num1--;
cout << "Post Decrement Operation";
// Value of a will not change
cout << "\na = " << a;
// Value of num1 change after execution of a=num1--;
cout << "\nnum1 = " << num1;
return 0;
}
output
2. SOLUTION:
Code
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
int main()
{
float const pi=3.14;
int result1,result2,result;
int a=65;
int b=625;
result1 =pow(a,4);
result2 =sqrt(b);
result=result1+result2+pi;
cout<<"the result is :"<<result;
return 0;
}
output:
3. SOLUTION:
Code
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
int main()
{
int a,b;
float res,res1,res2;
cout<<"enter angle value"<<endl;
cin>>a;
cout<<"enter another value for logarithm"<<endl;
cin>>b;
res1=sin(a);
res2=log10(b);
res=res1+res2;
cout<<res1;
cout<<res2;
cout<<"the final result is :"<<res<<endl;
return 0;
}
output
Home ASSIGNMENTS
4. Write a program that takes float or double input from user
and return ceiling and floor value of entered input.
Code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a,b;
cout<<"enter any value for floor ";
cin>>a;
cout<<"enter any value for ceil ";
cin>>b;
cout << "Floor value is: " << floor(a) << endl; //dec
//Returns the value of x rounded down to its nearest integer
cout << "Ceil value is : " << ceil(b) << endl;//inc
//Returns the value of x rounded up to its nearest integer
return 0;
}
output
5. Write a program to calculate cube root of every integer input
value entered at run time.
Code
By std::pow function
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number, result;
cout << "Enter any number : ";
cin >> number;
result = pow(number, 1.0/3.0);
cout << "\n\Cube root of " << number << " is: " << result;
}
////////////////////////////
By std::cbrt function
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number, result;
cout << "Enter any number: ";
cin >> number;
result = cbrt(number);;
cout << "\n Cube Root of "<< number <<" is: " <<result;
}
Lab Session 3
Decision making statement
OBJECTIVES
To understand the structure and procedure of if-else statement in C++
DESCRIPTION:
The if-else statement is the decision making statements that check
certain condition with the aid of relational operators. The if statement
evaluates the test expression inside parenthesis. If test expression is
evaluated to true, statements inside the body of if is executed. If test
expression is evaluated to false, statements inside the body of if is
skipped and body of else is executed.
Format of Execution : If-Else statement
if (testExpression is true)
{
//execute statements
}
Else
{
// body of else block is executed
}
Example :
Write a program to print positive number entered by the user only,
other wise skip that number.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if ( number >= 0) // This program considers 0 as positive number
{
cout << "You entered a positive integer: " << number << endl;
}
Else
{
cout << "You have entered a negative number ";
}
return 0;
}
C++ Nested if...else
The if...else statement executes two different codes depending
upon whether the test expression is true or false. Sometimes, a choice
has to be made from more than 2 possibilities. Then in those situations
we go towards nested if-else statement that allows us to check for
multiple test expressions and execute different codes for more than two
conditions.
Syntax of Nested if...else
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3
is true
}
else
{
// statements to be executed if all test expressions are false
}
Example C++ Nested if...else
Write a Program to check whether an integer is positive, negative or zero
#include <iostream>
#include <conio.h>
using namespace std;
int main()
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
else if (number < 0)
cout<<"You entered a negative integer: " << number << endl;
else
cout << "You entered 0." << endl;
return 0;
}
Tasks
1. Write a program that design Transport Route decision chart
through nested if-else statement that takes distance in
kilometers from residence to university and checks the
condition in the following format:
If distance is less than 1km than print “Come university on foot”
If distance is above 1 km but below 3km than print “Come
University by public transport”
If distance is above above 3km than print “Come university by
university point”
2. Write a program that checks the blood pressure range of a
person by taking integer input and checking the range of input
for the following conditions through nested if-else statement:
If a patient blood pressure is in the range of between 80 and 120 so
print "he /she has normal blood pressure”
If a patient has below 80 but above 60 so print “he / she has reported
to further intake”.
If a patient has below 60 so print “he / she must be taken to
hospital.
If a patient has above 120 but below 150 so print “he / she has a high
blood pressure. Have some rest!!
If a patient has above150 so print “he / she has a serious high blood
pressure. Must be taken to hospital!!
Home Task:
Write a program to check whether the input integer is even or odd
by checking condition that if taking modulus of an input by 2 is
equals to zero than it is even otherwise print “It’s not an even
number. Its odd number”
Lab no. 4
Control / Branch statement
OBJECTIVES
To understand the structure and procedure of switch cases in C++
DESCRIPTION:
Switch Statement in C++
Switch case statements are a substitute for long if statements that
compare a variable to several integral values. The switch statement is a
multi-way branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Switch is a control statement that allows a value to change control of
execution.
A switch statement allows a variable to be tested for equality
against a list of values. Each value is called a case, and the variable
being switched on is checked for each case.
Syntax:
//here n is integer
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
Syntax for character input
//here ch is character
switch (ch)
{
case ‘a’: // code to be executed if n = 1;
break;
case ‘b’: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
Note: character is written in single quotes ‘’ where integer, float
values are written without ‘’.
EXAMPLE:
1. Write a program to make a Calculator using switch case
#include<iostream.h>
#include<conio.h>
using namespace std;
int main()
{
char c, operatr;
double operand1,operand2;
cout<<"Enter first number,operator,second number:";
cin>>operand1>>operatr>>operand2;
switch(operatr)
{
case '+':
cout<<"Answer="<<operand1+operand2;
break;
case '-':
cout<<"Answer="<<operand1-operand2;
break;
case '*':
cout<<"Answer="<<operand1*operand2;
break;
case '/':
cout<<"Answer="<<operand1/operand2;
break;
default:
cout<<"invalid operator";
}
return 0;
}
TASKS
Write a program to design calculator of five operators that is addition
(+), subtraction (-), multiplication (*), division (/) and modulus (%). And
perform all five operation by taking half digits of your enrollment id as
operand 1 and half digits of enrollment id is operand 2
Write a program whose display heading on the top as “Admissions in
Iqra University” that offers admission in Computer Science, Software
Engineering, Electrical, Electronics, and Mechanical Engineering. The
program takes integer input from user and decide the department display
message “Your admission is confirmed”.
Home Task:
Write a program whose display heading on the top as “Grading Scheme
in Iqra University” that offers grades in respective departments as
A= You have shown Excellent performance
B= Your performance is average.
C= You are below average. Needs improvement!!
D= You need serious hard work!!
E= Your are failed
This program takes character input from user and display their remarks
as per university criteria.
Lab Session 5
Loops
Loops are the mechanism of control flow statement that allows code to execute repeatedly.
Example For Loop, While, Do- while.
FOR- LOOP
A for loop is a repetition control structure that allows you to efficiently write a code that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C++ is
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement can be left blank, as long as a semicolon appears
after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the
condition becomes false, the for loop terminates.
Flow Diagram
Following is the flow chart of the execution of For loop.
Example: write a program to print numbers 10 to 20.
#include <iostream>
#include <conio.h>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a =< 20; a ++ )
{
cout << "the number is" << a<< endl;
}
return 0;
}
Code:
Output:
Nested For loop:
Nested loop uses for loop structure within a for loop structure.
The syntax for a nested for loop statement in C++ is as follows −
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
Example write a program to print Floyd’s triangle
*
**
***
****
*****
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int range, i, j;
cout<<"Enter the range (upto how many line ?) : ";
cin>>range;
cout<<"\nFloyd's Triangle :\n";
for(i=1; i<=range; i++)
{
for(j=1; j<=i; j++)
{
cout<<"*"<<" ";
}
cout<<"\n";
Code:
Output:
return 0;
}
TASKS
1.Write a program that takes user input and print its table using for loop
Code
Output
2. Write a program to print FLOYD’s Triangle
In to two ways using nested for loop
1
12
123
1234
12345
123456
Code:
Output:
Code:
Output:
Write a program to print using nested for loop
ABCDEF
ABCDE
ABCD
ABC
AB
A
Code:
Output:
HOME TASK
Write a program to print using nested for loop
$
$$
$$$
$$$$
Code:
Output:
Lab Session 6
Loops continued
While loop:
In while loop, condition is evaluated first and if it returns true then the statements inside
while loop execute, this happens repeatedly until the condition returns false. When
condition returns false, the control comes out of loop and jumps to the next statement in
the program after while loop.
Note: The important point to note when using while loop is that we need to use increment
or decrement statement inside while loop so that the loop variable gets changed on each
iteration, and at some point condition returns false. This way we can end the execution of
while loop otherwise the loop would execute indefinitely.
Syntax of while loop
Initialization of variables;
while(condition)
{
statement(s);
increment;
}
Flow Diagram of While loop
Example:
Write a program that takes print backward counting starting from the point of user input.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int range;
cout<<"Enter the number from where you want to desire to print backward counting : ";
cin>>range;
cout<<"\n Backward Counting :\n";
while(range!=0)
{
cout<< range<<"\n";
range --;
}
return 0;
}
Code:
Output:
Do While loop
The do..while loop is similar to the while loop with one important difference. The body of do...while loop
is executed at least once. Only then, the test expression is evaluated. If the test expression is true, the body
of the loop is executed again and the test expression is evaluated. This process goes on until the test
expression becomes false.If the test expression is false, the loop ends. In this increment is not mandatory.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i;
do
{
// statements inside the body of the loop
cout<<"Enter a number LESS THAN 5 to continue : ";
cin>>i;
cout<<"I am a girl";
}
while (i<5);
return 0;
}
Code:
Output:
Flowchart of do...while Loop
Task
Write a program that initialize the variable num amd takes user iput 1 to 5 . If user enters
1 to 5 that means user is ready to enter its registration number else if user enter 0 then
terminates the program. Implements the program using while loop.
Output: