i have been trying this code.
i think the logic is ok but the program terminates abruptly when the display_rev function is called
here is code of display_rev
void display_rev(emp_node *head) {
emp_node *p=head, *q;
while(p->next != NULL)
p=p->next;
while(p!=head || p==head){
q=head;
display_rec(p);
while(q->next != p)
q=q->next;
p=q;
}
}
here is my whole code
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
//Declarations===============================================================
typedef struct //employee record
{
int emp_id;
char name[150];
char mob_no[11];
float salary;
int proj[5];
struct emp_node *next;
} emp_node;
emp_node* add_rec(emp_node*);
emp_node* create_db(emp_node*);
emp_node* search_db(emp_node*, int);
emp_node* delete_rec(emp_node*, int);
void read_name(emp_node*);
void read_mob(emp_node*);
void display_db(emp_node*);
void display_rec(emp_node*);
void display_rev(emp_node*);
void modify_rec(emp_node*);
void swtch(emp_node*);
//===========================================================================
int main() {
char ans;
emp_node *head = NULL;
head = create_db(head);
display_db(head);
do {
swtch(head);
printf("\n\n\tDo you want to continue (y/n) : ");
getchar();
scanf("%c", &ans);
} while (ans == 'y' || ans == 'Y');
return 0;
}
//Definitions================================================================
emp_node* create_db(emp_node *head) //database creation
{
int i = 1, no;
emp_node *p;
printf("Enter number of employees:");
scanf("%d", &no);
printf("\n\n");
head = (emp_node *) malloc(sizeof(emp_node));
head = add_rec(head);
head->next = NULL;
p = head;
while (i < no) {
p->next = (emp_node *) malloc(sizeof(emp_node));
p = p->next;
p = add_rec(p);
p->next = NULL;
i++;
}
return head;
}
emp_node* add_rec(emp_node *p) //new record
{
int j;
printf("\n\tEmployee ID : ");
scanf("%d", &(p->emp_id));
printf("\n\tFirst Name:");
read_name(p);
printf("\n\tMobile No.:");
read_mob(p);
printf("\n\tSalary :");
scanf("%f", &(p->salary));
printf(
"\n\tEnter \"1\" for the projects employee is working on, otherwise enter \"0\": \n");
for (j = 0; j < 5; j++) {
printf("\n\t\tProject No. %d : ", j + 1);
scanf("%d", &(p->proj[j]));
while (p->proj[j] != 1 && p->proj[j] != 0) {
printf("\n\nInvalid entry!! Please re-enter.");
printf("\n\t\tProject No. %d : ", j + 1);
scanf("%d", &(p->proj[j]));
}
}
printf("\n\n\n");
return p;
}
void read_name(emp_node *p) //validation for name
{
int j, len;
scanf("%s", p->name);
len = strlen(p->name);
for (j = 0; j < len; j++) {
if (!isalpha(p->name[j])) {
printf(
"\n\n\tInvalid name!!Can contain only characters. Please Re-enter.\n");
printf("\n\tName : ");
read_name(p);
}
}
}
void read_mob(emp_node *p) //validation for mobile no.
{
int j;
scanf("%s", p->mob_no);
while (strlen(p->mob_no) != 10) {
printf("\n\nInvalid Mobile No!!Please Re-enter");
printf("\n\n\tMobile No.:");
read_mob(p);
}
for (j = 0; j < 10; j++) {
if (!(48 <= p->mob_no[j] && p->mob_no[j] <= 57)) {
printf(
"\n\nInvalid Mobile No!!Can contain only digits. Please Re-enter.");
printf("\n\n\tMobile No.:");
read_mob(p);
}
}
}
void display_db(emp_node *head) //displaying whole database
{
emp_node *p;
p = head;
printf("\n\n\t\t****** EMPLOYEE DATABASE ******\n");
printf(
"\n==============================================================================");
printf("\n Id.\t Name\t\t Mobile No\t Salary\t Projects\n");
while (p != NULL) {
display_rec(p);
p = p->next;
printf("\n\n\n");
}
printf(
"\n==============================================================================");
}
void swtch(emp_node *head) //function for menu and switch case
{
int cho, x;
emp_node *p;
printf("\n\n\t\t****** MENU ******");
printf(
"\n\n\t1. insert Record\n\t2. Search Record\n\t3. Modify Record\n\t4. Delete Record\n\t5. Display Reverse\n\t6. Exit");
printf("\n\tWhich operation do you want to perform? ");
scanf("%d", &cho);
switch (cho) {
case 1:
p=head;
while(p->next != NULL)
p=p->next;
p->next = (emp_node *) malloc(sizeof(emp_node));
p=p->next;
p = add_rec(p);
p->next = NULL;
display_db(head);
break;
case 2:
printf("\n\n\tEnter employee ID whose record is to be Searched :");
scanf("%d", &x);
p = search_db(head, x);
if (p == NULL)
printf("\n\nRecord not found.");
else
display_rec(p);
break;
case 3:
printf("\n\n\tEnter employee ID whose record is to be modified :");
scanf("%d", &x);
p = search_db(head, x);
if (p == NULL)
printf("\n\nRecord not found.");
else
modify_rec(p);
display_db(head);
break;
case 4:
printf("\n\n\tEnter employee ID whose record is to be deleted :");
scanf("%d", &x);
head = delete_rec(head, x);
display_db(head);
break;
case 5:
display_rev(head);
case 6:
exit(0);
default:
printf("Invalid Choice!! Please try again.");
}
}
emp_node* search_db(emp_node *head, int id) //search database
{
emp_node *p = head;
while (p != NULL) {
if (p->emp_id == id)
return p;
p = p->next;
}
return NULL;
}
void display_rec(emp_node *p) //display a single record
{
int j;
printf("\n %d", p->emp_id);
printf("\t %10s", p->name);
printf("\t %10s", p->mob_no);
printf("\t %05.2f", p->salary);
printf("\t ");
for (j = 0; j < 5; j++) {
if (p->proj[j] == 1)
printf(" %d,", j + 1);
}
}
void modify_rec(emp_node *p) //modifying a record
{
int j, cho;
char ch1, edt;
do {
printf(
"\n\t1. Name\n\t2. Email Address\n\t3. Mobile No.\n\t4. Salary\n\t5. Date of birth\n\t6. Projects\n");
printf("Enter your choice : ");
scanf("%d", &cho);
switch (cho) {
case 1:
printf("\n\tPrevious name:%s", p->name);
printf("\n\tDo you want to edit ? (y/n)");
getchar();
scanf("%c", &ch1);
if (ch1 == 'y' || ch1 == 'Y') {
printf("\n\tEnter New Name:");
read_name(p);
}
break;
case 2:
printf("\n\tPrevious Mobile No. : %s", p->mob_no);
printf("\n\tDo you want to edit ? (y/n)");
getchar();
scanf("%c", &ch1);
if (ch1 == 'y' || ch1 == 'Y') {
printf("\n\tEnter New Mobile No. :");
read_mob(p);
}
break;
case 3:
printf("\n\tPrevious salary is : %f", p->salary);
printf("\n\tDo you want to edit ? (y/n)");
getchar();
scanf("%c", &ch1);
if (ch1 == 'y' || ch1 == 'Y') {
printf("\n\tEnter New salary:");
scanf("%f", &(p->salary));
}
break;
case 4:
printf("the employee is currently working on project no. ");
for (j = 0; j < 5; j++) {
if (p->proj[j] == 1)
printf(" %d,", j + 1);
}
printf("\n\tDo you want to edit ? (y/n)");
getchar();
scanf("%c", &ch1);
if (ch1 == 'y' || ch1 == 'Y') {
printf(
"\n\tEnter \"1\" for the projects employee is working on : \n");
for (j = 0; j < 5; j++) {
printf("\n\t\tProject No. %d : ", j + 1);
scanf("%d", &(p->proj[j]));
while (p->proj[j] != 1) {
printf("\n\nInvalid entry!! Please re-enter.");
printf("\n\t\tProject No. %d : ", j + 1);
scanf("%d", &(p->proj[j]));
}
}
}
break;
default:
printf("\n\nInvalid Choice!! Please Try again.");
}
printf("\n\nDo you want to edit any other fields ?(y/n)");
getchar();
scanf("%c", &edt);
} while (edt == 'y' || edt == 'Y');
}
emp_node* delete_rec(emp_node *head, int id) //physical deletion of record
{
emp_node *p = head, *q;
if (head->emp_id == id) {
head = head->next;
free(p);
return head;
} else {
q = p->next;
while (q->emp_id != id) {
p = p->next;
q = q->next;
}
if (q->next == NULL)
p->next = NULL;
else
p->next = q->next;
free(q);
return head;
}
}
void display_rev(emp_node *head) {
emp_node *p=head, *q;
while(p->next != NULL)
p=p->next;
while(p!=head || p==head){
q=head;
display_rec(p);
while(q->next != p)
q=q->next;
p=q;
}
}
I know it is "cheating" but you could just do this:
void display_rev(emp_node *head) {
if (head->next != null)
{
display_rev(head->next);
}
display_rec(head);
}
How this works: This routine recurses for each element of the list till it gets to the end, then as it "unwinds" back up it prints each element.
void display_rev(emp_node *head) {
emp_node *p=head, *q;
if (p == null) return;
while(p->next != NULL)
p=p->next;
while(p != head) {
q=head;
display_rec(p);
while(q->next != p)
q=q->next;
p=q;
}
display_rec(p);
}
this test is always true
while(p!=head || p==head)
I think you should remove the p==head part
edit I tested the loop, you must add also the head printing:
void display_rev(emp_node *head) {
emp_node *p=head, *q;
while(p->next != NULL)
p=p->next;
while(p!=head) {// || p==head){
q=head;
display_rec(p);
while(q->next != p)
q=q->next;
p=q;
}
display_rec(p); // print the head also
}
the segmentation fault (as I assume you intended with 'terminates abruptly') can be caused from some data non correctly initialized in your program...
Related
When I try to swap between strings in the function Update_student it doesn't make it. Why?
#include <stdio.h>
#include <string.h>
#define SIZE 1
struct student {
int id_number;
char name[50];
char sex[6];
int quiz_score[2];
int total_score;
};
void Add_Student_Records(struct student *pupil) {
printf("ID:");
scanf("%d", &pupil->id_number);
printf("Name: ");
scanf("%s", &pupil->name);
printf("Sex :");
scanf("%s", &pupil->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:", i + 1);
scanf("%d", &pupil->quiz_score[i]);
}
pupil->total_score = pupil->quiz_score[0] + pupil->quiz_score[1];
return;
}
void Add_Students(struct student *students) {
for (int i = 0; i < SIZE; i++) {
printf("Student %d:\n", i + 1);
Add_Student_Records(students);
}
return;
}
void Print_Students(struct student *students) {
for (int i = 0; i < SIZE; i++) {
printf("Student %d details: \n", i + 1);
printf("ID:%d\n", students->id_number);
printf("Name:%s\n", students->name);
printf("Sex:%s\n", students->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:\n", students->quiz_score[i]);
}
printf("Total score: %d\n", students->total_score);
students++;
}
return;
}
void Replace_Strings(char **old_string, char **new_string) {
*old_string = *new_string;
return;
}
void Update_Student(struct student *students) {
int i = 0;
char name[50], new_name[50], cur_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
scanf("%s", name);
printf("new name: ");
scanf("%s", &new_name);
while (i < SIZE) {
strcpy(cur_name, students->name);
if (strcmp(cur_name, name) == 0) {
char *ptr_old_stud_name = students->name;
char *ptr_new_stud_name = new_name;
Replace_Strings(&ptr_old_stud_name, &ptr_new_stud_name);
}
i++;
students++;
}
return;
}
int main() {
struct student students[SIZE];
char ch;
/*1.Add student, 2. Print student*/
printf("1.Add student\n2.Print students\n3.Update student\n");
scanf("%c", &ch);
while (ch != 'E') {
if (ch == '1') {
Add_Students(&students[0]);
}
else if (ch == '2') {
Print_Students(&students[0]);
}
else if (ch =='3') {
Update_Student(&students[0]);
}
printf("Another operation:\t");
scanf("%c", &ch);
}
}
Replace_Strings(&ptr_old_stud_name,&ptr_new_stud_name); passes the addresses of ptr_old_stud_name and ptr_new_stud_name to ReplaceStrings.
ptr_old_stud_name and ptr_new_stud_name are local variables. The first is a pointer that has been set to point to students->name. The second is a pointer that has been set to point to new_name.
Replace_Strings changes the first thing it is passed a pointer to to the second thing it is passed a pointer to. So it changes ptr_old_stud_name to have the value of ptr_new_stud_name.
The result is that the local variable ptr_old_stud_name has a new value. This does not change the thing it points to, students->name.
More specifically, ptr_old_stud_name was pointing to the first character of students->name. students->name is an array, and it cannot be altered by changing pointers to it, and its address cannot be changed. To change its contents, you must copy new values into the bytes within it, which you could do by using strcpy to copy bytes into it from new_name.
Your function Update_student is confusing, you should just iterate through the array of students and compare the student's name with cur_name and replace the name when there is a match.
You should also pass the number of students to handle as an argument.
Here is a modified version:
void Update_Student(struct student *students, int count) {
char cur_name[50], new_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
scanf("%49s", cur_name);
printf("new name: ");
scanf("%49s", new_name);
for (int i = 0; i < count; i++) {
if (strcmp(cur_name, students[i].name) == 0) {
strcpy(students[i].name, new_name);
}
}
}
Call from main as Update_Student(students, SIZE);
Note also that you should ignore whitespace when reading the commands by adding a space before the %c:
scanf(" %c", &ch);
Here is a modified version with for multiple students:
#include <stdio.h>
#include <string.h>
#define SIZE 10
struct student {
int id_number;
char name[50];
char sex[6];
int quiz_score[2];
int total_score;
};
int Add_Student_Records(struct student *pupil) {
printf("ID:");
if (scanf("%d", &pupil->id_number) != 1)
return 0;
printf("Name: ");
if (scanf("%49s", pupil->name) != 1)
return 0;
printf("Sex :");
if (scanf("%1s", pupil->sex) != 1)
return 0;
for (int i = 0; i < 2; i++) {
printf("Quiz score %d:", i + 1);
if (scanf("%d", &pupil->quiz_score[i]) != 1)
return 0;
}
pupil->total_score = pupil->quiz_score[0] + pupil->quiz_score[1];
return 1;
}
int Add_Students(struct student *students, int count) {
int i;
for (int i = 0; i < count; i++) {
printf("Student %d:\n", i + 1);
if (Add_Student_Records(students + i) == 0)
break;
}
return i;
}
void Print_Students(struct student *students, int count) {
for (int i = 0; i < count; i++) {
printf("Student %d details: \n", i + 1);
printf("ID:%d\n", students->id_number);
printf("Name:%s\n", students->name);
printf("Sex:%s\n", students->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:\n", students->quiz_score[i]);
}
printf("Total score: %d\n", students->total_score);
students++;
}
}
void Update_Student(struct student *students, int count) {
char cur_name[50], new_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
if (scanf("%49s", cur_name) != 1)
return;
printf("new name: ");
if (scanf("%49s", new_name) != 1)
return;
for (int i = 0; i < count; i++) {
if (strcmp(cur_name, students[i].name) == 0) {
strcpy(students[i].name, new_name);
}
}
}
int main() {
struct student students[SIZE];
int n = 0;
char ch = 'E';
/* print the menu */
printf("1. Add student\n"
"2. Print students\n"
"3. Update student\n");
scanf(" %c", &ch);
while (ch != 'E') {
if (ch == '1') {
if (n == SIZE) {
printf("student array is full\n");
} else {
/* add more students */
n += Add_Students(&students[n], SIZE - n);
}
} else
if (ch == '2') {
Print_Students(students, n);
} else
if (ch =='3') {
Update_Student(students, n);
}
scanf("%*[^\n]"); // consume the rest of the pending input line
printf("Another operation:\t");
if (scanf(" %c", &ch) != 1)
break;
}
return 0;
}
How can one make the input to not only able to input number but also word? I tried changing the int with char[20] but that just made the program run continuously without stop. I'm still a newbie and looking for advice. Also, int x, c = 1, z; is confusing, why does the int have an equal value to 1? My thanks for anyone that would help.
struct node*insert(struct node*r, int x)
{
if (r == NULL)
{
r = (struct node*)malloc(sizeof(struct node));
r->info = x;
r->left = r->right = NULL;
return r;
}
else if (x < r->info)
r->left = insert(r->left, x);
else if (x > r->info)
r->right = insert(r->right, x);
return r;
}
int main()
{
struct node* root = NULL;
int x, c = 1, z;
int element;
char ch;
while(1)
{
printf("\n1. Insert an element");
printf("\n2. Search for an element");
printf("\n3. Delete an element");
printf("\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &c);
switch(c)
{
case 1:
printf("\nEnter the item:");
scanf("%d", &z);
root = insert(root,z);
break;
case 2:
printf("\nEnter element to be searched: ");
scanf("%d", &element);
search(root, element);
if(LOC != NULL)
printf("\n%d Found in Binary Search Tree !!\n",element);
else
printf("\nIt is not present in Binary Search Tree\n");
break;
case 3:
printf("\nEnter the info to be deleted:");
scanf("%d", &z);
root = del(root, z);
break;
case 4:
printf("\nExiting...");
return;
default:
printf("Enter a valid choice: ");
}
}
return 0;
}
I really need help for this, like i want to print out them and what do i need to adding to this function to work.
#include <stdio.h>
#include <stdlib.h>
#define nameSizeMax 31
#define listSizeMax 100
char studentList[listSizeMax][nameSizeMax];
int listSize;
void addStudent() {
if(listSize == listSizeMax) {
printf("List is full!\n\n");
} else {
printf("Enter name of the student: ");
fflush(stdin);
char name[nameSizeMax];
gets(name);
trim(name);
strupr(name);
strcpy(studentList[listSize], name);
listSize++;
printf("The new student have been added!\n\n");
}
}
int searchStd(char list[][nameSizeMax], char item[], int size) {
int i;
for(i=0;i<size; i++);
if (strcmp(list[i], item) == 0) return 1;
return -1;
}
void removeStudent() {
int i
if (listSize == 0) {
printf("List is empty!\n\n");
} else {
printf ("Enter name of the removed student: ");
fflush(stdin);
char name[nameSizeMax];
gets(name);
trim(name);
strupr(name);
int pos = searchStd(studentList, name, listSize);
}
if(pos == -1) {
printf("This student does not exist!\n\n");
} else {
for (i=pos; i<listSize-1; i++);
strcpy(studentList[i], studentList[i+1]);
printf("This student has been removed from the list: \n\n");
listSize--;
}
}
void fintStudent() {
int i;
printf("Enter the name of student you want to search: ");
fflush(stdin);
char name[nameSizeMax];
gets(name);
trim(name);
strupr(name);
int pos = searchStd(studentList, name, listSize);
if(pos == -1) {
printf("This student does not exist:\n\n");
} else {
printf("\n This is the student list in the order you entered: \n");
for(i=0; i<listSize; i++) printf("%d - %s\n", i, studentList[i]);
printf ("This student's postition in the list is: %d\n\n", pos);
}
}
void printStudentAsc(char list[][nameSizeMax], int size) {
int i,j:
if (listSize == 0) {
printf("List is empty!\n\n");
} else {
char **listP = (char **) calloc(sizeof(char *));
for (i=o; i<size; i++) listP[i] = list[i];
for (i=0; i<size-1; i++)
for(j=i+1; j<size; j++) {
char *ln1,*ln2;
ln1= lastname(listP[i]);
ln2= lastname(listP[j]);
if (strcmp(ln1, ln2) == 1) {
char *tmp = listP[i];
listP[i] =listP[j];
listP[j] = tmp;
}
}
}
for (i = 0; i < (*pn); i++)
{
nameStr(list[i]);
printf("Name[%d] : %s \n", i, list[i]);
}
}
int menu(){
printf("Menu:\n");
printf("1- Add a student\n");
printf("2- Remove a student\n");
printf("3- Search a student\n");
printf("4- Print out the student list in ascending order\n");
int userChoice;
do{
printf("Insert ur operation: "); scanf("%d", &userChoice);
}
}
Edited :'( i really struggle about the printAsc like i dont know what to do next . Its really messed me up here. Only the printStudentAsc.
the Menu interface that im not finish yet but i can hanlde this.
I am building a student management system in which users add student details dynamically. When I first add 2 students at the beginning of lists, the students are added correctly. However then when I add another student at a position for example 1 (which means I am trying to make this the head node again), the program crashes. I have tried finding out the error but no success. The program just crashes
#pragma warning(disable: 4996)
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <Windows.h>
struct students{
char *name;
int age;
char *degree;
struct students* next;
};
int TotalStudents = 0;
struct students* ptrToHead;
void insertAtBeginning(char name[], int age, char degree[]){
struct students * temp = (students *)malloc(sizeof(struct students));
temp->name= strdup(name);
temp->age = age;
temp->degree=strdup(degree);
temp->next = NULL;
if (ptrToHead != NULL)
{
temp->next = ptrToHead;
}
ptrToHead = temp;
//printf("%s\n%d\n%s", temp->name, temp->age, temp->degree);
}
void insertAtAnyPosition(int position, char name[], int age, char degree[]){
int i = 1;
struct students * temp = (students *)malloc(sizeof(struct students));
struct students * temp2 = ptrToHead, *temp3;
temp = ptrToHead;
if (position <= TotalStudents || position <= TotalStudents + 1){
while (i < position){
if (i == position - 1)
temp3 = temp2;
temp2 = temp2->next;
i++;
}
}
temp->name = strdup(name);
temp->age = age;
temp->degree = strdup(degree);
temp2->next = temp;
temp--;
temp = temp2;
}
void MainMenu();
void addStudent();
void print(){
struct students* temp = ptrToHead;
printf("List of Students: ");
while (temp != NULL){
printf("\nStudent's Name: %s", temp->name);
printf("\nStudent's Age: %d", temp->age);
printf("\nStudent's Degree: %s", temp->degree);
printf("\nEND - OF - STUDENT");
temp = temp->next;
}
printf("\n");
Sleep(7000);
system("cls");
MainMenu();
}
int main(){
MainMenu();
//students * temp= (students *)malloc(sizeof(students));
//temp->age = 22;
//temp->degree = "Software Engineering";
//temp->name = "Fahad Bin Saleem";
//temp->next = NULL;
//ptrToHead = temp;
//
//printf("Age: %d\n", ptrToHead->age);
//printf("Name: %s\n", ptrToHead->name);
//printf("Degree: %s\n", ptrToHead->degree);
//temp = (students *)malloc(sizeof(students));
//temp->age = 19;
//temp->degree = "Electrical Engineering";
//temp->name = "Rafay Hayat Ali";
//temp->next = NULL;
//students * temp1 = ptrToHead;
//while (temp1->next != NULL){
// temp1 = temp1->next;
//}
//temp1->next = temp;
//
_getch();
return 0;
}
void MainMenu(){
int choice;
printf("Welcome to Student Information Center!\n\n");
char* mainmenu[] = { "Display All Students", "Add A Student" };
for (int i = 0; i < 2; i++){
printf("%d: %s\n", i + 1, mainmenu[i]);
}
printf("\n\nEnter Your Choice: ");
scanf_s(" %d", &choice);
if (choice == 2){
addStudent();
}
if (choice == 1){
print();
}
}
void addStudent(){
int NumberOfStudents;
int choiceOfAdding;
char tempName[40];
char tempDegree[40];
int tempAge;
system("cls");
ptrToHead = NULL;
for (int i = 0; i < 15; i++){
printf(" ");
}
printf("**ADD A STUDENT**");
printf("\n\nHow many students do you want to add? Enter Choice: ");
scanf_s(" %d", &NumberOfStudents);
printf("\n\n");
for (int i = 0; i < NumberOfStudents; i++){
printf("\n\n");
printf("Enter Student's Name: ");
fflush(stdin);
gets_s(tempName, 40);
printf("Enter Student's Age: ");
scanf_s(" %d", &tempAge);
printf("Enter Student's Degree: ");
fflush(stdin);
gets_s(tempDegree, 40);
//insert(tempName, tempAge, tempAgeDegree);
printf("\n\nWhere Do You Want To Add This Student?\n\n1: At The Beginning\n\n2: At A Position N\n\n3: At The End");
scanf_s(" %d", &choiceOfAdding);
fflush(stdin);
if (choiceOfAdding == 1){
insertAtBeginning(tempName, tempAge, tempDegree);
}
else if (choiceOfAdding == 2){
int position;
printf("\nEnter the position you want to insert: ");
scanf_s(" %d", &position);
insertAtAnyPosition(position, tempName, tempAge, tempDegree);
}
TotalStudents++;
printf("\n\n");
}
MainMenu();
}
Your problem is you have temp2 and temp equal to ptrHead:
struct students * temp = (students *)malloc(sizeof(struct students));
struct students * temp2 = ptrToHead, *temp3;
temp = ptrToHead;
you only need one temp pointing to ptrToHead and and additional temp (temp2) to make the swap. In your code you don't need temp3.
I'm no expert but give this a try:
void insertAtAnyPosition(int position, char name[], int age, char degree[]){
int i = 1;
struct students * temp = (students *)malloc(sizeof(struct students));
struct students *temp2;
temp->name = strdup(name);
temp->age = age;
temp->degree = strdup(degree);
temp2 = &ptrToHead;
if (position <= TotalStudents + 1){
while (i < position){
if (i == position - 1)
temp->next = temp2->next;
temp2->next = temp;
temp2 = temp2->next;
i++;
}
}
}
I am trying to edit a program I made a year ago, but it seems I am failing somewhere because I can't get the result I want. I want to make the program to sort the numbers from low to high and the user should enter numbers until 0 is pressed. Would love ot get some help from someone advanced!
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* List;
void Add(struct node* p, int d)
{
struct node* q;
q = malloc(sizeof(struct node));
if (q == NULL)
printf("Not enaugh memory!");
else{
q->data = d;
if (List == NULL || List->data < d)
{
q->next = List;
List = q;
} else {
struct node *ptr = List;
while ((ptr->next != NULL) && (ptr->next->data>d)){
ptr = ptr->next;
}
q->next = ptr->next;
ptr->next = q;
}
}
}
int main()
{
int n, i, a;
printf("How many numbers are you going to enter? ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\nEnter a number: ");
scanf("%d", &a);
Add(List, a);
}
printf("\nEntered and sorted numbers are: ");
struct node *ptr = List;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n\n");
system("PAUSE");
return 0;
}
Just change to line
if (List == NULL || List->data < d)
to
if (List == NULL || List->data > d)
And change the line
while ((ptr->next != NULL) && (ptr->next->data>d)){
to
while ((ptr->next != NULL) && (ptr->next->data<d)){
And you have not added 0 check.Please add that, rest is fine. For this modify the for loop with this one
//printf("How many numbers are you going to enter? ");
//scanf("%d", &n);
for (;;)
{
printf("\nEnter a number: ");
scanf("%d", &a);
if(a == 0)
break;
Add(List, a);
}