1-1 Lab Manual - Programming Fundamentals
1-1 Lab Manual - Programming Fundamentals
LAB MANUAL
PROGRAMMING FUNDAMENTALS
Course Code: CS141
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
Tools/ Technologies
• C++ Language
• Dev C++
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.
statements.
Experiment
TOPICS TO BE COVERED
#
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
Arrays initialization , operations, , passing to functions, Multidimensional Arrays
14
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
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):
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
SAVE SETUP
SELECT LANGUAGE
LISCENESE AGREEMENT
CHOOSE COMPONENTS
CHOOSE DIECTORY
INSTALLATION FINISHED
SAVE FILE
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
cout<<"hello world";
getch();
}
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.
● 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.
Objectives:
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):
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;
}
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.
Objectives:
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):
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.
Theoretical Description:
Lab Task(s):
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;
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;
}
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:
Theoretical Description:
Lab Task(s):
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
}
}
● 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
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
Lab Task(s):
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"; }
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;}
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;
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
OUTPUT:
CONDITIONAL OPERATORS
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;
}}
• 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):
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':
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;
}
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;
}
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):
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.
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
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++;
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;
}
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.
Objectives:
Theoretical Description:
Lab Task(s):
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
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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
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;
} } }
STUDENT TASK:
Theoretical Description:
Lab Task(s):
Student will implement various C++ programs using the concepts of Array.
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:
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.
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:
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 {}:
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;
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)
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; }
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;
}
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
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!!!
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.
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
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;
}
}
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};
#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++){
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
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.
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.
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;
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:
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;
}
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>
STUDENT TASK:
1. Write a program in c++ to define a program in a structure that has the following
members:
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.
• 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.
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 −
● 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
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.
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
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
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.
#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>
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';
}
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);
}
.
.
.
}
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 −
#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
}
}
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;
}
⮚ 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; }
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.
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:
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
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
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.
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.
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:
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
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
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;
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.
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.
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.
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.
#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
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;
}
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;
▪ 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.
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; }
}
▪ 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; }
Task No. 05
#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;
}
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
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
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.
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:
• 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):
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
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;
}
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;
}
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.