PF Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 72

Programming Fundamentals

LAB MANUAL

University Of Engineering and Technology, KSK Campus Lahore.


Programming Fundamentals

Lab Instructor: Mr. Amjad Majeed

Session: 2017

Department: Department of Computer Science.


Programing Fundamentals
Lab Manual

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 No. Contents

Week 1 Introduction to C++ compiler, File streaming, print statement, variables and their
use

Week 2 Input, Output, Variables, Arithmetic Operations

Week 3 Conditional & Nested Conditional Structure

Week 4 Loops introduction (for loop)

Week 5 Loops (for loop, nested for loop)

Week 6 Quiz

Week 7 Introduction and use of arrays

Week 8 Arrays Cont., Two dim. arrays

Week 9 Recursion and Strings

Week 10 File handling, read and write data to files, use files as database

Week 11 Structure and their use

Week 12 Project Presentations


Lab Manual

Programing Fundamentals (Lab 1)

Target: Basics of C++

Installation of Software:

Visual Studio Download and Installation guideline link: https://docs.microsoft.com/en-


us/visualstudio/install/install-visual-studio?view=vs-2017

Introduction to C++
Week 13 Project Presentations

What is C++?

C++ is a cross-platformed language that can be used to create sophisticated high-


performance applications.

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.

Why Use C++

C++ is one of the world's most popular programming languages.

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.

C++ Program Structure


Let us look at a simple code that would print the words Hello World.

#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}

1. Creating a new project:

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.

2. Source File (.cpp):

Go to Project menu. Select Add to Project. Select New. From File Tab, select a C++ Source
file.

Write name of file and press ok.

3. Compiling the code:

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.

Then do the following to start debugging.

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.

Syntax of declaring a variable in C++

data_type variable1_name = value1, variable2_name = value2;

For example:

int num1=20, num2=100;


//We can also write it like this:
int num1,num2;
num1=20;
num2=100;
Types of variables
Variables can be categorized based on their data type. For example, in the above example
we have seen integer type variables. Following are the types of variables available in C++.

int: These type of of variables holds integer value.

char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.

bool: holds boolean value true or false.

double: double-precision floating point value.

float: Single-precision floating point value.

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: For characters. Size 1 byte.

char ch = 'A';

int: For integers. Size 2 bytes.

int num = 100;


float: For single precision floating point. Size 4 bytes.

float num = 123.78987;

double: For double precision floating point. Size 8 bytes.

double num = 10098.98899;

bool: For booleans, true or false.

bool b = true;

wchar_t: Wide Character. This should be avoided because its size is implementation defined and
not reliable.

User-defined data types

We have three types of user-defined data types in C++

1. struct
2. union
3. enum

Operator represents an action. For example + is an operator that represents addition. An


operator works on two or more operands and produce an output. For example 3+4+5 here +
operator works on three operands and produce 12 as output.
Types of Operators in C++

1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator

1) Basic Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %


+ is for addition.
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 20 % 5 would return 0

Example of Arithmetic Operators

#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: 280

num1 - num2: 200

num1 * num2: 9600

num1 / num2: 6

num1 % num2: 0

2) Assignment Operators

Assignments operators in C++ are: =, +=, -=, *=, /=, %=


num2 = num1 would assign value of variable num1 to the variable.
num2+=num1 is equal to num2 = num2+num1
num2-=num1 is equal to num2 = num2-num1
num2*=num1 is equal to num2 = num2*num1
num2/=num1 is equal to num2 = num2/num1
num2%=num1 is equal to num2 = num2%num1

Example of 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

3) Auto-increment and Auto-decrement Operators

++ and --
num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

#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:

num1++ is: 241


num2-- is: 39

4) Logical Operators

Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.

Logical operators in C++ are: &&, ||, !

Let’s say we have two boolean variables b1 and b2.

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.

Example of Logical Operators

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

Example of Relational operators

#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:

num1 and num2 are not equal


num1 and num2 are not equal
num1 is greater than num2
num1 is greater than or equal to num2
num1 is not less than num2
num1 is greater than num2

6) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.

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:

num1 & num2: 2


num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2
7) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.
Syntax:

variable num1 = (expression) ? value if true : value if false

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.

Example of Ternary Operator

#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

 Write a program to print “Hello World!”


 Write a C++ program that prints your name 3 times
 Write C++ code to print “Pakistan” and “Zindabad” at two different lines

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

Programing Fundamentals (Lab 2)

Target: Input, Output, Variables, Arithmetic Operations

Problem Set

 Write C++ code to elaborate all the data types.


 Write a program that input three numbers say x, z and y. and then
(a) Print the numbers.
(b) Determine the maximum of the three numbers and print the number saying that it is the
greater of the two.
(c) Similarly determine the minimum of the two numbers and print the number saying
that it is the smaller of the three.
(d) Print those numbers in ascending order.

 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

(a) It can be evenly divided by 4 (such as 2012, 2016, etc.).


(b) Or if it can be evenly divided by 400, or not evenly divided by 100. (such as 2100,
2200, etc. which are evenly divided but 100 but not 400 so it’s not leap) or (such
as 2000, 2400 which is evenly divided by 400).
 Write a program in C++ to swap two numbers.
 Write a C++ program to check whether a character is alphabet or not and also write a C++
program to input any alphabet and check whether it is vowel or consonant.

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

Programing Fundamentals (Lab 3)

Target: Conditional Structure

Conditional Structure

Sometimes we need to execute a block of statements only when a particular condition is


met or not met. This is called decision making, as we are executing a certain code after making a
decision in the program logic. For decision making in C++, we have four types of control
statements (or control structures), which are as follows:

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

If statement in C++

If statement consists a condition, followed by statement or a set of statements as shown


below:

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

if(num > 100){


/* This cout statement will only execute,
* if the above condition is true
*/
cout<<"number is greater than 100";
}
return 0;
}

Output:

number is less than 100

Nested if statement in C++

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.

Example of Nested if statement

#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:

number is less than 100


number is greater than 50

If else statement in C++

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.

This is how an if-else statement looks:

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.

Flow diagram of if-else

Figure 1Flow of IF-else Statement

Example of if-else statement

#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:

num is greater than or equal 50

if-else-if Statement in C++

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:

Enter an integer number between 1 & 99999: 8976


It is a four digit number

Switch Case statement in C++ with example

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.

The syntax of Switch case statement:


switch (variable or an integer expression)
{
case constant:
//C++ code
;
case constant:
//C++ code
;
default:
//C++ code
;
}

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

Example of Switch Case

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

Break statement in Switch 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.

Let’s take the same example with 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

2) Using characters in switch case. For example –

#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

 Write a C program to find maximum between two numbers.


 Write a C program to find maximum between three numbers.
 Write a C program to check whether a number is negative, positive or zero.
 Write a C program to check whether a number is divisible by 5 and 11 or not.
 Write a C program to check whether a number is Even or Odd.
 Write a C program to check whether a year is leap year or not.
 Write a C program to check whether a character is alphabet or not.

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

Programing Fundamentals (Lab 4)

Target: Looping Structure (for loop)

For loop in C++ with example

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.

Syntax of for loop

for(initialization; condition ; increment/decrement)


{
C++ statement(s);
}
Execution of For loop:

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:

Value of variable i is: 1


Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
Infinite for loop in C++

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.

Here is another example of infinite for loop:

// 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

 Write a C program to print all natural numbers from 1 to n.


 Write a C program to print all natural numbers in reverse (from n to 1)
 Write a C program to print all alphabets from a to z.
 Write a C program to print all even numbers between 1 to 100.
 Write a C program to print all odd number between 1 to 100.
 Write a C program to find sum of all natural numbers between 1 to n.
 Write a C program to find sum of all even numbers between 1 to n.

Problem Set 2

 Write a C program to find sum of all odd numbers between 1 to n.


 Write a C program to print multiplication table of any number.
 Write a C program to count number of digits in a number.
 Write a C program to find first and last digit of a number.
 Write a C program to find sum of first and last digit of a number.
 Write a C program to swap first and last digits of a number.

Problem Set 3

 Write a C program to calculate sum of digits of a number.


 Write a C program to calculate product of digits of a number.
 Write a C program to enter a number and print its reverse.
 Write a C program to check whether a number is palindrome or not.
 Write a C program to find frequency of each digit in a given integer.
 Write a C program to enter a number and print it in words.
 Write a C program to print all ASCII character with their values.
Lab Manual

Programing Fundamentals (Lab 5)

Target: Looping Structure (for, while & do-while)

Syntax of while loop

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

Flow Diagram of While loop


While Loop example in C++

#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:

Value of variable i is: 1


Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6

Syntax of do-while loop

do
{
statement(s);
} while(condition);

How do-while loop works?

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

 Write a C program to find power of a number using while loop.


 Write a C program to find all factors of a number.
 Write a C program to calculate factorial of a number.
 Write a C program to find HCF (GCD) of two numbers.
 Write a C program to find LCM of two numbers.
 Write a C program to check whether a number is Prime number or not.
 Write a C program to print all Prime numbers between 1 to n.

Problem Set 2

 Write a C program to find sum of all prime numbers between 1 to n.


 Write a C program to find all prime factors of a number.
 Write a C program to check whether a number is Armstrong number or not.
 Write a C program to print all Armstrong numbers between 1 to n.
 Write a C program to check whether a number is Perfect number or not.
 Write a C program to print all Perfect numbers between 1 to n.
 Write a C program to check whether a number is Strong number or not.
 Write a C program to print all Strong numbers between 1 to n.

Problem Set 3

 Write a C++ program to print the following star pattern.


*
**
***
****
*****

 Write a C++ program to print the following star pattern.


*
***
*****
*******
*********
 Write a C++ program to print the following star pattern.

*****
****
***
**
*
 Write a C++ program to print the following star pattern.

* * * * *
* * * *
* * *
* *
*
Lab Manual

Programing Fundamentals (Lab 6)

Target: Up to Looping Structure

Quiz:

Quiz until looping structure.


Lab Manual

Programing Fundamentals (Lab 7)

Target: Arrays and Pointer Introduction

Arrays in C++

An array is a collection of similar items stored in contiguous memory locations. In


programming, sometimes a simple variable is not enough to hold all the data. For example, lets
say we want to store the marks of 500 students, having 500 different variables for this task is not
feasible, we can define an array with size 500 that can hold the marks of all students.

Declaring an array in C++

There are couple of ways to declare an array.

Method 1:

int arr[5];
arr[0] = 34;
arr[1] = 21;
arr[2] = 2;
arr[3] = 66;
arr[4] = 567;
Method 2:

int arr[] = {34, 21, 2, 66, 567};

Method 3:

int arr[5] = {10, 20, 30, 40, 50};

Accessing Array Elements

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

Average= (10+11+56+45+12)/5 = 13.8

15 16 15.8 25.6 33.4 26.8

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

(pointer) points. For example, given the statements:

int x;

int *p;
p = &x; // assigns address of x to p

cout << *p << endl; // pointer p points to x

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

 Write a C program to read and print elements of array.


 Write a C program to print all negative elements in an array.
 Write a C program to find sum of all array elements.
 Write a C program to find maximum and minimum element in an array.
 Write a C program to find second largest element in an array.

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

 Write a C program to find reverse of an array.


 Write a C program to put even and odd elements of array in two separate array.
 Write a C program to search an element in an array.
 Write a C program to sort array elements in ascending or descending order.
 Write a C program to sort even and odd elements of array separately.
Lab Manual

Programing Fundamentals (Lab 8)

Target: Looping Structure (Two Dim Arrays)

Multidimensional Arrays in C++

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:

A two dimensional array:

int arr[2][3];
This array has total 2*3 = 6 elements.

A three dimensional array:

int arr[2][2][2];
This array has total 2*2*2 = 8 elements.

Two dimensional array

Lets see how to declare, initialize and access Two Dimensional Array elements.

How to declare a two dimensional array?

int myarray[2][3];

Initialization of array:
We can initialize the array in many ways:
Method 1:

int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};


Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.

int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};


Accessing array elements:
arr[0][0] – first element
arr[0][1] – second element
arr[0][2] – third element
arr[1][0] – fourth element
arr[1][1] – fifth element
arr[1][2] – sixth element

Example: Two dimensional array in C++

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

Declaring a three dimensional array:

int myarray[2][3][2];
Initialization:
We can initialize the array in many ways:

Method 1:

int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};

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

Programing Fundamentals (Lab 9)

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.

1) Array of Characters – Also known as C Strings

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:

A Song of Ice and Fire

Example 2: Getting user input as string

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:

Enter your favorite book name: The Murder of Roger Ackroyd


You entered: The
You can see that only the “The” got captured in the book and remaining part after space got
ignored. How to deal with this then? Well, for this we can use cin.get function, which reads the
complete line entered by user.

Example 3: Correct way of capturing user input string using cin.get

#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";

//reading user input


cin.get(book, 50);
cout<<"You entered: "<<book;
return 0;
}
Output:

Enter your favorite book name:The Murder of Roger Ackroyd


You entered: The Murder of Roger Ackroyd
Drawback of this method

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.

What is the solution of these problems?


We can create string using string object. Lets see how we can do it.

String object in C++

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;

/* This function adds a character at


* the end of the string
*/ str.push_back('A');
cout<<"The string after push_back: "<<str<<endl;
/* This function deletes a character from
* the end of the string
*/
str.pop_back();
cout << "The string after pop_back: "<<str<<endl;
return 0;
}
Output:
Enter a String:XYZ
You entered: XYZ
The string after push_back: XYZA
The string after pop_back: XYZ

C++ Recursion with example

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.

C++ recursion example: Factorial

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

Indirect Recursion Example in C++

#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

 Print first 10 Fibonacci numbers using recursion.


 Print factorial of a number using recursion.
 Solve Tower of Hanoi problem using recursion.
 Write a C program to find length of a string.
 Write a C program to copy one string to another string.
 Write a C program to concatenate two strings.
 Write a C program to compare two strings.

Problem Set 2

 Write a C program to convert lowercase string to uppercase.


 Write a C program to convert uppercase string to lowercase.
 Write a C program to toggle case of each character of a string.

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

Programing Fundamentals (Lab 10)

Target: File Handling

File Handling

Input/output with filesC++ provides the following classes to perform output and input of
characters to/from files:

ofstream: Stream class to write on files

ifstream: Stream class to read from files

fstream: Stream class to both read and write from/to 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:

// basic file operations

#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:

open (filename, mode);

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:

ios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

Set the initial position at the end of the file.


ios::ate
If this flag is not set, the initial position is the beginning of the file.

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;

myfile.open ("example.bin", ios::out | ios::app | ios::binary);


Each of the open member functions of classes ofstream, ifstream and fstream has a default mode
that is used if the file is opened without a second argument:

class default mode parameter

ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out

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:

ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);

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:

if (myfile.is_open()) { /* ok, proceed with output */ }


Closing a file

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:

// writing on a text file


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

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:

// reading a text file


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

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.

Checking state flags

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

 Program to create file using C++ code.


 Design a C++ code to create a file, write your data to the file and in the end display all
data on console by reading it from file. Your data must be.
 Registration No.
 Full Name
 CNIC / Form-B No.
 Last Semester’s GPA
 Design a program that accepts a number from user as input write the table of this number
from 1 to 10 in following format.
o If user entered 7
 7*1=7
7 * 2 = 14
7 * 3 = 21
….
….
….
7 * 10 = 70
 C++ code to create a file, write your data to the file and in the end display all data on
console by reading it from file. Your data must be.
 Registration No.
 Full Name
 CNIC / Form-B No.
 Last Semester’s GPA
 Write C++ program to open a file and read it to display the contents of file on console.
 Write a C++ Program that takes a positive integer input from user as many times until
pressed ‘X’ (using do-while loop). Stores these numbers in a newly created file. And
displays the minimum and maximum number when entered ‘X’.
 Read the file created in program III and display its contents character by character.
Lab Manual

Programing Fundamentals (Lab 11)

Target: Struct in C++

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:

Student s1, s2;


Then I can access the members of Student structure like this:

//Assigning name to first student


s1.stuName = "Ajeet";
//Assigning age to the second student
s2.stuAddr = 22;
Similarly we can set and get the values of other data members of the structure for every
student. Lets see a complete example to put this up all together:
Structure Example in C++

#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:

Enter Student Name: Negan


ENter Student Roll No: 4101003
Enter Student Age: 22
Student Record:
Name: Negan
Roll No: 4101003
Age: 22
Problem Set.

 Program to create a simple struct.


 C++ program to create a struct Student (rollno, name, semester, gpa). Store data of 10
students using this struct and display data.
 C++ program to create a struct Student (rollno, name, semester, gpa). Store data of 10
students using this struct and display data of student having max gpa.
 C++ program to create a struct Student (rollno, name, semester, gpa). Store data of 10
students using this struct and display data of student whose name starts with ‘A’ or ‘a’.
 C++ program to create a struct Employee(empid, name, designation, salary). Store data
of 10 employees using this struct and display data of employess having salary between
20000 to 40000 only.
 C++ program to create a struct Employee(empid, name, designation, salary). Store data
of 10 employees using this struct and display data of employess whose name contains any
vowel character.

You might also like