PF Lab Manual
PF Lab Manual
PF Lab Manual
LAB MANUAL
Session: 2017
The purpose of this course is to provide students with a firm foundation of “Basics of Programing
Fundamentals” and to make them able to design C++ code of algorithms. The aim was to provide
foundation of programing and to polish the skills of understanding computational problems in
algorithmic way.
Week 1 Introduction to C++ compiler, File streaming, print statement, variables and their
use
Week 6 Quiz
Week 10 File handling, read and write data to files, use files as database
Installation of Software:
Introduction to C++
Week 13 Project Presentations
What is C++?
C++ was developed by Bjarne Stroustrup at Bell labs in 1979, as an extension to the C
language.
C++ gives programmers a high level of control over system resources and memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14, and C++17.
C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.
C++ is an object oriented language which gives a clear structure to programs and allows
code to be reused, lowering development costs.
C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
#include <iostream>
using namespace std;
Go to the File menu. Select New. In the Project Tab, select Win32 Console Application. Write
the Project Name. You can change the default location of the project from the location box. Check
the Win32 Platform. Press OK. A new window appears. Select An Empty Project. Press Finish. If
a new window appears showing project details, press OK.
Go to Project menu. Select Add to Project. Select New. From File Tab, select a C++ Source
file.
After writing the code, press CTRL+ F7, or from the Build menu, select Compile (Building the
executable file). After compiling, press F7.
4. Running the exe file:
Press CTRL+F5forDebugging the code at any line of the code. Press F9to insert a breakpoint.
Build>Start Debug>Go OR Press F5. Debugging is started now. Press F11 for step into, F10
for step over and shift+f11 for step out.
File Streaming:
We have been dealing with input and output streams the whole time (cin and cout). The
input/output stream is used with <iostream>library.
In C++ and any other programming language, you can read and write from a text file (.txt
extension). We have to include a library in the same way as we include a library for cin and cout.
A variable is a name which is associated with a value that can be changed. For example
when I write int num=20; here variable name is num which is associated with value 20, int is a
data type that represents that this variable can hold integer values. We will cover the data types in
the next tutorial. In this tutorial, we will discuss about variables.
For example:
char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
Data types define the type of data a variable can hold, for example an integer variable can
hold integer data, a character type variable can hold character data etc.
Data types in C++ are categorized in three groups: Built-in, user-defined and Derived.
Built in data types
char ch = 'A';
bool b = true;
wchar_t: Wide Character. This should be avoided because its size is implementation defined and
not reliable.
1. struct
2. union
3. enum
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
cout<<"num1 + num2: "<<(num1 + num2)<<endl;
cout<<"num1 - num2: "<<(num1 - num2)<<endl;
cout<<"num1 * num2: "<<(num1 * num2)<<endl;
cout<<"num1 / num2: "<<(num1 / num2)<<endl;
cout<<"num1 % num2: "<<(num1 % num2)<<endl;
return 0;
}
Output:
num1 / num2: 6
num1 % num2: 0
2) Assignment Operators
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num2 = num1;
cout<<"= Output: "<<num2<<endl;
num2 += num1;
cout<<"+= Output: "<<num2<<endl;
num2 -= num1;
cout<<"-= Output: "<<num2<<endl;
num2 *= num1;
cout<<"*= Output: "<<num2<<endl;
num2 /= num1;
cout<<"/= Output: "<<num2<<endl;
num2 %= num1;
cout<<"%= Output: "<<num2<<endl;
return 0;
}
Output:
= Output: 240
+= Output: 480
-= Output: 240
*= Output: 57600
/= Output: 240
%= Output: 0
++ and --
num++ is equivalent to num=num+1;
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num1++; num2--;
cout<<"num1++ is: "<<num1<<endl;
cout<<"num2-- is: "<<num2;
return 0;
}
Output:
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and it would return
false if b1 is true.
#include <iostream>
using namespace std;
int main(){
bool b1 = true;
bool b2 = false;
cout<<"b1 && b2: "<<(b1&&b2)<<endl;
cout<<"b1 || b2: "<<(b1||b2)<<endl;
cout<<"!(b1 && b2): "<<!(b1&&b2);
return 0;}
Output:
b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1
5) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 =40;
if (num1==num2) {
cout<<"num1 and num2 are equal"<<endl;
}
else{
cout<<"num1 and num2 are not equal"<<endl;
}
if( num1 != num2 ){
cout<<"num1 and num2 are not equal"<<endl;
}
else{
cout<<"num1 and num2 are equal"<<endl;
}
if( num1 > num2 ){
cout<<"num1 is greater than num2"<<endl;
}
else{
cout<<"num1 is not greater than num2"<<endl;
}
if( num1 >= num2 ){
cout<<"num1 is greater than or equal to num2"<<endl;
}
else{
cout<<"num1 is less than num2"<<endl;
}
if( num1 < num2 ){
cout<<"num1 is less than num2"<<endl;
}
else{
cout<<"num1 is not less than num2"<<endl;
}
if( num1 <= num2){
cout<<"num1 is less than or equal to num2"<<endl;
}
else{
cout<<"num1 is greater than num2"<<endl;
}
return 0;
}
Output:
6) Bitwise Operators
num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both
bits are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the
binary form of num1 and num2 only second last bits are matching.
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit
is 1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are
not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our
example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit, and
assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to 00101100
Note: In the example below we are providing 2 at the right side of this shift operator that is the
reason bits are moving two places to the left side. We can change this number and bits would be
moved by the number of bits specified on the right side of the operator. Same applies to the right
side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right bit, and
assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010
Example of Bitwise Operators
#include <iostream>
using namespace std;
int main(){
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
cout<<"num1 & num2: "<<result<<endl;
result = num1 | num2;
cout<<"num1 | num2: "<<result<<endl;
result = num1 ^ num2;
cout<<"num1 ^ num2: "<<result<<endl;
result = ~num1;
cout<<"~num1: "<<result<<endl;
result = num1 << 2;
cout<<"num1 << 2: "<<result<<endl;
result = num1 >> 2;
cout<<"num1 >> 2: "<<result;
return 0;
}
Output:
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:
If the expression results true then the first value before the colon (:) is assigned to the
variable num1 else the second value is assigned to the num1.
#include <iostream>
using namespace std;
int main(){
int num1, num2; num1 = 99;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
*/
num2 = (num1 == 10) ? 100: 200;
cout<<"num2: "<<num2<<endl;
/* num1 is equal to 99 that's why
* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 99) ? 100: 200;
cout<<"num2: "<<num2;
return 0;
}
Output:
num2: 200
num2: 100
Problem Set 1
Problem Set 2
Print your Name, Father’s Name, Class, Address and GPA using ‘cout’ statement.
Write a C++ program that declares a variable, stores value in it and displays it.
Write a program that takes two values from user, stores them in variables and calculates
the sum in third variable. Finally display the result.
Write C++ program that takes a 30.5(floating-point number) from user as input, add 300
in the input number and display the result.
Lab Manual
Problem Set
Write a program that finds the area of rectangle taking its dimensions. Area should
be calculated if and only if the dimensions provided are positive.
Write a program that takes an input from user and informs the user if provided number
is even or odd.
Develop a Calculator program. Program should ask the user about operation to be
performed and its operands, then should provide the result (Note: you can start with
simple arithmetic operators like + - / * % etc.).
Write a program that takes a year from user and tells if that year is a Leap Year or not. A
year Y is leap year if
Home Assignment
Although following problems do not require if-else necessarily but interesting enough for practice:
Let us suppose you input a 2-digit integer number which does not end with zero. If
we take the remainder of this number with 10, we see that the answer will give us the
last digit of the number. And if we divide the number by 10, we will get the number
excluding the last digit. For example, 24
Using this concept, write a program that takes a 3-digit integer as an input. Initialize
a variable called count and sum. Using the remainder-by-10 concept, _nd the value of
the 3rd digit. If it is greater than zero, add it in sum. Also, using the division-by-10
concept determine the remaining 2 digits and store them in a variable. Increment
count. Otherwise, store the remaining 2 digits in a variable and increment count.
Repeat the process until the last digit remains. The remaining digit just must be
added to sum and count must be incremented. Take the average of the three numbers
and print the average.
Write a program that takes n no of days from user and tell how many years months
and days it is approximately equivalent to. For e.g. 789 days is equivalent to 2 years,
1 month and 29 days. (Note take each year to be roughly of 365 days and month to
be of 30 days)
Write program that takes two timestamps between a day and then calculates the time
duration in between. For e.g. in between 5:50 and 8:30 2 hours and 40 minutes have
elapsed (Note: Use 24 hours format for simplification).
Lab Manual
Conditional Structure
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
If statement in C++
if(condition){
Statement(s);
}
The statements inside if parenthesis (usually referred as if body) gets executed only when the given
condition is true. If the condition is false then the statements inside if body are completely ignored.
Flow diagram of If statement
Example of if statement
#include <iostream>
using namespace std;
int main(){
int num=70;
if( num < 100 ){
/* This cout statement will only execute,
* if the above condition is true
*/
cout<<"number is less than 100";
}
Output:
When there is an if statement inside another if statement then it is called the nested if
statement.
The structure of nested if looks like this:
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the
conditions( condition_1 and condition_2) are true.
#include <iostream>
using namespace std;
int main(){
int num=90;
/* Nested if statement. An if statement
* inside another if body
*/
if( num < 100 ){
cout<<"number is less than 100"<<endl;
if(num > 50){
cout<<"number is greater than 50";
}
}
return 0;
}
Output:
Sometimes you have a condition and you want to execute a block of code if condition is
true and execute another piece of code if the same condition is false. This can be achieved in C++
using if-else statement.
if(condition) {
Statement(s);
}
else {
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside “else”
would execute if the condition is false.
#include <iostream>
using namespace std;
int main(){
int num=66;
if( num < 50 ){
//This would run if above condition is true
cout<<"num is less than 50";
}
else {
//This would run if above condition is false
cout<<"num is greater than or equal 50";
}
return 0;}
Output:
if-else-if statement is used when we need to check multiple conditions. In this control
structure we have only one “if” and one “else”, however we can have multiple “else if” blocks.
This is how it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
Note: The most important point to note here is that in if-else-if, as soon as the condition is met,
the corresponding set of statements get executed, rest gets ignored. If none of the condition is met
then the statements inside “else” gets executed.
Example of if-else-if
#include <iostream>
using namespace std;
int main(){
int num;
cout<<"Enter an integer number between 1 & 99999: ";
cin>>num;
if(num <100 && num>=1) {
cout<<"Its a two digit number";
}
else if(num <1000 && num>=100) {
cout<<"Its a three digit number";
}
else if(num <10000 && num>=1000) {
cout<<"Its a four digit number";
}
else if(num <100000 && num>=10000) {
cout<<"Its a five digit number";
}
else {
cout<<"number is not between 1 & 99999";
}
return 0;
}
Output:
Switch case statement is used when we have multiple conditions and we need to perform
different action based on the condition. When we have multiple conditions and we need to execute
a block of statements when a particular condition is satisfied. In such case either we can use
lengthy if..else-if statement or switch case. The problem with lengthy if..else-if is that it becomes
complex when we have several conditions. The switch case is a clean and efficient method of
handling such scenarios.
Switch Case statement is mostly used with break statement even though the break statement is
optional. We will first see an example without break statement and then we will discuss switch
case with break
#include <iostream>
using namespace std;
int main(){
int num=5;
switch(num+2) {
case 1:
cout<<"Case1: Value is: "<<num<<endl;
case 2:
cout<<"Case2: Value is: "<<num<<endl;
case 3:
cout<<"Case3: Value is: "<<num<<endl;
default:
cout<<"Default: Value is: "<<num<<endl;
}
return 0;
}
Output:
Default: Value is: 5
Explanation: In switch I gave an expression, you can give variable as well. I gave the expression
num+2, where num value is 5 and after addition the expression resulted 7. Since there is no case
defined with value 4 the default case got executed.
Switch Case Flow Diagram It evaluates the value of expression or variable (based on whatever is
given inside switch braces), then based on the outcome it executes the corresponding case.
Before we discuss about break statement, Let’s see what happens when we don’t use break
statement in switch case. See the example below:
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
case 3: cout<<"Case3 "<<endl;
case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
}
Output:
Case2
Case3
Case4
Default
In the above program, we have the variable i inside switch braces, which means whatever the value
of variable i is, the corresponding case block gets executed. We have passed integer value 2 to the
switch, so the control switched to the case 2, however we don’t have break statement after the case
2 that caused the flow to continue to the subsequent cases till the end. However this is not what
we wanted, we wanted to execute the right case block and ignore rest blocks. The solution to this
issue is to use the break statement in after every case block.
Break statements are used when you want your program-flow to come out of the switch
body. Whenever a break statement is encountered in the switch body, the execution flow would
directly come out of the switch, ignoring rest of the cases. This is why you must end each case
block with the break statement.
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1:
cout<<"Case1 "<<endl;
break;
case 2:
cout<<"Case2 "<<endl;
break;
case 3:
cout<<"Case3 "<<endl;
break;
case 4:
cout<<"Case4 "<<endl;
break;
default:
cout<<"Default "<<endl;
}
return 0; }
Output:
Case2
Now you can see that only case 2 got executed, rest of the subsequent cases were ignored.
Important Notes
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after
case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them
in any order based on the requirement
#include <iostream>
using namespace std;
int main(){
char ch='b';
switch(ch) {
case 'd': cout<<"Case1 ";
break;
case 'b': cout<<"Case2 ";
break;
case 'x': cout<<"Case3 ";
break;
case 'y': cout<<"Case4 ";
break;
default: cout<<"Default ";
}
return 0;
}
3) Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.
Problem Set 1
Problem Set 2
Write a C program to input any alphabet and check whether it is vowel or consonant.
Write a C program to input any character and check whether it is alphabet, digit or special
character.
Write a C program to check whether a character is uppercase or lowercase alphabet.
Write a C program to input week number and print weekday.
Write a C program to input month number and print number of days in that month.
Write a C program to count total number of notes in given amount.
Write a C program to input angles of a triangle and check whether triangle is valid or not.
Write a C program to input all sides of a triangle and check whether triangle is valid or not.
Write a C program to check whether the triangle is equilateral, isosceles or scalene triangle.
Problem Set 3
Write a C program to find all roots of a quadratic equation.
Write a C program to calculate profit or loss.
Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics
and Computer. Calculate percentage and grade according to following:
Percentage >= 90% : Grade A
Percentage >= 80% : Grade B
Percentage >= 70% : Grade C
Percentage >= 60% : Grade D
Percentage >= 40% : Grade E
Percentage < 40% : Grade F
Write a C program to input basic salary of an employee and calculate its Gross salary according
to following:
Basic Salary <= 10000 : HRA = 20%, DA = 80%
Basic Salary <= 20000 : HRA = 25%, DA = 90%
Basic Salary > 20000 : HRA = 30%, DA = 95%
Write a C program to input electricity unit charges and calculate total electricity bill according
to the given condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill
Lab Manual
A loop is used for executing a block of statements repeatedly until a particular condition
is satisfied. For example, when you are displaying number from 1 to 100 you may want set the
value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration.
In C++ we have three types of basic loops: for, while and do-while.
First step: In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each loop iteration, if the condition is true then
the statements inside for for loop body gets executed. Once the condition returns false, the
statements in for loop does not execute and the control gets transferred to the next statement in the
program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop
executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
The steps from second to fourth repeats until the loop condition returns false.
Example of a Simple For loop in C++
Here in the loop initialization part I have set the value of variable i to 1, condition is i<=6
and on each loop iteration the value of i increments by 1.
#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=6; i++){
/* This statement would be executed
* repeatedly until the condition
* i<=6 returns false.
*/
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Output:
A loop is said to be infinite when it executes repeatedly and never stops. This usually
happens by mistake. When you set the condition in for loop in such a way that it never return false,
it becomes infinite loop.
For example:
#include <iostream>
using namespace std;
int main(){
for(int i=1; i>=1; i++){
cout<<"Value of variable i is: "<<i<<endl;
}
return 0; }
This is an infinite loop as we are incrementing the value of i so it would always satisfy the condition
i>=1, the condition would never return false.
// infinite loop
for ( ; ; ) {
// statement(s)
}
Example: display elements of array using for loop
#include <iostream>
using namespace std;
int main(){
int arr[]={21,9,56,99, 202};
/* We have set the value of variable i
* to 0 as the array index starts with 0
* which means the first element of array
* starts with zero index.
*/
for(int i=0; i<5; i++){
cout<<arr[i]<<endl;
}
return 0;
}
Output:
21
9
56
99
202
Problem Set 1
Problem Set 2
Problem Set 3
while(condition)
{
statement(s);
}
How while Loop works?
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
#include <iostream>
using namespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
cout<<"Value of variable i is: "<<i<<endl; i++;
}
}
Output:
do
{
statement(s);
} while(condition);
First, the statements inside loop execute and then the condition gets evaluated, if the condition
returns true then the control jumps to the “do” for further repeated execution of it, this happens
repeatedly until the condition returns false. Once condition returns false control jumps to the next
statement in the program after do-while
do-while loop example in C++
#include <iostream>
using namespace std;
int main(){
int num=1;
do{
cout<<"Value of num: "<<num<<endl;
num++;
}while(num<=6);
return 0;
}
Output:
Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6
Problem Set 1
Problem Set 2
Problem Set 3
*****
****
***
**
*
Write a C++ program to print the following star pattern.
* * * * *
* * * *
* * *
* *
*
Lab Manual
Quiz:
Arrays in C++
Method 1:
int arr[5];
arr[0] = 34;
arr[1] = 21;
arr[2] = 2;
arr[3] = 66;
arr[4] = 567;
Method 2:
Method 3:
Array index starts with 0, which means the first array element is at index 0, second is at
index 1 and so on. We can use this information to display the array elements. See the code below:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}
Output:
11
22
33
44
55
Although this code worked fine, displaying all the elements of array like this is not
recommended. When you want to access a particular array element then this is fine but if you want
to display all the elements then you should use a loop like this:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
int n=0;
while(n<=4){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
Lab Task:
Write a program which takes 10 values as input and stores them in an array. Calculate the
average of five values starting from index zero. Increment the index by one till the end of array.
On every increment, calculate average of next five values starting from incremented index and
store the calculated average in a separate array.
Example:
5 12 7 6 45 10 11 56 45 12
Average= (5+12+7+6+45)/5 = 15
15
5 12 7 6 45 10 11 56 45 12
Average= (12+7+6+45+10)/5 = 16
15 16
5 12 7 6 45 10 11 56 45 12
Average= (7+6+45+10+11)/5 = 15.8
15 16 15.8
5 12 7 6 45 10 11 56 45 12
Pointers:
Pointer variable: A variable whose content is an address (i.e., a memory address).In C++, you
declare a pointer variable by using the asterisk symbol (*) between the data type and the variable
name. The general syntax to declare a pointer variable is as follows:
datatype * identifier;
In C++, the ampersand (&), address of the operator, is a unary operator that returns the address of
its operand. Similarly “*” is a dereferencing operator, refers to the object to which its operand
int x;
int *p;
p = &x; // assigns address of x to p
The arrays discussed in last lab are called static arrays because their size was fixed at
compile time. One of the limitations of a static array is that every time you execute the program,
the size of the array is fixed. One way to handle this limitation is to declare an array that is large
enough to process a variety of data sets. However, if the array is very big and the data set is small,
such a declaration would result in memory waste. On the other hand, it would be helpful if, during
program execution, you could prompt the user to enter the size of the array and then create an array
of the appropriate size.
Dynamic Array: An array created during the execution of a program. To create a dynamic array,
we use new operator.
int size;
int *p;
p = newint [size];
If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which de-allocates memory previously allocated by new operator.
delete [] p;
Problem Set 1
Problem Set 2
Write a C program to count total number of even and odd elements in an array.
Write a C program to count total number of negative elements in an array.
Write a C program to copy all elements from an array to another array.
Write a C program to insert an element in an array.
Write a C program to delete an element from an array at specified position.
Write a C program to count frequency of each element in an array.
Write a C program to print all unique elements in the array.
Write a C program to count total number of duplicate elements in an array.
Write a C program to delete all duplicate elements from an array.
Write a C program to merge two array to third array.
Problem Set 3
Multidimensional arrays are also known as array of arrays. The data in multi-
dimensional array is stored in a tabular form as shown in the diagram below:
int arr[2][3];
This array has total 2*3 = 6 elements.
int arr[2][2][2];
This array has total 2*2*2 = 8 elements.
Lets see how to declare, initialize and access Two Dimensional Array elements.
int myarray[2][3];
Initialization of array:
We can initialize the array in many ways:
Method 1:
#include <iostream>
using namespace std;
int main(){
int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
for(int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:
arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66
Three dimensional array
Lets see how to declare, initialize and access Three Dimensional Array elements.
int myarray[2][3][2];
Initialization:
We can initialize the array in many ways:
Method 1:
Method 2:
This way of initializing is preferred as you can visualize the rows and columns
here.
int arr[2][3][2] = {
{ {1,-1}, {2, -2}, {3, -3}},
{ {4, -4}, {5, -5}, {6, -6}}
}
Lab Task:
Write a C++ program to take the transpose of a matrix. A transpose of the matrix, is the matrix
obtained by interchanging the rows and columns of the original matrix. Consider following
Exampe
1. Given Matrix
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
2. Given Matrix
1 2
3 4
5 6
Transpose:
1 3 5
2 4 6
A matrix is represented by a 2D array. Use a double pointer to declare this 2D array dynamically.
The number of rows and columns should be taken as input from the user. Your code should be
generic, i.e., it should work for any number of rows and columns.
You will have to create a new matrix of reversed size. For example, if the input matrix is of size
(2x3), the new matrix should be of a size (3x2). Create the new matrix dynamically.
Problem Set
Write a C program declare an array of size 3x5, take input from user and store it in array.
Find out the maximum number in array and display its index (ROW x COL).
Write C++ code that takes a two dim array of length 5x5. Enter number in array after taking
input from user. Print the left diagonal of array.
Write C++ code that takes a two dim array of length 4x4. Enter number in array after taking
input from user. Print the right diagonal of array.
Take an array 4x7. Enter numbers in array as input from user. Print the sum of every row
Lab Manual
Target: Strings
Strings in C++
Strings are words that are made up of characters, hence they are known as sequence of
characters. In C++ we have two ways to create and use strings: 1) By creating char arrays and treat
them as string 2) By creating string object
Lets discuss these two ways of creating string first and then we will see which method is better
and why.
Example 1:
A simple example where we have initialized the char array during declaration.
#include <iostream>
using namespace std;
int main(){
char book[50] = "A Song of Ice and Fire";
cout<<book;
return 0;
}
Output:
This can be considered as inefficient method of reading user input, why? Because when we read
the user input string using cin then only the first word of the string is stored in char array and rest
get ignored. The cin function considers the space in the string as delimiter and ignore the
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
//reading user input
cin>>book;
cout<<"You entered: "<<book;
return 0;
}
Output:
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
1) Size of the char array is fixed, which means the size of the string created through it is fixed in
size, more memory cannot be allocated to it during runtime. For example, lets say you have created
an array of character with the size 10 and user enters the string of size 15 then the last five
characters would be truncated from the string.
On the other hand if you create a larger array to accommodate user input then the memory is wasted
if the user input is small and array is much larger then what is needed.
2) In this method, you can only use the in-built functions created for array which don’t help much
in string manipulation.
Till now we have seen how to handle strings in C++ using char arrays. Lets see another
and better way of handling strings in C++ – string objects.
#include<iostream>
using namespace std;
int main(){
// This is how we create string object
string str;
cout<<"Enter a String:";
/* This is used to get the user input
* and store it into str
*/
getline(cin,str);
cout<<"You entered: ";
cout<<str<<endl;
The process in which a function calls itself is known as recursion and the corresponding
function is called the recursive function. The popular example to understand the recursion is
factorial function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil
discuss what is base condition and why it is important.
In the following diagram. I have shown that how the factorial function is calling itself until the
function reaches to the base condition.
Lets solve the problem using C++ program.
#include <iostream>
using namespace std;
//Factorial function
int f(int n){
/* This is called the base condition, it is
* very important to specify the base condition
* in recursion, otherwise your program will throw
* stack overflow error.
*/
if (n <= 1)
return 1;
else
return n*f(n-1);
}
int main(){
int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"Factorial of entered number: "<<f(num);
return 0;
}
Output:
Enter a number: 5
Factorial of entered number: 120
Base condition
In the above program, you can see that I have provided a base condition in the recursive function.
The condition is:
if (n <= 1)
return 1;
The purpose of recursion is to divide the problem into smaller problems till the base condition is
reached. For example in the above factorial program I am solving the factorial function f(n) by
calling a smaller factorial function f(n-1), this happens repeatedly until the n value reaches base
condition(f(1)=1). If you do not define the base condition in the recursive function then you will
get stack overflow error.
Direct recursion vs indirect recursion
Direct recursion: When function calls itself, it is called direct recursion, the example we have
seen above is a direct recursion example.
Indirect recursion: When function calls another function and that function calls the calling
function, then this is called indirect recursion. For example: function A calls function B and
Function B calls function A.
#include <iostream>
using namespace std;
int fa(int);
int fb(int);
int fa(int n){
if(n<=1)
return 1;
else
return n*fb(n-1);
}
int fb(int n){
if(n<=1)
return 1;
else
return n*fa(n-1);
}
int main(){
int num=5;
cout<<fa(num);
return 0;
}
Output:
120
Problem Set 1
Problem Set 2
Problem Set 3
Write a C program to find total number of alphabets, digits or special character in a string.
Write a C program to count total number of vowels and consonants in a string.
Write a C program to count total number of words in a string.
Write a C program to find reverse of a string.
Write a C program to check whether a string is palindrome or not.
Write a C program to reverse order of words in a given string.
Lab Manual
File Handling
Input/output with filesC++ provides the following classes to perform output and input of
characters to/from files:
These classes are derived directly or indirectly from the classes istream and ostream. We have
already used objects whose types were these classes: cin is an object of class istream and cout is
an object of class ostream. Therefore, we have already been using classes that are related to our
file streams. And in fact, we can use our file streams the same way we are already used to
use cin and cout, with the only difference that we have to associate these streams with physical
files. Let's see an example:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
This code creates a file called example.txt and inserts a sentence into it in the same way we are
used to do with cout, but using the file stream myfile instead.
But let's go step by step:
Open a file
The first operation generally performed on an object of one of these classes is to associate it to a
real file. This procedure is known as to open a file. An open file is represented within a program
by a stream (i.e., an object of one of these classes; in the previous example, this was myfile)
and any input or output operation performed on this stream object will be applied to the
physical file associated to it.
In order to open a file with a stream object we use its member function open:
Where filename is a string representing the name of the file to be opened, and mode is an
optional parameter with a combination of the following flags:
All output operations are performed at the end of the file, appending the content to
ios::app
the current content of the file.
If the file is opened for output operations and it already existed, its previous content
ios::trunc
is deleted and replaced by the new one.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.binin binary mode to add data we could do it by the following call to
member function open:
ofstream myfile;
ofstream ios::out
ifstream ios::in
For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively
assumed, even if a mode that does not include them is passed as second argument to
the open member function (the flags are combined).
For fstream, the default value is only applied if the function is called without specifying
any value for the mode parameter. If the function is called with any value in that parameter the
default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations independently of
any format considerations. Non-binary files are known as text files, and some translations may
occur due to formatting of some special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream is generally to open a file, these three
classes include a constructor that automatically calls the open member function and has the exact
same parameters as this member. Therefore, we could also have declared the
previous myfile object and conduct the same opening operation in our previous example by
writing:
Combining object construction and stream opening in a single statement. Both forms to open a
file are valid and equivalent.
To check if a file stream was successful opening a file, you can do it by calling to
member is_open. This member function returns a bool value of true in the case that indeed the
stream object is associated with an open file, or false otherwise:
When we are finished with our input and output operations on a file we shall close it so that the
operating system is notified and its resources become available again. For that, we call the
stream's member function close. This member function takes flushes the associated buffers and
closes the file:
myfile.close();
Once this member function is called, the stream object can be re-used to open another file, and
the file is available again to be opened by other processes.
In case that an object is destroyed while still associated with an open file, the destructor
automatically calls the member function close.
Text files
Text file streams are those where the ios::binary flag is not included in their opening mode.
These files are designed to store text and thus all values that are input or output from/to them can
suffer some formatting transformations, which do not necessarily correspond to their literal
binary value.
Writing operations on text files are performed in the same way we operated with cout:
int main () {
ofstream myfile ("example.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Reading from a file can also be performed in the same way that we did with cin:
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
This last example reads a text file and prints out its content on the screen. We have
created a while loop that reads the file line by line, using getline. The value returned by getline is
a reference to the stream object itself, which when evaluated as a boolean expression (as in this
while-loop) is true if the stream is ready for more operations, and false if either the end of the file
has been reached or if some other error occurred.
The following member functions exist to check for specific states of a stream (all of them
return a bool value):
bad()
Returns true if a reading or writing operation fails. For example, in the case that we try to
write to a file that is not open for writing or if the device where we try to write has no
space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens,
like when an alphabetical character is extracted when we are trying to read an integer
number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of
the previous functions would return true. Note that good and bad are not exact opposites
(good checks more state flags at once).
The member function clear() can be used to reset the state flags.
Problem Statement
Structures in C++
Structure is a compound data type that contains different variables of different types. For
example, you want to store Student details like student name, student roll num, student age. You
have two ways to do it, one way is to create different variables for each data, but the downfall of
this approach is that if you want to store the details of multiple students, in that case it is not
feasible to create separate set of variables for each student.
The second and best way of doing it by creating a structure like this:
struct Student
{
char stuName[30];
int stuRollNo;
int stuAge;
};
Now these three members combined will act like a separate variable and you can create structure
variable like this:
Syntax:
structure_name variable_name
So if you want to hold the information of two students using this structure then you can do it like
this:
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
int main(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"ENter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
return 0;
}
Output: