I was writing some code and every thing seemed alright. I carefully watched it run, but only to half way and then it stops, when it's time to give output from my given input.
But when I removes while loop and added do while loop it worked. After that I again used the while loop, i.e. exactly the code that was not running before, not changing anything, same to same code as before. But now it works.
I faced this problem 3-4 times.
I fixed all and even though my code was correct, sometimes it runs and sometimes it doesn't.
This wastes my time a lot. Why is this happening?
My pc is i5 7200u @ 2.5 ghz, 4 gb ram.
I notice that in Visual Studio Code the text looked like they move from its place while i am scrolling through. my code is this
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head;
void insert(int a);
void print();
int main (){
head = NULL;
printf("How many numbers?\n");
int x,n;
scanf("%d",&x);
for(int i=0 ;i<x ;i++){
printf("enter no\n");
scanf("%d",&n);
insert(n);
}
print();
}
void insert(int a){
struct node *temp=(struct node*)malloc(sizeof(struct node));
(*temp).data=a;
(*temp).next=head;
head=temp;
}
void print(){
struct node *temp=head;
/* i declearde this while i was doing do while loop*/ int i=0;
printf("list is :");
while(temp != NULL) //only changed this with do while
{ //and again replaced this same code i am 100% sure
printf(" %d",(*temp).data);
temp=(*temp).next;
}
/* do{
printf("list is :");
printf("%d",(*temp).data);
temp=(*temp).next;
i++
}while(i<3);//just to conform that I was right I set i and looped for 3 times
//and then the code worked out and after this I tried while loop then also it
worked out fine same code that was not working before, started working
*/
printf("\n");
}