0% found this document useful (0 votes)
4 views39 pages

Programming Fundamental Lab Manual Updated (1)

This laboratory workbook provides an introduction to programming fundamentals, specifically focusing on C++. It covers various programming languages, the C++ language features, and a series of lab exercises designed to familiarize students with programming concepts, data types, and the Integrated Development Environment (IDE) Microsoft Visual Studio. The workbook includes objectives for each lab, theoretical explanations, and practical exercises to reinforce learning.

Uploaded by

Jokerrr Noub
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views39 pages

Programming Fundamental Lab Manual Updated (1)

This laboratory workbook provides an introduction to programming fundamentals, specifically focusing on C++. It covers various programming languages, the C++ language features, and a series of lab exercises designed to familiarize students with programming concepts, data types, and the Integrated Development Environment (IDE) Microsoft Visual Studio. The workbook includes objectives for each lab, theoretical explanations, and practical exercises to reinforce learning.

Uploaded by

Jokerrr Noub
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 39

Laboratory Workbook

Programming Fundamentals

Name _______________________
Roll No ______________________
Semester
_____________________
Marks ______________ Signature____________________

Department of Computer Science


2016
Introduction
Computer programming (often shortened to programming) is a process that leads from an
original formulation of a computing problem to executable computer programs.
Programming involves activities such as analysis, developing understanding, generating
algorithms, verification of requirements of algorithms and implementation of algorithms in
a target programming language. The purpose of programming is to find a sequence of
instructions that will automate performing a specific task or solving a given problem.

Computer programming involves developing lists of instructions - the source code


representation of software. Source code is written in one or more programming languages.
Following are types of programming languages.

1. Machine Language
The fundamental language of the computer’s processor, also called Low Level
Language. All programs are converted into machine language before they can be
executed. It consists of combination of 0’s and 1’s.

2. Assembly Language
A low level language that is similar to machine language. It uses symbolic operation
code called mnemonics to represent the machine operation code.

3. High level Language


These Computer programming languages are easier to learn. Uses English like
statements. This is not machine readable thus needs to be converted to machine
language before execution.
Examples: C, C ++, Visual Basic, Pascal, FORTRAN etc.

C++-language
C++ is a powerful, high-performance programming language that is widely used for system software, game
development, real-time applications, and other performance-critical tasks. It is an extension of the C programming
language, incorporating object-oriented features such as classes and inheritance, which enable more structured
and modular code. C++ provides a rich set of features like manual memory management, pointers, and templates,
giving developers fine-grained control over system resources. Its flexibility and efficiency make it a preferred
choice for applications where speed and resource optimization are essential. However, this also means that it has a
steeper learning curve compared to higher-level languages.
Content
Lab
Lab Objective
No.
1 Introduction to C++
2 Console Output
3 Data Types & Variables
4 Console Input
5 Operators in C++ & Math functions
6 Loops
7 Selection Statements
8 Functions

9 Arrays

10 Structures
11 Pointers
12 Graphics
13 Charts – Graphics
14 Filing
15 Hardware Programming
Lab Details
Marks
Lab Signatur
Lab Objective Obtaine
No. e
d
Introduction to C++
Objective: Getting familiar with the IDE and working with Microsoft
1 Visual Studio. Installing and copying the compiler, changing directory
settings. Making first program in C++. Saving / copying files to USB or
other storage devices.
Student Feedback:

Console Output
2 Objective:Understanding and Using format specifier
and escape sequences with cout
Student Feedback:

Data Types & Variables


Objective:Studying different data types, variables,
3
variable names, variable declaration, variable
definition and variable initialization
Student Feedback:

Console Input
4 Objective:Taking Input from the user at console
screen using scanf and getche commands.
Student Feedback:

Operators in C++ &Math functions


Objective:Arithmetic operators, conditional operators,
5
assignment operators, Increment/decrement
operators.Studying Math functions.
Student Feedback:

Loops
Objective:Studying loops. For loops, nested for loops,
6 while loops, nested while loops, do while loops,
nested do while loops.Studying loops with cross
combination.
Student Feedback:
Selection Statements
7 Objective:Decision making and conditioning using If
statements, If-else statements, switch-case.
Student Feedback:

Functions
8 Objective:User defined functions, passing values to
function, and returning values from functions.
Student Feedback:

Arrays
Objective:Arrays, array index, single and multi-
9
dimensional arrays. Arrays and loops. Sorting data in
arrays.
Student Feedback:

Structures
10 Objective:Studying Structures, different ways to declare define
and initialize structures.
Student Feedback:

Pointers
11
Objective:Learnhow Pointers access data using memory address.
Student Feedback:

Graphics
12 Objective:Graphics, basic applications of graphics by making
buttons and animations.
Student Feedback:

Charts -Graphics
13
Objective:Draw different charts using C++ graphics.
Student Feedback:

Filing
14 Objective:Learn to create, open, write and close text
files for data storage With C++ language.
Student Feedback:

15 Hardware Programming
Objective:Understanding registers and accesses the
hardware using C++ language. Learn the basics of
Inline Assembly.
Student Feedback:

Experiment 1 .
Objective
Getting familiar with the IDE and working with Microsoft Visual Studio. Installing and copying the compiler, changing
directory settings. Making first program in C++. Saving / copying files to USB or other storage devices.

Unit 1.1: Getting familiar with the IDE

Theory

IDE
An integrated development environment (IDE) is a software suite that consolidates the basic tools developers need to write
and test software. Typically, an IDE contains a code editor, a compiler or interpreter and a debugger that the developer
accesses through a single graphical user interface (GUI). An IDE may be a standalone application, or it may be included as
part of one or more existing and compatible applications.

There are different IDE’s to write C program. Following are the two most common;
1. Microsoft Visual Studio

Microsoft Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer
programs for Microsoft Windows, as well as web sites, web applications and web services. Visual Studio uses Microsoft
software development platforms.

Visual Studio includes a code editor supporting IntelliSense as well as code refactoring. The integrated debugger works
both as a source-level debugger and a machine-level debugger. Visual Studio supports different programming
languages and allows the code editor and debugger to support nearly any programming language. Built-in languages
include C, C++, VB.NET, C# and F#.

Working withMicrosoft Visual Studio

Open Microsoft Visual Studio by double clicking on the Icon. The icon similar to the following (depending upon the version)
should be available on your desktop.

Figure 1.4: Visual Studio 2013

The application will run and following window will appear.


Figure 1.5: Visual Studio Start Page

We first have to create a project. To create a new project, click on “New Project” option present on the left side. A Window
similar to the one shown below will appear. Expand the template option present on left side of the window. Select “Visual C+
+” and under this, select “General” option. Select first option “Win32 Console Application” from the middle section. Provide
name for the project as “Lab1” and press OK.

Figure 1.6: Create new project

After you click OK, following screen will be displayed which has a Solution Explorer on the right hand side. This panel will be used to
access all the files of the project.
Figure 1.7: Solution Explorer

Now right click on your project “Lab1, and go to Add and then select New item, refer to the screenshot below.

Figure 1.8: Add new item

A window similar to one given below will appear. Select Visual C++ and code from the left panel. Select C++ file from the
middle panel. Give a name to your source file. This will by default create a file with .cpp extension which represents(C++).
Your file will appear in solution explorer under folder Source Files.

Now you can simply add a C program and execute the file.

Unit 1.2: Making first program in C

First C++ Program


#include< iostream >
#include<conio.h>
The first line of this program is #include<iostream> . Here #include tells the compiler to include something where as .h
means that it is a header file or in short we are including standard input/output header file. In the same way the next line is
similar to the first one but it has conio.h in it where conio means the black colour console screen where we see our output
and .h tells us that this is a header file. In other words we tell the compiler that we are including two files and the code we
will write will be of c language as the compiler also supports C++ code.

int main()
This is third line. The first word in this is void which means any thing that has no value or is useless. The next word is main
which is the brain function and is the only function readable in most programming languages. All the other functions are
called within the main function. The third word within brackets is also void. The first void means that the main function won’t
return any value while the second void means that the main function is not going to accept any value. This complete line
means that we have declared the main function here. For example a simple calculator takes two or more numbers from you
and returns the result like addition, subtraction, multiplication etc. It may be confusing at this time to understand the void
functionality but in experiment 11 we will discuss it in detail.

{
Following the main function line is a curly bracket which marks the starting of mains body. Always remember that if any
bracket is opened in C++ language it needs to be closed hence the last line of the above program marks the ending of main
function.

A black window will appear which is called console. The console will display the output of your program.

Excercise:
Task 1:
Run the following program and check the output

#include <iostream>
using namespace std;
int main() {
cout << "hello world" << endl; //prints hello world and endl means end the line.
return 0;
}
Task 2:
Write a C++ program to print the following lines:

You are 10 years old.


You are too young to play the game.

Experiment 2 .
Objective
Understanding and Using format specifier and escape sequences with cout

Theory
The C++ library function cout() sends formatted output to stdout. Following is the declaration for cout() function.

(void cout(const std::string& format))

Unit 2.1: Format specifier

format
This is the string that contains the text to be written to stdout. It can optionally contain embedded format tags that are replaced by the v

Format specifiers are used to substitute and print values inside a cout or scanf statement which are further applicable on
variables. Below is a chart of format specifier examples using cout.

No. Type Syntax Value Example


1 Single Character %c One character within single quotes cout(“%c”,’a’);
2 String %s A sentence of an unfixed length within double quotes cout(“%s”,”Iqra Univ”);
3 Decimal Integer %d Any whole number between -32,768 to 32,767 cout(“%d”, 12345);
4 Long Integer %ld Any number between -2,147,483,648 to 2,147,483,647 cout(“%ld”,1234567);
5 Float %f Any decimal point number between 1 0-38 to 1 038 cout(“%f”, 1234.567);
6 Double %lf Any decimal point number between 10-308 to 10308 cout(“%lf”,12345678);

Unit 2.2: Escape sequences with cout

Escape Sequences are used to adjust spacing between lines or characters or the characters themselves.

No. Syntax Application Example


1 \n New Line cout(“\n”);
2 \t Tab eight spaces to right cout(“\t”);
3 \b Back space One space back cout(“\b”);
4 \r Carriage return Start of same line cout(“\r”);
5 \’ Printing single quote cout(“\’”);
6 \” Printing double quotes cout(“\””);
7 \\ Printing back space cout(“\\”);
8 \xdd Printing characters by Hexa decimal ASCII value cout(“\x45”);
9 \ddd Printing characters by decimal ASCII value cout(“\d45”);

Example 2.1:
int main() {
// prints "Hello,World!":
cout << "Hello,W" << 'o' << "rld" << '!' << '\n';
}
This shows that the output operator can process characters as well as string literals. The three individual characters 'o', '!',
and '\n' are concatenated into the output the same was as the two string literals "Hello,W" and "rld".

Example 2.2:
int main() {
// prints "The Millennium ends Dec 31 2000.":
cout << "The Millennium ends Dec " << 3 << 1 << ' ' << 2000 << endl;
}
When numeric literals like 3 and 2000 are passed to the output stream they are automatically converted to string literals and
concatenated the same way as characters. Note that the blank character (' ') must be passed explicitly to avoid having the
digits run together.

Exercise:
Task 1:
Write a C++ program to make your resume with format specifiers and escape sequences showing your complete details.

Task 2:
Write and run a program that demonstrates round-off error by executing the following steps:
(1) initialize a variable a of type float with the value 666666;
(2) initialize a variable b of type float with the value 1-1/a;
(3) initialize a variable c of type float with the value 1/b - 1;
(4) initialize a variable d of type float with the value 1/c + 1;

Task 3:
int main() {
// prints the values of uninitialized variables
bool b; // not initialized
cout << "b = " << b << endl;
char c; // not initialized
cout << "c = [" << c << "]" << endl;
int m; // not initialized
cout << "m = " << m << endl;
int n; // not initialized
cout << "n = " << n << endl;
long nn; // not initialized
cout << "nn = " << nn << endl;
float x; // not initialized
cout << "x = " << x << endl;
double y; // not initialized
cout << "y = " << y << endl;
}
Experiment 3 .
Objective
Studying different data types, variables, variable names, variable declaration, variable
definition and variable initialization.

Unit 3.1: Data types & variables

Theory
Variables are declared by first writing
data types followed by a variable name, e.g.
int

a=10;

Here

int is data type,


a is variable name
and after the equals to sign (=) is the value in it
10 the value is always followed by a
terminator(;)

Supported Example
No. Data Type Syntax format Specifier Value
1 Single Character char %c One character within single quotes char a=’a’;
2 Decimal Integer int %d Any whole number between -32,768 to 32,767 int a=10;
3 Long Integer long int %ld Any number between -2,147,483,648 to 2,147,483,647 long int a=12345;
4 Float float %f Any decimal point number between 10-38 to 1038 float a=1234.567;
0-308
5 Double double %lf Any decimal point number between 1 to 10308 double a=1 23456;
Variable Names
Variable names will always start with an alphabet.
Variable names can contain numbers (1,2,45,66) and underscores (_) but no other special characters (!@#$%^&*).
Variable names cannot resemble to any predefined word e.g. include, printf, getch, scanf etc..
A variable name cannot be used for multiple declarations.

Example 2.1:

In the following C++ program, two integer variables num1 and num2 are declared and initialized. Answer the
following questions:

1. What is the value of num1 after initialization?


2. How is num2 initialized, and what is its value when it is printed?
3. Can you explain the difference between the initialization of num1 and num2 in this program?

Exercise:
Task 1:
Write a C++ program that declares three integer variables: num1, num2, and num3. Initialize num1 to 50 at the time
of declaration, and declare num2 and num3 without initialization. Later, prompt the user to input a value for num2
and set num3 to 100. The program should then print the values of all three variables and, based on the value
entered for num2, display a message: if num2 is less than 50, print "num2 is less than 50"; if num2 is 50 or greater,
print "num2 is greater than or equal to 50." Ensure that the output is clear, showing which value corresponds to
which variable.

Task 2:
Write a C++ program that declares three variables: length, width, and area. Initialize length to 10 and width
to 5 at the time of declaration. Declare area without initializing it, and then compute the area of a rectangle using
the formula area = length * width. Print the values of length, width, and area. Additionally, prompt the
user to input a new value for length and calculate the new area based on the user’s input. After updating the
area, if the new area is greater than 50, print the message "Area is large," otherwise print "Area is small." Ensure
your program outputs all values with clear labels.
Experiment 4 .
Objective
Taking Input from the user at console screen using cin and getche commands.

Unit 4.1: Taking Input from the user

Theory
cin command can take input of different data types at a time.
Getche command can take only one character input.

Unit 4.2: Scenario example question

Question: What will be the output if the user enters the following input?
 Name: Ali
 Age: 25

Output:
Exercise:

Task 1:

Write a C++ program that calculates and displays the Body Mass Index (BMI) based on user input for weight (in
kilograms) and height (in meters). The program should prompt the user to enter their weight and height, then
calculate the BMI using the formula BMI = weight / (height * height). Based on the BMI value, the
program should display whether the user is underweight (BMI < 18.5), normal weight (18.5 <= BMI < 24.9),
overweight (25 <= BMI < 29.9), or obese (BMI >= 30). The program should output the calculated BMI and the
corresponding category, ensuring accurate handling of floating-point input and conditional logic.

Task 2:
Write and run a program that prints the sum, difference, product, quotient, and remainder of two integers that are
input interactively

Task 3:
Write a C++ program that performs the following tasks:

1. Prompt the user to enter a full name (first and last name):
o Use cin to take the input.
o Display the full name entered by the user.
2. Prompt the user to press a key:
o Use the getche() or _getch() function to read and display the key pressed by the user without
requiring the user to press Enter.
Experiment 5 .
Objective
Arithmetic operators, conditional operators, assignment operators, Increment/decrement operators.Studying Math
functions.

Unit 5.1: Studying Math functions

Theory
Math.h header file is included for the definitions of math functions listed below. It is written as #include<math.h>.

Example
The program below shows the result for math and trigonometric functions. The functions pass the values to variables which
are further used for printing in cout.
Program Output
#include <iostream>
#include <cmath> // For math functions like sin,
cos, tan, sinh, cosh, tanh
#include <cstdlib> // For system("cls")

using namespace std;

int main() {
// Clear the console screen (works on Windows)
system("cls");

// Declare variables Trigonometric Functions


float a = 45, b = 1; sin 45 = 0.707107
float sn, cs, tn, snh, csh, tnh; cos 45 = 0.707107
// Calculate trigonometric and hyperbolic
tan 45 = 1
functions
sn = sin(a * M_PI / 180); // Convert 45
degrees to radians Hyperbolic Functions
cs = cos(a * M_PI / 180); // Convert 45 sinh 1 = 1.175201
degrees to radians
tn = tan(a * M_PI / 180); // Convert 45 degrees
cosh 1 = 1.543081
to radians tanh 1 = 0.761594

snh = sinh(b);
csh = cosh(b);
tnh = tanh(b);

// Display the results


cout << "\n\n\n Trigonometric Functions" <<
endl;
cout << "sin 45 = " << sn << endl;
cout << "cos 45 = " << cs << endl;
cout << "tan 45 = " << tn << endl;

cout << "\n\n\n Hyperbolic Functions" << endl;


cout << "sinh 1 = " << snh << endl;
cout << "cosh 1 = " << csh << endl;
cout << "tanh 1 = " << tnh << endl;

return 0;
}

Unit 5.2: Arithmetic operators

Unit 5.3: conditional operators

Unit 5.4: Assignment operators

Unit 5.5: Increment/decrement operators

Operators

Arithmetic Relational Assignment Increment/decrement


operators operators operators operators
Add + Greater Than > Addition assignment += Increment ++
Subtract - Less Than < Subtraction assignment -= Decrement --
Multiplication * Greater or Equal >= Multiplication assignment *=
Division / Less or Equal <= Division assignment /=
Remainder % Equal Equal ==
Not Equal !=
Example
Explain the following program after careful study.

Program Output
#include <iostream>
#include <cstdlib> // For system("cls")

using namespace std;

int main() {
// Clear the console screen (works on Windows)
system("cls");

// Declare variables
int a = 2, b = 4;
int c1, c2, c3, c4, d1, d2, d3, d4;

// Initialize variables
c1 = c2 = c3 = c4 = 5;
d1 = d2 = d3 = d4 = 8;
6 -2 8 0
// Perform and display arithmetic operations 010101
cout << "\n" << a + b << " " << a - b << " " << a 8 2 15 1
* b << " " << a / b << endl; 8 5 15 7
// Perform and display relational operations
cout << "\n" << (a > b) << " " << (a < b) << " "
<< (a >= b) << " " << (a <= b) << " " << (a == b) <<
" " << (a != b) << endl;

// Perform and display compound assignment


operations
cout << "\n" << (c1 += 3) << " " << (c2 -= 3) << "
" << (c3 *= 3) << " " << (c4 / 3) << endl;

// Perform and display increment/decrement


operations
cout << "\n" << (d1++) << " " << (++d2) << " "
<< (d3--) << " " << (--d4) << endl;

return 0;
}
Exercise:

Task 1:
Program the following.
Implement the following equation
3x4sin(180x) + 4x3 cos(90x) + x2sin(tan(45)) + 7x +

9cos(90x2 )

where x may be user defined value.

Task 2:
Program the following.
● Prompt user to input distance in Kilometers and display it in meters.
● Input any number from user and generate its square e.g. square of 8 is 64
● Input any number from user and generate its cube e.g. cube of 8 is 512
● Input a 4 digit number in any integer type variable and sum all the four digits, e.g. int a =3487, result
= 22
● Generate the table for a number input by the user.
For the following equation 3x4 + 4x3 + x2 + 7x + 9, substitute the user provided value of x and generate the
result.

Task 3:
Write a C++ program that demonstrates the use of arithmetic, relational, and logical operators.
The program should:

1. Perform arithmetic operations on two integer variables.


2. Compare these two variables using relational operators.
3. Use logical operators to combine multiple relational expressions.
4. Display the results for each of the above operations.

Requirements:

1. Use arithmetic operators (+, -, *, /, %).


2. Use relational operators (>, <, >=, <=, ==, !=).
3. Use logical operators (&&, ||, !).
4. Take two integer inputs from the user for performing operations.
5. Display the results of all operations clearly on the console.
Experiment 6
Objective
Studying loops. For loops, nested for loops, while loops, nested while loops, do while loops, nested do
while loops. Studying loops with cross combination.
Unit 6.1: For loops
Unit 6.2: while loops & do while loops
Theory
for while do while
initialization; initialization;
for(initialization ; check range ; iteration) do
while(check range)
{ {
{
body
b iteration;
b
o } while(check range)
o
d d
y y
} iteration;
}
Unit 6.3: Nested loops
Example This table below shows nested loops. All the three programs have same output

This program of while loops takes continuous input until enter key is pressed.

PROGRAM OUTPUT
#include <iostream>
#include <cstdlib> // For system("cls")

using namespace std;

int main() {
system("cls");
int a = 0;
char ch; Type any Sentence
cout << "Type any sentence" << endl;
while (true) { Iqra University
ch = cin.get(); Total Character typed=15
if (ch == '\r' || ch == '\n') {
break;
}
a++;
}
cout << "\nTotal Characters typed = " << a << endl;
return 0;
}

Exercise
Carefully observer the following program and write output with reasons.

Program Output
#include <iostream>
#include <cstdlib> // For system("cls")
using namespace std;
int main() {
system("cls");
for (int a = 1; a <= 12; a++) {
// Start loop from 1 to 12
cout << a << " x 2 = " << a * 2 << endl; } return 0;
}

#include <iostream>
#include <cstdlib> // For system("cls")
using namespace std; int main() {
system("cls");
for (int a = 0; a <= 12; a++) {
cout << a << " x 2 = " << a * 2 << endl;
}
return 0;
}

Program:
Following program gives the sum of all numbers input by the user using while loop. The program will display
the
sum when user enters 0 as input.
#include <iostream>
#include <cstdlib> // For system("cls")

using namespace std;

int main() {
system("cls"); // Clear the screen
int num = -1;
int sum = 0;

cout << "\nEnter 0 to stop adding the numbers" << endl;


while (num != 0)
{
cout << "\nEnter Number: ";
cin >> num;

sum = sum + num;


}

cout << "\nSum = " << sum << endl;


return 0; // Fixed typo here
}

Unit 6.4: loops with cross combination


Studying loops with cross combination
for do- do-while do-while
for while while for while do-while
while for while
for( ) while( ) for( ) do whil do
{ { { { e( ) { {
while( ) for( ) for( ) do while( ) }w
} } d }while( ) whil hile( )
o e( ) }
while( )
}

Example
The table below shows loops with cross combinations
Loop Program Output

For While #include <iostream>


#include <cstdlib> // For system("cls")

using namespace std;

int main() {
system("cls"); // Clear the screen
int a, b = 0;
000 001 002 003
100 101 102 103
for (a = 0; a <= 3; a++) {
200 201 202 203
b = 0;
300 301 302 303
while (b <= 3) {
cout << a << b << "\t"; // Use cout for printing
b++;
}
cout << endl;
}

return 0; // Corrected typo here


}
While for #include <iostream>
#include <cstdlib> // For system("cls")
using namespace std;
int main() {
000 001 002 003
system("cls"); // Clear the screen
100 101 102 103
int a = 0, b;
200 201 202 203
300 301 302 303
while (a <= 3) {
for (b = 0; b <= 3; b++) {
cout << a << b << "\t"; // Use cout for printing
}
cout << endl;
a++;
}

return 0; // Fixed typo here


}

Unit 6.5: Break & Continue


Understand the difference between break and continue by executing following programs.
break continue
int main() int main()
{ {
int i; int i;
double number, sum = 0.0; double number, sum = 0.0;

for(i=1; i <= 10; ++i) for(i=1; i <= 10; ++i)


{ {
cout << "Enter number " << i << ": "; cout << "Enter number " << i << ": ";
cin >> number; cin >> number;
// If user enters negative number, loop is terminated // If user enters negative number, loop is terminated
if(number < 0.0) if(number < 0.0)
{ {
break; continue;
} }

sum += number; // sum = sum + number; sum += number; // sum = sum + number;
} }

printf("Sum = %.2lf",sum); printf("Sum = %.2lf",sum);

return 0; return 0;
} }
Exercise:

Task 1:
You are tasked with writing a program to determine how many even and
how many odd numbers there are in a given list of integers . The program should:

Take the total number of integers to be entered.


Accept each integer one by one.
Count how many of the integers are even and how many are odd.
Display the counts of even and odd numbers.

Task 2:
A company organizes an annual coding competition.
The participants are divided into multiple teams, and each team has multiple rounds of practice.
The company wants to display the number of participants in each round for every team in a specific
format.
The format should display the number of participants in each round for each team,
followed by a horizontal line separating each team's data.
Task: Write a C++ program that takes the following input:
The number of teams.
The number of rounds for each team.
The number of participants in each round.

Team 1:
Round 1: 5 participants
Round 2: 8 participants
Round 3: 10 participants
---------------------------
Team 2:
Round 1: 6 participants
Round 2: 7 participants
Round 3: 9 participants

Task 3:
Write a C++ program that prints the following pattern:
1
**
22
****
333
******
4444
********
55555
Experiment 7
Objective
Decision making and conditioning using If statements, If-else statements, switch-case.
Theory
If Nested If If-else Else-if Switch-case
if(con if(cond switch(con
if(cond) if(cond)
d) ) d)
{ { { { {
Body If(cond) body body case’1‘:
} { } } body
el
body else case’2‘:
se
} { If(cond) body
} Body { }
} Body
}

Example
This program lets the user choose a number between 1 and 99 and guesses it in less than 10 hints.
Program Output
#include <iostream>
#include <limits> // For clearing input buffer

using namespace std;

int main() {
int lower = 1, upper = 99, guess, ch;
char response;

cout << "Think of a number between 1 & 99.\n";


cout << "Respond with the following:\n";
cout << "Press 'g' for greater, 'l' for less, 'e' for equal, 'q' to Think of a number between 1 & 99. Respond with the
quit.\n"; following:
Press 'g' for greater, 'l' for less, 'e' for equal, 'q' to quit. Is your
while (lower <= upper) { number greater, less, or equal to 50?
guess = lower + (upper - lower) / 2; // Binary search Enter your response (g/l/e): g
method to guess the number Is your number greater, less, or equal to 75?
cout << "\nIs your number greater, less, or equal to " << Enter your response (g/l/e): l
guess << "?\n"; Is your number greater, less, or equal to 62? Enter your
cout << "Enter your response (g/l/e): "; response (g/l/e): g
Is your number greater, less, or equal to 56? Enter your
// Input handling response (g/l/e): l
cin >> response; Is your number greater, less, or equal to 53? Enter your
response (g/l/e): g
// Check if the user wants to quit Is your number greater, less, or equal to 51? Enter your
if (response == 'q') { response (g/l/e): l
cout << "You chose to quit. Goodbye!" << endl; Is your number greater, less, or equal to 52? Enter your
break; response (g/l/e): e
} Great! I guessed your number: 52
// Validate input
if (response == 'e') {
cout << "Great! I guessed your number: " << guess <<
endl;
break;
} else if (response == 'g') {
lower = guess + 1; // The number is greater, so adjust
the lower bound
} else if (response == 'l') {
upper = guess - 1; // The number is less, so adjust the
upper bound
} else {
cout << "Invalid input. Please enter 'g' for greater, 'l' for
less, or 'e' for equal.\n";
Design a marks sheet for a student with 5 subjects includingMath, Physics,
Electronics, Islamiat and Computer Programming.

Take} marks as input from user calculate grade for each subject,CGPA and
percentage.
// Clearing
Detect input
error for outbuffer
rangedin case invalide.g.
numbers databelow
was entered
0 or above 100.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return 0;
}

This program prompts the user to type his/her name. If any thing other than Upper/lower case alphabets
or a space is entered for example 1 ,2,@#$% then it is detected and nothing is printed until a correct
character is input.
Program Output
#include <iostream>
#include <limits> // For clearing input buffer

using namespace std;

int main() {
char ch;

cout << "Name: ";

while ((ch = getchar()) != '\n') { // Read characters until Enter


is pressed
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '
') { Write the output for the program on left
// Valid character (alphabetic or space)
cout << ch; // Output the valid character
} else {
// Invalid character, so remove the last one
cout << "\b \b"; // Erase the last character from the
screen
}
}

cout << endl;

return 0;
}

Exercise:

Task 1:
Program the following.
● Make the number guessing program with switch case.
● Make an alphabet guessing program using if-else.
● Complete the simple calculator program for multiplication and division. Also make it using if-else.
● Make your resume such that in the name field it does not accept anything else than alphabets and
space bar.
● Look at the scenario below.
Marks Grade GPA
0-49 F 2
50-59 C 2.25
60-69 C+ 2.5
70-79 B 2.75
80-89 B+ 3
90-95 A 3.5
96-90 A+ 4
Task 2:
Program the following.

● Ask User to select one option from the following.


● Calculate area of Circle [c]
● Calculate area of Rectangle [r]
● Calculate area of Triangle [t]

● If user enters c then ask user to enter radius and calculate area using following formula.

● If user enters r then ask user to enter length & width and calculate area using following formula.

● If user enters t then ask user to enter base & height and area using following formula.

● Display the area.

Experiment 8
Objective
User defined functions, passing values to function, and returning values from functions.

Theory
Functions give user a facility to make functions according to their own needs.

Example
This program has a simple function with no return type or arguments passing and prints a sentence.
Program Output
#include <iostream>
#include <cstdlib> // For system("cls")

void iqra(void);

int main() {
system("cls"); // Clears the screen (works on
Windows)
iqra();
return 0;
} Iqra University
void iqra(void) {
std::cout << "\nIqra University" << std::endl;
}

This program has a function with no return type but two arguments passed as integers and printed with
their sum.

Program Output
#include <iostream>
#include <cstdlib> // For system("cls")

void add1(int a, int b);

int main() {
system("cls"); // Clears the screen (works on
Windows)
add1(2, 4);
return 0; // Corrected typo from 'retrun' to 'return'
} 2+4=6
void add1(int a, int b) {
std::cout << "\n" << a << " + " << b << " = " << a + b <<
std::endl;
}

Exercise:

Task 1:
Program the following.
● Rewrite the program you made in assignment 2 of last experiment using following functions.
✔ double circleArea(double radius)
✔ double rectangleArea(double width, double length)
✔ double triangleArea(double base, double height)
✔ displayArea(double area)
Task 2:
Program the following.
● Design a mark sheet for a student with 5 subjects including Math, Physics, Electronics, Islamiat and
Computer Programming.Take marks as input from user.
● Make separate functions for following;
✔ Calculate grade for each subject.
✔ Calculate CGPA for each subject.

Task 3:
Write a C++ program that includes overloaded functions to compute the sum of two values. The program
should behave as follows: if both arguments are integers, it should return the sum of the two integers; if
one or both arguments are floating-point numbers (float or double), it should return the sum as a floating-
point number. Additionally, include a function with a default argument, where the default argument is used
when only one value is passed, and the function should add the default argument to the provided value.
Demonstrate the behavior of these overloaded functions in main() with multiple test cases, including both
integer and floating-point inputs, and using the default argument.

Experiment 9
Objective
Arrays, array index, single and multi-dimensional arrays.Arrays and loops.Sorting data in arrays.

Theory
a
Arrays are variables that can hold 0 9
multiple values at one time. They have 1 4
a specified length and have addresses Values

known int a[5]={9,4,7,2,6}; Index/address


2 7
as indexes for data retrieval
starting from zero. 3 2
4 6

Stdlib.h is used for rand function which generates random numbers within a given range.
Example
Below are three tables showing one dimensional character, integer and float arrays. Each table shows
three different methods of declaring and initializing an array.
ONE DIMENSIONAL CHARACTER ARRAY
Method 1 Method 2 Method 3
(Declaration and initialization) (Declaration and initialization) (Separate declaration and initialization)
char a
[5];
a[0]='a';
char char a[5]={'a','b','c','d','e'}; char a [5]={"abcde"}; a[1]='b';
a[2]='c';
a[3]='d';
a[4]='e';

ONE DIMENSIONAL INTEGER ARRAY


Method 1 Method 2 Method 3
(Declaration and Initialization) (Separate declaration and initialization) (Separate declaration and initialization)
int int a[5];
a[5];
a[0]=1; for(int a1=0;a1<=4;a1++) printf("\
int int a[5]={1,2,3,4,5}; a[1]=2; na[%d]=%-3d",a1,a[a1]=a1 +1);
a[2]=3;
a[3]=4;
a[4]=5;

ONE DIMENSIONAL FLOAT ARRAY


Method 1 Method 2 Method 3
(Declaration and initialization) (Separate declaration and initialization) (Separate declaration and initialization)
float a[5]; a[0]=1 float a[5];
.1; a[1]=1 .2;
float a[2]=1.3; for(int a1=1 ;a1 <=5;a1++) printf("\
float a[5]={1 .1,1.2,1.3,1.4 a[3]=1 .4;
,1 .5}; a[4]=1.5; na[%d]=%2.2f",a1 ,a[a1]=1+(a1/10.0));

The picture below shows how a two dimensional array may look like.
0 1 2 3
0 0 5 10 15
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 4 9 14 19

Table below shows three different methods of declaring and initializing a two dimensional integer array.

TWO DIMENSIONAL INTEGER ARRAY

Method 1 Method 2 Method 3


(Declaration and initialization) (Separate declaration and initialization) (Separate declaration and initialization)
#include<stdio.h>
#i nclude<conio.
h>
int aa[4][5]; #include<stdlib.>

aa[0][0]=1; aa[0][1]=2; aa[0][2]=3; int main()


aa[0][3]=4; aa[0][4]=5; {
int aa[4] system(“cls”);
[5]={ aa[1][0]=6; aa[1][1]=7; aa[1][2]=8; int aa[4][5];
Int {0,1,2,3,4}, aa[1][3]=9; aa[1][4]=1 0;
{5,6,7,8,9}, for(int a=0;a<4;a+
{10,1 +) {
1,12,13,14}, for(int b=0;b<5;b+
{15,16,17,18,19} +) {
}; aa[2][0]=11; aa[2][1]=12; aa[2][2]=13; printf("%d \t",aa[a]
aa[2][3]=14; aa[2][4]=15; [b]=((a*10)+b)); }
printf("\n");
aa[3][0]=16; aa[3][1]=17; aa[3][2]=18; }
aa[3][3]=19; aa[3][4]=20; printf("");
retrun 0;
}
This program shows a three dimensional integer array namely aaa, of such length that has 4 two
dimensional arrays and each two dimensional array has 3 rows and 2 columns initialized in one of the
several ways shown above for integer arrays this function prints the element on address 2,1,0.
Program Output
#include<stdio.h> Write the output for the program on left
#include<conio.h>

#include<stdlib.h>
int main()
{
system(“cls”);
int aaa[4][3][2]={
{{1,2},{3,4},{5,6}},
{{7,8},{9,10},{1 1,12}},
{{1 3,14},{1 5,16},{1 7,1 8}},
{{19,20},{21,22},{23,24}},
};
printf("%d",aaa[2][1][0]);
retrun 0;
}
ALGORITHMS
Arrays have many properties applicable on them. Three such properties are.
- Searching an array,
-Entering data in an array,
- Sorting an array.

Hence we apply these on array using algorithms which may be categorized as follows.

- Searching
- By address or location - By Value

- Input
- FIFO (First in First out) - FILO or LIFO

- Sorting
- Ascending / Descending

Exercise:

Task 1: Program the following.


● Prompt the values from user for a single dimensional integer array of length 5 and accept them
in First In First Out form.
● Consider a one dimensional character array of length 5 and holding data a, e, i, o and u. Sort
them in ascending order.
● Randomly place values in a 2 dimensional integer array.
● Prompt values from user for a one dimensional integer array of length 10 in FILO order. Arrange
this array in ascending and descending order in other 2 arrays.

Task 2: Program the following.


Consider the data set given below. Map the data in array.
33,4,55,42,66,22,77,21,33,34,66,88,73,2,71,23
Find the mean, median and mode using following formula

Task 3:
Write a C++ program that demonstrates the use of both static and dynamic 2D arrays. First, declare a
statically allocated 2D array with 4 rows and 3 columns, initialize it with values from 1 to 12, and
print it in a tabular format. Then, dynamically allocate a 2D array based on user input for the number of
rows and columns, fill it with values from 1 to the total number of elements (rows * columns), and print it.
Finally, ensure proper memory deallocation for the dynamically allocated array.

Experiment 10
Objective
Studying Structures, different ways to declare define and initialize structures.

Theory
Structures are variables which can accept values of different data types (e.g. char, int, float, etc.) or as
defined by the user.

Example
The structure iqra of this program has been defined and declared at a time. While its initialized in another
statement
Program Output
#include <iostream>
#include <cstdlib>

struct iqra {
char chr;
int nmb;
};

int main() {
system("cls");
iqra iq1, iq2; iq1.chr = a iq1.nmb = 1
iq1.chr = 'a'; iq1.chr = b iq1.nmb = 2
iq1.nmb = 1;
iq2.chr = 'b';
iq2.nmb = 2;
std::cout << "\niq1.chr = " << iq1.chr << " \t iq1.nmb = " <<
iq1.nmb;
std::cout << "\niq2.chr = " << iq2.chr << " \t iq2.nmb = " <<
iq2.nmb;
return 0;
}

The structure of this program has been defined, declared and initialized in three different steps.
Program Output
#include <iostream>
#include <cstdlib>

struct iqra {
char chr;
int nmb;
};

int main() {
system("cls");

iqra iq1; iq1 .chr =


iq1 .nmb = 1
a
iqra iq2; iq1 .chr = iq1 .nmb = 2
b
iq1.chr = 'a';
iq1.nmb = 1;
iq2.chr = 'b';
iq2.nmb = 2;

std::cout << "\niq1.chr = " << iq1.chr << " \t iq1.nmb = " <<
iq1.nmb;
std::cout << "\niq2.chr = " << iq2.chr << " \t iq2.nmb = " <<
iq2.nmb;

The structure in this program has first been defined. But declared and initialized in another statement
together.
Program Output
#include <iostream>
#include <cstdlib>

struct iqra {
char chr;
int nmb;
};

int main() {
system("cls"); iq1.chr = a iq1.nmb = 1
iqra iq1 = {'a', 1}; iq1.chr = b iq1.nmb = 2
iqra iq2 = {'b', 2};

std::cout << "\niq1.chr = " << iq1.chr << " \t iq1.nmb = " <<
iq1.nmb;
std::cout << "\niq2.chr = " << iq2.chr << " \t iq2.nmb = " <<
iq2.nmb;

return 0;
This program has structure with arrays.
Program Output
#include <iostream>
#include <vector>
#include <string>

int main()
{
system("cls");

struct iqra
{
std::string name;
int nmb;
}; Department = Engineering Department Code = 1
Department = Media Science Department Code = 2
std::vector<iqra> departments = { Department = Management Department Code = 3
{"Engineering", 1}, Department = Computer Science Department Code = 4
{"Media Science", 2}, Department = Fashion Design Department Code = 5
{"Management", 3},
{"Computer Science", 4},
{"Fashion Design", 5}
};

for (const auto& dept : departments) {


std::cout << "\nDepartment = " << dept.name << "\t\t
Department Code = " << dept.nmb;
}

return 0;
}

Exercise:

Task 1:
Create a strucutre named “student”. Structure has four members: name (string), gender (char),
rollNumber (integer) and marks (float). Create structure variable std to store information and display it on
the screen.

Task 2:
You are designing a program for a library system where you need to store details of books, including the
title, author, year of publication, and price. Create a Book structure in C++ to store this information, and
write a function that accepts a Book structure as a parameter and displays its details. In the main()
function, initialize an array of at least three Book structures, input the details for each book, and call the
function to display each book's information. Make sure the program correctly outputs the title, author,
publication year, and price for each book.

Task 3:
Write a C++ program to add two distances entered by user. Measurement of distance should be in inch
and feet. (Note: 12 inches = 1 foot)

Experiment 11
Objective
Learn how Pointers access data using memory address.

Theory
Every variable is a memory location and every memory location has its address defined which can be
accessed using ampersand (&) operator, which denotes an address in memory.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is

type *var-name;

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointervariable. The asterisk * used to declare a pointer. In this statement the asterisk is being used to
designate a variable as a pointer.
Exercise :
Program Output
#include <iostream>
Address of var variable: bffd8b3c
int main() { Address stored in ip variable: bffd8b3c
int var = 20; // actual variable declaration Value of *ip variable: 20
int* ip; // pointer variable declaration

ip = &var; // store address of var in pointer variable

std::cout << "Address of var variable: " << &var <<


std::endl;

// address stored in pointer variable


std::cout << "Address stored in ip variable: " << ip <<
std::endl;

// access the value using the pointer


std::cout << "Value of *ip variable: " << *ip << std::endl;

return 0;
}

Exercise:

Task 1: Write the output of the following programs.

Program Output
#include <iostream>
int main() {
static const char *s[] = {"black", "white",
"pink", "violet"};
const char **ptr[] = {s + 3, s + 2, s + 1, s};
const char ***p = ptr;
++p;
std::cout << **p + 1;
return 0;
}
#include <iostream>
int main() {
int i = 3, *j, k;
j = &i;
std::cout << (i * (*j) * i + *j) << std::endl;
return 0;
}
#include <iostream>
#include <cstring>
int main() {
char str[20] = "Hello";
char *const p = str;
*p = 'M';
std::cout << str << std::endl;
return 0;
}

Task 2: Program the following.


Array of pointers - Create an array which can store pointers to an int data type. Create a simple int type
array so the pointer array can point to addresses of the elements of int array. Fill the pointer array by
refereing the addresses of elements of int array and display the elements using loop.

Experiment 12
Objective
Graphics, basic applications of graphics by making buttons and animations.

Theory

1. Graphics Functions (graphics.h): In C++, to use graphical functions (like drawing shapes, lines,
etc.), older compilers like Turbo C++ use graphics.h. However, in modern C++, graphics
programming is typically done using libraries such as SDL, SFML, or OpenGL.
2. Delay Function (dos.h): The delay() function from dos.h is used to create a pause in execution.
It takes a delay time in milliseconds. In modern C++, you can use the std::this_thread::sleep_for
function from the <thread> library to achieve similar functionality.
3. Mathematical Functions (math.h): The math.h header file provides standard mathematical
functions such as trigonometric functions (sin(), cos(), etc.), logarithms, and other common
mathematical operations.

In the table, xc, yc, x1, y1, n represent constant values used within the program. These could be
coordinates for drawing, or specific parameters for calculations. These values are typically fixed and used
throughout the program.

ellipse(xc,yc,start,end,xrad,yr setlinestyle(n);
ad); rectangle(x1 ,y1 ,x2,y2); setfillstyle(n);
line(x1 ,y1 ,x2,y2); floodfill(n);
circle(xc,yc, rad); setfillpattern(n);
arc(xc,yc,start,end, setfillstyle(n);
rad); settextstyle(n);
bar(x1,y1,x2,y2); settextjustify(n);
bar3d(x1 ,y1 ,x2,y2,z1 textheight(n);
,z2); textwidth(n);
putpixel(x,y,color); setusercharsize
outtextxy(x,y,"Text"); (n);
setcolor(n);
setbkcolor(n);

Example
This program has a graphical button which is animated to be pressed when ever any keyboard button is
pressed

Program Output
#include <iostream>
#include <graphics.h>
#include <cstdlib>
#include <conio.h>
#include <dos.h>

void btn1(void);

int main() {
system("cls");
int driver = DETECT, mode;
initgraph(&driver, &mode, "C:\\TC\\BGI");
btn1();
return 0;
}

void btn1(void) {
int x1 = 250, y1 = 125, x2 = 275, y2 = 150, dly = 75;
rectangle(x1, y1, x2, y2);
line(x2 + 2, y1, x2 + 2, y2 + 2); // Vertical
line(x1, y2 + 2, x2 + 2, y2 + 2); // Horizontal

while (getche() != '\r') {


setcolor(0); // Black
line(x2 + 2, y1, x2 + 2, y2 + 2); // Vertical
line(x1, y2 + 2, x2 + 2, y2 + 2); // Horizontal
delay(dly);
setcolor(15); // White
line(x1 + 2, y1 + 2, x1 + 2, y2); // Vertical
line(x1 + 2, y1 + 2, x2 - 1, y1 + 2); // Horizontal
delay(dly);
setcolor(0); // Black
line(x1 + 2, y1 + 2, x1 + 2, y2 - 1); // Vertical
line(x1 + 2, y1 + 2, x2 - 1, y1 + 2); // Horizontal
setcolor(15); // White
line(x2 + 2, y1, x2 + 2, y2 + 2); // Vertical
line(x1, y2 + 2, x2 + 2, y2 + 2); // Horizontal
}
}

Exercise:

Task 1: Graphically program the following.


● Design simple calculator with buttons such that it resembles an actual calculator.
● Make any presentation with animation to any selected topic (e.g. solar system, trigonometric
waveform).

You might also like