This C Program creates a support for infinite precision arithmetic which allows storage of large integers which is beyond the range of the integral limit. C is architecture dependent so primitive data type such as int is not capable of storing large integral values. So we make use of linked list in order to create and store such great integral values.
Here is a source code of the C program that supports infinite precision arithmetic and store a number as list of digits. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Support Infinite Precision Arithmetic & Store a
* Number as a List of Digits
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct node
{
int num;
struct node *next;
};
int feednumber(struct node **);
void release(struct node **);
void display(struct node *);
int main()
{
struct node *p = NULL;
int pcount = 0, qcount = 0;
printf("Enter number of any length\n");
pcount = feednumber(&p);
printf("Number of integers entered are: %d\n", pcount);
printf("Displaying the number entered:\n");
display(p);
release(&p);
return 0;
}
/*Function to create nodes of numbers*/
int feednumber(struct node **head)
{
char ch, dig;
int count = 0;
struct node *temp, *rear = NULL;
ch = getchar();
while (ch != '\n')
{
dig = atoi(&ch);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = dig;
temp->next = NULL;
count++;
if ((*head) == NULL)
{
*head = temp;
rear = temp;
}
else
{
rear->next = temp;
rear = rear->next;
}
ch = getchar();
}
return count;
}
/*Function to display the list of numbers*/
void display (struct node *head)
{
while (head != NULL)
{
printf("%d", head->num);
head = head->next;
}
printf("\n");
}
/*Function to free the allocated list of numbers*/
void release (struct node **head)
{
struct node *temp = *head;
while ((*head) != NULL)
{
(*head) = (*head)->next;
free(temp);
temp = *head;
}
}
$ gcc infinitedigits.c $ ./a.out Enter number of any length 932429842394820948234948098391830283192193818310398291830131209 Number of integers entered are: 63 Displaying the number entered: 932429842394820948234948098391830283192193818310398291830131209
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Related Posts:
- Check Computer Science Books
- Check Programming Books
- Check Data Structure Books
- Practice Computer Science MCQs
- Apply for Computer Science Internship