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

1-1 Lab Manual - Programming Fundamentals

Programming fundamental

Uploaded by

tayyabaliaqat373
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

1-1 Lab Manual - Programming Fundamentals

Programming fundamental

Uploaded by

tayyabaliaqat373
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

BS (Computer Science) 2023

LAB MANUAL
PROGRAMMING FUNDAMENTALS
Course Code: CS141

DEPARTMENT OF COMPUTER SCIENCE


FACULTY OF ENGINEERING & COMPUTER SCIENCES
NATIONAL UNIVERSITY OF MODERN LANGUAGES
H-9, ISLAMABAD
PAKISTAN

Programming Fundamentals (Lab Manual) Page 0 of 147


BS (Computer Science) 2023

Preface
The implementation of various issues is included in the lab manual for Programming Basics
to help students become familiar with the language's fundamentals. The full complement of
computer hardware and experiment-related software is available in the lab. The purpose of
programming fundamentals lab manual is to introduce students to the basic ideas behind
structured computer programming languages like C++. Studying computer fundamentals and
programming is important for students because it empowers them with critical tools, skills,
mindsets and knowledge to better succeed in education and future careers.

Objective
The course learning outcome along with domain and taxonomy level are listed below

S# CLO STATEMENT DOMAIN TAXONOMY


LEVEL

1 CLO 1: Acquire fundamental concepts of structured C C2


programming along with problem solving techniques and
analytical thinking.

2 CLO 2: Formulate C++ constructs to design solutions for C C3


small scale computational problems.

3 CLO 3: Analyze problem requirements to recognize what C C4


type of data and processes are involved in the solution.

* BT= Bloom’s Taxonomy, C=Cognitive domain, P=Psychomotor domain, A= Affective domain

Tools/ Technologies
• C++ Language
• Dev C++

Programming Fundamentals (Lab Manual) Page 1 of 147


BS (Computer Science) 2023

Effectiveness
● In this course, Student is able to learn and understand the basic requirements for
problem solving process. Many basic problems were given for practice in class and
students are evaluated through lab exams and quizzes.
● Student can analyze the flow of a process i.e. student can easily execute the working
of any algorithm.
● Student is able to understand all the basic and advance of C++. Many practice
examples were given for assessment of their concept understanding.

Weekly Breakdown
ASSIGNMENT
WEEK # TOPIC MATERIAL
/QUIZ
Introduction, Introduction to Programming
Languages, Benefits gained and obtained from
Programming Languages. Generations of Lecture slides
Week No 1
Programming Languages, Use of different Practice examples
languages in different generations. Working of
Compilers, and Linkers.
Introduction to C/C++, Advantages of using
C/C++, Character set White space characters, Lecture slides Lab
Week No 2
Naming rules in C/C++, Data types, Data type Practice examples Assignment 1
sizes, Types of C/C++ Instructions.
First program in C/C++, Preprocessor
directive, Function body, Statement
Lecture slides
Week No 3 terminator, Compiling and Executing the Assignment 1
Practice examples
program.

Variable definition and declaration, Escape


sequences, Arithmetic Operators, Relational Lecture slides
Week No 4 Quiz1
Operators, Input gathering and Type casting. Practice examples
Library Functions
Loops, for loop, nested for loop, Using for
Lecture slides Lab
Week No 5 loop with single and multiple statements,
Practice examples Assignment 2
while and nested while loop.
The do while loop, Difference between while
Lecture slides
Week No 6 and do while loop, Decision making
Practice examples
statements, if, if else and nested if else
Programming Fundamentals (Lab Manual) Page 2 of 147
BS (Computer Science) 2023

statements.

Using switch and break statements, Logical


Lecture slides
Week No 7 and Conditional Operators, Operators Quiz 2
Practice examples
Precedence, continue and goto statements.
Structures, Defining structures and structure
Lecture slides Assignment 2
Week No 8 variables, Accessing structure members,
Practice examples
Combining structure specifier and definition,.
Initializing Structure members, Structures Lecture slides
Week No 9
within structures, Enumerated data types, Practice examples
Functions, Functions Declaration. Function
Calling, Function Definition, and Eliminating
function declaration, Passing arguments to
Week No Lecture slides Lab
functions (by value). Passing variables to
10 Practice examples Assignment 2
functions, Passing structure variables to
functions, Returning values from functions,
Return statement.
Week No Overloading, Overloaded functions and Lecture slides
11 Examples, Inline functions. Practice examples
Arrays, Array Introduction, Defining and
Week No Lecture slides
Initializing Arrays, Strings arrays. Arrays Assignment 3
12 Practice examples
initialization , operations, passing to functions
Pointers, Pointers of Arrays, Pointer constants
Week No Lecture slides
and pointer variables, Passing pointers as Quiz 3
13 Practice examples
arguments, Pointer and Arrays
File Handling, Introduction to ifstream and
Week No Lecture slides Lab
ofstream, Writing to /from file, Simple
14 Practice examples Assignment 3
programs: word count, sentence count.
Introduction to Python, Advantages of using
Week No python, Character set White space characters, Lecture slides
15 Naming rules in python, Data types, First Practice examples
Program.
Variable definition and declaration.
Arithmetic Operators, Relational Operators,
Week No Lecture slides
Indentation. Examples, Loops, for loop,
16 Practice examples
nested for loop, Using for loop with single and
multiple statements, while and do while loop.

Programming Fundamentals (Lab Manual) Page 3 of 147


BS (Computer Science) 2023

Experiment
TOPICS TO BE COVERED
#

Introduction, Introduction to Programming Languages, to dev c++


Experiment No integrated development environment, installation of Dev C++. Introduction
1 to Dec C++, text editor, menu bars, creating a new file, saving a file,
compiling and execution of a program.

Writing first program in Dev C++, Code Explanation, Preprocessor Directive,


Experiment No
main function, terminator, header file. Compiling and execution of a program.
2
How to solve errors.

Simple Cout statement command, Cin command. Variable definition and


Experiment No
declaration. Integer, floating point and double variable declaration, Using
3
integers, float and double in programs.

What are Escape sequences. How they are used in a program. Arithmetic
Experiment No
Operators, Relational Operators, Input gathering and Type casting. Using
4
multiple Library Functions in a program.

Introduction to Loops, for loop, nested for loop, Using for loop with single and
Experiment No Multiple statements. Dry run and programming Examples of for
5 loop. Introduction to while and nested while loop. Dry run and programming
Examples of for loop

Experiment No The do while loop, Difference between while and do while loop,
6 Decision making statements, if, if else and nested if else statements.

Experiment No Using switch and break statements, Logical and Conditional


7 Operators, Operators Precedence, continue and goto statements.

Experiment No Structures, Defining structures and structure variables, Accessing


8 structure members, Combining structure specifier and definition,

Experiment No Initializing Structure members, Structures within structures,


9 Enumerated data types, Functions, Functions Declaration.

Programming Fundamentals (Lab Manual) Page 4 of 147


BS (Computer Science) 2023

Experiment No Function Calling, Function Definition, Eliminating function


10 declaration, Passing arguments to functions (by value).

Experiment No Passing variables to functions, Passing structure variables to


11 functions, Returning values from functions, Return statement.

Experiment No Returning structure variables, Passing arguments to functions


12 Overloaded functions, Inline functions.

Experiment No Storage classes of variables, Automatic variables, External variables


13 and Static variables, Defining and Initializing Arrays, Strings.

Experiment No
Arrays initialization , operations, , passing to functions, Multidimensional Arrays
14

Experiment No Pointers, Pointers of Arrays, Pointer constants and pointer variables,


15 Passing pointers as arguments, Pointer and functions.

Experiment No Python introduction, basic syntax, if else statements, break statement and
16 nested if, else if statements and conditional operators
Experiment No
Lists in python, collections, multi-dimensional lists, functions in python
17
Experiment No
Revision
18

Programming Fundamentals (Lab Manual) Page 5 of 147


BS (Computer Science) 2023

LAB 1: INTRODUCTION TO DEV C++ INTEGRATED


DEVELOPMENT ENVIRONMENT
Objectives:
IDE's is used to create software applications, drivers and utilities. It allows developing
software in any programming language without spending much time on language syntax. IDE
has the ability to correct syntaxes, gives a warning about memory leaks, assist in writing
quality of code, etc.

Theoretical Description:

• Basic introduction about IDE will help student to get familiar with an integrated
development environment (IDE)
• Helps student to get knowledge about the basic tools required to write and test
software.

Lab Task(s):

• Install Visual studio/ dev C++ IDE on your system

Programming Fundamentals (Lab Manual) Page 6 of 147


BS (Computer Science) 2023

INTRODUCTION TO DEV C++ INTEGRATED DEVELOPMENT


ENVIRONMENT
An integrated development environment (IDE) is a software suite that consolidates the basic
tools developers need to write and test software. Typically, an IDE contains a code editor, a
compiler or interpreter and a debugger that the developer accesses through a single graphical
user interface (GUI).

In computer program and software product development, the development environment is the
set of processes and programming tools used to create the program or software product. The
term may sometimes also imply the physical environment.

INSTALLATION TIPS
● Go to Website:
http://www.bloodshed.net/dev/devcpp.html
● Read “Requirements” Carefully.
DOWNLOAD SETUP

● Click “SourceForge”.

DOWNLOAD SETUP

● Click “Direct link”.

Programming Fundamentals (Lab Manual) Page 7 of 147


BS (Computer Science) 2023

SAVE SETUP

● Save setup on desktop.


SAVE SETUP

● Double click dev c++ setup icon.

INSTALLER WITH START

Programming Fundamentals (Lab Manual) Page 8 of 147


BS (Computer Science) 2023

SELECT LANGUAGE

LISCENESE AGREEMENT

CHOOSE COMPONENTS

CHOOSE DIECTORY

Programming Fundamentals (Lab Manual) Page 9 of 147


BS (Computer Science) 2023

INSTALLATION WILL START

INSTALLATION FINISHED

DEV C++ IDE

Programming Fundamentals (Lab Manual) Page 10 of 147


BS (Computer Science) 2023

SAVE FILE

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
cout<<"hello world";
getch();
}

Programming Fundamentals (Lab Manual) Page 11 of 147


BS (Computer Science) 2023

COMPILING THE PROGRAM

Programming Fundamentals (Lab Manual) Page 12 of 147


BS (Computer Science) 2023

OUTPUT

CODE EXPLANATION
● Preprocessor:
In computer science, a preprocessor is a program that processes its input data to produce
output that is used as input to another program. The output is said to be a preprocessed form
of the input data, which is often used by some subsequent programs like compilers.
● Preprocessor Directives:
# is called Preprocessor Directive. The # line tells the compiler to use a file <iostream.h>or
<stdio.h> or whatever written in <angle brackets>. Files having .h extension in C/C++are
called header files. They are also sometimes called include files. The iostream.h file is
included in the program as it contains the information about the “cout” identifier and the <<
operator. Normally all the header files of C/C++ are present in the INCLUDE directory.

Programming Fundamentals (Lab Manual) Page 13 of 147


BS (Computer Science) 2023

● Main Function:
A C/C++ program may consist of many functions, classes and other program elements, but
on startup, control always goes to main() function. The first statement executed by the C/C++
compiler will be the one that is the first statement in function void main(void) or Int main().In
C/C++ all the statements of a function, either it is main () or any other should be in blocks. A
block starts with {(starting brace), then we write statements in the function, and at the end we
put} (closing brace), in order to tell the compiler that the above written statements within the
block are the statements of a function. The body of a function starts from {and ends at}.
Every starting brace should have a closing brace. The statement cout<<” Welcome to C++”;
displays the string constant “Welcome to C++” on the screen. We can have one or more
statements inside a function. Statements tell the computer to do something. C/C++ statements
are always terminated by semicolon.
● Header File:
Header files contain definitions of Functions and Variables, which is imported or used into
any C++ program by using the pre-processor #include statement. Header file have an
extension ".h" which contains C++ function declaration and macro definition.

Programming Fundamentals (Lab Manual) Page 14 of 147


BS (Computer Science) 2023

LAB 2: INPUT OUTPUT COMMANDS

Objectives:

• Input and output, or I/O is the communication between an information processing


system, such as a computer, and the outside world, possibly a human or another
information processing system.
• Inputs are the signals or data received by the system and outputs are the signals or
data sent from it.

Theoretical Description:

• Student will get familiar with cin and cout commands that are two predefined objects
which represent standard input and output stream
• The standard output stream represents the screen, while the standard input stream
represents the keyboard. These objects are members of iostream class.

Lab Task(s):

• Use of Cin and Cout commands in programs.

Programming Fundamentals (Lab Manual) Page 15 of 147


BS (Computer Science) 2023

cout COMMAND
The cout command is basically used to show output on screen.
Task No. 01
Q: Write a program to calculate the total cost of apples if number of apples are 10 and
cost per apple is 5?
#include<iostream>
using namespace std;
int main()
{ int a=10,b=5,total;
total=a*b;
cout<<"Total Cost of Apples="<<total;
return 0;
}

Task No. 02
Q: Write a program to take any integer value and in another variable, add 5 to the
value enter by user by using endl display output in separate line.
#include<iostream>
using namespace std;
int main()
{
int a,b;
a=10;
b=a+5;
cout<<"A is"<<a<<endl;
cout<<"B is"<<b<<endl;
return 0;
}

Programming Fundamentals (Lab Manual) Page 16 of 147


BS (Computer Science) 2023

Task No. 03
Q: Write a program to take any integer value and in another variable add 5 to the value
enter by user without using endl, disdplay output on single line.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{ inta,b;
a=10; b=a+5;
cout<<"A is"<<a<<" and B is"<<b;
cout<<"Press any key to finish";
getch();
}

STUDENT TASKS:
1. Write a program to calculate the sum of three integers and store its result in fourth
variable.
2. Write a program to Display welcome message to the user.
3. Write a program to add, multiply, subtract and divide two integer variables. Use only
three variables in this program.

Programming Fundamentals (Lab Manual) Page 17 of 147


BS (Computer Science) 2023

LAB 3: INPUT OUTPUT COMMANDS

Objectives:

• Input and output, or I/O is the communication between an information processing


system, such as a computer, and the outside world, possibly a human or another
information processing system.
• Inputs are the signals or data received by the system and outputs are the signals or
data sent from it.

Theoretical Description:

• Student will get familiar with cin and cout commands that are two predefined objects
which represent standard input and output stream
• The standard output stream represents the screen, while the standard input stream
represents the keyboard. These objects are members of iostream class.

Lab Task(s):

• Use of Cin and Cout commands in programs.

Programming Fundamentals (Lab Manual) Page 18 of 147


BS (Computer Science) 2023

cin Command
The function cin>> reads a value into variable the user must press enter before the number is
read by the program. cin.ignore() is another function that reads and discards a character.
Task No. 01
Q: write a program to take three integer values from user and calculate the average and
display the output.
#include<iostream>
using namespace std;
int main()
{ int a,b,c,avg;
cout<<"1st Number:";
cin>>a;
cout<<"2nd Number:";
cin>>b;
cout<<"3rd Number:";
cin>>c;
avg=(a+b+c)/3;
cout<<"Average="<<avg;
return 0;
}

Task No. 02
Q: Writ a program to calculate total cost of three items. The price and quantity of item
taking from the user and display the total cost.
#include<iostream>
using namespace std;
int main()
{ int a,ap,b,bp,c,cp,total;
cout<<"Quantity of 1st Item=";
cin>>a;
cout<<"Price Per 1st Item=";
cin>>ap;
cout<<"Quantity of 2nd Item=";
cin>>b;
cout<<"Price Per 2nd Item=";
cin>>bp;
cout<<"Quantity of 3rd Item=";
cin>>c;
cout<<"Price Per 3rd Item=";
Programming Fundamentals (Lab Manual) Page 19 of 147
BS (Computer Science) 2023

cin>>cp;
total=(a*ap)+(b*bp)+(c*cp);
cout<<"Total Bill="<<total;
return 0; }

Task No. 03
Q: Write a program to take temperature in farenheit and convert into celcius and
display the output.
#include<iostream>
using namespace std;
int main()
{ doublea,b;
cout<<"Enter the temperature in farenheite=";
cin>>a;
b=(a-32)*5/9;
cout<<"Temperature in Celcius="<<b<<endl;
return 0; }

Task No. 04
Q: Write a program to calculate the sum, difference, and product, quotient of four
values entered by the user and display on screen.
#include<iostream>
using namespace std;
int main()
{ int a,b,sum,sub,mul,div,mod;
cout<<"Enter 1st Value=";
cin>>a;
cout<<"Enter 2nd Value=";
cin>>b;
sum=a+b;
cout<<"Summation="<<sum<<endl;
sub=a-b;
Programming Fundamentals (Lab Manual) Page 20 of 147
BS (Computer Science) 2023

cout<<"Subtraction="<<
sub<<endl;
mul=a*b;
cout<<"Multiplication="
<<mul<<endl;
div=a/b;
cout<<"Division="<<di
v<<endl;
mod=a%b;
cout<<"Modulus="<<mod;
return 0; }

Task No. 05
Q: Write A Program To Calculate Total Cost Of Apples. The Number Of Apples And
Cost Per Apple Is Enterd By The User.
#include<iostream>
using namespace std;
int main()
{
int a,b,total;
cout<<"No. of Apples=";
cin>>a;
cout<<"Cost per Apple=";
cin>>b;
total=a*b;
cout<<"Total Cost of Apples="<<total;
return 0;
}

Task No. 06
Q: write a program to calculate the sum of four values enterd by the user and display
on screen.
#include<iostream>
using namespace std;
int main()
{
double a,b,c,d,sum;
cout<<"Positive Num1=";
cin>>a;
cout<<"Positive Num2=";
Programming Fundamentals (Lab Manual) Page 21 of 147
BS (Computer Science) 2023

cin>>b;
cout<<"Positive num3=";
cin>>c;
cout<<"Positive Num4=";
cin>>d;
sum=a+b+c+d;
cout<<"Sum="<<sum;
return 0;
}

STUDENT TASK:
1. Write a program in c++ to input your name, address and age during program
execution and then print it on the screen.
2. Write a program in c++ to input an amount in rupees and then convert it into dollars
and then print the result on the screen.
3. Write a program in c++ to input your age in years, convert the age in months, days,
hours, minutes and seconds and then print all these values on the screen.

Programming Fundamentals (Lab Manual) Page 22 of 147


BS (Computer Science) 2023

LAB 4: “ESCAPE SEQUENCES, CONTROL STATEMENT AND


LIBRARY FUNCTIONS”
Objectives:

• Escape sequences useful for action specification


• Useful for tab movements on terminals and printers
• Provide literal representations of nonprinting characters and characters that usually
have special meanings, such as the double quotation mark (")
• Helps students to add multiple functionality in their programming tasks

Theoretical Description:

• An escape sequence in C language is a sequence of characters that doesn't represent


itself when used inside string literal or character
• Escape sequences are also known as Backslash Character Constants.

Lab Task(s):

• Use of escape sequence in C++ programs.

Programming Fundamentals (Lab Manual) Page 23 of 147


BS (Computer Science) 2023

ESCAPE SEQUENCES
\ is considered an escape sequence character that causes and escape from the
normal. Interpretation of a string so that the next character is recognized as
having a special meaning. Following are the escape sequence characters along
with their usage.
Escape Sequence Character
● \a Audible Alert
● \b Backspace
● \f Form feed
● \n New Line (Carriage Return + Line Feed)
● \r Return
● \t Tab
● \\ Backslash
● \’ Single quotation
● \” Double quotation
● \xDD \xDB Hexadecimal Representation
Task No. 01
Q: write a program to print the following text:
Hellow
How
Are
You
Hellow
How
Are
You

#include <iostream>
using namespace std;
int main()
{
cout<<"Hello\nHow\nAre\nYou\n";
cout<<"Hello\n\tHow\n\t\tAre\n\t\t\tYou\n";
return 0;

Programming Fundamentals (Lab Manual) Page 24 of 147


BS (Computer Science) 2023

IF ELSE STATEMENTS
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
The syntax of an if...else statement in C++
if(boolean_expression) {
}
else {
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.

Task No. 02
Q: Write a program which takes two integer values from user and shows that the values
are equal or not equal?
#include<iostream>
using namespace std;
int main()
{ int a,b;
cout<<"1st Integer=";
cin>>a;
cout<<"2nd Integer=";
cin>>b;
if(a==b)
{
cout<<"Equal";
}
Programming Fundamentals (Lab Manual) Page 25 of 147
BS (Computer Science) 2023

else
{
cout<<"Different";
}
return 0; }

Task No. 03
Q: Write a program that take character type value from user and display the value is
vowel or consonant?
include<iostream>
using namespace std;
int main(){
char alphabet;
char a,e,i,o,u,A,E,I,O,U;
cout<<"Enter alphabet"<<endl;
cin>>alphabet;
if(alphabet=='a'||alphabet=='e'||alphabet=='i'||alphabet=='o'||alphabet=='u'||alphabet=='
A'||alphabet=='E'||alphabet=='I'||alphabet=='O'||alphabet=='U')
{
cout<<"Alphabet is vowel";
}
else
{
cout<<"Alphabet is consonent";
}
return 0;
}

Programming Fundamentals (Lab Manual) Page 26 of 147


BS (Computer Science) 2023

getche() library function():


So far we’ve used only cin and >> for input. That approach requires that the user always
press the Enter key to inform the program that the input is complete. This is true even for
single characters: The user must type the character, and then press Enter. However, as in the
next example, program needs to process each character typed by the user without waiting for
an Enter.
The getche() library function performs this service. It returns each character as soon as
it’s typed.

Task No. 04
#include <iostream>
using namespace std;
#include <conio.h> // for getche()
main()
{
Programming Fundamentals (Lab Manual) Page 27 of 147
BS (Computer Science) 2023

int chcount=0;
char ch;
cout<<"Enter charater: ";
cin>>ch
cout<<ch<<endl<<endl <<"Letters : "<<ch<<endl;
getch();
}

STUDENT TASK:
1. Write a C++ Program that allows the user to type up to 10 numbers, and displays the
sum of all the numbers entered at the end. If the user enters 0, the break causes the
loop to terminate early (before 10 numbers have been entered).
2. Create the equivalent of a four-function calculator. The program should ask the user
to enter a number, an operator, and another number. (Use floating point.) It should
then carry out the specified arithmetical operation: adding, subtracting, multiplying,
or dividing the two numbers. Use a switch statement to select the operation. Finally,
display the result.
When it finishes the calculation, the program should ask whether the user wants to do
another calculation. The response can be ‘y’ or ‘n’. Some sample interaction with the
program might look like this:

Enter first number, operator, second number: 10 / 3


Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n

Programming Fundamentals (Lab Manual) Page 28 of 147


BS (Computer Science) 2023

LAB 5: “IF ELSE STATEMENTS, BREAK STATEMENT AND


NESTED IF”
Objectives:

• Controls conditional branching.


• Statements in the if-branch are executed only if the condition evaluates to a non-zero
value (or true ).
• If the value of condition is nonzero, the following statement gets executed, and the
statement following the optional else gets skipped.

Theoretical Description:

• An escape sequence in C language is a sequence of characters that doesn't represent


itself when used inside string literal or character
• Escape sequences are also known as Backslash Character Constants.
• Using switch and break statements, Logical and Conditional Operators, Operators
Precedence, continue and goto statements.

Lab Task(s):

• Use of escape sequence in C++ programs.

Programming Fundamentals (Lab Manual) Page 29 of 147


BS (Computer Science) 2023

Decision Making in C / C++ (if , if..else, Nested if, if-else-if )


There comes situations in real life when we need to make some decisions and based
on these decisions, we decide what should we do next. Similar situations arises in
programming also where we need to make some decisions and based on these decision
we will execute the next block of code.
Decision making statements in programming languages decides the direction of flow
of program execution. Decision making statements available in C++ are:
● if statement
● if..else statements
● nested if statements
● if-else-if ladder
● switch statements

nested-if
● A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, C++ allows
us to nest if statements within if statements. i.e, we can place an if statement
inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Programming Fundamentals (Lab Manual) Page 30 of 147


BS (Computer Science) 2023

● Flowchart:

Task No. 01
Q: Write a program which takes four integer vales from user and shows which value is
greater by using “nested if”.
#include<iostream>
using namespace std;
int main()
{ inta,b,c,d;
cout<<"Enter 1st Integer:";
cin>>a;
cout<<"Enter 2nd Integer:";
cin>>b;
cout<<"Enter 3rd Integer:";
cin>>c;
cout<<"Enter 4th Integer:";
cin>>d;
if(a>b)
{
if(a>c && a>d)
Programming Fundamentals (Lab Manual) Page 31 of 147
BS (Computer Science) 2023

{cout<<"Greatest Number="<<a; }
}
if(b>a) {
if(b>c && b>d)
{cout<<"Greatest Number="<<b; } }
if(c>a) {
if(c>b && c>d)
{cout<<"Greatest Number="<<c; } }
if(d>a) {
if(d>b && d>c)
cout<<"Greatest Number="<<d; }
return 0;}

Task No. 02
Q: Write a program that input marks of student and display either a student is passed
or fail.
#include<iostream>
using namespace std;
int main()
{
int mark ;
cin>>marks;
if (mark >= 50) {
cout << "You passed." << endl;
if (mark == 100) {
cout <<"Perfect!" << endl;
}
}
else {
cout << "You failed." << endl;
}
Task No. 03
Q:Write a program that input the birth year from the user. If the birth year is later
than 2000, then the program outputs the string “You were born in the 21st century”.
// NestedIf - demonstrate a nested if statement
//
#include <cstdio>
#include <cstdlib>
Programming Fundamentals (Lab Manual) Page 32 of 147
BS (Computer Science) 2023

#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{ // enter your birth year
int nYear;
cout << "Enter your birth year: ";
cin >> nYear;
// Make determination of century
if (nYear > 2000)
{ cout << "You were born in the 21st century" << endl;
}
else
{ cout << "You were born in ";
if (nYear < 1950)
{ cout << "the first half"; }
else
{ cout << "the second half"; }
cout << " of the 20th century"
<< endl; }
// wait until user is ready before terminating program
// to allow the user to see the program results
cout << "Press Enter to continue..." << endl;
cin.get();
return 0;
}
Task No. 04
Q: C++ program to add all number entered by user until user enters 0.
// C++ Program to demonstrate working of break statement
#include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;
// test expression is always true
cout<<"Enter a number: ";
cin>>number;
if (number != 0.0) {
sum += number;
}
else {
break; // terminating the loop if number equals to 0.0
}
}
cout<<"Sum = "<<sum;
return 0;}
Programming Fundamentals (Lab Manual) Page 33 of 147
BS (Computer Science) 2023

LAB 6: “ELSE IF STATEMENTS AND CONDITIONAL OPERATORS”


Objectives:

• Allows execution of statements in a more controlled way.


• Statements in the if-branch are executed only if the condition evaluates to a non-zero
value (or true ).
• If the value of condition is nonzero, the following statement gets executed, and the
statement following the optional else gets skipped.

Theoretical Description:
C++ has the following conditional statements: Use if to specify a block of code to be
executed, if a specified condition is true.
...
C++ Conditions and If Statements

1. Less than: a < b.


2. Less than or equal to: a <= b.
3. Greater than: a > b.
4. Greater than or equal to: a >= b.
5. Equal to a == b.
6. Not Equal to: a != b.

Lab Task(s):

• Use of else if statements in c++ programs

Programming Fundamentals (Lab Manual) Page 34 of 147


BS (Computer Science) 2023

If ELSE IF STATEMENT
if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.When using if , else if , else
statements there are few points to keep in mind. if can have zero or one else's and it must
come after any else if's. if can have zero to many else if's and they must come before the
else. Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if...else if...else statement in C++ is
if( ) {
}
else if( boolean_expression 2) {
}
else if( boolean_expression 3) {
}
else {
}

Task No. 01
Q: Write a program that take total marks from the user and display the grade by using
‘if-else if’ statement.
#include<iostream>
using namespace std;
int main(){
//conditional statements
int marks;
cout<<"Enter total marks"<<endl;
cin>>marks;
if(marks>50&&marks<=60)
{
cout<<"Grade C";
}
else if(marks>60&&marks<=70)
{
cout<<"Grade B";
}
else if(marks>70&&marks<=80)
{ cout<<"Grade A"; }

Programming Fundamentals (Lab Manual) Page 35 of 147


BS (Computer Science) 2023

else if(marks>80)
{ cout<<"Grade A+"; }
return 0;
}

Task No. 02
Q: Writ a program to calculate the electricity bill. Taking the number of units from
user by using ‘if-else if’ statement display the total bill.
#include<iostream>
using namespace std;
int main(){
int units;
int bill;
cout<<"Units consumed are"<<endl;
cin>>units;
if(units>=1&&units<=100)
{
bill=units*7;
cout<<"Bill is"<<bill;
}
else if(units>100&&units<=300)
{
bill=units*13;
cout<<"Bill is"<<bill;
}
else if(units>300&&units<=500)
{
bill=units*18;
cout<<"Bill is"<<bill;
}
return 0;}

Programming Fundamentals (Lab Manual) Page 36 of 147


BS (Computer Science) 2023

Task No. 03
Q: write a program to take an integer value from user and dislay the value is even or
odd?
#include<iostream>
using namespace std;
int main(){
int number;
cout<<"Enter a number"<<endl;
cin>>number;
if(number%2==1)
{
cout<<"Number is odd";
}
else if(number%2==0)
{
cout<<"Number is even";
}
return 0;
}

Task No. 04
Q: write a program to calculate the net pay. Take the basic from user. The house rent is
45% of basic pay. If basic pay is greater than 5000 than medical allowance is 2% of
basic pay and if it is less than 5000 than medical allowance is 5% of basic pay. If basic
pay is greater than 5000 than conveyance allowance is 96 and if it is less than 5000 than
conveyance allowance is 193 allowances is 5% of basic pay. Net pay is sum of house
rent, medical and convince allowance.
#include<iostream>
using namespace std;
int main(){
int net_pay;
int basic_pay;

Programming Fundamentals (Lab Manual) Page 37 of 147


BS (Computer Science) 2023

int house_rent;
int medical_allowance;
int conveyance_allowance;
cout<<"Enter basic pay"<<endl;
cin>>basic_pay;
house_rent=45*basic_pay/100;
cout<<"House rent is"<<house_rent<<endl;
if(basic_pay>5000)
{
medical_allowance=2*basic_pay/100;
cout<<"Medical allowance is"<<medical_allowance<<endl;
}
else if(basic_pay<5000)
{
medical_allowance=5*basic_pay/100;
cout<<"Medical Allowance is"<<medical_allowance<<endl;
}
if(basic_pay<5000)
{
conveyance_allowance=96;
cout<<"Conveyance allowance is"<<conveyance_allowance<<endl;
}
else if(basic_pay>5000)
{
conveyance_allowance=193;
cout<<"Conveyance allowance is"<<conveyance_allowance<<endl;
}
net_pay=basic_pay+house_rent+medical_allowance+conveyance_allowance;
cout<<"Net pay is"<<net_pay;
return 0; }

Task No. 05
Write a program that will take three values a, b and c and prints the roots, if real , of
the quadratic equation (a(x*x) + bx + c = 0).
SOURCECODE:
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
Programming Fundamentals (Lab Manual) Page 38 of 147
BS (Computer Science) 2023

int main(){while (true) {


float num1, num2, num3;
cout << "Enter any three numbers : " << endl;
cin >> num1 >> num2 >> num3;
cout << "(" << num1 << ")(x*x) + (" << num2 << ")(x) + (" << num3 << ")"
<< endl;
if (num1 == 0){
cout << "Sorry we can not help you " << endl;
}
else {
float negationnum2 = -1 * num2;
float sqrnum2 = num2 * num2;
float fournum1num3 = 4 * num3*num1;
float twonum1 = 2 * num1;
float fsqrtpart = sqrnum2 - fournum1num3;
float sqrtv = sqrt(fsqrtpart);
float add = negationnum2 + sqrtv;
float sub = negationnum2 - sqrtv;
float divadd = add / twonum1;
float divsub = sub / twonum1;
if (fsqrtpart < 0) {
cout << "Sorry the roots are not real" << endl;}
else
cout << "roots are : " << divadd << " And " << divsub << endl;
}
}system("pause");
return 0;
}

OUTPUT:

CONDITIONAL OPERATORS

This operator consists of two symbols, which operate on three operands.

Programming Fundamentals (Lab Manual) Page 39 of 147


BS (Computer Science) 2023

It is same as we write:

● The part of this statement to the right of the equal sign is called the
conditional expression:
● The question mark and the colon make up the conditional operator. The
expression before the question mark is the test expression.
● If the test expression is true, the entire conditional expression takes on the
value of the operand following the question mark: alpha in this example.
● If the test expression is false, the conditional expression takes on the
value of the operand following the colon: beta.
Task No. 06
Q: Input a single letter in a char variable if ‘m’ is input, print “you are
male” otherwise print “you are female” by using conditional expression
operator.
#include<iostream>
using namespace std;
int main()
{ char g;
cout<<"Enter any letter:";
cin>>g;
(g=='m')?cout<<"You are male":cout<<"You are female";
return 0;
}}

Programming Fundamentals (Lab Manual) Page 40 of 147


BS (Computer Science) 2023

LAB 7: “SWITCH STATEMENT, SETW() AND ASCII CHARACTERS”


Objectives:

• The switch statement allows us to execute a block of code among many alternatives.
• A switch statement causes control to transfer to one labeled-statement in its statement
body, depending on the value of condition.
• The C++ switch statement executes one statement from multiple conditions.

Theoretical Description:
The switch statement evaluates an expression, matching the expression's value against a
series of case clauses, and executes statements after the first case clause with a matching
value, until a break statement is encountered.

Lab Task(s):

• Use of switch statements in c++ programs

Programming Fundamentals (Lab Manual) Page 41 of 147


BS (Computer Science) 2023

SWITCH STATEMENT
If you have a large decision tree, and all the decisions depend on the value of the same
variable, you will probably want to consider a switch statement instead of a ladder of if...else
or else if constructions.
● The keyword switch is followed by a switch variable in parentheses.
● Braces { } then delimit a number of case statements.
● Each case keyword is followed by a constant (i.e., integer or character constant),
which is not in parentheses but is followed by a colon.
● The data type of the case constants should match that of the switch variable.
● Before entering the switch, the program should assign a value to the switch variable.
● This value will usually match a constant in one of the case statements.
● When this is the case the statements immediately following the keyword case will be
executed, until a break is reached.
Task no. 01
Q: write a program which takes character value from user and dislpay that the value is
vowel or consonant by switch statement?
#include<iostream>
using namespace std;
int main()
{ char ch;
cout<<"Enter any alphabet:";
cin>>ch;
switch(ch)
{ case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':

Programming Fundamentals (Lab Manual) Page 42 of 147


BS (Computer Science) 2023

case 'U':
cout<<"Vowel"; break;
default:
cout<<"Consonant"; }
}

Task No. 02
Q: Write a program which take character type data from user such type that if user
enter 1 then it display “one” upto 9 “nine”?
#include<iostream>
using namespace std;
int main()
{ int n;
cout<<"Enter any number from 0 to 9=";
cin>>n;
switch(n)
{ case 0:
cout<<"Zero"; break;
case 1:
cout<<"One"; break;
case 2:
cout<<"Two"; break;
case 3:
cout<<"Three"; break;
case 4:
cout<<"Four"; break;
case 5:
cout<<"Five"; break;
case 6:
cout<<"Six"; break;
case 7:
cout<<"Seven"; break;
Programming Fundamentals (Lab Manual) Page 43 of 147
BS (Computer Science) 2023

case 8:
cout<<"Eight"; break;
case 9:
cout<<"Nine"; break;
default:
cout<<"Wrong Input"; }
return 0;
}

SETW( )
setw( ) is library function in C++. It is declared inside #include<iomanip>. It will set field
width. Setw() sets the number of characters to be used as the field width for the next insertion
operation.
cout<<”Love”<<setw(10)<<”Pakistan”;
Task No. 03
Q: write a program which takes length and breadth and calculate area and parameter
of rectangle, with the use of “setw” display the output.
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{ float length,breadth;
double area,perimeter;
cout<<"Enter the length and breadth of rectangle:";
cin>>length>>breadth;
area=length*breadth;
perimeter=2*(length+breadth);
cout<<endl;
cout<<setw(20)<<"Area is:"<<setw(5)<<area<<endl<<setw(20)<<"Perimeter
is:"<<setw(5)<<perimeter;
return 0;
}

Programming Fundamentals (Lab Manual) Page 44 of 147


BS (Computer Science) 2023

ASCII CHARACTERS
A character variable holds ASCII value (an integer number between 0 and 127) rather than
that character itself in C programming. That value is known as ASCII value. For example,
ASCII value of 'A' is 65. What this means is that, if you assign 'A' to a character variable, 65
is stored in that variable rather than 'A' itself.
Task No. 04
Q: Write a program in which user enter the enteger number between o to 127, then
according to that number ASCII character is displayed in output?
#include<iostream>
using namespace std;
int main()
{ int x;
cin>>x;
cout<<(char)x<<endl;
}

Task No. 5

Q: Write a program in which four values are given var1=5, var2=3, var3=5, var4=3,
var5=5, var6=6. Perform modulus with each other like (var1%var2) and display the
output?
#include<iostream>
using namespace std;
int main()
{ int var1=5,var2=3;
int var3=5,var4=3;
int var5=5,var6=6;
cout<<var1%var2<<endl;
cout<<var3%var4<<endl;
cout<<var5%var6<<endl;
return 0;
}

Programming Fundamentals (Lab Manual) Page 45 of 147


BS (Computer Science) 2023

LAB 8: “LOOPS”
Objectives:

• Loops are programming elements that repeat a portion of code a set number of times
until the desired process is complete.
• Repetitive tasks are common in programming, and loops are essential to save time and
minimize errors.

Theoretical Description:

• The purpose of loops is to repeat the same, or similar, code a number of times.
• Loops are among the most basic and powerful of programming concepts

Lab Task(s):

• Use of loop statements in c++ programs

Programming Fundamentals (Lab Manual) Page 46 of 147


BS (Computer Science) 2023

LOOPS
There may be a situation, when you need to execute a block of code several numbers of
times. Loops causes a section of your program to be repeated a certain number of times. The
repetition continues while a condition is true a certain number of times. When the condition
becomes false, the loop ends and control passes to the statements following the loop.
There are three kinds of loops in C++:
● for loop.
● while loop.
● do loop.
FOR LOOP
The for loop executes a section of code a fixed number of times. It’s usually (although not
always) used when you know, before entering the loop, how many times you want to execute
the code.
How does it works?
● The for statement controls the loop.
● It consists of the keyword for, followed by parentheses that contain three expressions
separated by semicolons.
For(j=0; j<=15; j++)
● These three expressions are the initialization expression, the test expression, and the
increment expression.
● These three expressions usually (but not always) involve the same variable, which we
call the loop variable.
THE INITIALIZATION EXPRESSION
The initialization expression is executed only once, when the loop first starts. It gives the
loop variable an initial value.
THE TEST EXPRESSION
● The test expression usually involves a relational operator.
● It is evaluated each time through the loop, just before the body of the loop is executed.
● It determines whether the loop will be executed again.
● If the test expression is true, the loop is executed one more time.
● If it’s false, then loop ends, and control passes to the statements following the loop.
THE INCREMENT/DECREMENT EXPRESSION
● The increment expression changes the value of the loop variable, often by
incrementing it.
● It is always executed at the end of the loop, after the loop body has been executed.

Programming Fundamentals (Lab Manual) Page 47 of 147


BS (Computer Science) 2023

Task No. 01
Q: Write a program that display the counting from 1 to 10 using for loop.
#include<iostream>
using namespace std;
int main()
{
int j;
for(j=1;j<=10;j++)
{
cout<<j;
}
return 0;
}

Task No. 02
Q: Write a program that display the counting from 1 to 10 using for loop
and endl.
#include<iostream>
Programming Fundamentals (Lab Manual) Page 48 of 147
BS (Computer Science) 2023

using namespace std;


int main()
{
int j;
for(j=1;j<=10;j++)
{
cout<<j<<endl;
}
return 0;
}

WHILE LOOP
The while loop looks like a simplified version of the for loop. It contains a test expression but
no initialization or increment expressions.
Although there is no initialization expression, the loop variable must be initialized before the
loop begins.
The loop body must also contain some statement that changes the value of the loop variable;
otherwise the loop would never end.
Int i=0;
While(i<=15)
i++;

Programming Fundamentals (Lab Manual) Page 49 of 147


BS (Computer Science) 2023

Task No. 03
Q: Write a program that display the counting from 1 to 10 using while
loop.
#include<iostream>
using namespace std;
int main()
{
int j=0;
while(j<=10)
{
cout<<j;
j++;
}
return 0;
}

Task No. 04
Q: Write a program that display the counting from 1 to 10 using while loop and endl.
#include<iostream>
using namespace std;
int main()
{ int j=0;
while(j<=10)
{ cout<<j<<endl;
j++;
}
return 0;
}

Programming Fundamentals (Lab Manual) Page 50 of 147


BS (Computer Science) 2023

DO WHILE LOOP
In a while loop, the test expression is evaluated at the beginning of the loop. If the test
expression is false when the loop is entered, the loop body won’t be executed at all. But
sometimes you want to guarantee that the loop body is executed at least once, no matter what
the initial state of the test expression. When this is the case you should use the do loop, which
places the test expression at the end of the loop.
● The keyword do marks the beginning of the loop.
● Then, as with the other loops, braces delimit the body of the loop.
● Finally, a while statement provides the test expression and terminates the loop.
● This while statement looks much like the one in a while loop, except for its position at
the end of the loop and the fact that it ends with a semicolon.
Task No. 05
Q: Write a program on division is perform on two values and also display the quotient
and remainder and ask from user if it can be continue so press ‘y’ using do while.
#include<iostream>
using namespace std;
int main()
{ char ch;
int dividend,divisor;
do
{ cout<<"Enter dividend: ";
cin>>dividend;
cout<<"Enter divisor: ";
cin>>divisor;
cout<<"Quotient is "<<dividend/divisor<<endl;
cout<<"Remainder is "<<dividend%divisor<<endl;
cout
<<"If you want to do it again press 'y'";
cin>>ch;
}
while(ch=='y');
cout<<endl;
return 0;
}
Programming Fundamentals (Lab Manual) Page 51 of 147
BS (Computer Science) 2023

NESTED LOOPS
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
The syntax for a nested for loop statement in C++
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s);
}
Task No. 07
Q: Write a program to print 10 stars horizontally using for loop.
#include<iostream>
using namespace std;
int main()
{ int j;
for(j=1;j<=10;j++)
{ cout<<"*"; }
return 0;
}

Task No. 08
Q: Write a program to print 10 stars vertically using for loop.
#include<iostream>
using namespace std;
int main()
{ int j;
for(j=1;j<=10;j++)
{ cout<<"*"<<endl; }
return 0;
}
Programming Fundamentals (Lab Manual) Page 52 of 147
BS (Computer Science) 2023

Task No. 09
Q. Write a program to create the following pattern using while loop.
*
**
***
****
*****
#include<iostream>
using namespace std;
int main()
{ int a,b;
a=1;
while(a<=5)
{
b=1;
while(b<=a)
{
cout<<"*";
b++;
}
cout<<endl;
a++;
}
return 0;
}

STUDENT TASK:
Programming Fundamentals (Lab Manual) Page 53 of 147
BS (Computer Science) 2023

1. Write a program in c++ to print the sum of odd numbers of first 10 natural numbers
by using the for loop.
2. Write the above program by using while loop.
3. Write the above program by using do while loop.
4. Write a program in c++ to calculate the product of the even numbers from 1 to 12by
using while loop.
5. Write a program in c++ to calculate (ab) without using any built-in-function.

Programming Fundamentals (Lab Manual) Page 54 of 147


BS (Computer Science) 2023

LAB 9: “NESTED LOOPS”

Objectives:

Theoretical Description:

Lab Task(s):

Programming Fundamentals (Lab Manual) Page 55 of 147


BS (Computer Science) 2023

NESTED LOOPS
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
The syntax for a nested for loop statement in C++
for ( init; condition; increment ) {
for ( init; condition; increment ) {
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C++
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C++
do {
statement(s); // you can put more statements.
do {
statement(s);
} while( condition );

} while( condition );
Task No. 01

Q. Write a program to create the following pattern using for loop.


*
**
***
****
*****
#include<iostream>
using namespace std;
int main()
{ int a,b;
for(a=1;a<=5;a++)
{ for(b=1;b<=a;b++)
{ cout<<"*"; }
cout<<endl;
}
return 0;
Programming Fundamentals (Lab Manual) Page 56 of 147
BS (Computer Science) 2023

Task No. 02
Q. Write a program to create the following pattern using while loop.
1
1
1
2
2
2
3
3
3
4
4
4
5
5

#include<iostream>
using namespace std;
int main()
{ int a,b;
a=1;
while(a<=5)
{ b=1;
while(b<=3)
{ cout<<a<<endl; b++;
}
a++; }
return 0;
}

Programming Fundamentals (Lab Manual) Page 57 of 147


BS (Computer Science) 2023

Task No. 03
Q. Write a program to create the following pattern using for loop.
1
1
1
2
2
2
3
3
3
4
4
4
5
5
5
#include<iostream>
using namespace std;
int main()
{ int a,b;
for(a=1;a<=5;a++)
{
for(b=1;b<=3;b++)
{
cout<<a<<endl;
}
}
return 0;
}

Programming Fundamentals (Lab Manual) Page 58 of 147


BS (Computer Science) 2023

Task No. 04
Q. Write a program to create the following pattern using while loop.
1
2
3
1
2
3
1
2
3
1
2
3
1
2
3

#include<iostream>
using namespace std;
int main()
{ int a,b;
a=1;
while(a<=5)
{ b=1;
while(b<=3)
{ cout<<b<<endl;
b++;
}
a++; }
return 0;
}

Programming Fundamentals (Lab Manual) Page 59 of 147


BS (Computer Science) 2023

Task No. 05
Q. Write a program to create the following pattern using for loop.
1
2
3
1
2
3
1
2
3
1
2
3
1
2
3
#include<iostream>
using namespace std;
int main()
{ int a,b;
for(a=1;a<=5;a++)
{
for(b=1;b<=3;b++)
{
cout<<b<<endl;
}
}
return 0;
}

Programming Fundamentals (Lab Manual) Page 60 of 147


BS (Computer Science) 2023

Task No. 06
Q. Write a program to create the following pattern using while loop.
1
22
333
4444
55555
#include<iostream>
using namespace std;
int main()
{ int a,b;
a=1;
while(a<=5)
{ b=1;
while(b<=a)
{ cout<<a;
b++;
}
cout<<endl;
a++; }
return 0;
}

Programming Fundamentals (Lab Manual) Page 61 of 147


BS (Computer Science) 2023

Task No. 07
Q. Write a program to create the following pattern using for loop.
1
22
333
4444
55555
#include<iostream>
using namespace std;
int main()
{ int a,b;
for(a=1;a<=5;a++)
{ for(b=1;b<=a;b++)
{ cout<<a; }
cout<<endl;
}
return 0;
}

Task No. 08
Q. Write a program to create the following pattern using while loop.
1
12
123
1234
12345
#include<iostream>
using namespace std;
int main()
{ int a,b; a=1;
while(a<=5)
{ b=1;
while(b<=a)
{ cout<<b;
b++;
}
Programming Fundamentals (Lab Manual) Page 62 of 147
BS (Computer Science) 2023

cout<<endl;
a++; }
return 0;
}

Task No. 09
Q. Write a program to create the following pattern using for loop.
1
12
123
1234
12345
#include<iostream>
using namespace std;
int main()
{ int a,b;
for(a=1;a<=5;a++)
{ for(b=1;b<=a;b++)
{cout<<b;
}
cout<<endl;
}
return 0;
}

Task No. 10
Q. Write a program to create the following pattern using while loop.
A
BB
Programming Fundamentals (Lab Manual) Page 63 of 147
BS (Computer Science) 2023

CCC
DDDD
EEEEEE
#include<iostream>
using namespace std;
int main()
{ char a,b;
a='A';
while(a<='E')
{ b='A';
while(b<=a)
{cout<<char(a);
b++; }
cout<<endl;
a++; }
return 0;
}

Task No. 11
Q. Write a program to create the following pattern using for loop.
A
BB
CCC
DDDD
EEEEEE

#include<iostream>
using namespace std;
int main()
{
char a,b;
for(a='A';a<='E';a++)
{
for(b='A';b<=a;b++)
Programming Fundamentals (Lab Manual) Page 64 of 147
BS (Computer Science) 2023

{
cout<<char(a);
}
cout<<endl;
}
return 0;
}

Task no. 12
Q. Write a program to create the following pattern using while loop.
A
AB
ABC
ABCD
ABCDE
#include<iostream>
using namespace std;
int main()
{ char a,b;
a='A';
while(a<='E')
{ b='A';
while(b<=a)
{ cout<<char(b);
b++;
}
cout<<endl;
a++; }
return 0;
}

Programming Fundamentals (Lab Manual) Page 65 of 147


BS (Computer Science) 2023

Task No. 13
Q. Write a program to create the following pattern using for loop.
A
AB
ABC
ABCD
ABCDE

#include<iostream>
using namespace std;
int main()
{
char a,b;
for(a='A';a<='E';a++)
{ for(b='A';b<=a;b++)
{
cout<<char(b);
}
cout<<endl;
}
return 0;
}

Task No. 14
Q: Draw a pattern.
SOURCECODE:
#include <iostream>
using namespace std;
int main(){
for (int i = 1 ; i<= 7; i++)
{ for (int j = 1, k = 13 ; j <= 13 ; j++,k--)
{ if(i==1 && j== 7)
{ cout << j << " "; }
else if( i == 1 && j>=8)
{ cout << k <<" "; }
else if( i== 2 )
{ if (j==7 )
cout <<" ";
else if (j>=8)
Programming Fundamentals (Lab Manual) Page 66 of 147
BS (Computer Science) 2023

cout <<k << " ";


else
cout <<j<< " ";
} else if( i == 3)
{if (j>=6 && j<=8 )
cout <<" ";
else if (j>=8)
cout <<k << " ";
else
cout <<j<< " ";
} else if( i == 4)
{if (j>=5 && j<=9 )
cout <<" ";
else if (j>=8)
cout <<k << " ";
else
cout <<j<< " ";
} else if( i == 5)
{if (j>=4 && j<=10 )
cout <<" ";
else if (j>=8)
cout <<k << " ";
else
cout <<j<< " ";
} else if( i == 6)
{if (j>=3 && j<=11 )
cout <<" ";
else if (j>=8)
cout <<k << " ";
else
cout <<j<< " ";
} else if( i == 7)
{if (j>=2 && j<=12 )
cout <<" ";
else if (j>=8)
cout <<k << " ";
else
cout <<j<< " ";
}
else
{ cout<< j<<" "; }

Programming Fundamentals (Lab Manual) Page 67 of 147


BS (Computer Science) 2023

OUTPUT:

Task No. 15
Write a program which shows finds the prime numbers between 100 and 500 and also
checks whether these numbers are palindrome or not if yes then displays the numbers .
SOURCECODE:
#include<iostream>
using namespace std ;
int main (){
for (int i = 100; i<= 500 ; i++){
int p = 1 ;
for (int j = 2; j<= i/2 ; j++){
if (i%j== 0)
{ p=0;
break; } }
if (p==1){ int prime = i;
int r = 0 ;
int reverse = 0 ;
while (prime != 0){
r= prime%10;
if (r == 0 && prime >= 1 && prime <=9)
{reverse = reverse*10 + prime;
} else {reverse = reverse*10 + r;
}
prime = prime / 10; }
if (reverse == i )
cout<< i<<endl;
} } }

Programming Fundamentals (Lab Manual) Page 68 of 147


BS (Computer Science) 2023

STUDENT TASK:

1. Write a program in c++ to print the output as given below:


xxxxxx
xxxxx
xxxx
xxx
xx
x
2. Write a program in c++ to print the output as given below:
xxxxxx
xxxxx
xxxx
xxx
xx
x
3. Write a program in c++ to print the output as given below:
Y
YY
YYY
YYYY
XXXX
XXX
XX

Programming Fundamentals (Lab Manual) Page 69 of 147


BS (Computer Science) 2023

LAB 10: “ARRAYS”


Objectives:

• In coding and programming, an array is a collection of items, or data, stored in


contiguous memory locations, also known as database systems.
• The purpose of an array is to store multiple pieces of data of the same type together.
• Easier to store elements of same data type.
• Used to implement other data structures like stack and queue.
• Convenient way to represent matrices as a 2D array

Theoretical Description:

• As An array is a collection of similar data elements stored at contiguous memory


locations that represent datatypes.
• In this lab student will learn about Arrays and functions, passing to functions, Passing
arguments to functions (by value). Passing variables to functions, passing structure
variables to functions, Returning values from functions, Return statement.

Lab Task(s):
Student will implement various C++ programs using the concepts of Array.

Programming Fundamentals (Lab Manual) Page 70 of 147


BS (Computer Science) 2023

C++ Array
An array is a series of elements of the same type placed in contiguous memory locations that
can be individually referenced by adding an index to a unique identifier. That means that, for
example, five values of type int can be declared as an array without having to declare 5
different variables (each with its own identifier). Instead, using an array, the five int values
are stored in contiguous memory locations, and all five can be accessed using the same
identifier, with the proper index.

Example:
For example, an array containing 5 integer values of type int called foo could be represented
as:

TYPES:

Arrays are divided into two types:


⮚ One-dimensional Arrays
⮚ Multi-dimensional Arrays

ONE – DIMENSIONAL ARRAYS:


One – dimensioall arrays is known as list or a linear array. It consists of only
one column or one row.
Example:
For example the temperature of each hour of a day is stored in an array.
The name of the array is “temp” and its elements are
temp[0],temp[1],temp[2],temp[3],……….temp[23].

DECLARING ARRAYS
like a regular variable, an array must be declared before it is used. A typical declaration for
an array in C++ is:
type name [elements]; .
Therefore, the foo array, with five elements of type int, can be declared as:
int foo [5];
The elements field within square brackets [], representing the number of elements in the
array, must be constant expression, since arrays are blocks of static memory whose size must
be determined at compile time, before the program runs.

Programming Fundamentals (Lab Manual) Page 71 of 147


BS (Computer Science) 2023

INITIALIZING ARRAYS
The elements in an array can be explicitly initialized to specific values when it is declared, by
enclosing those initial values in braces [].
For example: int foo [5] = { 16, 2, 77, 40, 12071 };

The number of values between braces [] shall not be greater than the number of elements in
the array. For example, in the example above, foo was declared having 5 elements (as
specified by the number enclosed in square brackets, []), and the braces [] contained exactly 5
values, one for each element.
If declared with less, the remaining elements are set to their default values (which for
fundamental types, means they are filled with zeroes). For example:

int bar [5] = { 10, 20, 30 };

Will create an array like this:

The initializer can even have no values, just the braces:

int baz [5] = { };

This creates an array of five int values, each initialized with a value of zero:

When an initialization of values is provided for an array, C++ allows the possibility of
leaving the square brackets empty []. In this case, the compiler will assume automatically a
size for the array that matches the number of values included between the braces {}:

int foo [] = { 16, 2, 77, 40, 12071 };

After this declaration, array foo would be 5 int long, since we have provided 5 initialization
values.
ACCESSING THE VALUES OF AN ARRAY:
The values of any of the elements in an array can be accessed just like the value of a regular
variable of the same type. The syntax is: For example, the following statement stores the
value 75 in the third element of foo:
foo [2] = 75;

Programming Fundamentals (Lab Manual) Page 72 of 147


BS (Computer Science) 2023

Following copies the value of the third element of foo to a variable called x:
x = foo[2];

In C++, it is syntactically correct to exceed the valid range of indices for an array. This can
create problems, since accessing out-of-range elements do not cause errors on compilation,
but can cause errors on runtime. The reason for this being allowed will be seen in a later
when pointers are introduced.
TASK NO. 01
Q: Write a program to calculate sum of all the elements of array using loop.
#include <iostream>
using namespace std;
int foo [] = {1, 2, 3, 4, 5};
int n, result=0;
int main ()
{ for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result<<endl;
return 0;
}

TASK NO. 02
#include<iostream>
using namespace std;
int main()
{ int a=2; int b=1;int foo[5];
foo[0] = a;
cout<<foo[0]<<endl;
foo[a] = 75;
cout<<foo[a]<<endl;
b = foo [a+2];
cout<<b<<endl;
foo[foo[a]] = foo[2] + 5;
cout<<foo[foo[a]]<<endl;
Programming Fundamentals (Lab Manual) Page 73 of 147
BS (Computer Science) 2023

TASK NO. 03
Q: Write a program to initialized the values to array and display the enter by user with
array index.
#include<iostream>
using namespace std;
int main(){
float a[3];
a[0]=20;
a[1]=30;
a[2]=50;
for(int i=0;i<3;i++)
{ cout<<a[i]<<endl; }
return 0;
}

TASK NO. 04

Q: Write a program to initialize the values to array and then add these values and
display the sum.
#include<iostream>
using namespace std;
int foo[]={1,2,3,4,5};
int n,result=0;
int main(){
for(n=0;n<5;++n)

Programming Fundamentals (Lab Manual) Page 74 of 147


BS (Computer Science) 2023

result+=foo[n]; }
cout<<result<<endl;
return 0; }

TASK NO. 05
Q: Write a program in which size of array is 5 and then take values from user and
dipaly in reverse order the values enterd by user.
#include<iostream>
using namespace std;
int main(){
int a[5];
for(int i=0;i<3;i++)
{ cout<<"Enter a value"<<endl;
cin>>a[i];
}
cout<<endl;
cout<<"Reverse order is"<<endl;
for(int i=2;i>=0;i--)
{ cout<<a[i]<<endl; }
return 0;
}

TASK NO. 06
Q: Write a program using array of size of 5 and take values from user then display the
greatest value.
#include<iostream>
using namespace std;
Programming Fundamentals (Lab Manual) Page 75 of 147
BS (Computer Science) 2023

int main(){
int a[5];
for(int i=0;i<5;i++)
{ cout<<"Enter a number"<<endl;
cin>>a[i];
}
cout<<endl;
if(a[0]>a[1] && a[0]>a[2] && a[0]>a[3] && a[0]>a[4])
{ cout<<a[0]<<" is greatest"; }
else if(a[1]>a[0] && a[1]>a[2] && a[1]>a[3] && a[1]>a[4])
{ cout<<a[1]<<" is greatest"; }
else if(a[2]>a[0] && a[2]>a[1] && a[2]>a[3] && a[2]>a[4])
{ cout<<a[2]<<" is greatest"; }
else if(a[3]>a[0] && a[3]>a[1] && a[3]>a[2] && a[3]>a[4])
{ cout<<a[3]<<" is greatest"; }
else if(a[4]>a[0] && a[4]>a[1] && a[4]>a[2] && a[4]>a[3])
{ cout<<a[4]<<" is greatest"; }
return 0; }
TASK NO. 07
Q: Write a program using array of size 5 and take values from user and find sum and
average of numbers.
#include<iostream>
using namespace std;
int main(){
int sum=0,avg; int a[5];
for(int i=0;i<5;i++)
{ cout<<"Enter a number"<<endl;
cin>>a[i];
}
for(int i=0;i<5;i++)
{ sum+=a[i]; }
cout<<"Sum of 5 numbers is "<<sum<<endl;
avg=sum/5;
cout<<"Average of 5 numbers is "<<avg;
return 0; }

Programming Fundamentals (Lab Manual) Page 76 of 147


BS (Computer Science) 2023

TASK NO. 08
Q: Write a program using array of size 5 and take values from user and ask user to
enter value of any 5 arrays and then display the location of that integer.
#include<iostream>
using namespace std;
int main(){
int a[5],integer,pos;
for(int i=0;i<5;i++)
{
cout<<"Enter a value"<<endl;
cin>>a[i];
}
pos=0;
cout<<"Enter a integer"<<endl;
cin>>integer;
for(int i=0;i<5;i++)
{ if(integer==a[i])
{ pos=i+1;
break;
} }
if(pos==0)
cout<<"Number not found";
else
cout<<"Number found at position ";
cout<<pos;
return 0;
}

TASK NO. 09
Programming Fundamentals (Lab Manual) Page 77 of 147
BS (Computer Science) 2023

Q: Write a program to initialized value to array of size 5 in float data type and display
in output.
#include<iostream>
using namespace std;
int main(){
float a[5]={1.1, 2.2, 3.3, 4.4, 5.5};
for(int i=0;i<5;i++)
{ cout<<a[i]<<endl; }
return 0;
}

Programming Fundamentals (Lab Manual) Page 78 of 147


BS (Computer Science) 2023

TASK NO. 10
Q: Write program to take two arrays of size 5 and initialized the values of array 1 to
array2 and displayed.
#include<iostream>
using namespace std;
int main(){
char x[5]={'a','b','c','d','e'};
char y[5];
y[0]=x[0];
y[1]=x[1];
y[2]=x[2];
y[3]=x[3];
y[4]=x[4];
for(int i=0;i<5;i++)
{ cout<<y[i]<<endl; }
return 0;}

TASK NO. 11
Q: Write a program to input two different arrays and then to add the two arrays and
store result in a third array.
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
float a[5],b[5],s[5];
int i;
cout<<"Enter value in first array"<<endl;
for(i=0;i<=4;i++)
{ cout<<"Enter value in first element "<<i<<"=";
cin>>a[i];
}
cout<<"Enter value in second array "<<endl;
for(i=0;i<=4;i++)
{ cout<<"Enter value in element "<<i<<"=";
cin>>b[i];
}
cout<<"First + second = sum"<<endl;
for(i=0;i<=4;i++)
{ s[i]=a[i]+b[i];
cout<<a[i]<<"+"<<b[i]<<"="<<s[i]<<endl;
}}
Programming Fundamentals (Lab Manual) Page 79 of 147
BS (Computer Science) 2023

Sorting Arrays

Definition: Sorting is the process of putting data in order; eitherr numerically or


alphabetically.It is often necessary to arrange the elements in an array in numerical order
from highest to lowest values (descending order) or vice versa (ascending order). If the array
contains string values, alphabetical order may be needed (which is actually ascending order
using ASCII values). The process of sorting an array requires the exchanging of
values. While this seems to be a simple process, a computer must be careful that no values
are lost during this exchange. Consider the following dilemma:

Suppose that grade[1] = 10 and grade[2] = 8 and you want to exchange their values so that
grade[1] = 8 and grade[2] = 10. You could NOT just do this:

grade[1] = grade[2];
grade[2] = grade[1]; // DOES NOT WORK!!!

In the first step, the value stored in grade[1] is erased and replaced with grade[2]. The result
is that both grade[1] and grade[2] now have the same value. Oops! Then what happened to
the value in grade[1]? It is lost!!!

In order to swap two values, you must use a third variable,


(a "temporary holding variable"), to temporarily
hold the value you do not want to lose:
//swapping variables
temp = grade[1]; // holding variable
grade[1] = grade[2];
grade[2] = temp;
Programming Fundamentals (Lab Manual) Page 80 of 147
BS (Computer Science) 2023

This process successfully exchanges, "swaps", the values of the two variables (without the
loss of any values). Remember the example in class of the two horses switching stalls!!
Types Of Sorting:
There are two types of sorting:
1.BUBBLE SORTING
2. SELECTION SORTING
Bubble Sorting
In the bubble sort, as elements are sorted they gradually "bubble" (or rise) to their proper
location in the array, like bubbles rising in a glass of soda. The bubble sort repeatedly
compares adjacent elements of an array. The first and second elements are compared and
swapped if out of order. Then the second and third elements are compared and swapped if
out of order. This sorting process continues until the last two elements of the array are
compared and swapped if out of order. When this first pass through the array is complete, the
bubble sort returns to elements one and two and starts the process all over again. So, when
does it stop? The bubble sort knows that it is finished when it examines the entire array
and no "swaps" are needed (thus the list is in proper order). The bubble sort keeps track
of occurring swaps by the use of a flag.
The table below follows an array of numbers before, during, and after a bubble sort for
descending order. A "pass" is defined as one full trip through the array comparing and if
necessary, swapping, adjacent elements. Several passes have to be made through the array
before it is finally sorted. -

Array at beginning: 84 69 76 86 94 91
After Pass #1: 84 76 86 94 91 69
After Pass #2: 84 86 94 91 76 69
After Pass #3: 86 94 91 84 76 69
After Pass #4: 94 91 86 84 76 69
After Pass #5 (done): 94 91 86 84 76 69

The bubble sort is an easy algorithm to program, but it is slower than many other sorts. With
a bubble sort, it is always necessary to make one final "pass" through the array to check to see
that no swaps are made to ensure that the process is finished. In actuality, the process is
finished before this last pass is made.

Programming Fundamentals (Lab Manual) Page 81 of 147


BS (Computer Science) 2023

Task no. 12(Ascending Order)


Q:Write a program to sort the list given in the by using bubble sorting method in
descending order.
#include<iostream>
using namespace std;
int main(){
int i,u,t, ARR[4]={4,19,1,3};
for(u=3;u>=1;u--)
{ for(i=0;i<u;i++)
{ if (ARR[i]>ARR[i+1])
{ t=ARR[i];
ARR[i]=ARR[i+1];
ARR[i+1]=t;
} } }
cout<<"Sorted values "<<endl;
for(i=0;i<=3;i++)
cout<<ARR[i]<<endl;
}

Task No. 13 (Descending Order)


Q: Write a program to sort the list given in the by using bubble sorting method in
descending order.
#include<iostream>
using namespace std;
int main(){
int i,u,t, ARR[4]={4,19,1,3};
for(u=3;u>=1;u--)
{ for(i=0;i<u;i++)
{ if (ARR[i]<ARR[i+1])
{ t=ARR[i];
ARR[i]=ARR[i+1];
ARR[i+1]=t;
} }}
cout<<"Sorted values "<<endl;
for(i=0;i<=3;i++)

Programming Fundamentals (Lab Manual) Page 82 of 147


BS (Computer Science) 2023

cout<<ARR[i]<<endl;
}

Selection Sorting

The selection sort is a combination of searching and sorting. During each pass, the unsorted
element with the smallest (or largest) value is moved to its proper position in the array. The
number of times the sort passes through the array is one less than the number of items in the
array. In the selection sort, the inner loop finds the next smallest (or largest) value and the
outer loop places that value into its proper location.Let's look at our same table of elements
using a selection sort for descending order. Remember, a "pass" is defined as one full trip
through the array comparing and if necessary, swapping elements.

Array at beginning: 84 69 76 86 94 91
After Pass #1: 84 91 76 86 94 69
After Pass #2: 84 91 94 86 76 69
After Pass #3: 86 91 94 84 76 69
After Pass #4: 94 91 86 84 76 69
After Pass #5 (done): 94 91 86 84 76 69

Task No. 14(Ascending order)


#include<iostream>
using namespace std;
int main(){
int i,u,p,m,t, ARR[4]={4,19,1,3};
for(u=0;u<3;u++)
{ m=ARR[u];

Programming Fundamentals (Lab Manual) Page 83 of 147


BS (Computer Science) 2023

for(i=u;i<=3;i++)
if (m>ARR[i])
{ m=ARR[i];
p=i;
t=ARR[p];
ARR[p]=ARR[u];
ARR[u]=t;
}
cout<<"Sorted values "<<endl;
for(i=0;i<=3;i++)
cout<<ARR[i]<<endl;
}
}

Task No. 15 (Descending order)


#include<iostream>
using namespace std;
int main(){
int i,u,p,m,t, ARR[4]={22,15,23,34};
for(u=0;u<3;u++)
{
m=ARR[u];
for(i=u;i<=3;i++)
if (m<ARR[i])
{ m=ARR[i];
p=i;
t=ARR[p];
ARR[p]=ARR[u];
ARR[u]=t;
}
cout<<"Sorted values "<<endl;
for(i=0;i<=3;i++)
cout<<ARR[i]<<endl;
}
}

Programming Fundamentals (Lab Manual) Page 84 of 147


BS (Computer Science) 2023

Multi-dimensional Arrays
C++ programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration − type name[size1][size2]...[sizeN]; For example, the
following declaration creates a three dimensional integer array
int threedim[5][10][4];
Two dimensional Arrays:
The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows.
type arrayName [x][y];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y
number of columns. A two-dimensional array a, which contains three rows and four columns
can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each
element in 'a'.
Initializing Two-Dimensional Arrays:
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is
an array with 3 rows and each row has 4 columns.
int a[3][4]={
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */ };
The nested braces, which indicate the intended row, are optional. The following initialization
is equivalent to the previous example
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements:


An element in a two-dimensional array is accessed by using the subscripts, i.e., row index
and column index of the array. For example
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You can verify
it in the above figure. Let us check the following program where we have used a nested loop
to handle a two-dimensional array.
EXAMPLE:
Programming Fundamentals (Lab Manual) Page 85 of 147
BS (Computer Science) 2023

#include<stdio.h
int main (){
/* an array with 5 rows and 2 columns*/
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
int i, j;
/* output each array element's value */
for( i =0; i <5; i++){

for( j =0; j <2; j++){


printf("a[%d][%d] = %d\n", i,j, a[i][j]);
}}
return0; }
When the above code is compiled and executed, it produces the following result :
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.
Task No. 16
Q: write a program to print out data from the elements of a table.
#include<iostream>
using namespace std;
int main(){
int abc[2][3],r,c;
cout<<"Input data into table "<<endl;
r=0;
while(r<=1)
{c=0;
while(c<=2)
{cout<<"Enter value in row ";
cout<<r<<" column "<<c<<"= ";
cin>>abc[r][c];
c=c+1;}
r=r+1;
}
cout<<"Printing data from table "<<endl;
r=0;
Programming Fundamentals (Lab Manual) Page 86 of 147
BS (Computer Science) 2023

while(r<=1)
{c=0;
while(c<=2)
{cout<<abc[r][c]<<"\t";
c=c+1;
}
cout<<endl;
r=r+1;
}
}
Task No. 17
Q: Write a program to imitialized value to a table xyz having 4 coulumns and 3 rows at
the time of declaration.Also print data from the tablein tabular form.
#include<iostream>
using namespace std;
int main(){
int xyz[3][4]={{2,3,10,1},
{6,12,16,3},
{4,3,13,17}};
int r,c;
for(r=0;r<=2;r++){
for(c=0;c<=3;c++)
{ cout<<xyz[r][c]<<"\t"; }
cout<<endl; }
Task No. 18
Declare a function which accepts a 2-d array of numbers as an argument. This function
should tell whether each number in array is an even number or an odd number.
SOURCECODE:
#include<iostream>
using namespace std;
void ftn(int arra[3][3]);
int main()
{int arr[3][3];
for (int i = 0 ;i<3 ;i++)
{ for (int j = 0 ; j<3;j++)
{ cout << "Enter the number : " ;
cin >>arr[i][j];
}}
ftn (arr);
system ("pause");
return 0;
}
Programming Fundamentals (Lab Manual) Page 87 of 147
BS (Computer Science) 2023

void ftn(int arra[3][3])


{ int n = 0;
for (int i = 0 ; i< 3;i++)
{ for (int j = 0 ; j<3; j++)
{ if (arra[i][j] % 2 == 0)
{cout << "This number is an even number : " << arra[i][j] << endl;
n++;
}}}
cout << "There total " << n << " even numbers!" << endl;
}

STUDENT TASK:
1. Write a program in c++ to input value into an array. Find out the total number of odd
and even values entered in the array.
2. Write a program in c++ to input values into a table. Find out the total number of odd
values entered in it and print these on the screen.
3. Write a program in c++ to input values into a table, sort these values in ascending
order and print them on the screen in tabular form.

Programming Fundamentals (Lab Manual) Page 88 of 147


BS (Computer Science) 2023

LAB 11: “STRUCTURES”


Objectives:
• Structures (also called structs) are a way to group several related variables into one
place.
• Each variable in the structure is known as a member of the structure.
• A structure can contain many different data types (int, string, bool, etc.).
• Structure is a collection of variables of different data types under a single name
• allow you to define variables that combine several data items of the same kind, but
structure is another user defined data type

Theoretical Description:
• In this lab student will learn about Structures, Defining structures and structure
variables, Accessing structure members, Combining structure specifier and definition.
• Initializing Structure members, Structures within structures, Enumerated data types.
• Overloading, Overloaded functions and Examples, Inline functions

Lab Task(s):
Implement various concepts of basic structure implementation along with overloading and
inline functions.

Programming Fundamentals (Lab Manual) Page 89 of 147


BS (Computer Science) 2023

Structure
Structure is the collection of variables of different types under a single name for better
visualization of problem. Arrays is also collection of data but arrays can hold data of only one
type whereas structure can hold data of one or more types.
How to define a structure in C++ programming?
The struct keyword defines a structure type followed by an identifier (name of the structure).
Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:

struct person {

string name;

int age;

float salary;

};
Here a structure person is defined which has three members: name, age and salary.
When a structure is created, no memory is allocated. The structure definition is only the
blueprint for the creating of variables. You can imagine it as a datatype. When you define an
integer as below:

int foo;
The int specifies that, variable foo can hold integer element only. Similarly, structure
definition only specifies that, what property a structure variable holds when it is defined.
How to define a structure variable?
Once you declare a structure person as above. You can define a structure variable as:

person bill;
Here, a structure variable bill is defined which is of type structure person. When structure
variable is defined, then only the required memory is allocated by the compiler.
How to access members of a structure?
The members of structure variable is accessed using dot operator. Suppose, you want to
access ageof structure variable bill and assign it 50 to it. You can perform this task by using
following code below:

bill.age = 50;

Programming Fundamentals (Lab Manual) Page 90 of 147


BS (Computer Science) 2023

Task No. 01
#include<iostream>
#include<iomanip>
using namespace std;
struct student{
string name;
int rn;
int pfm;
};
int main()
{ student c1,c2,c3;
int a,b;
string name;
bool cf=1;
lable2:
cout<<setw(20)<<"MAIN MENU"<<endl;
cout<<endl;
cout<<"1: press 1 to enter student record"<<endl;
cout<<"2: press 2 disply the record"<<endl;
cout<<"3 press 3 for exist"<<endl;
cout<<"Enter the choise"<<endl;
cin>>a;
// in the following we use switch statement
switch (a)
{ case 1:
{
cout<<"1:press to entre the 1 student record"<<endl;
cout<<"2:press to enter the 2 student record"<<endl;
cout<<"3.press to enter the 3 student record"<<endl;
cout<<"4:press to main maniu"<<endl;
cout<<"5:press to exist"<<endl;
lable:
cout<<endl;
cout<<"entre choise"<<endl;
cin>>b;
}
switch (b)
{ case 1:
{ cout<<"entre the marks of 1 student"<<endl;
cin>>c1.pfm;
goto lable;
}
case 2:

Programming Fundamentals (Lab Manual) Page 91 of 147


BS (Computer Science) 2023

{ cout<<"enter the marks of 2 student"<<endl;


cin>>c2.pfm;
goto lable;
}
case 3:
{ cout<<"enter the marks of 3 student"<<endl;
cin>>c3.pfm;
goto lable;
}
case 4:
{ goto lable2;
}
case 5:
{ goto lable3;
}
}
case 2:
{ cout<<setw(20)<<" STUDENT RECORD "<<endl;
cout<<endl;
cout<<"1"<<" "<<c1.pfm<<endl;
cout<<"2"<<" "<<c2.pfm<<endl;
cout<<"3"<<" "<<c3.pfm<<endl;
goto lable2;
}
lable3:
case 3:
cout<<"FNISH"<<endl;
} return 0; }

Programming Fundamentals (Lab Manual) Page 92 of 147


BS (Computer Science) 2023

Task No. 02
Q: Write a program to take first name, last name and age from user and display the
message
“Hello (name enter by user can be displayed). How are you.
Congratulation on reaching the age of (age enter by user can be displayed”
This can be perform using structures.
#include<iostream>
#include<iomanip>
using namespace std;
struct PersonRec
{ string FirstName;
string LastName;
int age;
};
main(){
PersonRec ThePerson;
cout<<"Enter first name"<<endl;
cin>>ThePerson.FirstName;
cout<<"Enter last name"<<endl;
cin>>ThePerson.LastName;
cout<<"Enter age"<<endl;
cin>>ThePerson.age;
cout<<"\n\nHELLO "<<ThePerson.FirstName<<' '<<ThePerson.LastName<<". How
are you?\n";
cout<<"\n\nCongratulations on reaching the age of "<<ThePerson.age<<".\n";
}

Task No. 03
Q: Write a program to take first name, last name , age and overall percentage from user
and display the message
“Hello (name enter by user can be displayed). How are you.
Congratulation on reaching the age of (age enter by user can be displayed).
Yor overall percent score is (percent enter by user) for a grade (according percentage)”
This can be perform using structures.
Programming Fundamentals (Lab Manual) Page 93 of 147
BS (Computer Science) 2023

#include <iostream>
using namespace std;
struct GradeRec
{float Percent;
char Grade;};
struct StudentRec
{string FirstName;
string LastName;
int age;
GradeRec CourseGrade;};
main()
{StudentRec Student;
cout<< "Enter first name"<<endl;
cin>>Student.FirstName;
cout<< "Enter last name"<<endl;
cin>>Student.LastName;
cout<< "Enter age"<<endl;
cin>>Student.age;
cout<< "Enter overall percent"<<endl;
cin>>Student.CourseGrade.Percent;
if(Student.CourseGrade.Percent>= 90)
{Student.CourseGrade.Grade='A';}
else if(Student.CourseGrade.Percent>= 75)
{Student.CourseGrade.Grade='B';}
else
{Student.CourseGrade.Grade='F';}
cout<<"\n\nHello "<<Student.FirstName<< ' '<<Student.LastName<<". How are you?\n";
cout<<"\nCongratulations on reaching the age of "<<Student.age<<".\n";
cout<<"Your overall percent score is "<<Student.CourseGrade.Percent<<" for a grade of
"<<Student.CourseGrade.Grade;
}

Programming Fundamentals (Lab Manual) Page 94 of 147


BS (Computer Science) 2023

Task No. 04
Declare a structure book. Define two variables of book and input the book id, number
of pages, price and name of authors. And display the record of costly book.
Source Code:
#include<iostream>
#include <string>
using namespace std;
struct book{
int id ;
int pages ;
float price;
string author[2]; };
int main ()
{ book books[4] = {1,453,450};
for (int i =1 ; i< 4 ; i++)
{ cin>> books[i].id;
cin>> books[i].pages;
cin >>books[i].price;
cin >> books[i].author[0];
cin >> books[i].author[1];
}
int m ;
int max= books[0].price;
m = 0;
for (int i =0;i<4; i++)
{ if (max < books[i].price )
{ max = books[i].price ;
m = i;
} }
cout << " ID : " << books[m].id;
cout << " Pages : " << books[m].pages ;
cout << " Price : " << books[m].price << endl;
cout << " author : " << books[m].author[0] << " And "<< books[m].author[1]
<<endl;
system(" pause");
return 0;
}
Task No. 05
Declare a structure employ which inputs name, CNIC, id and grade. And then declare a
structure teacher which inputs the data (no of courses) of a teacher using the employ
structure. And then display the record of teacher.
#include <iostream>

Programming Fundamentals (Lab Manual) Page 95 of 147


BS (Computer Science) 2023

using namespace std;


struct emp {
string name, cnic;
int id;
char g;
};
struct teacher {
int noofcourse;
emp e;
};
int main ()
{teacher y = {3, {"Iqra" , "123455556",22,'f'}};
teacher x;
cin >> x.noofcourse>>
x.e.name>>x.e.cnic>> x.e.id >>x.e.g;
cout << y.noofcourse << endl <<
y.e.name<<endl<< y.e.cnic <<endl;
cout << y.e.id<<endl<< y.e.g<< endl<<
x.noofcourse << endl << x. e. name << endl
cout<< x.e.cnic<< endl<< x.e.id << endl << x.e.g << endl;
system("pause"); }
Task No. 06
Write a program which declares a structure xyz and defines two variables of xyz using
which the program inputs the name and population of two countries and then displays
the record of most populous country!
SOURCECODE:
#include <iostream>
using namespace std;
struct xyz {
int pop ;
char name[30];
};
xyz d(xyz c1,xyz c2)
{ if (c1.pop < c2.pop )
{ return c2; }
else { return c1;} }
int main (){
xyz c1 , c2;
cin>> c1.pop>> c1.name>> c2.pop >> c2.name;
xyz c = d(c1,c2);
cout << "The name of country : " << c.name<< endl << " The population of " <<
c.name << " is : " << c.pop << endl;
system("pause"); return 0; }
Programming Fundamentals (Lab Manual) Page 96 of 147
BS (Computer Science) 2023

STUDENT TASK:
1. Write a program in c++ to define a program in a structure that has the following
members:

Member Name Data Type

code int

name string

city string

country string

Declare the structure as defined above, input the data into it and print it on the screen.

2. Write a program to declare variables of structure type as mentioned above Q. input


data into two structure type variables. Swap the values and print the result on the
screen after swapping.

Programming Fundamentals (Lab Manual) Page 97 of 147


BS (Computer Science) 2023

LAB 12: “FUNCTIONS”


Objectives:

• A function is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
Theoretical Description:

• As a function is a code segment that performs a particular task. You can reuse it,
which means that you can execute it more than once.
• In this lab student will learn about Functions, Functions Declaration. Function
Calling, Function Definition, and Eliminating function declaration, Arrays and
functions, passing to functions, Passing arguments to functions (by value). Passing
variables to functions, Passing structure variables to functions, Returning values from
functions, Return statement.

Lab Task(s):

Student will implement various C++ programs using the concepts of Functions.

Programming Fundamentals (Lab Manual) Page 98 of 147


BS (Computer Science) 2023

Functions
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts :
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration
int max(int, int);
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the file
calling the function.
Types Of Functions:
There are two types of functions:
1. Built in Functions
2. User defined Functions
Built -in Functions
The functions that have already been defined as a part of the language and can be used in
any program are called built-in fuctions. The built-in functions are provided for general use
like clrscr, cout, cin etc.
User-defined Functions
The functions created by a user are called user defined functions. These functions are written
as a part of a program to perform a specific task. These functions are written for a specific
use.
A user defined functions has three parts. These are:
1. Function declaration(prototype)
2. Function definition
3. Function calling
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.
A function declaration has the following parts :
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration
int max(int, int);
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the file
calling the function.
Defining a Function
The general form of a C++ function definition is as follows −

Programming Fundamentals (Lab Manual) Page 99 of 147


BS (Computer Science) 2023

return_type function_name( parameter list ) {


body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function −

● Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
● Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
● Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the parameters
of a function. Parameters are optional; that is, a function may contain no parameters.
● Function Body − The function body contains a collection of statements that define
what the function does.
Example

Following is the source code for a function called max(). This function takes two parameters
num1 and num2 and return the biggest of both
// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function. When a program calls a function,
program control is transferred to the called function. A called function performs defined task
and when it’s return statement is executed or when its function-ending closing brace is
reached, it returns program control back to the main program. To call a function, you simply
need to pass the required parameters along with function name, and if function returns a
value, then you can store returned value.
For Example
#include<iostream>
using namespace std;
// function declaration
int max(int num1,int num2);
Programming Fundamentals (Lab Manual) Page 100 of 147
BS (Computer Science) 2023

int main (){


// local variable declaration:
int a =100;
int b =200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout <<"Max value is : "<< ret << endl;
return0;
}
// function returning the max between two numbers
int max(int num1,int num2){
// local variable declaration
int result;
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While
running final executable, it would produce the following result:
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:

1.Call by Value
This method copies the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the function have no effect on
the argument.
2. Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the
function, the address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
3.Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the
function, the reference is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within
a function cannot alter the arguments used to call the function and above mentioned example
while calling max() function used the same method.

Programming Fundamentals (Lab Manual) Page 101 of 147


BS (Computer Science) 2023

Default Values for Parameters


When you define a function, you can specify a default value for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the
function definition. If a value for that parameter is not passed when the function is called, the
default given value is used, but if a value is specified, this default value is ignored and the
passed value is used instead. Consider the following example:
Example:
#include<iostream>
Using namespace std;
int sum(int a,int b =20){
int result;
result = a + b;
return(result);
}
int main (){
// local variable declaration:
int a =100;
int b =200;
int result;
// calling a function to add the values.
result = sum(a, b);
cout <<"Total value is :"<< result << endl;
// calling a function again as follows.
result = sum(a);
cout <<"Total value is :"<< result << endl;
return0;
}
When the above code is compiled and executed, it produces the following result.
Total value is :300
Total value is :120

Task No. 01
Q: Write a program to print a message on the screen using a function.
#include<iostream>
using namespace std;
Programming Fundamentals (Lab Manual) Page 102 of 147
BS (Computer Science) 2023

void display (void);


int main()
{ display();
cout<<"OK";
}
void display (void)
{ cout<<"It is my first function program "<<endl;
}

PASSING ARGUMENTS TO FUCTIONS


● An argument is a piece of data (an int value, for example) passed from a program to
the function.
● Arguments allow a function to operate with different values, or even to do different
things, depending on the requirements of the program calling it.

Task No. 02
Q: Write a program in which two numbers are passing as argument to a function and
calculate their sum.
#include<iostream>
using namespace std;
void sum (int,int);
int main()
{ cout<<"performing sum "<<endl;
sum(20,15);
cout<<"\nThat was the answer ";
return 0;
}
void sum(int a, int b)
{ int s;
s=a+b;
cout<<s; }

Task No. 03

Programming Fundamentals (Lab Manual) Page 103 of 147


BS (Computer Science) 2023

Q: Write a program for calculator by passing three arguments to a function biody, first
for numeric number, second arithmetic operators and third other numeric numbers.
Perform arithmetic operation on the given numbers and print on the screen.
#include<iostream>
#include<conio.h>
using namespace std;
void cal(int,char,int);
int main(){
int n1,n2;
char op;
cout<<"Enter 1st value, operator and 2nd value"<<endl;
cin>>n1>>op>>n2;
cal(n1,op,n2);
getch(); }
void cal(int x,char aop,int y)
{ switch(aop)
{ case'+':
cout<<"sum:"<<x+y;
break;
case'-':
cout<<"subtraction:"<<x-y;
break;
case '*':
cout<<"Multiplication:"<<x*y;
break;
case '/':
cout<<"Division:"<<x/y;
break;
case'%':
cout<<"Remainder:"<<x%y;
break;
default:
cout<<"invalid input";
} }

PASSING CONSTANTS
Task No. 04
Q: Write a program to pass the constants to fuctions.

Programming Fundamentals (Lab Manual) Page 104 of 147


BS (Computer Science) 2023

#include<iostream>
using namespace std;
#include<conio.h>
void repchar(char,int);//function decleration
int main(){
repchar('-',43); //callin to a function
cout<<" DATA TYPE RANGE "<<endl;
repchar('=',23);//call to function
cout<<"char -128 to 127 "<<endl<<"short -32,768 to 32767"<<endl;
cout<<"int system dependent"<<endl<<"double -2,147,483,648 to 2,";
cout<<"147,483,647"<<endl;
repchar('-',43);//caal to a function
return 0;
}
//function definition
void repchar(char ch,int n){ //function declarator
for(int j=0;j<n;j++)
cout<<ch;
cout<<endl;
}
Passing Variables
Task No. 05
Q: Write a program to pass the variables to fuctions.
#include<iostream>

using namespace std;


#include<conio.h>
void repchar(char,int);//function decleration
int main(){
char chin;
int nin;
cout<<"Enter a character: ";
cin>>chin;
cout<<"Enter number of times to repeat it:";
cin>>nin;
repchar(chin,nin);
Programming Fundamentals (Lab Manual) Page 105 of 147
BS (Computer Science) 2023

getch();
}
//function definition
void repchar(char ch,int n ){//function declarator
for(int j=0;j<n;j++)//function body
cout<<ch;
cout<<endl;
}
Task No. 05
Q: Write a program which inputs the marks of student and then displays the grade
according to given criteria:
1. > 80 THEN A
2. >= 60<=79 THEN B
3. >=40<=59 THEN C
4. <40 THEN F
SOURCECODE:
#include <iostream>
using namespace std;
char markss(int marks);
int main ()
{ int marks ;
a:
cin>> marks;
if (marks > 0 && marks < 101)
{
char g = markss(marks);
cout << "Grade : " << g << endl; }
else
{ goto a; }
system ("pause");
return 0;
}
char markss(int marks) {
if (marks >= 80)
return 'A';
else if (marks >= 60 && marks <= 79)
return 'B';
else if (marks >= 40 && marks <= 59)
return 'C';
else
return 'F';
}

Programming Fundamentals (Lab Manual) Page 106 of 147


BS (Computer Science) 2023

Task No. 06
Q: Write a program which passes an array to a function and also passes its length and
that function returns the maximum number in that array!
SOURCECODE:
#include <iostream>
using namespace std;
void maxi(int arr[5],int len)
{ int max = arr[0];
for (int i = 1 ; i <len ; i++)
{
if(max < arr[i])
{max = arr[i]; }
}
cout << "Maximum : " << max << endl ;
}
int main()
{ int array[5] = {1,3,5,2,9};
maxi(array,5);
}

Passing Arrays To A Function


C++ does not allow to pass an entire array as an argument to a function. However, You can
pass a pointer to an array by specifying the array's name without an index. If you want to pass
a single-dimension array as an argument in a function, you would have to declare function
formal parameter in one of following three ways.
Way-1
Formal parameters as a sized array as follows:
void myFunction(int param[10]) {
.
.
.
}
Way-2
Formal parameters as an unsized array as follows −

void myFunction(int param[]) {

Programming Fundamentals (Lab Manual) Page 107 of 147


BS (Computer Science) 2023

.
.
.
}
Now, consider the following function, which will take an array as an argument along with
another argument and based on the passed arguments, it will return average of the numbers
passed through the array as follows −

double getAverage(int arr[], int size) {


int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
}

Now, let us call the above function as follows.

#include <iostream>
using namespace std;
// function declaration:
double getAverage(int arr[], int size);
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
When the above code is compiled together and executed, it produces the following result
Average value is: 214.4
As you can see, the length of the array doesn't matter as far as the function is concerned
because C++ performs no bounds checking for the formal parameters.
datatype array_name [ array_size ];
For example, take an integer array 'n'.
int n[6];
n[ ] is used to denote an array named 'n'.
So, n[6] means that 'n' is an array of 6 integers. Here, 6 is the size of the array i.e., there are
6 elements of array 'n'. Giving array size i.e. 6 is necessary because the compiler needs to
allocate space to that many integers. The compiler determines the size of an array by
calculating the number of elements of the array. Here 'int n[6]' will allocate space to 6
integers. We can also declare an array by another method.
Programming Fundamentals (Lab Manual) Page 108 of 147
BS (Computer Science) 2023

int n[ ] = { 2,3,15,8,48,13 };
In this case, we are declaring and assigning values to the array at the same time. Hence, no
need to specify the array size because the compiler gets it from { 2,3,15,8,48,13 }.
Following is the pictorial view of the array.

element 2 3 15 8 48 13
index 0 1 2 3 4 5
0,1,2,3,4 and 5 are the indices. It is like these are the identities of 6 different elements of the
array. Index starts from 0. So, the first element has index 0. We access the elements of an
array by writing array_name[index].

Initializing An Array
By writing int n[ ]={ 2,4,8 }; , we are initializing the array. But when we declare an array like
int n[3]; , we need to assign the values to it separately. Because 'int n[3];' will definitely
allocate the space of 3 integers in the memory but there are no integers in that.
To assign values to the array, assign a value to each of the element of the array.
n[0] = 2;
n[1] = 4;
n[2] = 8;
It is just like we are declaring some variables and then assigning the values to them.
int x,y,z;
x=2;
y=4;
z=8;
Thus, the two ways of initializing an array are:
int n[ ]={ 2,4,8 };
and the second method is declaring the array first and then assigning the values to its
elements.
int n[3];
n[0] = 2;
n[1] = 4;
n[2] = 8;
You can understand this by treating n[0], n[1] and n[2] as different variables you used before.
Just like a variable, an array can be of any other data type also.
float f[ ]= { 1.1, 1.4, 1.5};
Here, f is an array of floats.
First, let's see the example to calculate the average of the marks of 3 students. Here, marks[0],
marks[1] and marks[2] represent the marks of the first, second and third student respectively.
Task No. 07
Q: Write a program to find a number and its location in the array using a function.
#include<iostream>
using namespace std;
void find(int[],int);
int main(){
int arr[10],i,n;
Programming Fundamentals (Lab Manual) Page 109 of 147
BS (Computer Science) 2023

cout<<"Enter values into array ?\n";


for(i=0;i<=9;i++)
{ cout<<"Value of arr["<<i<<"]=";
cin>>arr[i];
}
cout<<"Enter number to find ?=";
cin>>n;
find(arr,n);
}
void find(int x[],int a){
int p=0;
for(int c=0;c<=9;c++){
if(a==x[c]){
p=c;
break;

}
}
if(p==0)
{ cout<<"Number not found"; }
else
{ cout<<"Number found at position:"<<p+1; }
}
Task No. 08
Q: Write a program to find the maximum number from an array by using function.
#include<iostream>
using namespace std;
void max(int[]);
int main(){
int c,aa[5];
for(c=0;c<4;c++)
{ cout<<"Enter data in ["<<c<<"]=";
cin>>aa[c];
Programming Fundamentals (Lab Manual) Page 110 of 147
BS (Computer Science) 2023

}
max(aa);
}
void max(int x[])
{ int m,co;
m=x[0];

for(co=0;co<4;co++){
if(m<x[co]){
m=x[co];
} }
cout<<"The Maximum Value is ="<<m<<endl;
}

Passing Structure Elements to Functions


When an element of a structure is passed to a function, you are actually passing the values of
that element to the function. Therefore, it is just like passing a simple variable (unless, of
course, that element is complex such as an array of character). For example, consider the
following structure :
struct date
{ short day ;
short month ;
short year ;
}Bdate ;
Individual elements of this structure can be passed as follows :
func1(Bdate.day, Bdate.month, Bdate.year) ;
The above function-call invokes a function, func1() by passing values of individual structure
elements of structure Bate. The function can either receive the values by creating its own
copy for them (call by value) or by creating references for the original variables (call by
reference). If You want that the values of the structure elements should not be altered by the
function, then you should pass the structure elements by value and if you want the function to
alter the original values, then you should pass the structure elements by reference.
Returning Values from Functions
Programming Fundamentals (Lab Manual) Page 111 of 147
BS (Computer Science) 2023

⮚ When a function completes its execution, it can return a single value to the calling
program.
⮚ Usually this return value consists of an answer to the problem the function has solved.
⮚ However, there are other approaches to returning multiple variables from functions.
⮚ One is to pass arguments by reference.
⮚ Another is to return a structure with the multiple values as members.
⮚ You should always include a function’s return type in the function declaration.
⮚ If the function doesn’t return anything, use the keyword void to indicate this fact.
⮚ If you don’t use a return type in the declaration, the compiler will assume that the
function returns an int value.
Function definition that returns a value
Task No. 10
Q: Write a program that converts the grams into kg and return value.
#include<iostream>
using namespace std;

int grams(int );
int main(){
int kg,gm;
cout<<"Enter value in kilograms = ";
cin>>kg;
gm=grams(kg);
cout<<"Answer in gram is = "<<gm;
}
int grams(int val)
{ return val*100; }

Returning structures From Functions


Task No. 11
Q: Write a program using structures taking name and marks of a student and the
return.
#include<iostream>
using namespace std;
struct temp
{ char mn[12];
float marks;
};
temp abc(void);

Programming Fundamentals (Lab Manual) Page 112 of 147


BS (Computer Science) 2023

int main()
{ temp xyz;

xyz=abc();
cout<<"Name = "<<xyz.mn<<endl;
cout<<"Marks = "<<xyz.marks<<endl;
cout<<"OK";
}
temp abc(void)
{ temp rec;
cout<<"Enter name :";
gets(rec.mn);
cout<<"Enter marks :";
cin>>rec.marks;
return (rec); }
Local Variables
Variables that are declared inside a function or a block are called local variables and are said
to have local scope. These local variables can only be used within the function or block in
which these are declared.

For functions, local variable can either be a variable which is declared in the body of that
function or can be defined as function parameters in the function definition.

Implementation in programs using local variables

Task No. 12

#include<iostream>
using namespace std;
int sum(int,int);
int main(){
int a,b,s;
a=10;
b=100;
s=sum(a,b);
cout<<"sum = "<<s;
cout<<"\nok";
}
int sum(int x,int y)
Programming Fundamentals (Lab Manual) Page 113 of 147
BS (Computer Science) 2023

{ int rs;
rs= x+y;
return rs;

}
Global Variables
Variables that are defined outside of all the functions and are accessible throughout the
program are global variables and are said to have global scope. Once declared, these can be
accessed by any function in the program.

Lifetime
The period of time during program execution when an identifier has memory allocated to it.
A local variable's lifetime:

⮚ Starts when entering the block


⮚ Ends when the block is exited.
A global variable's lifetime:
⮚ Duration of the entire program.

Implementation in programs using Global variables


Task No. 13
Q: Write a program that define the use of global variables.
#include<iostream>
using namespace std;
void sum(int,int);
int a,b,s;
int main(){
a=10;
b=100;
sum(a,b);
cout<<"sum = "<<s;
cout<<"\nok";
}
void sum(int x,int y)
{ s= x+y; }
Static Variables
Static variables are special variables that are declared inside a function by using the keyword
“static”. Like local variables, these can only be accessed in the function in which they are
declared but they remain in existence for the lifetime of program. Another difference between
local variables and static local variables is that the initialization in the static variables takes
place only once when the function is called for the first time.
Task No. 14
#include<iostream>

Programming Fundamentals (Lab Manual) Page 114 of 147


BS (Computer Science) 2023

using namespace std;


int temp(int);
int main()
{ int i;
for(i=1;i<=3;i++)
{ cout<<temp(i)<<endl;
}
cout<<"OK"; }
int temp(int x)
{ static int co=10;
co=co*x;
return (co); }}

Programming Fundamentals (Lab Manual) Page 115 of 147


BS (Computer Science) 2023

Reference Parameters
Reference Variables
● A reference variable is a nickname, or alias, for some other variable
● To declare a reference variable, we use the unary operator &
int n = 5; // this declares a variable, n
int & r = n; // this declares r as a reference to n
In this example, r is now a reference to n. (They are both referring to the SAME
storage location in memory).
● To declare a reference variable, add the & operator after the type
● Here is a small example program that illustrates a reference variable
● Note: The notation can become confusing when different sources place the &
differently. The following three declarations are equivalent:
int &r = n;
int& r = n;
int & r = n;
The spacing between the "int" and the "r" is irrelevant. All three of these declare r as a
reference variable that refers to n.

Pass By Value
● Recall that the variables in the formal parameter list are always local variables of a
function
● Consider this example program
o The Twice function takes two integer parameters, and multiplies each by 2.
o Note that the original variables passed into the function from main() are not
affected by the function call
o The local parameters a and b are copies of the original data sent in on the call
● This is known as Pass By Value , function parameters receive copies of the data sent
in.
void Func1(int x, double y)
{
x = 12; // these lines will not affect the caller
y = 20.5; // they change LOCAL variables x and y
}

● In the function above, any int and double r-values may be sent in

int num = 5;
double avg = 10.7;
Func1(num, avg); // legal
Func1(4, 10.6); // legal
Func1(num + 6, avg - 10.6); // legal

Programming Fundamentals (Lab Manual) Page 116 of 147


BS (Computer Science) 2023

Task No. 15
Q: Write a program to exchange the values of two variables by using reference
arguments in the function.
#include<iostream>
using namespace std;
void exch(int &,int &);
int main(){
int a,b;
cout<<"Assign value to variable A =";
cin>>a;
cout<<"Assign value to variable B =";
cin>>b;
exch(a,b);
cout<<"Values after exchange"<<endl;
cout<<"Value of A= "<<a<<endl;
cout<<"Value of B= "<<b<<endl;
cout<<"OK";
}
void exch(int &x,int & y)
{
int t;
t=x;
x=y;
y=t;
}
Task No. 16
Q: Write a to find the factorial
of a given number by using
function and also by using
reference parameters.
#include<iostream>
using namespace std;
void fact(int &,int &);
int main(){
int f=1,n;
cout<<"Enter any number to find thier factorial =";
cin>>n;
fact(f,n);
cout<<"Calculated factorial is ="<<f;
}
Programming Fundamentals (Lab Manual) Page 117 of 147
BS (Computer Science) 2023

void fact(int & fact,int & a)


{ for(;a>=1;a--){
fact*=a; }
}

Default Arguments
In C++ programming, you can provide default values for function parameters. The idea
behind default argument is simple. If a function is called by passing argument/s, those
arguments are used by the function. But if the argument/s are not passed while invoking a
function then, the default values are used. Default value/s are passed to argument/s in the
function prototype.

Working of default arguments

Programming Fundamentals (Lab Manual) Page 118 of 147


BS (Computer Science) 2023

Task No. 17
Q: Write a program in which two default
parameters are defined in the function
declaration.
#include<iostream>
using namespace std;
void temp(char[]="Pakistan", int =2);
int main(){
temp();
temp("Islamabad",10);
cout<<"OK";
}
void temp(char x[15], int y)
{ for(int c=1;c<=y;c++)
{ cout<<x<<endl;
}
}
Command line arguments
The most important function of C/C++ is main() function. It is mostly defined with a return
type of int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C and C++. Command-line arguments are
given after the name of the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first
argument is the number of command line arguments and second is list of command-line
arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv[]) { /* ... */ }
● argc (ARGument Count) is int and stores number of command-line arguments
passed by the user including the name of the program. So if we pass a value to a
program, value of argc would be 2 (one for argument and one for program name)
● The value of argc should be non negative.
● argv(ARGument Vector) is array of character pointers listing all the arguments.
● If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
● Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.

Programming Fundamentals (Lab Manual) Page 119 of 147


BS (Computer Science) 2023

Task No. 19
Q: Write a program to copy one
string to another by using the
command line arguments.
#include<iostream>
void repchar(char ='*',int=45);
using namespace std;
int main()
{
repchar();
cout<<endl;
repchar('=');
cout<<endl;
repchar('+',30);
}
void repchar(char ch,int n)
{ for(int j=0;j<n;j++)
{ cout<<ch;
}
}
Inline Functions in C++
Inline function is one of the important feature of C++. So, let’s first understand why inline
functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the memory address
of the instruction following the function call, copies the arguments of the function on the
stack and finally transfers control to the specified function. The CPU then executes the
function code, stores the function return value in a predefined memory location/register and
returns control to the calling function. This can become overhead if the execution time of
function is less than the switching time from the caller function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of the function call is
usually insignificant compared to the amount of time the function takes to run. However, for
small, commonly-used functions, the time needed to make the function call is often a lot
more than the time needed to actually execute the function’s code. This overhead occurs for
small functions because execution time of small function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead. Inline function is a
function that is expanded in line when it is called. When the inline function is called whole
code of the inline function gets inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small. The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
Remember, inlining is only a request to the compiler, not a command. Compiler can ignore
the request for inlining. Compiler may not perform inlining in such circumstances like:

Programming Fundamentals (Lab Manual) Page 120 of 147


BS (Computer Science) 2023

1) If a function contains a loop. (for, while, do-while)


2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in
function body.
5) If a function contains switch or goto statement.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal function
calls. Other optimizations can be obtained by considering the flows of calling context and the
called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.

Task No. 19
Q: Write a program to find
the exponential power of a
given number.
#include<iostream>
using namespace std;
inline int expp(int b,int e)
{ int c,pp=1;
for(c=1;c<=e;c++)
{
pp*=b;
return pp;
}
}
int main(){
int n,p,res;
cout<<"Enter any number = ";
cin>>n;
cout<<"Enter raise to the power = ";
cin>>p;
cout<<expp(n,p);
}
Task No. 20
Q: Write a program that inputs radius of circle and uses an inline function Area() to
calculate and return the area of circle.
SOURCECODE:
#include <iostream>
using namespace std;
Programming Fundamentals (Lab Manual) Page 121 of 147
BS (Computer Science) 2023

inline void Area(int r)


{ int area = (3.1416)*r*r;
cout << area << endl ;
}
int main()
{ int r ;
cout << "Enter the radius : " << endl;
cin>> r;
Area(r);
}

C++ Function Overloading


Two or more functions having same name but different argument(s) are known as overloaded
functions. Function refers to a segment that group’s code to perform a specific task. In C++
programming, two functions can have same name if number and/or type of arguments passed
are different. These functions having different number or type (or both) of parameters are
known as overloaded functions.
For example:
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }

Here, all 4 functions are overloaded functions because argument(s) passed to these functions
are different. Notice that, the return type of all these 4 functions are not same. Overloaded
functions may or may not have different return type but it should have different argument(s).
// Error code
int test(int a) { }
double test(int b){ }

The number and type of arguments passed to these two functions are same even though the
return type is different. Hence, the compiler will throw error.
Task No. 21
Q: Write a program that defines functions overloading.
#include<iostream>
using namespace std;
int sum(int ,int );
int sum(int,int,int);
double
sum(double,double,double
);
int main(){
Programming Fundamentals (Lab Manual) Page 122 of 147
BS (Computer Science) 2023

cout<<"Sum of 3 integer values = "<<sum(2,4,5)<<endl;


cout<<"Sum of 3 float values = "<<sum(2.6,4.7,5.6)<<endl;
cout<<"Sum of 2 integers values = "<<sum(2,4)<<endl;
cout<<"OK"; }
int sum(int x, int y)
{ return x+y; }
int sum(int x,int y,int z)
{ return x+y+z; }
double sum(double x,double y,double z)
{ return x+y+z; }

Task No. 21
Q: Write a program to perform the mathematical operations (Addition, Subtraction,
Multiplication, Division) using functions overloading.
Source Code:
#include <iostream>
using namespace std;
float add(float x, float y);
float sub(float x,float y);
float multiply (float x, float y);
float divide (float x, float y);
int main ()
{ while(true)
{
float x,y;
char op;
cout <<"Enter operator : ";
cin>>op;
switch (op)
{ case '+':
cout << "Enter num1 : ";
cin >> x;
cout << "Enter num2 : ";
cin >> y;
cout << "The sum of these numbers : "<< add(x,y) << endl <<endl;
break;
case '-':
cout <<
"Enter num1 : ";
cin >> x;

Programming Fundamentals (Lab Manual) Page 123 of 147


BS (Computer Science) 2023

cout << "Enter num2 : ";


cin >> y;
cout << "The sub of these numbers : "<< sub(x,y) << endl<<endl;
break;
case '*':
cout << "Enter num1 : ";
cin >> x;
cout << "Enter num2 : ";
cin >> y;
cout << "The result after multiplying these numbers : "<< multiply(x,y) <<
endl<<endl;
break;
case '/':
cout << "Enter num1 : ";
cin >> x;
cout << "Enter num2 : ";
cin >> y;
if (y!= 0 )
{ cout << "The result after dividing these numbers : "<< divide(x,y) << endl<<endl;
}
else
{
cout <<"The division is impossible!" << endl<<endl; }
break;
default:
cout << "Invalid Operator!" << endl<<endl;
}
}
system ("pause");
return 0;
}
float add(float x , float y)
{ return x + y; }
float sub (float x, float y)
{ return x - y; }
float multiply(float x, float y)
{ return x * y; }
float divide(float x , float y )
{ return x / y ;
}

Programming Fundamentals (Lab Manual) Page 124 of 147


BS (Computer Science) 2023

STUDENT TASK:
1. Write a program in c++ to print your bio data on screen by using functions.
2. Write a program in c++ to pass four arguments of float data type to a function,
compare the numbers and find out the larger value without using any logical
operators.
3. Write a program in c++ to copy one structure variable to another structure variable by
passing arguments of structure type to a function.
4. Write a program in c++ to find out if a numver entered from the keyboard is a prime
number or not by using a function.
5. Write a program in c++ to input values into an array. Pass the array as argument to a
function and print out the even values of array in the function. Also calculate the sum
of odd values of the array in the same function and return the sum to the calling
function.
6. Write a program in c++ to pass an integer value to a function so that the function
returns the integer with its digit reversed e.g to return 4567 as 7654.
7. Write a program in c++ to find out the greater of the two values by usin function
template.

Programming Fundamentals (Lab Manual) Page 125 of 147


BS (Computer Science) 2023

LAB 11: “POINTERS”


Objectives:
• A pointer is used that stores the memory address of an object.
• Pointers are used extensively in both C and C++ for three main purposes:
o to allocate new objects on the heap
o to pass functions to other functions

Theoretical Description:

• In this lab the student will learn the variable that stores the address of another
variable.
• As Pointers are easy and fun to learn. Some C++ tasks are performed more easily
with pointers, and other C++ tasks, such as dynamic memory allocation

Lab Task(s):
Student will implement various C++ programs using the concepts of Pointers.

Programming Fundamentals (Lab Manual) Page 126 of 147


BS (Computer Science) 2023

Pointers
Pointers are powerful features of C++ that differentiates it from other programming
languages like Java and Python. Pointers are used in C++ program to access the memory and
manipulate the address.

Address In C++
To understand pointers, you should first know how data is stored on the computer. Each
variable you create in your program is assigned a location in the computer's memory. The
value the variable stores is actually stored in the location assigned. To know where the data is
stored, C++ has an & operator. The & (reference) operator gives you the address occupied by
a variable. If var is a variable then, &var gives the address of that variable.
Pointers Variables
C++ gives you the power to manipulate the data in the computer's memory directly.
You can assign and de-assign any space in the memory as you wish. This is done
using Pointer variables. Pointers variables are variables that points to a specific
address in the memory pointed by another variable.

DECLARE A POINTER
int *p;
OR,
int* p;

● The statement above defines a pointer variable p. It holds the memory address
● The asterisk is a dereference operator which means pointer to.
● Here, pointer p is a pointer to int, i.e., it is pointing to an integer value in the memory
address.

Reference operator (&) and Deference operator (*)


Reference operator (&) as discussed above gives the address of a variable. To get the value
stored in the memory address, we use the dereference operator (*). For example: If a number
variable is stored in the memory address 0x123, and it contains a value 5. The reference (&)
operator gives the value 0x123, while the dereference (*) operator gives the value 5.

Note: The (*) sign used in the declaration of C++ pointer is not the dereference pointer. It is
just a similar notation that creates a pointer.

Programming Fundamentals (Lab Manual) Page 127 of 147


BS (Computer Science) 2023

Q. C++ Program to demonstrate the working of pointer.

#include <iostream>
using namespace std;
int main() {
int *pc, c;
c = 5;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
pc = &c; // Pointer pc holds the memory address of variable c
cout << "Address that pointer pc holds (pc): "<< pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;
c = 11; // The content inside memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;
*pc = 2;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;
return 0;
}
Output

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 5
Address that pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 5
Address pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 11
Address of c (&c): 0x7fff5fbff80c
Value of c (c): 2
Explanation of program

● When c = 5; the value 5 is stored in the address of variable c - 0x7fff5fbff8c.


● When pc = &c; the pointer pc holds the address of c - 0x7fff5fbff8c, and the expression
(dereference operator) *pc outputs the value stored in that address, 5.
● When c = 11; since the address pointer pc holds is the same as c - 0x7fff5fbff8c, change
in the value of c is also reflected when the expression *pc is executed, which now
outputs 11.
● When *pc = 2; it changes the content of the address stored by pc - 0x7fff5fbff8c. This is
changed from 11 to 2. So, when we print the value of c, the value is 2 as well.

Programming Fundamentals (Lab Manual) Page 128 of 147


BS (Computer Science) 2023

Task No. 01
Q: Write program to assign two values to integer variables a & b. Assign the memory
addresses of variables a & b to pointer variables x & y, respectively. Print out the
memory addresses of variables a & b through their pointer variables.

Code:
#include<iostream>
using namespace std;
int main(){
int a,b;
int *x,*y;
a=126;
b=19;
x=&a;
y=&b;
cout<<"Address of variable is a="<<x<<endl;
cout<<"Address of variable b= "<<y;
}

Programming Fundamentals (Lab Manual) Page 129 of 147


BS (Computer Science) 2023

Task No: 02
Q: Write a program to assign value to a variable using its pointer variable. Print out the
value using the variable name and also print out the memory adderess of the variable
using the pointer variable.
#include<iostream>
using namespace std;
int main(){
int *p;
int a;
p= &a;

cout<<"Enter data value= ";


cin>>*p;
cout<<"Value of variable a="<<a<<endl;;
cout<<"Memory address of variable is a="<<p;
}

Pointer and Arrays


▪ There is a close relationship between pointer and arrays.
▪ Array consists of consecutive locations in memory.

Programming Fundamentals (Lab Manual) Page 130 of 147


BS (Computer Science) 2023

▪ To access an array, memory location of the first element of array is accessed using
pointer variable.
▪ Pointer is then incremented to access other elements of array.
▪ When an array is declared, array name point to the starting address of the array.
e.g int a[5];
int *ptr;
▪ To store staring address of array a(or the address of first element)following statement
is used: ptr = a; //Address operator is not used when array name is used.
▪ If an element of array is used , then & operator is used as:
ptr = &a[0]; // memory address of 1st element of array
▪ When an integer value is added to or subtracted from the pointer variable “ptr” the
contents of pointer variable is incremented or decremented by:
(1 x size of element)
▪ E.g
▪ Array of int type has elements of 2 bytes
▪ Array of float type has elements of 4 bytes
▪ Array of char type has elements of 1 byte
▪ Suppose the location of first element in 200, i.e. value of pointer variable ptr is 200
and it refers to an integer variable.
▪ When following statement is executed,
ptr = ptr + 1 ;
The new value of ptr will be:
200 + 1 * 2 = 202.

ptr ptr+1 ptr+2 ptr+3 ptr+4


200 202 204 206 208

a[0] a[1] a[2] a[3] a[4] ----

Task N0. 01
Q: Write a program to input data into an array and then to print on the screen by using
pointer notation.
#include<iostream>
using namespace std;
#include<conio.h>
Programming Fundamentals (Lab Manual) Page 131 of 147
BS (Computer Science) 2023

int i,u;
main(){
int arr[5],*pp,i;
pp=arr;
for(i=0;i<=4;i++)
cin>>arr[i];
for(i=0;i<=4;i++)
cout<<*pp++<<endl;
}
Task No. 02
Q: Write a program to input
data into an array and find out
the maximum number from
array through pointer.
#include<iostream>
using namespace std;
#include<conio.h>
int i,u;
main(){
int arr[5],*pp,i,max;
pp=arr;
for(i=0;i<=4;i++)
{ cout<<"Enter value into an array["<<i<<"]=";
cin>>arr[i];
cout<<endl;
}
max=*pp;
for(i=1;i<=4;i++)
{ *pp++;
if(max<*pp)
{max=*pp;}
}
cout<<"Maximum value is = "<<max;
getch();
}
Task No. 03
Q: Declare an array of pointers and assign these pointers with addresses of different
variables and then display these addresses on the screen.
SOURCECODE:
#include <iostream>
using namespace std;
int main()
{ int *ptr[3];
Programming Fundamentals (Lab Manual) Page 132 of 147
BS (Computer Science) 2023

int a[3];
for (int i = 0 ; i < 3 ; i++)
{ cout << "Enter the number : " ;
cin >> a[i];
ptr[i]= &a[i];
}
for (int i = 0 ; i< 3 ; i++)
{ cout << ptr[i] << " \t" <<
*ptr[i] << endl;
}}

Task No. 04
Q: Write a program in which declare an array of integers and then display the
addresses of these integers using the pointer!
SOURCECODE:
#include<iostream>
using namespace std;
int main()
{ int *ptr; int set[5];
for (int i= 0 ;i<5 ; i++)
{ cin>>set[i]; }
ptr = &set[0];
for (int i = 0; i<5;i++)
{ cout << *ptr++ << " Its address is " << ptr << endl; }
}

Passing Pointers As an Arguments To Functions


▪ Pointer variable can also be passed to function as arguments.
Programming Fundamentals (Lab Manual) Page 133 of 147
BS (Computer Science) 2023

▪ When a pointer is passed to function, the address of the variable is passed to function.
▪ i.e variable is passed to function by reference.

Task No. 03
Q: Write a program that passing pointer as arguments to a function.
#include<iostream>
using namespace std;
void temp(int *,int *);
int main(){
int a,b;
a=10;
b=20;
temp(&a,&b);
cout<<"Value of a ="<<a<<endl;
cout<<"Value pf b ="<<b;
}
void temp(int*x,int*y)
{
*x=*x+100;
*y=*y+100;
}
Task No. 04
Q: Write a program to convert kilogram into grams by passing pointers as arguments
to the function.
#include<iostream>
#include<conio.h>
using namespace std;
void fc(float*);
main(){
float f,*c;
c=&f;
cout<<"Enter temperature in Farenheit ? ="; cin>>f;
fc(&f);
cout<<"Temperature in Celcius = "<<*c<<endl;
getch();
}
void fc(float *x)
{ *x=(*x-
32)*5.0/9.0; }

Programming Fundamentals (Lab Manual) Page 134 of 147


BS (Computer Science) 2023

Task No. 05

Q: Write a program to convert kilogram into grams by passing pointers as arguments


to the function.

#include<iostream>
#include<conio.h>
using namespace std;
void grams(float*);
main(){
float kg, *gm;
gm= &kg;
cout<<"Enter kilograms ? ="; cin>>kg;
grams(&kg);
cout<<"Calculated result in grams = "<<*gm<<endl;
getch();
}
void grams(float *x)
{ *x=*x*1000;
}

Pointers & Strings


▪ A string is a sequence of characters.
▪ A string type variable is declared in the same manner as an array type variable is declared.
▪ Since string is like an array , pointer variable can be used to access it.
Task No. 06

Q: Write a program in which a string is printed by printing its characters one by one.
#include<iostream>
#include<conio.h>
using namespace std;
void ppp(char *);
main()
char st[]="Pakistan";
ppp(st);
cout<<endl<<"OK";
}
Programming Fundamentals (Lab Manual) Page 135 of 147
BS (Computer Science) 2023

void ppp(char *sss)


{ while(*sss !='\0')
{

cout<<*sss<<endl;
*sss++;
}
}

Task No. 07
Q: Write a program to copy one string to another string by using pointers.
#include<iostream>
#include<conio.h>
using namespace std;
void copystr(char *, char *);
main(){
char str1[25],str2[25];
cout<<"Enter first string = ";
gets(str1);
copystr(str2,str1);
cout<<endl<<"First string is = "<<str1;
cout<<endl<<"Copied string is = "<<str2;
getch();
}
void copystr(char *tar,char *src)
{ while (*src !='\0')
{ *tar++=*src++; }
*tar='\0';
}

Task No. 08

Programming Fundamentals (Lab Manual) Page 136 of 147


BS (Computer Science) 2023

Q: Write a program to combine two strings by using pointers.


#include<iostream>
#include<conio.h>
using namespace std;
void combine(char*,char *,char *);
main()
{
char st1[25],st2[25],catstr[25];
cout<<"Enter first string = ";
gets(st1);
cout<<"Enter second string = ";
gets(st2);
combine(catstr,st1,st2);
cout<<endl<<"Combined string is = "<<catstr;
getch();
}
void combine(char *res,char *s1, char *s2)
{
while(*s1!='\0')
{
*res++=*s1++; }
while(*s2!='\0')
{
*res++=*s2++; }
*res='\0';
}

STUDENT TASK:
1. Write a program in c++ to exchange the values of two variables by using pointers.
Programming Fundamentals (Lab Manual) Page 137 of 147
BS (Computer Science) 2023

2. Write a program in c++ to input data into an array and then to find out the minimum value
in the array by using pointers.

3. Write a program in c++ to input any integer value and then to find out if the given value is
a prime number or not by passing the number to the function as a pointer argument.

4. Write a program in c++ to input data into an array of float type, sort the array in
descending order by using ponters.

Programming Fundamentals (Lab Manual) Page 138 of 147


BS (Computer Science) 2023

LAB 14: “FILE HANDLING”

Objectives:

• File handling is the method of storing data in the C++ program in the form of an
output or input that might have been generated while running a C program in a data
file
• A binary file or a text file for future analysis and reference in that very program.

Theoretical Description:

In this lab student will learn:

• File handling that provides a mechanism to store the output of a program in a file and
to perform various operations on it.
• A stream is an abstraction that represents a device on which operations of input and
output are performed.
• Files are used to store data in a storage device permanently.

Lab Task(s):

Student will implement File handling programs in C++.

Programming Fundamentals (Lab Manual) Page 139 of 147


BS (Computer Science) 2023

Data File Handling In C++


File: The information / data stored under a specific name on a storage device, is called a file.
Stream: It refers to a sequence of bytes.
Text file: It is a file that stores information in ASCII characters. In text files, each line of text
is terminated with a special character known as EOL (End of Line) character or delimiter
character. When this EOL character is read or written, certain internal translations take place.
Binary file: It is a file that contains information in the same format as it is held in memory. In
binary files, no delimiters are used for a line and no translations occur here.
Classes for file stream operation
● 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.
OPENING A FILE
OPENING FILE USING CONSTRUCTOR
● ofstream fout(“results”); //output only
● ifstream fin(“data”); //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode), ofstream ofile; ofile.open(“data1”); ifstream ifile;
ifile.open(“data2”);
FILE MODE PARAMETER MEANING
● ios::app Append to end of file
● ios::ate go to end of file on opening
● ios::binary file open in binary mode
● ios::in open file for reading only
● ios::out open file for writing only
● ios::nocreate open fails if the file does not exist
● ios::noreplace open fails if the file already exist
● ios::trunc delete the contents of the file if it exist
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open():
fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);
CLOSING FILE
● fout.close();
● fin.close();
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly, the function
get() reads a single character form the associated stream.
Programming Fundamentals (Lab Manual) Page 140 of 147
BS (Computer Science) 2023

For Example:
● file.get(ch);
● file.put(ch);
● write() and read() function
● write() and read() functions write and read blocks of binary data.
● example:
● file.read((char *)&obj, sizeof(obj));
● file.write((char *)&obj, sizeof(obj));
ERROR HANDLING FUNCTION
FUNCTION RETURN VALUE AND MEANING
● eof() returns true (non zero) if end of file is encountered while reading; otherwise return
false(zero)
● fail() return true when an input or output operation has failed
● bad() returns true if an invalid operation is attempted or any unrecoverable error has
occurred.
● good() returns true if no error has occurred.
File Pointers and Their Manipulation
All i/o streams objects have, at least, one internal stream pointer:
● ifstream, like istream, has a pointer known as the get pointer that points to the element
to be read in the next input operation.
● ofstream, like ostream, has a pointer known as the put pointer that points to the
location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream (which is itself
derived from both istream and ostream). These internal stream pointers that point to the
reading or writing locations within a stream can be manipulated using the following member
functions:
● seekg() moves get pointer(input) to a specified location
● seekp() moves put pointer (output) to a specified location
● tellg() gives the current position of the get pointer
● tellp() gives the current position of the put pointer
The other prototype for these functions is:
● seekg(offset, refposition );
● seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter refposition. The refposition takes one of the following
three constants defined in the ios class.
● ios::beg start of the file
● ios::cur current position of the pointer
● ios::end end of the file
Example:
Programming Fundamentals (Lab Manual) Page 141 of 147
BS (Computer Science) 2023

file.seekg(-10, ios::cur)

Task No. 01
Q. Program to write in a file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]="Time is a great teacher but unfortunately it kills all its pupils. -Berlioz";
fout<<str;
fout.close();
return 0;
}
Task No. 02
Q. Program to read from text file and display it.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
Task No. 03
Programming Fundamentals (Lab Manual) Page 142 of 147
BS (Computer Science) 2023

Q. Program to count number of characters.


#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<<count;
fin.close();
getch();
return 0;
}
Task No. 04
Q. Program to count number of words.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char word[30]; int count=0;
while(!fin.eof())
{
fin>>word;
count++;
}
cout<<"Number of words in file is "<<count;
fin.close();
getch();
return 0;
}
Programming Fundamentals (Lab Manual) Page 143 of 147
BS (Computer Science) 2023

Task No. 05
Q. Program to count number of lines.
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
char str[80]; int count=0;
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}
Task No. 06
Q: Write a program to write in a file.
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream a;
a.open("myfirstfile.txt");
a<<"Hello World"<<endl;
a<<"Ok Bye";
return 0;
}

Programming Fundamentals (Lab Manual) Page 144 of 147


BS (Computer Science) 2023

Task No: 07
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char data[100];
//writing to open a file
ofstream outfile;
outfile.open("afile.txt");
cout<<"Writing to the file"<<endl;
cout<<"Enter your name"<<endl;
cin.getline(data,100);
//write input
outfile<<data<<endl;
cout<<"Enter your age"<<endl;
cin>>data;
cin.ignore();
outfile<<data<<endl;
outfile.close();
//reading
ifstream inpfile;
inpfile.open("afile.txt");
cout<<"Reading from the file"<<endl;
inpfile>>data;
cout<<data<<endl;
inpfile>>data;
cout<<data;
return 0;
}

Programming Fundamentals (Lab Manual) Page 145 of 147


BS (Computer Science) 2023

STUDENT TASK:
1. Write a program in c++ to store records of a persons in a formatted file “data.dat”.
Each record contains the following information about a person:
Name, Address, Telephone number, Blood Group
2. Write a program in c++ to read records from the formatted file “data.dat” created in
the above program.

Programming Fundamentals (Lab Manual) Page 146 of 147

You might also like