Develop a program that gives the following information using stack.
⮚
Student name
⮚
Student ID
⮚ CNIC
CODE:
#include <iostream>
#include <stack>
using namespace std;
struct Student {
string name;
int id;
string cnic;
};
int main() {
stack<Student> students;
// Push three students into the stack
students.push({"John Smith", 12345, "12345-6789101-1"});
students.push({"Jane Doe", 23456, "23456-7891011-2"});
students.push({"Bob Johnson", 34567, "34567-8910111-3"});
// Print the information of each student
while (!students.empty()) {
Student s = students.top();
cout << "Name: " << s.name << endl;
cout << "ID: " << s.id << endl;
cout << "CNIC: " << s.cnic << endl;
cout << endl;
students.pop();
}
return 0;
}
OUTPUT:Name: Bob Johnson
ID: 34567
CNIC: 34567-8910111-3
Name: Jane Doe
ID: 23456
CNIC: 23456-7891011-2
Name: John Smith
ID: 12345
CNIC: 12345-6789101-1
Explanation:
- The program defines a
Student
struct to store the name, ID, and CNIC of a student. - The program declares a
stack<Student>
variable namedstudents
to store the student information. - Using a series of
push
operations, the program adds threeStudent
objects to the stack, each with a different name, ID, and CNIC. - The program then prints the information of each student in the stack by repeatedly calling
students.top()
to get the topStudent
object, and printing its name, ID, and CNIC. The loop continues until the stack is empty. The program also callsstudents.pop()
to remove the topStudent
an object from the stack after printing its information.
Tags
C-Codes