while() loop not working as expected. What could be the reason? - c

I have started coding Linked list in C. My code is as follows:
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node * create(struct node *);
display(struct node *);
int main()
{
struct node *head=NULL;
head = create(head);
display(head);
getch();
return 0;
}
struct node * create(struct node *Head)
{
struct node *temp;
char ch='y';
int i=1;
while(ch=='y')
{
temp=malloc(sizeof(struct node));
temp->data=i*10;
temp->next=Head;
Head=temp;
printf("\nAdded node : %d",Head->data);
printf("\nContinue to add more nodes ? : ");
scanf("%c",&ch);
}
return Head;
}
display(struct node *Head)
{
while(Head!=NULL)
{ printf("%d\t%d\n",Head->data,Head->next);
Head=Head->next;
}
}
The problem that I am facing is that after entering into the function "create" and creating just one node, my program jumps back to main, then jumps to "display" function and then jumps back to function "create" at the line where it asks me whether I want to continue. At this point, when I do enter "y", program just exits!
Why this sorta behaviour??
Someone please explain me how the control flows and why is my program going haywire!!!

Reason:
This happens because when you type in 'y' and then hit enter, a newline character '\n' gets buffered and will be read on the next iteration of scanf(). This will cause while(ch=='y') to evaluate to false (since now ch == '\n'), breaking off the loop.
Normally scanf() would skip whitespaces and newlines before hitting the expected value. However, when you use the character format %c, this doesn't happen, as newlines and whitespaces are also valid characters.
How to fix:
You can fix it by using scanf(" %c",&ch);. The space before %c will skip any leading backspace or newline characters found on the buffer before actually reading the value.

Related

C Programming -Linked List Implementation with characters

MY CODE:
#include<stdio.h>
#include<stdlib.h>
struct node{
char data;
struct node *next;
};
void main()
{ char A;
struct node *head,*ptr;
ptr=(struct node *)malloc(sizeof(struct node));
printf("Enter data for node 1 \n");
scanf("%c",&ptr->data);
head=ptr;
int i=2;
while(1)
{
ptr->next=(struct node*)malloc(sizeof(struct node));
ptr=ptr->next;
printf("\nEnter data for node %d:::\n",i);
scanf("%c",&ptr->data);
ptr->next=NULL;
i=i+1;
printf("Do you want to continue Y OR N");
scanf("%c",&A);
if(A=='Y')
continue;
else
break;
}
struct node *temp;
temp=head;
while(temp!=NULL)
{
printf("%c=>",temp->data);
temp=temp->next;
}
printf("NULL");
}
For this code I can only enter the first character data after that it is skipping the scanf portion within the while loop.
But when I am doing the same code with integer it is giving me the right output.
Here if I replace the same code instead of having characters I replace it by integers it works fine.
I couldnt find a way to fix it.
Plz help.
As stated in the comments your problem lies not in the linked list implementation, but in the code lines here.
scanf("%c",&ptr->data); //line number 14
scanf("%c",&ptr->data); //line number 22
scanf("%c",&A); //line number 26
in all these lines %c consumes the new line character(\n) instead of the users input.
To correct the issue, you can place a whitespace in front of the %c like this,
scanf(" %c",&ptr->data); //line number 14
scanf(" %c",&ptr->data); //line number 22
scanf(" %c",&A); //line number 26

Linked List issue - Why is it adding a 0 as a element to my list when the user types in 'N to quit adding more elements?

So I working on creating a function called 'Create' that asks the user to enter numbers for a linked list. If the user types in 'Y', then ask to enter another element else if the user types 'N' stop and display the linked list, but I am having a bit of trouble. When I run it, it doesn't give me the option to type in Y or N and also when I type in N, it adds a 0 to the linked list. What is happening?
#include <stdio.h>
#include <stdlib.h>
//-------------------------------------------------
struct node {
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------
void create() {
char ch;
do {
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL) {
start=new_node;
current=new_node;
} else {
current->next=new_node;
current=new_node;
}
printf("Do you want to create another?(Y\N) ");
ch = getchar();
} while(ch!='N');
}
//------------------------------------------------------------------
void display() {
struct node *new_node;
printf("The Linked List : ");
new_node=start;
while(new_node!=NULL) {
printf("%d--->",new_node->data);
new_node=new_node->next;
}
printf("NULL\n");
}
//----------------------------------------------------
int main() {
create();
display();
}
1- move the declaration of struct node *new_node, *current; to outside the do loop (to just before the do), because you want them to keep their values between iterations.
2- a newline character remained in the buffer after the scanf that read the number, because the user had to type return after the number, and the scanf did not consume it. To skip this newline when getting the Y/N answer, get your Y/N answer in this way instead of ch = getchar();:
scanf(" %c", &ch); // notice the blank before the %c, important to skip the newline that remained in the buffer
3- although not necessary, better avoid using the escape character \ in your question, use "Y/N" instead of "Y\N"
Your code worked perfectly after I made these modifications.

Error of expression syntax

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *create_cll(node *head,int n);
void main()
{
clrscr();
node *head,*p;
int n;
printf("Enter the no.of elements:");
scanf("%d",&n);
head=create_cll(*head,int n);
getch();
}
node *create_cll(node *head,int n)
{
node *rear,*p;
int i;
head=p;
for(i=1;i<n;i++)
{
p=(node*)malloc(sizeof(node));
scanf("%d",&p->data);
p=rear;
rear->next=p;
p=p->next;
}
printf("Circular linked list created..!");
return (head);
}
Code is about creating the circular linked list.
But here I have an error of expression syntax which I am unable to solve.
The error is in the line in the main() section where head is equalled to the function.
So I need help...
You need to pass a ptr-to-node, not a node; and remove the int keyword:
head = create_cll(head, n);
In other news:
It's int main in C, not void main
Don't cast the return from malloc in C
Not testing the return value from scanf is a sure recipe for surprises.
printf format strings usually have a newline "\n" at the end.
<conio.h> and getch are not C (even though Mr. Gates wants you to believe that.) Use getchar() instead.
head is already a pointer
*head in your code could be changed to head as the method definition follows.

Creating two link list using one function

This is a program to print two link lists using one function.
I have used two functions i.e create and display.Create() is to create the linklist and display() to display the result of linklist.
But this code is printing NULL. I'm not not getting where is the error???
`#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* next;
}
*start=NULL,*start1=NULL;
//to create the linklist
struct node* create(struct node* ptr)
{ int ch;
do
{
struct node* new_node=(struct node*)malloc(sizeof(struct node));
struct node* current;
printf("enter the data\n");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(ptr==NULL)
{
ptr=new_node;
current=new_node;
}
else
{
current->next=new_node;
current=new_node;
}
printf("Do u want to add more ");
scanf("%d",&ch);
}while(ch!=0);
return ptr;
}
//to display the linklist
void display(struct node* temp)
{
while(temp!=NULL)
{
printf("%d--->",temp->data);
temp=temp->next;
}
printf("NULL\n");
}
int main()
{
clrscr();
create(start);
display(start);
printf("\n 2nd linklist\n");
create(start1);
display(start1);
getch();
return 0;
}
First problem
current must be declared outside the do/while loop, otherwise you will get undefined behaviour because there is no guarantee that current will keep it'svalue from one iteration to the next. However with certain compilers you may get away with it.
Second problem
Calling create(start); will not modify start because variables in C are passed by value. You need to write start = create(start);. See also this SO question. In your program start is still NULL after the call to the create function. You could have found out that easily by yourself.

getchar() not accepting input

I am writing a program to implement a linked list in C.Here is my program.
/*Implementing a singly linked list in c*/
#include<stdio.h>
#include<stdlib.h>
#include<alloca.h>
struct node{
int data;
struct node* link;
}*start=NULL;
void main(){
char choice;
int data;
do{
printf("Enter data\n");
scanf("%d",&data);
struct node* temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->data=data;
temp->link=NULL;
if(start==NULL)
start=temp;
else
{
struct node* traversing_pointer;
traversing_pointer=start;
while(traversing_pointer!=NULL)
traversing_pointer=traversing_pointer->link;
traversing_pointer->link=temp;
}
printf("Do you want to enter more");
choice=getchar();
}
while(choice=='y'|| choice=='Y');}
I basically want at least one node in the linked list to be created, that is why I am using a do, while loop. But after the first data input the program terminates without accepting an input for choice variable. Here is my output. What can be the
Enter data
45
Do you want to enter more
RUN FINISHED; exit value 10; real time: 2s; user: 0ms; system: 0ms
What can be the possible error?
To consume the newline character left in the input stream, do:
scanf("%d",&data);
getchar(); //To consume a newline
or use a loop to read all newlines.
scanf("%d",&data);
int c=0;
while ((c = getchar()) != '\n' && c != EOF) ; // Read & ignore all newlines
Another problem I see is you are not linking the nodes properly. You want to link the new node as the last one. So you have to traverse till the last node (not till you reach NULL). Change the loop condition to:
while(traversing_pointer->link!=NULL)
traversing_pointer=traversing_pointer->link;
traversing_pointer->link=temp;
It is because your getchar reads the end of line you've entered by pressing Enter after the 45 input.

Resources