How To Modify Data In a c++ Linked List - c++

I have made a Student record system in c++ using the concept of linked list. The program will take the student id, name and marks for 3 different exams. Then it will calculate the aggregate percentage based on those exams marks and display the relevant message according to the aggregate percentage. The program is running without any errors.
But I want student id to be unique. For example, if a user inputs a student id which has been already assigned to previous student than it will show a message that "please enter a different id."
How would I do that. Any help will be appreciated.
struct student
{
int id;
char name[MAX];
string status;
double aggr;
int matric_marks, inter_marks, entryTest_marks;
};
struct node
{
struct student *data;
struct node *next;
node()
{
data = 0;
next = NULL;
}
};
struct student *readStudent()
{
clearWindow();
struct student *stdnt = new student;
gotoxy(33,8);cout<<"Student ID: ";
while(!(cin >> stdnt->id) || cin.peek() != '\n')
{
char ch;
cin.clear();
cout << "sorry";
while(cin.get(ch) && ch != '\n');
}
cin.ignore();
gotoxy(33,10);cout<<"Student Name: ";
cin.getline(stdnt->name, 50);
gotoxy(33,12);cout<<"Enter Matriculation Marks: ";
cin>>(stdnt->matric_marks);
gotoxy(33,14);cout<<"Enter Intermediate Marks: ";
cin>>(stdnt->inter_marks);
gotoxy(33,16);cout<<"Enter Entry Test Marks: ";
cin>>(stdnt->entryTest_marks);
stdnt->aggr = calculate_aggregiate(stdnt);
gotoxy(33,18);cout<<"Student Aggregate Marks: "<< stdnt->aggr;
if (stdnt->aggr >= 70)
{
gotoxy(33,20);cout<<"Student Registered In Electrical Engg";
}
else if (stdnt->aggr >= 60)
{
gotoxy(33,22);cout<<"Student Registered In Mechanical Engg";
}
else if (stdnt->aggr >=50)
{
gotoxy(33,24);cout<<"Student Registered In Computer Science";
}
else
{
gotoxy(33,20);cout<<"Sorry! The Student Doesnt Qualify";
}
return stdnt;
}
struct node *createDatabase(int size)
{
int i = 0;
struct node *head = NULL;
struct node *last = NULL;
for(i = 0; i < size; i++)
{
struct student *stdnt = readStudent();
struct node * current = new node;
current->data = stdnt;
current->next = NULL;
if(last)
last->next = current;
else
head = current;
last = current;
}
return head;
}
struct node *InsertRecord(struct node *head)
{
struct node *record = new node;
struct student *stdnt = readStudent();
record->data=stdnt;
record->next=head;
return record;
}
double calculate_aggregiate(struct student *stud)
{
student *stdnt = stud;
double aggr;
aggr = stdnt->matric_marks * 10/100 + stdnt->inter_marks * 50/100 +
stdnt->entryTest_marks * 40/100;
return aggr;
}
struct node *DeleteRecord(struct node *head)
{
clearWindow();
struct node *curr,*prev, *temp;
int tdata;
if(head==NULL)
{
gotoxy(33,10);cout<<"NO RECORDS TO DELETE......!";
}
else
{
gotoxy(33,10);cout<<"Enter Student ID To Be Deleted: ";
cin>>tdata;
prev=curr=head;
while((curr!=NULL)&&(curr->data->id!=tdata))
{
prev=curr;
curr=curr->next;
}
if(curr==NULL)
{
gotoxy(33,12);cout<<"The Requested ID Is Not Found...!";
}
else if(curr==head)
{
head=head->next;
gotoxy(33,12);cout<<"DATA DELETED....!";
}
else
{
prev->next=curr->next;
if(curr->next==NULL)
{
temp=prev;
}
gotoxy(33,12);cout<<"DATA DELETED....!"<<tdata;
}
delete(curr);
}
return head;
}
void ModifyRecord(struct node *head)
{
clearWindow();
int ch, sid;
struct node *current;
struct student *stdnt;
if (head==NULL)
{
gotoxy(33,8);cout<<"NO RECORD TO MODIFY..!";
}
else
{
gotoxy(33,8);cout<<"Enter Student ID To Modify: ";
cin>>sid;
current=head;
while((current!=NULL) && (current->data->id!=sid))
{
current=current->next;
}
if (current==NULL)
{
gotoxy(33,10);cout<<"The Requested ID is Not Found";
}
else if(current->data->id==sid)
{
gotoxy(33,10);cout<<"What Do You Want To Modify";
gotoxy(33,12);cout<<"1. Student's Name";
gotoxy(33,14);cout<<"2. Student's Matric Marks";
gotoxy(33,16);cout<<"3. Student's Intermediate Marks";
gotoxy(33,18);cout<<"4. Student's Entry Test Marks";
gotoxy(33,20);cout<<"Enter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1 : gotoxy(33,22);cout<<"Enter New Name: ";
cin.getline(current->data->name, 50);break;
case 2 : gotoxy(33,22);cout<<"Enter New Matric Marks: ";
cin>>(current->data->matric_marks);break;
case 3 : gotoxy(33,22);cout<<"Enter New Intermediate Marks: ";
cin>>(current->data->inter_marks);break;
case 4 : gotoxy(33,22);cout<<"Enter New Entry Test Marks: ";
cin>>(current->data->entryTest_marks);break;
current->data->aggr = current->data->matric_marks * 10/100 + current->data- >inter_marks * 50/100 +
current->data->entryTest_marks * 40/100;
}
gotoxy(33,24);cout<<"RECORD MODIFIED....!";
}
}
}
void SearchRecord(struct node *head)
{
clearWindow();
int s_id;
struct node *current;
if (head==NULL)
{
gotoxy(33,8);cout<<"NO RECORD TO SEARCH..!";
}
else
{
gotoxy(33,8);cout<<"Enter Student ID To Be Searched: ";
cin>>s_id;
current=head;
while ((current!=NULL) && (current->data->id!=s_id))
{
current=current->next;
}
if (current==NULL)
{
gotoxy(33,10);cout<<"The Requested ID is Not Found";
}
else if (current->data->id==s_id)
{
gotoxy(33,10);cout<<"Student ID: "<<current->data->id;
gotoxy(33,12);cout<<"Student Name: "<<current->data->name;
gotoxy(33,14);cout<<"Student Matric Marks: "<<current->data->matric_marks;
gotoxy(33,16);cout<<"Student Intermediate Marks: "<<current->data - >inter_marks;
gotoxy(33,18);cout<<"Student Entry Test Marks: "<<current->data- >entryTest_marks;
gotoxy(33,20);cout<<"Student Aggregate Marks: "<<current->data->aggr;
if (current->data->aggr >= 70)
{
gotoxy(33,22);cout<<"Student Registered In Electrical Engg";
}
else if (current->data->aggr >= 60)
{
gotoxy(33,22);cout<<"Student Registered In Mechanical Engg";
}
else if (current->data->aggr >=50)
{
gotoxy(33,22);cout<<"Student Registered In Computer Science";
}
else
{
gotoxy(33,22);cout<<"Sorry! The Student Doesnt Qualify";
}
}
}
}
void print(struct node *head)
{
clearWindow_p();
struct node *current = head;
if (head == NULL)
{
gotoxy(33,8);cout<<"No Student Registered Yet......!";
}
else
{
cout<<"\n\t\t\t\t\tSTUDENTS STATISTICS";
while(current)
{
struct student *stdnt = current->data;
cout<<"\n\t\t\t\t\t-------------------------------- ";
cout<<"\n\t\t\t\t\tStudent ID :"<<stdnt->id;
cout<<"\n\t\t\t\t\tStudent Name :"<<stdnt->name;
cout<<"\n\t\t\t\t\tMatric Marks :"<<stdnt->matric_marks;
cout<<"\n\t\t\t\t\tIntermediate Marks :"<<stdnt->inter_marks;
cout<<"\n\t\t\t\t\tEntry Test Marks: "<<stdnt->entryTest_marks;
cout<<"\n\t\t\t\t\tAggregate: "<<stdnt->aggr;
if (stdnt->aggr >= 70)
{
cout<<"\n\t\t\t\t\tStudent Registered In Electrical Engg";
}
else if (stdnt->aggr >= 60)
{
cout<<"\n\t\t\t\t\tStudent Registered In Mechanical Engg";
}
else if (stdnt->aggr >=50)
{
cout<<"\n\t\t\t\t\tStudent Registered In Computer Science";
}
else
{
cout<<"\n\t\t\t\t\tSorry! The Student Doesnt Qualify";
}
current=current->next;
}
cout<<"\n\t\t\t\t\t--------------------------------";
}
}
int compareStudents(struct student *left, struct student *right)
{
return strcmp(left->name, right->name);
}
struct node *sort(struct node *head)
{
//using bubble sort
int swapped = 0;
do
{
swapped = 0;
struct node *current = head;
struct node *previous = NULL;
while(current && current->next)
{
if(compareStudents(current->data, current->next->data) > 0)
{
//swap here
struct node *next = current->next;
if(previous)
{
previous->next = next;
}
else
{
head = next;
}
current->next = next->next;
previous = next;
previous->next = current;
swapped = 1;
}
else
{
previous = current;
current = current->next;
}
}
} while(swapped);
return head;
}
int main()
{
system("color f0");
window();
SetColor(28);
int total,i,choice;
int x = 2;
struct node *head;
head=NULL;
do
{
menu:
gotoxy(x, 8);cout<<"1.Create a Record File";
gotoxy(x, 10);cout<<"2.Insert Student's Record";
gotoxy(x, 12);cout<<"3.Modify Student's Record";
gotoxy(x, 14);cout<<"4.Delete Student's Record";
gotoxy(x, 16);cout<<"5.Search Student's Record";
gotoxy(x, 18);cout<<"6.Print All Records";
gotoxy(x, 20);cout<<"7.Sort According To Names";
gotoxy(x, 22);cout<<"8.Clear The Screen";
gotoxy(x, 24);cout<<"9.Exit";
gotoxy(x, 26);cout<<"Enter your choice";
cout<<" [ ]\b\b";
cin>>choice;
switch(choice)
{
case 1:
clearWindow();
gotoxy(33, 8);cout<<"How Many Students Do You Want To Register: ";
cin>>total;
head=createDatabase(total);
break;
case 2:
head=InsertRecord(head);
break;
case 3:
ModifyRecord(head);
break;
case 4:
DeleteRecord(head);
break;
case 5:
SearchRecord(head);
break;
case 6:
print(head);
break;
case 7:
sort(head);
print(head);
break;
case 8:
main();
break;
default: gotoxy(33,8);cout<<"INVALID OPTION";
}
}while(choice!=9);
getch();
return 0;
}

Since you are using C++, you should take advantage of the built-in types. If there is only one student with a given ID, use the std::map<> template. For example:
struct student
{
char name[MAX];
string status;
double aggr;
int matric_marks, inter_marks, entryTest_marks;
};
map<int, student> students;
then, to traverse students:
for (auto i = students.begin(); i != students.end(); ++i) {
int studentId = i->first;
student& student = i->second;
student.aggr = ...
}
(auto is C++11, not all compilers enable it by default IIRC. See here.)

If You know the range of student ids , and it is within a feasible range of memory , you can use a UsedId[] array.
If the range is too big too be held , use a Hashmap ,(MAP in c++) .

I would probably implement something called FindRecordByID.
struct student *FindRecordByID(struct node *head, int id) {
for(; head != NULL; head = head->next)
if (head->data->id == id)
return head->data;
return NULL;
}
Then when you do your create_new_student routine, you could use that to verify that the given ID is not already used.

Related

How to sort nodes from a stack and put into a queue

im trying to implement both queue and stack in my mini project. Customer will enter nodes into stack and the seller will sort the nodes from stack and put them into queue. I want to sort nodes from a stack based on college name, where all nodes with college = "kdoj" will get into the queue first then followed by all nodes with college = "kdse". The problem is i have tried doing the sorting with 2 (for loop) and i dont know why only 2 nodes get into the queue when i have more than 2 nodes in the stack. i am not sure where is the problem and been stuck here for a while :(.
This is the input example:
name : david
ic num: 123
phone num: 123
college: kdse
quantity: 1
size: m
name : jojo
ic num: 123
phone num: 123
college: kdse
quantity: 1
size: m
name : zoro
ic num: 123
phone num: 123
college: kdoj
quantity: 1
size: m
This is the runnable code.
The problem will occur when you sort the list in seller menu after entering the data.
#include <iostream>
#include <cstring>
#include<iomanip>
#include <conio.h>
#include<string>
using namespace std;
//nodes
struct customerNode {
string name, id, college;
int phoneNum,quantity;
char size;
public:
customerNode* next;
customerNode(string name, string id, int phoneNum,string college, int quantity, char size)
{
name = name;
id = id;
phoneNum = phoneNum;
college = college;
quantity = quantity;
size = size;
next = NULL;
}
};
//class customer
class Customer{
public:
customerNode *head = NULL;
bool isEmpty(){
return(head == NULL);
}
void pushStack(string name, string id, int phoneNum, string college, int quantity, char size){
customerNode *newnode = new customerNode(name,id,phoneNum,college,quantity,size);
newnode->name = name;
newnode->id= id;
newnode->phoneNum = phoneNum;
newnode->college = college;
newnode->quantity = quantity;
newnode->size = size;
if(isEmpty()){
newnode->next = head;
head = newnode;
cout<<endl<<"created new stack."<<endl;
}
else{
newnode->next = head;
head = newnode;
cout<<endl<<"added node into a stack."<<endl;
}
}
//pop out node from stack
void popStack(){
customerNode *temp;
temp = head; //temp variable
head = temp->next;
temp->next = NULL;
cout<<endl<<"Order has been deleted!";
}
//push node into stack
void enterOrder(){
int phoneNum, quantity;
char size;
string name, id, college;
cout<<endl<<"\tADDING YOUR ORDER.\n";
cout<<"\tName: ";
cin.ignore();
getline(cin,name);
cout<<"\tIC Num: ";
cin>>id;
cout<<"\tPhone Number: ";
cin>>phoneNum;
cout<<"\tCollege name: ";
cin>>college;
cout<<"\tQuantity: ";
cin>>quantity;
cout<<"\tSize (S/M/L/XL): ";
cin>>size;
pushStack(name, id, phoneNum,college, quantity, size);
cin.get();
}
//see order and trigger popout funct
void deleteorder(){
char choice;
cout<<"YOUR ODER."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
stackTop();
cout<<endl;
cout<<endl<<"Confirm to delete?: ";
cin>>choice;
if(choice == 'y' || choice == 'Y'){
popStack();
}
}
//display node at the top
void stackTop(){
customerNode *check;
if(!isEmpty()){
check = head;
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
int getNumberNodes(){
customerNode *check;
check = head;
int counter = 0;
while(check!= NULL){
counter++;
check = check->next;
}
return counter;
}
};
//Customer main menu
void customerMenu(Customer &c){
int choice;
do{cout
<<endl<<"CUSTOMER MENU"
<<endl<<"Please choose your task."
<<endl<<"1. Insert Order"
<<endl<<"2. Delete Order"
<<endl<<"3. Check Order"
<<endl<<"4. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
//customer task
switch(choice){
case 1: c.enterOrder();
break;
case 2: c.deleteorder();
break;
case 3:
cout<<"\nYOUR ODER."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
c.stackTop();
cout<<endl;
break;
}
}while(choice != 4);
};
//SELLER CLASS
class Seller{
string id;
string password;
public:
customerNode *backPtr, *frontPtr;
//constructor seller
Seller(){
id = "12345";
password = "12345";
backPtr = NULL;
frontPtr = NULL;
}
//check queue empty
bool queueEmpty(){
return (backPtr == NULL && frontPtr == NULL);
}
//display all nodes in stack
void getStack(Customer &c){
customerNode *check;
if(!c.isEmpty()){
check = c.head;
while(check!=NULL){
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
check=check->next;
}
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
//will trigger getStack()
void displayStack(Customer &c){
cout<<"\nCUSTOMER FULL ORDERLIST."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
getStack(c);
cout<<endl;
}
//display all nodes in queue
void getQueue(){
customerNode *check;
if(!queueEmpty()){
check = frontPtr;
while(check!=NULL){
cout<<endl<<
setw(10)<<left<<check->id
<<setw(20)<<left<<check->name
<<setw(10)<<left<<check->phoneNum
<<setw(20)<<left<<check->college
<<setw(10)<<left<<check->quantity
<<setw(5)<<left<<check->size;
check=check->next;
}
}
else{
cout<<endl<<"Stack is an underflow.";
getch();
}
}
//display node in queue
void displayQueue(){
cout<<"\nSORTED CUSTOMER FULL ORDERLIST."<<endl<<
setw(10)<<left<<"ID"
<<setw(20)<<left<<"NAME"
<<setw(10)<<left<<"CONTACT"
<<setw(20)<<left<<"COLLEGE"
<<setw(10)<<left<<"QUANTITY"
<<setw(5)<<left<<"SIZE";
getQueue();
cout<<endl;
}
//insert queuee
void insertQueue(customerNode *newNode){
if(!queueEmpty()){
newNode->next = NULL;
backPtr->next = newNode;
backPtr = newNode;
cout<<endl<<"inserted node into queue."<<endl;
}
else{
frontPtr = newNode;
backPtr = newNode;
}
}
void sortOrder(Customer &c){
for(customerNode *node = c.head; node!=NULL; node = node->next){
if(node->college == "kdoj"){
cout<<endl<<node->college;
insertQueue(node);
}
}
for(customerNode *node = c.head; node!=NULL; node = node->next){
if(node->college == "kdse"){
cout<<endl<<node->college;
insertQueue(node);
}
}
displayQueue();
}
};
//seller main menu
void sellerMenu(Customer &c, Seller &s){
int choice;
do{cout
<<endl<<"SELLER MENU"
<<endl<<"Please choose your task."
<<endl<<"1. Display OrderList"
<<endl<<"2. Sort OrderList"
<<endl<<"4. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
//choose task
switch(choice){
case 1: s.displayStack(c);
break;
case 2: s.sortOrder(c);
break;
case 3:
break;
}
}while(choice != 4);
}
void menu(Customer &c, Seller &s){ //main menu function
int choice;
do{
cout
<<endl<<"Welcome to HotspotPrinting!"
<<endl<<"Please choose your role."
<<endl<<"1. Customer"
<<endl<<"2. Seller"
<<endl<<"3. Exit"
<<endl<<"Your Choice: ";
cin>>choice;
switch(choice){
case 1: customerMenu(c);
break;
case 2: sellerMenu(c,s);
break;
}
}while(choice != 3);
}
int main()
{
Customer c;
Seller s;
menu(c,s);
cout<<endl<<"Thank You For Using Our Service :)!";
return 0;
}
your problem is that customer node records exist in two containers, your queue and a list. But you only have one next pointer, when you insert a customer into the queue you set its next pointer to null, this destroys the linkage in the customer list.
If you need to have the same object in 2 containers then use shared_ptr in standard containers, like std::list and std::queue

I want to make a program where an input from the user is separated into 3 circular linked lists. But I am facing return value 3221225725 error

A Bank manager want to segregate different Currency notes in to 3 different baskets. Initially, all the currencies are in one Basket and the currencies are USD, INR and EUR. Now, you are supposed to write a program that can segregate the currencies to 3 different buckets. While, segregation, make sure to have a track of the overall sum of the currencies in terms of INR for each basket.
Program Requirements:
1.First get the input from the user for the overall Basket. [Even numbers are mapped as USD, Odd numbers are mapped as INR and Prime numbers are mapped as EUR, if there is an intersection, you are free to select any one of them]
2.After receiving the elements of the Basket, try a function to segregate the currencies
3.While adding the currency to its corresponding basket, ensure to calculate the overall sum.
4.Whenever, the bank manager wants to see the basket, you should display all the baskets and its corresponding SUM, MEAN, MEDIAN and MODE.
5.Also, there should be a provision to remove required amount of currency in each basket. [While removal, you need to enter the amount of removal in INR and its corresponding value should be removed from the respective basket]
NOTE: Use the value, USD = 73 INR and EUR = 86.5 INR
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int prime(int n);
struct node
{
int info;
struct node *next;
}*last;
class circular_llist
{
public:
void insert(int value);
void delete_element(int value);
void display_list();
circular_llist()
{
last = NULL;
}
};
int main()
{
int element, choice, ch;
int arr[100], i, n, x;
int sum_usd=0, sum_inr=0, sum_eur=0;
int c_usd=0, c_inr=0, c_eur=0;
int arr_usd[n], arr_inr[n], arr_eur[n];
cout << "Enter the total number of elements" << endl;
cin >> n;
cout << "Enter the elements:" << endl;
for(i=0;i<n;i++) {
cin >> x;
arr[i]=x;
}
circular_llist usd;
circular_llist inr;
circular_llist eur;
for(i=0;i<n;i++) {
if(prime(arr[i])==1) {
eur.insert(arr[i]);
sum_eur+=arr[i];
c_eur++;
}
else if(arr[i]%2==0) {
usd.insert(arr[i]);
sum_usd+=arr[i];
c_usd++;
} else {
inr.insert(arr[i]);
sum_inr+=arr[i];
c_inr++;
}
}
do{
cout << "1.Delete Element" << endl;
cout << "2.Display elements" << endl;
cout << "3.Show mathematical figures" << endl;
cout << "4.Quit" << endl;
cin >> ch;
switch(ch)
{
case 1:
cout << "From which basket do you want to delete?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
usd.delete_element(element);
cout<<endl;
break;
case 2:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
inr.delete_element(element);
cout<<endl;
break;
case 3:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
eur.delete_element(element);
cout<<endl;
break;
}
case 2:
cout << "From whick basket do you want to diplay thye elements?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
usd.display_list();
cout << endl;
break;
case 2:
inr.display_list();
cout << endl;
break;
case 3:
eur.display_list();
cout << endl;
break;
}
case 3:
cout << "For which basket do you want tp show the mathematical figures?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
cout << "Sum = " << sum_usd << endl;
cout << "Mean = " << endl;
case 2:
cout << "Sum = " << sum_inr << endl;
case 3:
cout << "Sum = " << sum_eur << endl;
}
case 4:
cout << "EXIT" << endl;
break;
default :
cout << "Choose a valid option" << endl;
break;
}
}while(ch!=4);
return 0;
}
/*
* Create Circular Link List
*/
void circular_llist::insert(int value)
{
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
/*
* Deletion of element from the list
*/
void circular_llist::delete_element(int value)
{
struct node *temp, *s;
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->info == value) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->info == value)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<value;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
/*Deletion of last element*/
if (s->next->info == value)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}
/*
* Display Circular Link List
*/
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last)
{
cout<<s->info<<"->";
s = s->next;
}
cout<<s->info<<endl;
}
/*
*Check in the element is prime or not
*/
int prime(int n) {
int i;
int a;
for(i=2;i<n;i++){
if(n%i==0) {
a = 0;
break;
}
}
return a;
}
Change this: int arr_usd[n], arr_inr[n], arr_eur[n];
Into this: int arr_usd[20], arr_inr[20], arr_eur[20];
or any other number other than 20. It shows an error as n value hasn't been initialised yet.
Done completely using LinkedList in C
#include <stdio.h>
#include <stdlib.h>
struct Node{
float data;
struct Node* next;
};
struct Node *EUR=NULL;
struct Node *USD=NULL;
struct Node *INR=NULL;
void sort(struct Node **h){
struct Node* node1;
struct Node* node2;
int temp;
for(node1=*h;node1!=NULL;node1=node1->next){
for(node2=node1->next;node2!=NULL;node2=node2->next){
if(node1->data>node2->data){
temp = node1->data;
node1->data = node2->data;
node2->data = temp;
}
}
}
}
void add(float val,struct Node **h){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = val;
temp->next = NULL;
if(*h==NULL){
*h = temp;
return;
}
struct Node *node = *h;
while(node->next!=NULL){
node = node->next;
}
node->next = temp;
}
void delete(struct Node** h, float amt){
struct Node *node = *h;
if(*h!=NULL){
if(node->data==amt){
*h = node->next;
}else{
int flag=0;
while(node->next!=NULL){
if(node->next->data==amt){
node->next = node->next->next;
flag=1;
printf("[*]Amount removed\n");
break;
}
node = node->next;
}
if(!flag){
printf("[*]Amount not in Basket!!!\n");
}
}
}else{
printf("[*]Failed\tZero Balance\n");
}
}
float sum(struct Node** h){
if(*h==NULL)
return 0;
float s=0;
struct Node *node = *h;
while(node!=NULL){
s += node->data;
node = node->next;
}
return s;
}
float mean(struct Node** h){
if(*h==NULL)
return 0;
int l=0;
float m,s=0;
struct Node *node = *h;
while(node!=NULL){
l++;
s += node->data;
node = node->next;
}
m =s/l;
return m;
}
float median(struct Node** h){
if(*h==NULL)
return -1;
float med;
struct Node* f_node = *h;
struct Node* p_node = *h;
struct Node* s_node = *h;
while(f_node!=NULL && f_node->next!=NULL){
f_node = f_node->next->next;
p_node = s_node;
s_node = s_node->next;
}
if(f_node!=NULL){//odd
med = s_node->data;
}else{
med = (p_node->data+s_node->data)/2;
}
return med;
}
int mode(struct Node **h){
if(*h==NULL)
return 0;
int max_value=0;
int count,max_count = 0;
struct Node *node = *h;
while (node!=NULL){
count = 0;
struct Node *node2 = node->next;
while(node2!=NULL){
if(node->data==node2->data)
count++;
node2 = node2->next;
}
if(count>max_count){
max_value = node->data;
max_count = count;
}
node = node->next;
}
if(max_count==0)
return 0;
return max_value;
}
void print(struct Node** h,char *m){
printf("printing %s>>>\n",m);
if(*h==NULL){
printf("[*]No bills\n");
return;
}
struct Node* node = *h;
while(node->next!=NULL){
printf("%.2f->",node->data);
node = node->next;
}
printf("%.2f\n",node->data);
printf("[*]SUM: %.2f\n",sum(h));
printf("[*]MEAN: %.2f\n",mean(h));
printf("[*]MEDIAN: %.2f\n",median(h));
printf("[*]MODE: %d\n",mode(h));
}
int even(int n){
if(n%2==0)
return 1;
return 0;
}
int prime(int n){
for(int i=2;i<=n/2;i++){
if(n%i==0){
return 0;
}
}
return 1;
}
int main(){
int n;
int num;
printf("Enter total no of bills: ");
scanf("%d",&n);
float eur = 86.5f;
float usd = 73.0f;
for(int i=0;i<n;i++){
printf("Enter bill %d: ",i+1);
scanf("%d",&num);
if(prime(num))
add(eur*num,&EUR);
else if(even(num))
add(usd*num,&USD);
else
add((float)num,&INR);
}
sort(&EUR);
sort(&USD);
sort(&INR);
int ch1,ch2,br=0;
float amt;
while(1){
printf("1.Display Baskets\n2.Delete Amount\n3.Quit\nEnter your choice: ");
scanf("%d",&ch1);
switch(ch1){
case 1:
print(&EUR,"EURO");
print(&USD,"USD");
print(&INR,"INR");
break;
case 2:
printf("Enter amount to be deleted: ");
scanf("%f",&amt);
printf("Delete From>>>\n1.EUR\t2.USD\t3.INR");
scanf("%d",&ch2);
switch(ch2){
case 1:
delete(&EUR,amt);
break;
case 2:
delete(&USD,amt);
break;
case 3:
delete(&INR,amt);
break;
default:
printf("[*]Wrong Input\n");
break;
}
break;
default:
br = 1;
break;
}
if(br)
break;
}
}```

Mistakes in Summary report code using linked lists

I am currently doing a C++ project for my uni assignments. I came across a bit difficulty to code this using linked list.
#include <iostream>
#include<stdlib.h>
#include <string.h>
#include <iomanip>
#include <conio.h>
#define MAX 100
using namespace std;
class User
{
public:
struct user_details
{
string data1;
user_details *next1;
};
struct user_date
{
string data2;
user_date *next2;
};
struct event
{
string data4;
event *next_event;
};
void push_user (string name, string date,string eventss)
{
user_details *newName;
user_date *newDate;
event *newEvent;
cout <<"\n\nList of Events services offered.\n1.Wedding\n2.Birthday\n3.Funeral\n4.Celebration event\n5.Open House"<<endl;
cin.sync();
cout<<"\nEnter name: ";
getline(cin, name);
cin.sync();
cout <<"Enter date: ";
getline(cin, date);
cin.sync();
cout<<"Write the events(e.g. Course.style-Wedding or Buffet.style-Wedding): "<< endl;
getline(cin, eventss);
if(top1 == NULL|| top2 == NULL||top_event==NULL) //checking for empty stack
{
top1 = new user_details;
top1-> data1= name;
top1->next1= NULL;
top2 = new user_date;
top2->data2=date;
top2->next2=NULL;
top_event = new event;
top_event->data4= eventss;
top_event->next_event= NULL;
}
else
{
newName= new user_details;
newName->data1 = name;
newName->next1 = top1;
top1 = newName;
newDate= new user_date;
newDate->data2 = date;
newDate->next2 =top2;
top2= newDate;
newEvent= new event;
newEvent->data4 = eventss;
newEvent->next_event= top_event;
top_event = newEvent;
cout<<"Added new user to stack."<<endl;
}
}
void pop_user (string name, string date, string eventss)
{
user_details *current1;
user_date *current2;
event *current23;
if(top1 == NULL)
{
cout<<"!!!Stack underflow" << endl;
}
if(top2 == NULL)
{
cout<<"!!!Stack underflow" << endl;
}
if(top_event == NULL)
{
cout <<"!!!Stack underflow"<<endl;
}
else
{
name = top1->data1;
current1 = top1;
top1 = top1->next1;
delete current1;
date = top2->data2;
current2=top2;
top2 = top2->next2;
delete current2;
eventss = top_event->data4;
current23 = top_event;
top_event = top_event->next_event;
delete current23;
cout << "Name: "<< name<<endl;
cout << "Date: " << date<<endl;
cout<<"Event" << eventss << " is removed " << endl;
}
}
void display_user ()
{
user_details *current1;
user_date *current2;
event *current23;
if(top1 == NULL)
{
cout<<"\nEmpty list" << endl;
// return;
}
else
{
current1 = top1;
current2 =top2;
current23=top_event;
while(current1 != NULL || current2 !=NULL||current23 != NULL)
{
cout<<"\nName: "<< current1->data1<<endl;
current1 = current1->next1;
cout <<"Date: "<<current2->data2<<endl;
current2 = current2->next2;
cout<<"Event: " << current23->data4<<endl;
current23 = current23->next_event;
}
}
}
void deleteStack_user()
{
user_details *current1;
user_date *current2;
event *current23;
if(top1 == NULL || top2 ==NULL||top_event==NULL)
return;
else
{
current1 = top1;
current2 = top2;
current23=top_event;
while(current1 != NULL || current2 != NULL||current23 != NULL)
{
top1 = top1->next1;
delete current1;
current1 = top1;
top2 = top2->next2;
delete current2;
current2 = top2;
top_event = top_event->next_event;
delete current23;
current23 = top_event;
}
}
}
void search(string user_name) //linear search
{
user_details *current1;
cout <<"Please enter the name you want to search: "<<endl;
cin.sync();
getline(cin,user_name);
if(top1==NULL)
{
cout<<"not found";
}
else
{
current1 = top1;
while(user_name==current1->data1||current1 != NULL)
{
cout<<"\nName: "<< current1->data1<<endl;
current1 = current1->next1;
cout <<"Found."<<endl;
}
}
}
user_details *top1=NULL;
user_date *top2=NULL;
event *top_event;
};
class reeves
{
public:
struct node
{
string data;
node *next;
};
void push(string menu)
{
node *newMenu;
cout<<"Enter the menu: ";
cin.sync();
getline(cin, menu);
if(top == NULL) //checking for empty stack
{
top = new node;
top->data= menu;
top->next= NULL;
cout<<"\nCreated new menu."<<endl;
}
else
{
newMenu= new node;
newMenu->data = menu;
newMenu->next = top;
top = newMenu;
cout<<"Added new menu to stack."<<endl;
}
}
void pop(string menu)
{
node *current;
if(top == NULL)
{
cout<<"!!!Stack underflow" << endl;
}
else
{
menu = top->data;
current = top;
top = top->next;
delete current;
cout<<"Menu " << menu << " is removed " << endl;
}
}
void display()
{
node *current;
if(top == NULL)
{
cout<<"\nEmpty menu" << endl;
// return;
}
else
{
current = top;
while(current != NULL)
{
cout<<current->data<<endl;
current = current->next;
}
}
}
void deleteStack()
{
node *current;
if(top == NULL)
return;
else
{
current = top;
while(current != NULL)
{
top = top->next;
delete current;
current = top;
}
}
}
node *top=NULL;
};
class summary_report_price
{
public:
//double wedding_menu=22.00; //per person
//double birthday_menu=17.00;
//double funeral_menu=16.00;
//double celebrationEvent_menu=30.00;
//double openHouse_menu=25.00;
summary_report (){}
~summary_report(){}
struct quantity
{
int Num;
quantity *next_quantity;
};
struct total_quantity
{
int total;
total_quantity *next_total;
};
void enter_quantity(int Quantity, int totalRevenue)
{ int choose;
int price;
quantity *newQuantity;
total_quantity *newTotal;
cout << "\n\nWhich event did you previously choose?\n1.Wedding\n2.Birthday\n3.Funeral\n4.Celebration Event\n5.Open House.\n"<<endl;
cin>>choose;
switch(choose)
{
case 1:
cout <<"Wedding..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*22;
break;
case 2:
cout <<"Birthday..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*17;
break;
case 3:
cout <<"Funeral..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin>>Quantity;
totalRevenue=Quantity*16;
break;
case 4:
cout <<"Celebration Event..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*30;
break;
case 5:
cout <<"Open House..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*25;
break;
case 6:
exit(1);
break;
default:
cout<<"You can only press 1-6 only."<<endl;
}
if(top_quantity == NULL||top_total==NULL) //checking for empty stack
{
top_quantity = new quantity;
top_quantity->Num= Quantity;
top_quantity->next_quantity= NULL;
top_total= new total_quantity; //calc total
top_total->total=totalRevenue;
top_total->next_total=NULL;
}
else
{
newQuantity= new quantity;
newQuantity->Num= Quantity;
newQuantity->next_quantity= top_quantity;
top_quantity= newQuantity;
newTotal= new total_quantity;
newTotal->total=totalRevenue;
newTotal->next_total=top_total;
top_total= newTotal;
}
}
void pop_price(int Quantity, int totalRevenue)
{
quantity *current36;
total_quantity *current71;
if(top_quantity== NULL)
{
cout<<"!!!Stack underflow" << endl;
}
if(top_total== NULL)
{
cout<<"!!!Stack underflow" << endl;
}
else
{
Quantity = top_quantity->Num;
current36 = top_quantity;
top_quantity= top_quantity->next_quantity;
delete current36;
totalRevenue = top_total->total;
current71=top_total;
top_total = top_total->next_total;
delete current71;
cout << "Quantity: "<< Quantity <<endl;
cout << "Total: RM" << totalRevenue<< " is removed " << endl;
}
}
void display_totalRevenue()
{
quantity *current36;
total_quantity *current71;
if(top_quantity == NULL || top_total==NULL)
{
cout<<"\nEmpty revenue" << endl;
// return;
}
else
{
current36 = top_quantity;
current71=top_total;
while(current36 != NULL || current71 !=NULL)
{
cout<<"\nQuantity: "<<current36->Num<<endl;
current36 = current36->next_quantity;
cout<<"Total: RM"<<current71->total<<endl;
current71=current71->next_total;
}
}
}
quantity *top_quantity;
total_quantity *top_total;
};
So here's the problem I'm facing, supposedly I tried to access these structs from different classes of linked lists and make it print out into a summary report. That was the plan, as soon as I entered data it only shows me the list is empty.
Below is the function I'm having trouble with...is there another way to do this? Sorry for the mistakes. I am just a beginner to programming for C++
void QuantityReady(User::user_details *current1, User::user_date *current2, User::event *current23, summary_report_price::quantity *current36, summary_report_price::total_quantity *current71,int count)
{
//quantity
summary_report_price::quantity *temp3;
temp3=current36;
//totalRevenue
summary_report_price::total_quantity *temp5;
temp5=current71;
//struct user_details
User::user_details *temp;
temp=current1;
//struct user_date
User::user_date *temp1;
temp1=current2;
//struct event
User::event *temp2;
temp2=current23;
int i,j;
int HoldNum, tempCount= count, sizeM[tempCount], countM[tempCount];
int RevenueM[tempCount], HoldRevenue;
string NameM[tempCount], HoldName;
string DateM[tempCount], HoldDate;
string EventM[tempCount], HoldEvent;
string events1="Course style-Wedding ";
string events2="Course style-Birthday ";
string events3="Course style-Funeral ";
string events4="Course style-Celebration Event ";
string events5="Course style-Open House ";
string events6="Buffet style-Wedding ";
string events7="Buffet style-Birthday ";
string events8="Buffet style-Funeral ";
string events9="Buffet style-Celebration Event ";
string events10="Buffet style-Open House ";
system("cls");
if(current1==NULL||current2==NULL||current23==NULL||current36==NULL||current71==NULL)
{
cout<<"The list is empty..."<< endl;
cout<<"Press any key to continue ..."<<endl;
getch();
}
else
{ User::user_details *next1;
User::user_date *next2;
User::event *next_event;
summary_report::quantity *next_quantity;
summary_report::total_quantity *next_total;
i=0;
while (i<tempCount)
{
RevenueM[i]=temp5->total;
temp5=temp5->next_total;
sizeM[i]=temp3->Num; //quantity
temp3=temp3->next_quantity;
;
NameM[i]=temp->data1;//struct user details
temp=temp->next1;
DateM[i]=temp1->data2; // user date
temp1=temp1->next2;
EventM[i]=temp2->data4; //event
temp2=temp2->next_event;
i=i+1;
}
j=0;
for(i=0;i<tempCount; i++)
{
for(j=i+1; j<tempCount; j++)
{
if(sizeM[i]<sizeM[j]&&NameM[i]<NameM[j]&&DateM[i]<DateM[j]&&EventM[i]<EventM[j]&&RevenueM[i]<RevenueM[j]) //bubble sorting algorithm
{
HoldRevenue=RevenueM[i];
RevenueM[i]=RevenueM[j];
RevenueM[j]=HoldRevenue;
HoldNum=sizeM[i];
HoldName=NameM[i];
sizeM[i]=sizeM[j];
NameM[i]=NameM[j];
sizeM[j]=HoldNum;
NameM[j]=HoldName;
//date
HoldDate=DateM[i];
DateM[i]=DateM[j];
DateM[j]=HoldDate;
//event
HoldEvent=EventM[i];
EventM[i]=EventM[j];
EventM[j]=HoldEvent;
}
}
}
for(i=0;i<tempCount;i++)
{
countM[i]=0;
}
cout<<"\t\t\t\tReeves Cartering Summary Report"<<endl;
for(i=0;i<tempCount;i++)
{ temp1=current2;
temp2=current23;
temp3=current36;
temp5=current71;
temp=current1;
while (temp!=NULL||temp1!=NULL||temp2!=NULL||temp3!=NULL||temp5 !=NULL)
{
if(temp->data1==NameM[i]||temp1->data2==DateM[i]||temp2->data4==EventM[i]||temp3->Num==sizeM[i]||temp5->total==RevenueM[i])
{
if(temp2->data4.compare(events1)==0)
{
cout<<temp->data1<< " "<<temp2->data4<<temp1->data2 <<temp3->Num<<" "<<temp5->total; //quantity
}
if(temp2->data4==events2)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events3)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events4)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events5)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events6)
{
cout<<temp->data1<< " "<<temp2->data4<<temp1->data2 <<temp3->Num<<" "<<temp5->total; //quantity
}
if(temp2->data4==events7)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events8)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events9)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events10)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
countM[i]=1;
}
temp3=temp3->next_quantity;
temp5=temp5->next_total;
temp1=temp1->next2;
temp2=temp2->next_event;
temp=temp->next1;
}
}
cout<<"Press any key to continue...";
getch();
}
}
```
Your mistake is on the following line:
if(current1==NULL||current2==NULL||current23==NULL||current36==NULL||current71==NULL)
It means if any of those are null than it will print out The list is empty, you never changed current23 71 or 36 from their default value, why do you think they will not be null??
summary_report::quantity *temp3;
temp3=current36;
//totalRevenue
summary_report::total_quantity *temp5;
temp5=current71;
//struct user_details
User::user_details *temp;
temp=current1;
//struct user_date
User::user_date *temp1;
temp1=current2;
//struct event
User::event *temp2;
temp2=current23;
At this point your current 1 through 10 are all null, after you intialize the current 23, 71 etc will null as well...

'temp' is undeclared, first use this function

#include<iostream>
#include<conio.h>
#include<string>
#include<cstring>
#include<stdlib.h>
using namespace std;
bool rgstr_stdnt(struct student *stud,struct list *ls);
double calculate_aggregate(struct student *);
void srch_student(struct student * next);
void addToList(struct student *stud, struct list *l);
void display(struct student *stud, struct list *l);
struct student
{
char name[20];
int matric_marks, inter_marks, aptitude_marks;
int temp;
student *next;
};
struct list
{
char name[20];
double aggr;
list *next;
};
this is where the problem shows up, it says temp undeclared, first use this function and I'm not able to rectify it
void srch_stdnt(struct student *stud)
{
char name[60];
cout << "Enter Student to search :";
cin>>name;
cout << name;
//down here, the error comes and whatever i knew, i have tried to solve it but could not
while (temp!=NULL){
if(strcmp(temp->name, name)==0){
}
temp = temp->next;
}
cout << "No match found";
}
int main()
{
student * temp=new student();
student *s;
s = (struct student *) malloc(sizeof(struct student));
struct list *ls;
ls = (struct list *) malloc(sizeof(struct list));
strcpy(ls->name,"");
ls->aggr = 0;
ls->next= NULL;
do
{
cout<<" STUDENT ENROLLMENT AND RECORDS MANAGEMENT"<<endl;
cout<<"1- To Enroll A New Sudent."<<endl;
cout<<"2- To View The Enrolled Students."<<endl;
cout<<"3- To Search Through The Already Enrolled Students."<<endl;
cout<<"4- Exit."<<endl;
int input;
cin>>input;
if (input == 1)
{
rgstr_stdnt(s, ls);
}
else if (input == 2)
{
display(s, ls);
}
else if(input == 3)
{
void srch_student(struct student * stud);
}
else if (input == 4)
exit(0);
cout<<endl;
} while(1);
getch();
}
bool rgstr_stdnt(struct student *stud,struct list *ls)
{
student *s = stud;
cout<<"Enter Name Of The Student: "<<endl;
cin>>s->name;
cout<<"Enter Percentage in 10th Grade: "<<endl;
cin>>s->matric_marks;
cout<<"Enter Intermediate Percentage:"<<endl;
cin>>s->inter_marks;
cout<<"Enter Percentage In Aptitude Test: "<<endl;
cin>>s->aptitude_marks;
double aggregate;
aggregate = calculate_aggregate(s);
cout<<"Aggregate Percentage Is: "<< aggregate<<"%"<<endl;
if (aggregate >= 70)
{
cout<<"-> Student Enrolled In BSCS. <-"<<endl;
addToList(s,ls);
return true;
}
else if (aggregate >= 60)
{
cout<<"-> Student Enrolled In BE. <-"<<endl;
addToList(s,ls);
return true;
}
else if (aggregate >=50)
{
cout<<"-> Student Enrolled In MS. <-"<<endl;
addToList(s,ls);
return true;
}
else
{
cout<<"Sorry, Low Percentage. Student Can't Be Enrolled!"<<endl;
return false;
}
}
double calculate_aggregate(struct student *stud)
{
student *s = stud;
double aggr;
aggr = s->matric_marks * 10/100 + s->inter_marks * 50/100 +
s->aptitude_marks * 40/100;
return aggr;
}
void addToList(struct student *stud, struct list *l)
{
list *pointer = l;
while (pointer->next != NULL)
{
pointer = pointer->next;
}
pointer->next = (struct list *) malloc(sizeof(struct list));
pointer = pointer->next;
strcpy(pointer->name , stud->name);
pointer->aggr = calculate_aggregate(stud);
pointer->next = NULL;
}
void display(struct student *stud, struct list *l)
{
list *pointer = l;
if (pointer->next == NULL)
cout<<"No Students Enrolled Yet."<<endl;
else
{
cout<<" !- - - - - - - - -. STUDENTS RECORDS .- - - - - - - - - -! "
<<endl;
while (pointer->next != NULL)
{
pointer = pointer->next;
cout<<"Name Of Student: "<<pointer->name<<endl;
cout<<"Aggregate Is: "<<pointer->aggr<<endl;
if (pointer->aggr >= 70)
cout<<"-> Student Enrolled In BSCS. <-"<<endl;
else if(pointer->aggr >=60)
cout<<"-> Student Enrolled In BE. <-"<<endl;
else
cout<<"-> Student Enrolled In MS. <-"<<endl;
cout<<endl;
}
}
}
Any who could help me solve this, i'd really be grateful.
As the error message states, you're using a variable called temp that you haven't declared yet. You need to declare it and give it an initial value:
struct student *temp = stud;
while (temp!=NULL){
...
//down here, the error comes and whatever i knew, i have tried to solve it but could not
while (temp!=NULL){
You have not declared temp in the function. That explains the compiler error.
Perhaps you meant to use:
struct student* temp = stud;
while ( temp != NULL )
Since you are in C++ land, discard the struct and use:
student* temp = stud;
while ( temp != NULL )
That change change can be made in rest of your code too.

Output of c++ program not coming as expected

I have made a C++ program for a binary tree. But the terminal is not asking the statement for inputting the direction for where the elements are to be placed.
Also when I replace the statement from " node *temp = new node " to "node *temp=NULL" the program stops working .
#include <iostream>
#include <cstring>
using namespace std;
class node {
int data;
node * left;
node * right;
public:
node * level_order(node * first);
node * create_bt(node * first);
void display(node * first);
};
//node *first=NULL;
node * node::create_bt(node * first) {
node * temp = new node;
int ele;
//char dir;
cout << "\n Enter data ";
cin >> ele;
temp->data = ele;
temp->left = NULL;
temp->right = NULL;
if (first == NULL) {
temp = first;
return first;
} else {
char dir[20];
cout << "\n Enter the direction ";
cin >> dir;
node * cur = first;
int j = 0;
while (dir[j] != '\0') {
if (dir[j] == 'l') {
cur = cur->left;
}
if (dir[j] == 'r') {
cur = cur->right;
}
j++;
}
cur = temp;
return first;
}
}
void node::display(node * first) {
if (first == NULL)
return;
cout << "\n " << first->data;
display(first->left);
display(first->right);
}
int main() {
int n;
node s;
node * first = NULL;
cout << "\n No of elements ";
cin >> n;
for (int i = 0; i < n; i++) {
first = s.create_bt(first);
}
s.display(first);
return 0;
}
first=s.create_bt(first); does not changes state, from NULL to 'l' or 'r'. You have to change that.
node*node::create_bt(node *first)
{
node *temp=new node;
int ele;
//char dir;
cout<<"\n Enter data ";
cin>>ele;
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
char dir[20];
cout<<"\n Enter the direction ";
cin>>dir;
if(first==NULL)
{
temp=first;
return first;
}
else
{
node*cur=first;
int j=0;
while(dir[j]!='\0')
{
if(dir[j]=='l')
{
cur=cur->left;
}
if(dir[j]=='r')
{
cur=cur->right;
}
j++;
}
cur=temp;
return first;
}
}
I believe you re looking something like this. This is a basic binary tree, i had to make a basic one in order to understand how it works and how it chooses left and right. I make a class inside a class, in order to have access to my data members (node class, int data, *left , *right) and have them at the same time protected, all-in-one. As you can see "newnode" just creates a node and NULL s the pointers. Thats it. "Find" searches and finds a node with a current key, and returns it when exits. All the rest, i guess, you can understand them, as they are prety much the same with your code. The only thing you have to do is to define, when you want to direct the node you want. REMINDER: You have to find a way to utilize it, so the leafs will not end far-left or far-right.("Enter the direction"). I hope i helped you understand.
#include <iostream>
#include <conio.h>
using namespace std;
class mybTree {
class node {
public:
int data;
node * left;
node *right;
};
node *root;
node *newnode(int num){
node *newnode1;
newnode1 = new (nothrow) node;
newnode1->data = num;
newnode1->left = NULL;
newnode1->right = NULL;
return newnode1;
}
public:
node *find (int key) {
node *current;
current = root;
while (current->data !=key){
if (key<current->data){
current = current->left;
} else {
current = current->right;
}
if (current == NULL){
return NULL;
}
}
return NULL;
}
void display (node *ptr);
void display_tree();
bool insert(int num);
void post_order_delete(node *ptr);
mybTree();
~mybTree();
};
int main(){
char ch = ' ';
int a;
mybTree mybTree1;
while (ch !='0'){
cout << "0->Exit"<<endl<< "1-> add"<<endl<< "2-> find" <<endl<<"3-> Show me the tree\n";
ch = getch();
switch (ch) {
case '0':
break;
case '1':
cout << "number";
cin >> a;
if (!mybTree1.insert(a)){
cout << "Not enough memory" << endl;
}
break;
case '2' :
cout << "Number:" ;
cin >> a;
if (mybTree1.find(a)!=NULL) {
cout << "Found" << endl;
} else {
cout << "Not existed" << endl;
}
break;
case '3':
mybTree1.display_tree();
cout<<endl;
break;
default:
cout << "Wrong Message";
break;
}
}
return 0;
}
void mybTree::display(node *ptr) {
if (ptr == NULL){
return;
}
display(ptr->left);
cout << ptr->data<<endl;
display(ptr->right);
}
void mybTree::display_tree() {
//Displays the Tree
display(root);
}
bool mybTree::insert(int num) {
//It inserts a node. Desides left or right.
node *next,*current,*ptr;
int isleft;
next = current = root;
ptr = newnode(num);
if (ptr == NULL) {
return false;
}
if (root == NULL) {
root = ptr;
return true;
}
while (1){
if (num < current->data){
next = current->left;
isleft = 1;
} else {
next = current->right;
isleft = 0;
}
if (next == NULL){
if (isleft){
current->left = ptr;
} else {
current->right = ptr;
}
return true;
}
current=next;
}
return false;
}
void mybTree::post_order_delete(node *ptr) {
//deletes the node. Usefull for destructor
if (ptr == NULL){
return;
}
post_order_delete(ptr->left);
post_order_delete(ptr->right);
cout << ptr->data;
delete ptr;
}
mybTree::mybTree() {
//Constructor
root = NULL;
}
mybTree::~mybTree() {
//Destructor
post_order_delete(root);
root = NULL;
}