0% found this document useful (0 votes)
15 views13 pages

Generic Stack and Lucky Draw Game in Java

The document describes a generic stack data structure that can handle different data types. It includes a Stack class template to implement stack operations and a menu-driven program to demonstrate pushing, popping and accessing the top element of stacks of integers, doubles and characters.

Uploaded by

samanvithavakati
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views13 pages

Generic Stack and Lucky Draw Game in Java

The document describes a generic stack data structure that can handle different data types. It includes a Stack class template to implement stack operations and a menu-driven program to demonstrate pushing, popping and accessing the top element of stacks of integers, doubles and characters.

Uploaded by

samanvithavakati
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

Winter 2023-24
Course: BCSE102L Slot: C2
Name : Vakati Samanvitha

RegNo : 21BCE3996

DIGITAL ASSIGNMENT – 1

1. List down the similarities and differences between structures and classes

Similarities between structures and classes:

• Data Organization: Both structures and classes are used to organize related data elements
together.
• Member Access: They both allow defining members, such as variables and methods, to
operate on the encapsulated data.
• Encapsulation: Both structures and classes support encapsulation, allowing data and related
functions to be bundled together and accessed through a single entity.
• Custom Data Types: Both can be used to define custom data types that represent a
collection of related attributes and behaviors.
• Instance Creation: Instances of both structures and classes can be created to work with the
defined data and methods.
• User-Defined Types: Both structures and classes allow programmers to define their own
custom data types, enabling abstraction and encapsulation of data.
• Grouping of Data: Both structures and classes provide a way to group related data elements
together, improving code organization and readability.
• Passing as Function Arguments: Instances of structures and classes can be passed as
arguments to functions, allowing functions to operate on the encapsulated data.
• Operators Overloading: Some languages allow operator overloading for both structures and
classes, enabling custom behavior for operators like '+', '-', '==', etc.
• Data Encapsulation: Both structures and classes support data encapsulation, meaning that
data members can be kept private and accessed only through public methods or properties.

Differences between structures and classes:

• Inheritance: Classes support inheritance, allowing one class to inherit properties and
behaviors from another class. Structures do not support inheritance.
• Access Modifiers: Classes support access modifiers like public, private, and protected,
allowing control over member visibility and accessibility. Structures typically do not have
access modifiers, and their members are public by default.
• Default Member Visibility: Members of a structure are public by default, whereas members
of a class are private by default (in many languages).
• Polymorphism: Classes support polymorphism, allowing methods to be overridden in
derived classes. Structures do not support polymorphism.
• Constructor and Destructor: Classes can have constructors and destructors to initialize and
clean up object instances. Structures generally do not have constructors or destructors
(except in some languages like C++).
• Usage: Classes are often used for more complex scenarios where encapsulation, inheritance,
and polymorphism are needed, such as in object-oriented programming. Structures are
typically used for simpler data types or when working with plain data without much
behavior associated with it.

2) What are static objects? Give examples.

In C and C++, static objects refer to variables and functions that retain their values and scope throughout
the entire program's execution. They are allocated memory at compile time and persist throughout the
program's lifetime. Here are some examples:

• Static variables:

#include <stdio.h>

void func() {

static int count = 0; // Static variable retains its value across function calls

count++;

printf("Count: %d\n", count);

int main() {

func(); // Count: 1

func(); // Count: 2

func(); // Count: 3

return 0;

• Static functions:

#include <stdio.h>
static void staticFunc() {

printf("This is a static function.\n");

int main() {

staticFunc(); // Call the static function directly

return 0;

• Static global variables:

#include <stdio.h>

static int globalVar = 100; // Static global variable

void func() {

printf("Global variable: %d\n", globalVar);

int main() {

func(); // Global variable: 100

return 0;

In C and C++, static objects help manage program state and scope effectively, providing a way to retain
values and functions across different parts of the program.
3) What are reference variables? Explain with examples.

Reference variables in C++ are aliases or alternative names for already existing variables. They are
declared using the & symbol and provide a way to access and modify the original variable indirectly. Here
are three examples of reference variables in C++:

• Swapping Variables:

#include <iostream>

using namespace std;

void swap(int &x, int &y) {

int temp = x;

x = y;

y = temp;

int main() {

int a = 5, b = 10;

cout << "Before swapping: a = " << a << ", b = " << b << endl;

swap(a, b);

cout << "After swapping: a = " << a << ", b = " << b << endl;

return 0;

In this example, x and y are reference variables passed to the swap function. Changes made to x and y
inside the function directly affect the original variables a and b in the main function.

• Array Manipulation:

#include <iostream>

using namespace std;

void printArray(int (&arr)[5]) {

cout << "Elements of the array: ";

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


cout << arr[i] << " ";

cout << endl;

int main() {

int numbers[] = {1, 2, 3, 4, 5};

printArray(numbers);

return 0;

Here, arr is a reference variable to an array of integers passed to the printArray function. Any
changes made to the array inside the function will directly affect the original array in the main
function.

• Function Return Values:

#include <iostream>

using namespace std;

int &increment(int &x) {

x++;

return x;

int main() {

int num = 5;

cout << "Original value of num: " << num << endl;

increment(num) = 10; // increment(num) returns a reference to num

cout << "Updated value of num: " << num << endl;

return 0;

}
In this example, the increment function takes a reference to an integer as a parameter and
increments its value. The function returns a reference to the same integer, allowing us to directly
assign a new value to num using the function call increment(num).

4) Design a generic stack data structure (not a STL object) which can handle integer, double, character
and any user-defined objects. Write a menu-driven C++ program to test it.

Here's a generic stack data structure implementation in C++ along with a menu-driven program to test it:

CODE:

#include <iostream>

#include <vector>

#include <stdexcept>

using namespace std;

template<typename T>

class Stack {

private:

vector<T> elements;

public:

// Push element onto the stack

void push(const T& element) {

elements.push_back(element);

// Pop element from the stack

void pop() {

if (empty()) {

throw out_of_range("Stack is empty");

}
elements.pop_back();

// Get the top element of the stack

T& top() {

if (empty()) {

throw out_of_range("Stack is empty");

return [Link]();

// Check if the stack is empty

bool empty() const {

return [Link]();

};

int main() {

Stack<int> intStack;

Stack<double> doubleStack;

Stack<char> charStack;

int choice;

do {

cout << "\n1. Push Integer\n2. Push Double\n3. Push Character\n"

<< "4. Pop Integer\n5. Pop Double\n6. Pop Character\n"

<< "7. Top Integer\n8. Top Double\n9. Top Character\n"

<< "0. Exit\n";

cout << "Enter your choice: ";


cin >> choice;

switch (choice) {

case 1: {

int value;

cout << "Enter an integer value to push: ";

cin >> value;

[Link](value);

break;

case 2: {

double value;

cout << "Enter a double value to push: ";

cin >> value;

[Link](value);

break;

case 3: {

char value;

cout << "Enter a character value to push: ";

cin >> value;

[Link](value);

break;

case 4:

if (![Link]()) {

[Link]();

} else {

cout << "Integer stack is empty.\n";


}

break;

case 5:

if (![Link]()) {

[Link]();

} else {

cout << "Double stack is empty.\n";

break;

case 6:

if (![Link]()) {

[Link]();

} else {

cout << "Character stack is empty.\n";

break;

case 7:

if (![Link]()) {

cout << "Top element of Integer stack: " << [Link]() << endl;

} else {

cout << "Integer stack is empty.\n";

break;

case 8:

if (![Link]()) {

cout << "Top element of Double stack: " << [Link]() << endl;

} else {

cout << "Double stack is empty.\n";

}
break;

case 9:

if (![Link]()) {

cout << "Top element of Character stack: " << [Link]() << endl;

} else {

cout << "Character stack is empty.\n";

break;

case 0:

cout << "Exiting program...\n";

break;

default:

cout << "Invalid choice. Please try again.\n";

} while (choice != 0);

return 0;

This program provides a menu-driven interface to interact with the generic stack data structure. It allows
the user to push and pop elements of different data types onto/from the stack and also view the top
element of each stack.
OUTPUT:

5) Implement a Lucky Draw game in which the user has to input an integer ‘input’ and

multiply it with a random integer to get the product ‘p’. Depending upon the value of

‘p’ display the prize amount. Use a suitable STL object in C++ to store the prize amount

for each value of ‘p’. [Hint: Use modulo operation to get final value of ‘p’]

Here's an implementation of the Lucky Draw game in C++:

CODE:

#include <iostream>

#include <cstdlib>

#include <ctime>

#include <unordered_map>
using namespace std;

// Function to generate a random integer within a specified range

int generateRandomInt(int min, int max) {

return rand() % (max - min + 1) + min;

// Function to calculate the prize amount based on the value of 'p'

int calculatePrize(int p) {

unordered_map<int, int> prizes = {

{0, 100},

{1, 200},

{2, 300},

{3, 400},

{4, 500},

{5, 600},

{6, 700},

{7, 800},

{8, 900},

{9, 1000}

};

return prizes[p % 10];

int main() {

srand(time(0)); // Seed for random number generation


int input;

cout << "Enter an integer 'input': ";

cin >> input;

int randomInt = generateRandomInt(1, 10); // Generate a random integer between 1 and 10

int p = input * randomInt; // Calculate the product 'p'

cout << "Random integer: " << randomInt << endl;

cout << "Product 'p': " << p << endl;

int prizeAmount = calculatePrize(p);

cout << "Prize amount: $" << prizeAmount << endl;

return 0;

In this implementation, we use the generateRandomInt function to generate a random integer between
1 and 10. Then, we calculate the product 'p' by multiplying the user input with the random integer.
Finally, we determine the prize amount based on the value of 'p' using an unordered map to store the
prize amounts for each possible value of 'p' (modulo 10).

You might also like