Lab 1 (1)
Lab 1 (1)
Here’s a simple C++ program that demonstrates the use of both typedef and enumerations,
with comments to explain each part.
#include <iostream>
int main() {
// Using typedef to declare a v
variable
ariable of type 'unsigned long long int'
ull bigNumber = 9876543210
9876543210;
1|Page
// Output the big number to demonstrate the typedef
std::cout << "The big number is: " << bigNumber << std::endl;
return 0;
}
Explanation:
1. typedef:
o typedef unsigned long long int ull; simplifies the use of long types by
allowing ull to be used as a shortcut for unsigned long long int.
o This is useful in data structures when dealing with large numbers (e.g., node
identifiers or keys).
2. enum DaysOfWeek:
o enum DaysOfWeek defines a set of named integer constants for the days of the
week.
o Each day is represented by an integer, starting from 0 (Sunday) to 6 (Saturday).
o This could be used in scheduling algorithms or calendar-related data structures.
3. Program Logic:
o A variable bigNumber of type ull is declared and initialized with a large number
to demonstrate the use of typedef.
2|Page
o The variable today is of type DaysOfWeek and is assigned WEDNESDAY (which is
3).
o A switch statement is used to print the current day based on the enumeration
value.
Sample Output:
The big number is: 9876543210
Today is Wednesday.
This program demonstrates how to simplify code using typedef and manage related constants
with enum. Both concepts are important in data structures for clean, readable code.
2. Pointers
Here’s a C++ program that demonstrates basic pointer operations such as declaring pointers,
dereferencing pointers, and pointer arithmetic. This program is tailored for students studying data
structures and aims to provide a simple introduction to how pointers work in C++.
#include <iostream>
int main() {
// Declare an integer variable
int num = 42;
// Output the value stored in the pointer (which is the address of 'num')
std::cout << "Value of ptr (address of num): " << ptr << std::endl;
// Dereference the pointer to get the value stored at the address it points to
std::cout << "Dereferenced value (value at the address stored in ptr): " << *ptr
<< std::endl;
3|Page
// Output the first element using pointer dereferencing
std::cout << "First element in array: " << *pArr << std::endl;
return 0;
}
1. Pointer Declaration:
o Int *ptr = #
Here, ptr is a pointer to an integer. It stores the memory address of the
variable num.
The & operator is used to getthe address of num.
2. Dereferencing a Pointer:
o *ptr gives us the value stored at the memory address that ptr is pointing to.
o In this case, dereferencing ptr (*ptr) gives the value of num, which is 42.
3. Modifying a Variable through a Pointer:
o *ptr = 100;
This modifies the value of num through the pointer ptr. After this line, num
is changed to 100.
4. Pointer Arithmetic:
o In the second part of the program, we demonstrate pointer arithmetic using an
array.
o An array is essentially a contiguous block of memory, so incrementing a pointer
to an array (pArr++) makes it point to the next element in the array.
o Dereferencing the pointer after each increment (*pArr) accesses different
elements in the array.
Output:
Value of num: 42
Address of num: 0x7ffee4429afc
Value of ptr (address of num): 0x7ffee4429afc
Dereferenced value (value at the address stored in ptr): 42
Modified value of num (via pointer): 100
First element in array: 10
Second element in array (after incrementing pointer): 20
Third element in array: 30
4|Page
Key Concepts Covered:
This example lays the foundation for more advanced topics like dynamic memory allocation and
linked data structures. Understanding pointers is essential for efficient data structure
manipulation in C++.
Here's a C++ program that demonstrates basic array concepts using a static single-dimension
array. The program simulates storing and processing student test scores.
int main() {
// Declare a static array to store test scores for 5 students
int testScores[NUM_STUDENTS];
5|Page
std::cout << "\nTotal sum of scores: " << sum << std::endl;
std::cout << "Average score: " << average << std::endl;
return 0;
}
1. Array Declaration:
o int testScores[NUM_STUDENTS]; declares a static single-dimension array
called testScores that can store integers for NUM_STUDENTS (5 students in this
case).
o Arrays are a common way to store fixed amounts of data, like test scores, in a
structured way.
2. Input Scores:
o The program uses a for loop to iterate through each element of the testScores
array and fill it with user input.
o Each score entered by the user is stored in the array at a specific index
(testScores[i]).
3. Calculate Sum and Average:
o A second for loop calculates the sum of the scores.
o The average is calculated by dividing the sum by the number of students
(NUM_STUDENTS). The sum is cast to double for precision.
4. Display Results:
o The program outputs the individual test scores, the total sum of the scores, and the
average score.
5. Find Highest and Lowest Scores:
o The program uses another for loop to find the highest and lowest scores by
comparing each value in the array to a stored value (highestScore and
lowestScore).
Output Example:
Enter test scores for 5 students:
6|Page
Enter score for student 1: 78
Enter score for student 2: 85
Enter score for student 3: 91
Enter score for student 4: 67
Enter score for student 5: 74
Test Scores:
Student 1: 78
Student 2: 85
Student 3: 91
Student 4: 67
Student 5: 74
1. Static Arrays:
o Arrays are of fixed size, and memory is allocated for all elements at the time of
declaration.
2. Array Indexing:
o Accessing elements in the array using an index (e.g., testScores[i]).
3. Basic Looping with Arrays:
o Using for loops to iterate through the array for both input, processing, and output.
4. Basic Processing with Arrays:
o Calculating sum, average, and finding the highest/lowest values using basic
operations with arrays.
This simple program forms a good foundation for further study of more advanced data structures,
such as dynamic arrays and linked lists.
4. Dynamic Arrays
Here's a C++ program that demonstrates the use of a dynamic single-dimension array. A
dynamic array is one whose size is determined at runtime, unlike a static array, where the size is
fixed at compile time. This example simulates storing and processing student test scores, where
the number of students is unknown until the program runs.
C++ Program: Storing and Processing Student Scores Using a Dynamic Array
#include <iostream>
int main() {
int numStudents; // Variable to store the number of students
7|Page
// Input: Ask the user for the number of students
std::cout << "Enter the number of students: ";
std::cin >> numStudents;
std::cout << "\nTotal sum of scores: " << sum << std::endl;
std::cout << "Average score: " << average << std::endl;
return 0;
}
8|Page
Explanation of the Program:
Practical Application:
This program simulates a simple application where an instructor can enter the number of
students and their corresponding test scores.
Dynamic arrays are useful in situations where the amount of data is unknown at compile
time but can be determined during runtime.
Output Example:
Enter the number of students: 3
Enter test scores for 3 students:
Enter score for student 1: 75
Enter score for student 2: 85
Enter score for student 3: 90
9|Page
Test Scores:
Student 1: 75
Student 2: 85
Student 3: 90
1. Dynamic Arrays:
o Arrays whose size is determined at runtime.
o Dynamically allocated arrays allow flexibility when the number of elements isn’t
known in advance.
2. Pointers and Memory Management:
o new operator: Allocates memory dynamically.
o delete[] operator: Deallocates dynamically allocated memory to prevent
memory leaks.
3. Basic Array Operations:
o Storing values in an array using loops.
o Calculating sum, average, and finding the highest/lowest values.
This example provides a basic understanding of dynamic arrays and memory management,
which are important concepts for working with data structures in C++.
5. Multi-dimensional array
Here's a C++ program that demonstrates the use of a multi-dimensional array. In this
example, we simulate a system that stores and processes the scores of multiple students across
different subjects. This will help second-year data structures students understand how to work
with two-dimensional arrays.
int main() {
// Declare a 2D array to store the scores of 3 students across 4 subjects
int scores[NUM_STUDENTS][NUM_SUBJECTS];
10 | P a g e
// Input: Prompt the user to enter the scores for each student in each
subject
std::cout << "Enter the scores for " << NUM_STUDENTS << " students across
" << NUM_SUBJECTS << " subjects." << std::endl;
// Processing: Calculate and display the total score and average score
for each student
for (int student = 0; student < NUM_STUDENTS; student++) {
int totalScore = 0;
for (int subject = 0; subject < NUM_SUBJECTS; subject++) {
totalScore += scores[student][subject]; // Add up all subject
scores for the student
}
double averageScore = static_cast<double>(totalScore) / NUM_SUBJECTS;
// Calculate average score
std::cout << "\nHighest score in Subject " << subject + 1 << ": " <<
highestScore << std::endl;
}
return 0;
}
11 | P a g e
This declares a 2D array called scores where:
The first dimension represents the students (3 students in this
case).
The second dimension represents the subjects (4 subjects in this
case).
A multi-dimensional array is essentially an array of arrays, where each
"row" represents a student's scores across different subjects.
2. Input of Scores:
o A nested for loop is used to iterate over both dimensions of the array:
The outer loop iterates over students.
The inner loop iterates over the subjects for each student.
o Each score is stored in the scores[student][subject] position in the array.
3. Processing the Data:
o Total and Average Score Calculation:
After entering the scores for all students, the program calculates the total
score for each student by adding up their subject scores.
The average score for each student is computed by dividing the total score
by the number of subjects (NUM_SUBJECTS).
o Finding the Highest Score in Each Subject:
The program iterates over each subject and checks the scores of all
students to find the highest score in that subject.
This is done using a nested loop where the outer loop goes through each
subject, and the inner loop checks the scores of all students for that
subject.
4. Output:
o The program outputs:
The total and average scores for each student.
The highest score in each subject across all students.
Practical Application:
This program can be used in a real-world scenario where instructors need to store and
process the exam scores of multiple students across several subjects.
A two-dimensional array is a good way to represent data in rows and columns, such as
students and their scores in different subjects.
Output Example:
Enter the scores for 3 students across 4 subjects.
12 | P a g e
Enter score for Subject 2: 74
Enter score for Subject 3: 80
Enter score for Subject 4: 92
1. Multi-Dimensional Arrays:
o Arrays with more than one dimension (e.g., a 2D array in this case) are useful for
representing tabular data, such as student scores across subjects.
2. Nested Loops:
o Accessing and processing multi-dimensional arrays requires nested loops where
each loop handles one dimension (students and subjects).
3. Basic Data Processing:
o Calculating the total and average scores for each student.
o Finding the highest score for each subject.
This example is a basic introduction to multi-dimensional arrays, a foundational concept for data
structures such as matrices, grids, and tables.
Here's a C++ program that demonstrates the use of a struct. A struct in C++ allows us to
group related data together, making it easier to manage complex data types. In this example, we
create a struct to represent student information including their name, roll number, and marks
in different subjects.
13 | P a g e
#include <iostream>
#include <string> // Include string library for using string variables
int main() {
// Declare a variable of type Student
Student student1;
// Processing: Calculate the total and average marks for the student
float totalMarks = student1.mathMarks + student1.scienceMarks +
student1.englishMarks;
float averageMarks = totalMarks / 3;
return 0;
}
1. Defining a struct:
14 | P a g e
oA struct (short for structure) is used to group different variables together under
one name. In this case, we are defining a struct called Student to hold the
following data for each student:
name: A string to store the student's name.
rollNumber: An integer to store the student's roll number.
mathMarks, scienceMarks, and englishMarks: Floating-point values to
store the student's marks in three subjects.
2. Declaring a struct Variable:
o We declare a variable of type Student called student1. This variable can hold
all the student details defined in the Student struct (name, roll number, and
marks).
3. Input of Student Data:
o The program prompts the user to enter the details for the student (name, roll
number, and marks in three subjects).
o The std::getline function is used to input the student's name, allowing for
spaces in the name.
4. Processing the Data:
o Total Marks: The program adds up the marks from the three subjects to get the
total score for the student.
o Average Marks: The average is calculated by dividing the total marks by 3 (the
number of subjects).
5. Output the Results:
o The program prints out the student's name, roll number, marks in each subject,
total marks, and the average marks.
Practical Application:
This program simulates a basic student management system where information about
students (name, roll number, and marks) is stored and processed.
struct is useful when you need to group multiple related variables into a single entity,
making your code easier to organize and manage.
Output Example:
Enter student's name: John Doe
Enter student's roll number: 101
Enter marks in Math: 85.5
Enter marks in Science: 78.0
Enter marks in English: 90.0
Student's Information:
Name: John Doe
Roll Number: 101
Math Marks: 85.5
Science Marks: 78.0
English Marks: 90.0
15 | P a g e
Key Concepts Covered:
1. struct Definition:
o struct allows you to define custom data types that can group variables of
different types (e.g., strings, integers, floats).
2. Accessing struct Members:
o Once a struct is declared, you can access and manipulate its members (like
name, rollNumber, etc.) using the dot operator (.).
3. Input and Output:
o The program demonstrates how to take input for a struct and output the stored
values.
4. Data Processing with struct:
o The example shows how to use the data in the struct for basic calculations like
the total and average marks.
This example introduces second-year students to the power of structs in C++, which are
important for creating more complex data structures, such as records, objects, or databases in
larger applications.
16 | P a g e