Not a member of gistpad yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- // 1. Define a Node to hold each question, its options, the answer, and a pointer to the next question.
- struct QuestionNode {
- string question;
- string options[4];
- int answer;
- QuestionNode* next;
- };
- // 2. Helper function to easily create and return a new question node.
- QuestionNode* createNode(string q, string opt1, string opt2, string opt3, string opt4, int ans) {
- QuestionNode* newNode = new QuestionNode();
- newNode->question = q;
- newNode->options[0] = opt1;
- newNode->options[1] = opt2;
- newNode->options[2] = opt3;
- newNode->options[3] = opt4;
- newNode->answer = ans;
- newNode->next = nullptr;
- return newNode;
- }
- int main()
- {
- // 3. Build the linked list by creating nodes and linking them together.
- QuestionNode* head = createNode("1. What is the extension of C++ file?", ".cp", ".cpp", ".c", ".java", 2);
- QuestionNode* q2 = createNode("2. Who developed C++ language?", "Dennis Ritchie", "Bjarne Stroustrup", "James Gosling", "Guido van Rossum", 2);
- head->next = q2;
- QuestionNode* q3 = createNode("3. Which symbol is used for comments in C++?", "//", "**", "##", "$$", 1);
- q2->next = q3;
- QuestionNode* q4 = createNode("4. Which function is used to display output?", "cin", "cout", "printf", "input", 2);
- q3->next = q4;
- QuestionNode* q5 = createNode("5. C++ is which type of language?", "Procedural", "Object Oriented", "Functional", "None", 2);
- q4->next = q5;
- int score = 0;
- int userAnswer;
- // 4. Traverse the linked list to ask the questions
- QuestionNode* current = head;
- while (current != nullptr)
- {
- cout << current->question << endl;
- for(int j = 0; j < 4; j++)
- {
- cout << j+1 << ". " << current->options[j] << endl;
- }
- cout << "Enter your answer (1-4): ";
- cin >> userAnswer;
- if(userAnswer == current->answer)
- {
- score++;
- }
- cout << endl;
- // Move to the next question in the list
- current = current->next;
- }
- cout << "Quiz Completed!" << endl;
- cout << "Your Score: " << score << "/5" << endl;
- // 5. Clean up dynamically allocated memory to prevent memory leaks
- current = head;
- while (current != nullptr)
- {
- QuestionNode* temp = current;
- current = current->next;
- delete temp;
- }
- return 0;
- }
RAW Gist Data
Copied
