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);
}
Related
I am trying to write numbers from type double outside of the stack but I can't quite work it out how to do it. I have tried doing it with while loop and if statements, sometimes I get only zeros but most of the time I get nothing displayed. Thanks for helping in advance.
#include <stdio.h>
struct element
{
double data;
element * next;
};
element *top = NULL;
void Get(double &x)
{
element *p;
if(top == NULL)
{
printf("\nThe stack is empty!");
return;
}
x = top -> data;
p = top;
top = top -> next;
delete(p);
}
void Put(double x)
{
element *p;
p = new(element);
if(p == NULL)
{
printf("\nNOT enough memory!");
return;
}
p -> data = x;
p -> next = top;
top = p;
}
int main()
{
printf("Enter integers in stack. Enter 0 to end!\n");
double val;
double m;
do
{
printf("Enter number: ");
scanf("%lf", &val);
if(val >= 3697 && val <= 3698)
{
Put(val);
}
}
while(val != 0);
printf("\nStack contains: ");
while(top != NULL)
{
Get(val);
printf("%lf ", val);
}
return 0;
}
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 write code that says if there is command line input then do something if not do something else.
int main(int argc, char *argv[])
{
int lowerBound, upperBound, i, count = 0;
float val;
char c;
if(argc = 2)
{
lowerBound = argv[1];
printf("Lower bound = %d", lowerBound);
item * curr, * head;
head = NULL;
do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));
if(val >= lowerBound)
{
curr->num = val;
curr->next = head;
head = curr;
count++;
}
getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );
curr = head;
float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
else if(argc = 3)
{
lowerBound = argv[1];
upperBound = argv[2];
printf("Lower bound = %d", lowerBound);
printf("Upper bound = %d", upperBound);
item * curr, * head;
head = NULL;
do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));
if(val >= lowerBound && val <= upperBound)
{
curr->num = val;
curr->next = head;
head = curr;
count++;
}
getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );
curr = head;
float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
else if(argc = 1 or argc = 0 or argc = NULL)
{
item * curr, * head;
head = NULL;
do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));
curr->num = val;
curr->next = head;
head = curr;
count++;
getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );
curr = head;
float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
For some reason or another currently, it ignores what is in the if statements and runs whatever is in the if. For instance, even if I have no command line arguments, it still wants to run the first if where arg = 2.
What am I doing wrong and how can I fix it?
You need to make that if(argc == 2)
(instead of if(argc = 2), which assigns 2 to argc and will always be true). I never liked the way C defined = versus == . Some compilers will produce a warning for this.
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...
I was trying to add some linked list to my recursive prime number codes, I was able to store the values using linked list then when I was to retrieve the prime numbers between the two inputted numbers i got this as a result.
for input 1 and 5: 1, 21, 301, 5
output should be:
2, 3, 5
the code is:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct node
{
//struct node *prev;
int num;
struct node *nxt;
}*head;
void store(int value){
struct node *var, *temp;
var = (struct node *)malloc(sizeof(struct node));
var->num = value;
if(head==NULL){
head = var;
head->nxt = NULL;
}else{
temp = var;
temp->nxt = head;
head=temp;
}
}
void accept(int value, int i){
if(i<2){
printf("Enter value: ");
scanf("%d", &value);
store(value);
i++;
accept(value,i);
}
}
void prime(){
int num,x,y;
struct node *temp,*temp2,*var;
temp = head;
temp2 = temp->nxt;
y = temp->num;
x = temp2->num;
primeloop(x,y);
}
int primeloop(int x,int y){
int num;
if ( x == 1 ) x++;
if(x <= y){
num = isPrime(x,2); // second input parameter added
printf("%d",num);
if(num == 0){
printf("");
}else{
printf("%5d",x);
}
primeloop(x+1,y);
}
}
int isPrime(int n, int i){
if(n%i==0 && n!=2 && n!=i){
return(0);
} else {
if (i < sqrt(n)) {
return( isPrime(n,i+1) );
} else
return(1);
}
}
void main(){
int i,value;
clrscr();
i = 0;
accept(value,i);
prime();
getch();
}
I had to change some lines to make it work with linked list, I could be missing something here since the algo is still the same. Do point out what I did wrong.
I found your problem I think. Your algorithm is correct, but you have two redundant printfs.
your primeloop should be like this
int primeloop(int x,int y){
int num;
if ( x == 1 ) x++;
if(x <= y){
num = isPrime(x,2); // second input parameter added
if(num != 0){
printf("%5d ",x);
}
primeloop(x+1,y);
}
}