Programming Fundamental Lab Manual Updated (1)
Programming Fundamental Lab Manual Updated (1)
Programming Fundamentals
Name _______________________
Roll No ______________________
Semester
_____________________
Marks ______________ Signature____________________
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.
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:
Console Input
4 Objective:Taking Input from the user at console
screen using scanf and getche commands.
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.
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#.
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.
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.
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.
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.
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:
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.
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.
Escape Sequences are used to adjust spacing between lines or characters or the characters themselves.
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.
Theory
Variables are declared by first writing
data types followed by a variable name, e.g.
int
a=10;
Here
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:
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.
Theory
cin command can take input of different data types at a time.
Getche command can take only one character input.
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.
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")
int main() {
// Clear the console screen (works on Windows)
system("cls");
snh = sinh(b);
csh = cosh(b);
tnh = tanh(b);
return 0;
}
Operators
Program Output
#include <iostream>
#include <cstdlib> // For system("cls")
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;
return 0;
}
Exercise:
Task 1:
Program the following.
Implement the following equation
3x4sin(180x) + 4x3 cos(90x) + x2sin(tan(45)) + 7x +
9cos(90x2 )
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:
Requirements:
This program of while loops takes continuous input until enter key is pressed.
PROGRAM OUTPUT
#include <iostream>
#include <cstdlib> // For system("cls")
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")
int main() {
system("cls"); // Clear the screen
int num = -1;
int sum = 0;
Example
The table below shows loops with cross combinations
Loop Program Output
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;
}
sum += number; // sum = sum + number; sum += number; // sum = sum + number;
} }
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:
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
int main() {
int lower = 1, upper = 99, guess, ch;
char response;
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
int main() {
char ch;
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.
● 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.
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")
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
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';
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.
#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 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");
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}
};
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
return 0;
}
Exercise:
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;
}
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
Exercise: