prime numbers using linked list and recursion in turbo c - c

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);
}
}

Related

Hashcode of a string in C with Chaining

I have this assignment where I need to implement string hashcoding with chaining in c++ I,ve already tried it but with int data type only could anyone provide some guidance on how to do it? Should I use another hashcode function ??
I’ve already done the display insert function I still have to convert it to string and add three functions of hashcoding and apply it each time to a file and tht each line contain a random word of length from 3 to 30 characters and I have 10000 line which means 10000 words
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10 // prime number for size of array
#define h(x) (x % m) // h(x) = x mod m
// Node for List
typedef struct Node {
int val;
struct Node *next;
} Node;
//function's declaration
Node *fill_table(Node *table, int table_range, int number);
Node *insert(Node *table, int hash_index, int val);
void print_table(Node *table, int table_range);
int main() {
Node *table; // hashtable
int n, i, j, choice, search;
int hash_num, val;
// allocate table
table = (Node*) malloc(N * sizeof(Node));
// make table "heads" NULL
for (i = 0; i < N; i++) {
table[i].next = NULL;
}
printf("--h(x) = xmod%d--\n", N);
printf("\n\n");
while (1) {
printf("1.Insert random numbers\n");
printf("2.Show Hash Table\n");
printf("0.Exit Programm\n");
printf("\n--------\n");
printf("Choice: ");
scanf("%d",&choice);
switch (choice) {
case 0: break;
case 1:
// insert random numbers
printf("Lot to insert: ");
scanf("%d", &n);
table = fill_table(table, N, n);
printf("Filled HashTable with %d random values\n", n);
printf("\n--------\n");
break;
case 2:
// print hashtable
printf("-HASHTABLE-\n\n");
print_table(table, N);
printf("\n--------\n");
break;
}
}
return 0;
}
// FUNCTIONS
Node *fill_table(Node *table, int table_range, int number) {
int i;
int num;
for (i = 0; i < number; i++) {
num = rand() % 10000; // random number from 0 to 9999
table = insert(table, num % table_range, num);
}
return table;
}
void print_table(Node *table, int table_range) {
int i;
Node* cur;
for (i = 0; i < table_range; i++) { // for each list
if (table[i].next == NULL) { // if empty
printf("Table[%d] is empty!\n", i);
continue;
}
cur = table[i].next;
printf("Table[%d]", i);
while (cur != NULL) { // else print all the values
printf("->%d", cur->val);
cur = cur->next; //cur=cur+1;
}
printf("\n");
}
}
Node *insert(Node *table, int hash_index, int val) {
Node *nn, *cur;
nn = (Node*)malloc(sizeof(Node));
nn->val = val;
nn->next = NULL;
if (table[hash_index].next == NULL) {
table[hash_index].next = nn;
return table;
}
cur = table[hash_index].next;
while (cur->next != NULL) {
cur = cur->next; //cur=cur+1;
}
cur->next = nn;
return table;
}
hash

evaluate a polyome for a given value

I wanted to evaluate a polynome for a given value so I have used a linked list to store the coefficients and the exponants,and I have defined a function evaluate() to evaluate the polynome for a given value, but I do have a problem when it comes to the output it always shows the value 0.00000
can I get some help ? thanks in advance.
here's the full code :
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int coef;
int expo;
struct list* next;
}list;
int compare(char* s1,char* s2)
{
int i=0;
char c1,c2;
do
{
c1= (*(s1+i));
c2= (*(s2+i));
i++;
if(c2 == '\0' || c1 == '\0')
return c1-c2;
}while(c1==c2);
return c1-c2;
}
int transform(char* arr)
{
int i,sign=0;
int s=0;
if((*arr) == '-') sign=1;
for(i=0;arr[i]!='\0';i++)
{
if(arr[i]>=0 && arr[i]<=9)
s=s*10+(arr[i]-'0');
}
if(sign) return -s;
return s;
}
list* insert(list* head,char* coef,int expo)
{
list* node=(list*)malloc(sizeof(list));
if(node==NULL)
{
printf("Stack Overflow");
exit(1);
}
node->next=NULL;
node->coef=transform(coef);
node->expo=expo;
if(head==NULL) return node;
list* temp=head;
while(temp && temp->next)
temp=temp->next;
temp->next=node;
return head;
}
float power_of(float x,int expo)
{
if(expo==0) return 1;
int i=1;
float s=1;
if(expo > 0)
while(i++ <= expo)
s*=x;
else if (expo < 0)
while(i++ <= -expo)
s*=1.0/x;
return s;
}
float evaluate(list* head,float x)
{
if(head==NULL) return 0;
float s=0.0;
while(head)
{
s+=(head->coef)*power_of(x,head->expo);
head=head->next;
}
return s;
}
int main()
{
list* head=NULL;
char coef[11];
int expo,i=1;
float x;
printf("insert the polynome <type end to stop>:\n");
do
{
printf("insert the coefficient %d> : ",i);
scanf("%s",coef);
if(compare(coef,"end"))
{
printf("insert the exposnant %d> : ",i++);
scanf("%d",&expo);
head=insert(head,coef,expo);
}
}while(compare(coef,"end"));
printf("insert a value to evaluate the polynome : ");
scanf("%f",&x);
float value=evaluate(head,x);
printf("output : %f ",value);
return 0;
}

For my C code to construct a binary search tree and print the tree on its side is not printing anything?

I am trying to write a program to construct a binary search tree and print the tree on its side. Read the input from the user as a sequence of integers and output the tree indented based on depth and with one value on each line. However, my code is working but not printing anything on console?
I think something might be wrong with my insert function but I am not sure.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
typedef struct node node;
node *insert(node *t, int a){ //insert values in tree
node* tmp= (node*)malloc(sizeof(node));;
if (t==NULL) {
tmp->data = a;
tmp->left = NULL;
tmp->right = NULL;
return(tmp);
}
else if (a < t->data)
t->left = insert(t->left,a);
else
t->right = insert(t->right,a);
return(t);
}
void print( node *t, int depth) {
int i;
if (t == NULL)
return;
print(t->right, depth + 1);
for (i = 0; i < 4 * depth; ++i)
printf(" ");
printf("%d\n", t->data);
print(t->left, depth + 1);
}
int main() {
node *root= NULL;
int n,a,i;
printf("Enter number of values "); //7
scanf("%d", &n);
printf("\nEnter numbers "); //10 6 14 4 8 12 16
for (i = 0; i < n; ++i) {
scanf("%d", &a);
insert(&root, a);
}
print(root, 0);
return 0;
}
Input: 10 6 14 4 8 12 16
Expected output:
16
14
12
10
8
6
4
The signature of insert is
node *insert(node *t, int a) // t is a pointer to node
But you are passing a pointer to pointer to node
insert(&root, a);
I think you want
root = insert(root, a);

Editing a List Program in C

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);
}

C: Structured Data Types - Linked Lists

Here is my code:
#include<stdio.h>
#include<stdlib.h>
typedef struct list_node
{
int data;
struct list_node *next;
} node;
node *head,*temp;
int counter;
void display_menu();
char get_choice();
void process(char option);
void Insert_first();
void Print_first();
void Delete_first();
void Delete_end(); // Problem
void Insert_end(); // Problem
void Search();
int main()
{
char choice;
display_menu();
do
{
choice=get_choice();
process(choice);
} while(choice!='J');
return 0;
}
void display_menu()
{
printf("What do you want do do?\n");
printf("A. Insert a node at the beginning of the list\n");;
printf("B. Delete the first node of the list\n");
printf("C. Print list\n");
printf("D. Insert end\n");
printf("E. Delete the last node of the list\n");
printf("F. Search\n");
}
char get_choice()
{
char select;
printf("Enter your choice:\t");
scanf("%c",&select);
getchar();
printf("\n");
return select;
}
void process(char option)
{
switch(option)
{
case 'A': Insert_first();break;
case 'B': Delete_first();break;;
case 'C': Print_first();break;
case 'D': Insert_end();break;
case 'E': Delete_end();break;
case 'F': Search(); break;
default:
printf("Invalid input!\n\n");
}
}
void Search()
{
node *a;
node *b;
int i, j;
a=head;
b=head;
for(i = 1; i < counter - 1; ++i){
a = a -> next;
for(j = i + 1; j < counter; ++j){
b = b -> next;
if((a -> data) == (b -> data)){
printf("0\n");
}
else{
printf("1\n");
}
}
}
counter++;
}
void Insert_first()
{
temp=(node *)malloc(sizeof(node));
printf("Enter a number:\t");
scanf("%d",&(temp->data));
getchar();
printf("\n");
temp->next=head;
head=temp;
counter++;
}
void Insert_end()
{
temp=(node *)malloc(sizeof(node));
node *x;
int y;
printf("Enter a number:\t");
scanf("%d",&(temp->data));
getchar();
printf("\n");
x=head;
for(y = 1; y < counter; ++y){
x=x->next;
}
temp->next=x->next;
x->next = temp;
counter++;
}
void Print_first()
{
if(head==NULL)
{
printf("The list is empty\n");
}
else
{
temp=head;
printf("-------------------------------------------------\n");
do
{
printf("\t%d\t", temp->data);
temp=temp->next;
} while(temp!=NULL);
printf("\n");
printf("-------------------------------------------------\n\n");
}
}
void Delete_first()
{
if(head==NULL)
{
printf("\nThe list is empty\n");
}
else
{
temp=head;
head=temp->next;
free(temp);
counter--;
}
}
void Delete_end()
{
node *x, *z;
int y;
if(head == NULL)
printf("The list is empty");
else{
x=head;
for(y = 1; y < counter; ++y){
x=x->next;
}
z=x;
x=x->next;
free(z);
counter--;
}
}
I have two problems to solve:
The Delete_end() function;
The Search() function.
I want the Delete_end() function to act as Delete_first() function, but instead of deleting the FIRST node and deallocates its space, it does these to the END node. I tried to code these functions, but it didnt return what I want it to be.
If we run the codes, and Enter the Following:
As you notice when I delete the first node (Switch Choice: B), the list from
--------------------------------
4 3 2
--------------------------------
becomes
--------------------------------
3 2
--------------------------------
Thus, it deletes the first node and deallocates the space. Now when I delete the end node (Switch Choice: E) and print the list (Switch Choice: C), the list becomes
--------------------------------
3 135704608
--------------------------------
I think the number 135704608 is the location in the memory. So what happen here is it didnt delete the last node and deallocates it but instead returns 135704608. I hope you can help me with that.
Second function is the Search(), this function should return 0 if the number is already in the list, else 1 is returned. Here is the Search() function from the above codes:
void Search()
{
node *a;
node *b;
int i, j;
a=head;
b=head;
for(i = 1; i < counter - 1; ++i){
a = a -> next;
for(j = i + 1; j < counter; ++j){
b = b -> next;
if((a -> data) == (b -> data)){
printf("0\n");
}
else{
printf("1\n");
}
}
}
counter++;
}
Any help is greatly appreciated!
For delete at end, your code finds the next to last element and does this:
z=x; // save next to last as z
x=x->next; //set last as x
free(z); // free next to last
Instead, I think you want to do something more like this:
free(x->next); // free last elem
x->next = NULL; // next to last now points to NULL, meaning x is now the last element
The problem with your search function is that you never check the first element! You should do your if comparison before you do b = b -> next and then do a = a -> next after the inner for loop - otherwise the head will never be compared to anything, and nothing will be compared to the element immediately after it.

Resources