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

Lab 1 (1)

Uploaded by

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

Lab 1 (1)

Uploaded by

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

1.

Typedef and Enumerations

Here’s a simple C++ program that demonstrates the use of both typedef and enumerations,
with comments to explain each part.

#include <iostream>

// Typedef to simplify writing 'unsigned long long int'


typedef unsigned long long int ull;

// Enumeration for Days of the Week


enum DaysOfWeek {
SUNDAY, // 0
MONDAY, // 1
TUESDAY, // 2
WEDNESDAY, // 3
THURSDAY, // 4
FRIDAY, // 5
SATURDAY // 6
};

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;

// Declare a variable of enumeration type DaysOfWeek


DaysOfWeek today = WEDNESDAY;

// Use the enum value in a switch-case structure to output the day


switch(today) {
case SUNDAY:
std::cout << "Today is Sunday." << std::endl;
break;
case MONDAY:
std::cout << "Today is Monday." << std::endl;
break;
case TUESDAY:
std::cout << "Today is Tuesday." << std::endl;
break;
case WEDNESDAY:
std::cout << "Today is Wednesday." << std::endl;
break;
case THURSDAY:
std::cout << "Today is Thursday." << std::endl;
break;
case FRIDAY:
std::cout << "Today is Friday." << std::endl;
break;
case SATURDAY:
std::cout << "Today is Saturday." << std::endl;
break;
default:
std::cout << "Invalid day!" << 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;

// Declare a pointer variable and store the address of 'num' in it


int* ptr = &num;

// Output the value of 'num' using the variable itself


std::cout << "Value of num: " << num << std::endl;

// Output the address of 'num' using the address-of operator (&)


std::cout << "Address of num: " << &num << std::endl;

// 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;

// Modify the value of 'num' using the pointer


*ptr = 100;

// Output the modified value of 'num' to show that it has changed


std::cout << "Modified value of num (via pointer): " << num << std::endl;

// Pointer arithmetic example: incrementing the pointer


int arr[3] = {10, 20, 30}; // Declare an array of integers
int* pArr = arr; // Pointer to the first element of the array

3|Page
// Output the first element using pointer dereferencing
std::cout << "First element in array: " << *pArr << std::endl;

// Move the pointer to the next element in the array


pArr++; // Pointer arithmetic: now 'pArr' points to the second element

// Output the second element using pointer dereferencing


std::cout << "Second element in array (after incrementing pointer): " <<
*pArr << std::endl;

// Move to the third element


pArr++;
std::cout << "Third element in array: " << *pArr << std::endl;

return 0;
}

Explanation of the Program:

1. Pointer Declaration:
o Int *ptr = &num;
 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:

 Pointers are variables that store memory addresses.


 Dereferencing a pointer gives access to the value stored at the memory location it points
to.
 Pointer arithmetic allows pointers to traverse arrays or other data structures in memory.

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++.

3. Static single dimension array

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.

C++ Program: Storing and Processing Student Scores Using an Array


#include <iostream>

const int NUM_STUDENTS = 5; // Constant to define the number of students

int main() {
// Declare a static array to store test scores for 5 students
int testScores[NUM_STUDENTS];

// Input: Prompt the user to enter the test scores


std::cout << "Enter test scores for " << NUM_STUDENTS << " students:" <<
std::endl;

for (int i = 0; i < NUM_STUDENTS; i++) {


std::cout << "Enter score for student " << i + 1 << ": ";
std::cin >> testScores[i]; // Store input in the array
}

// Processing: Calculate the sum and average of the test scores


int sum = 0;
for (int i = 0; i < NUM_STUDENTS; i++) {
sum += testScores[i]; // Add each score to the total sum
}

double average = static_cast<double>(sum) / NUM_STUDENTS;

// Output the results


std::cout << "\nTest Scores:" << std::endl;
for (int i = 0; i < NUM_STUDENTS; i++) {
std::cout << "Student " << i + 1 << ": " << testScores[i] <<
std::endl;
}

5|Page
std::cout << "\nTotal sum of scores: " << sum << std::endl;
std::cout << "Average score: " << average << std::endl;

// Find the highest and lowest scores


int highestScore = testScores[0];
int lowestScore = testScores[0];

for (int i = 1; i < NUM_STUDENTS; i++) {


if (testScores[i] > highestScore) {
highestScore = testScores[i];
}
if (testScores[i] < lowestScore) {
lowestScore = testScores[i];
}
}

std::cout << "Highest score: " << highestScore << std::endl;


std::cout << "Lowest score: " << lowestScore << std::endl;

return 0;
}

Explanation of the Program:

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

Total sum of scores: 395


Average score: 79
Highest score: 91
Lowest score: 67

Key Concepts Covered:

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;

// Dynamically allocate an array to store test scores based on the number


of students
int* testScores = new int[numStudents];

// Input: Prompt the user to enter the test scores


std::cout << "Enter test scores for " << numStudents << " students:" <<
std::endl;

for (int i = 0; i < numStudents; i++) {


std::cout << "Enter score for student " << i + 1 << ": ";
std::cin >> testScores[i]; // Store input in the dynamic array
}

// Processing: Calculate the sum and average of the test scores


int sum = 0;
for (int i = 0; i < numStudents; i++) {
sum += testScores[i]; // Add each score to the total sum
}

double average = static_cast<double>(sum) / numStudents;

// Output the results


std::cout << "\nTest Scores:" << std::endl;
for (int i = 0; i < numStudents; i++) {
std::cout << "Student " << i + 1 << ": " << testScores[i] <<
std::endl;
}

std::cout << "\nTotal sum of scores: " << sum << std::endl;
std::cout << "Average score: " << average << std::endl;

// Find the highest and lowest scores


int highestScore = testScores[0];
int lowestScore = testScores[0];

for (int i = 1; i < numStudents; i++) {


if (testScores[i] > highestScore) {
highestScore = testScores[i];
}
if (testScores[i] < lowestScore) {
lowestScore = testScores[i];
}
}

std::cout << "Highest score: " << highestScore << std::endl;


std::cout << "Lowest score: " << lowestScore << std::endl;

// Deallocate the dynamic array memory to avoid memory leaks


delete[] testScores;

return 0;
}

8|Page
Explanation of the Program:

1. Dynamic Memory Allocation:


o int* testScores = new int[numStudents];
 This line dynamically allocates memory for an array of integers, where the
size of the array (numStudents) is specified by the user at runtime.
 The new operator is used to request memory from the heap (free store)
instead of allocating it statically on the stack.
 testScores is a pointer to the first element of the dynamically allocated
array.
2. Input of Scores:
o The program uses a for loop to prompt the user to enter test scores for each
student. The scores are stored in the dynamic array testScores[i].
3. Processing the Data:
o Sum and Average:
 A loop calculates the sum of the scores, and the average is computed by
dividing the sum by the number of students.
 static_cast<double>(sum) / numStudents ensures that the division
result is a floating-point value.
o Finding the Highest and Lowest Scores:
 Another loop finds the highest and lowest scores by comparing each score
in the array to a stored value (highestScore and lowestScore).
4. Output:
o The program outputs the test scores for each student, the total sum, average,
highest, and lowest scores.
5. Memory Deallocation:
o delete[] testScores;
 After using the dynamic array, we must free the allocated memory with
the delete[] operator to prevent memory leaks.
 This is important because dynamically allocated memory is not
automatically freed when the program ends or when the array goes out of
scope.

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

Total sum of scores: 250


Average score: 83.3333
Highest score: 90
Lowest score: 75

Key Concepts Covered:

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.

C++ Program: Storing and Processing Student Scores Using a Multi-


Dimensional Array
#include <iostream>

const int NUM_STUDENTS = 3; // Number of students


const int NUM_SUBJECTS = 4; // Number of subjects

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;

for (int student = 0; student < NUM_STUDENTS; student++) {


std::cout << "\nEntering scores for Student " << student + 1 << ":"
<< std::endl;
for (int subject = 0; subject < NUM_SUBJECTS; subject++) {
std::cout << "Enter score for Subject " << subject + 1 << ": ";
std::cin >> scores[student][subject]; // Store the score in the
2D array
}
}

// 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

// Output the total and average score for the student


std::cout << "\nStudent " << student + 1 << " Total Score: " <<
totalScore << std::endl;
std::cout << "Student " << student + 1 << " Average Score: " <<
averageScore << std::endl;
}

// Find and output the highest score in each subject


for (int subject = 0; subject < NUM_SUBJECTS; subject++) {
int highestScore = scores[0][subject]; // Assume the first student's
score is the highest initially

for (int student = 1; student < NUM_STUDENTS; student++) {


if (scores[student][subject] > highestScore) {
highestScore = scores[student][subject]; // Update highest
score if current student's score is higher
}
}

std::cout << "\nHighest score in Subject " << subject + 1 << ": " <<
highestScore << std::endl;
}

return 0;
}

Explanation of the Program:

1. Multi-Dimensional Array Declaration:


o int scores[NUM_STUDENTS][NUM_SUBJECTS];

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.

Entering scores for Student 1:


Enter score for Subject 1: 78
Enter score for Subject 2: 85
Enter score for Subject 3: 91
Enter score for Subject 4: 88

Entering scores for Student 2:


Enter score for Subject 1: 67

12 | P a g e
Enter score for Subject 2: 74
Enter score for Subject 3: 80
Enter score for Subject 4: 92

Entering scores for Student 3:


Enter score for Subject 1: 90
Enter score for Subject 2: 82
Enter score for Subject 3: 89
Enter score for Subject 4: 85

Student 1 Total Score: 342


Student 1 Average Score: 85.5

Student 2 Total Score: 313


Student 2 Average Score: 78.25

Student 3 Total Score: 346


Student 3 Average Score: 86.5

Highest score in Subject 1: 90


Highest score in Subject 2: 85
Highest score in Subject 3: 91
Highest score in Subject 4: 92

Key Concepts Covered:

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.

6. Struct data structure.

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.

C++ Program: Using a struct to Store and Process Student Information


cpp

13 | P a g e
#include <iostream>
#include <string> // Include string library for using string variables

// Define a struct called Student to hold information about a student


struct Student {
std::string name; // Student's name
int rollNumber; // Student's roll number
float mathMarks; // Marks in math
float scienceMarks; // Marks in science
float englishMarks; // Marks in English
};

int main() {
// Declare a variable of type Student
Student student1;

// Input: Prompt the user to enter the student's details


std::cout << "Enter student's name: ";
std::getline(std::cin, student1.name); // Use getline to allow spaces in
the name

std::cout << "Enter student's roll number: ";


std::cin >> student1.rollNumber;

std::cout << "Enter marks in Math: ";


std::cin >> student1.mathMarks;

std::cout << "Enter marks in Science: ";


std::cin >> student1.scienceMarks;

std::cout << "Enter marks in English: ";


std::cin >> student1.englishMarks;

// Processing: Calculate the total and average marks for the student
float totalMarks = student1.mathMarks + student1.scienceMarks +
student1.englishMarks;
float averageMarks = totalMarks / 3;

// Output the student's details and the calculated results


std::cout << "\nStudent's Information:" << std::endl;
std::cout << "Name: " << student1.name << std::endl;
std::cout << "Roll Number: " << student1.rollNumber << std::endl;
std::cout << "Math Marks: " << student1.mathMarks << std::endl;
std::cout << "Science Marks: " << student1.scienceMarks << std::endl;
std::cout << "English Marks: " << student1.englishMarks << std::endl;

std::cout << "\nTotal Marks: " << totalMarks << std::endl;


std::cout << "Average Marks: " << averageMarks << std::endl;

return 0;
}

Explanation of the Program:

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

Total Marks: 253.5


Average Marks: 84.5

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

You might also like