Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
sol1.c File Reference

Problem 13 solution More...

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Include dependency graph for sol1.c:

Functions

int get_number (FILE *fp, char *buffer, uint8_t *out_int)
 Function to read the number from a file and store it in array. More...
 
int add_numbers (uint8_t *a, uint8_t *b, uint8_t N)
 Function to add arbitrary length decimal integers stored in an array. More...
 
int print_number (uint8_t *number, uint8_t N, int8_t num_digits_to_print)
 Function to print a long number.
 
int main (void)
 Main function.
 

Detailed Description

Problem 13 solution

Author
Krishna Vedala

Function Documentation

◆ add_numbers()

int add_numbers ( uint8_t *  a,
uint8_t *  b,
uint8_t  N 
)

Function to add arbitrary length decimal integers stored in an array.

a + b = c = new b

49 {
50  int carry = 0;
51  uint8_t *c = b; /* accumulate the result in the array 'b' */
52 
53  for (int i = 0; i < N; i++)
54  {
55  // printf("\t%d + %d + %d ", a[i], b[i], carry);
56  c[i] = carry + a[i] + b[i]; // NOLINT // This is a known false-positive
57  if (c[i] > 9) /* check for carry */
58  {
59  carry = 1;
60  c[i] -= 10;
61  }
62  else
63  {
64  carry = 0;
65  }
66  // printf("= %d, %d\n", carry, c[i]);
67  }
68 
69  for (int i = N; i < N + 10; i++)
70  {
71  if (carry == 0)
72  {
73  break;
74  }
75  // printf("\t0 + %d + %d ", b[i], carry);
76  c[i] = carry + c[i];
77  if (c[i] > 9)
78  {
79  carry = 1;
80  c[i] -= 10;
81  }
82  else
83  {
84  carry = 0;
85  }
86  // printf("= %d, %d\n", carry, c[i]);
87  }
88  return 0;
89 }

◆ get_number()

int get_number ( FILE *  fp,
char *  buffer,
uint8_t *  out_int 
)

Function to read the number from a file and store it in array.


index 0 of output buffer => units place
index 1 of output buffer => tens place and so on i.e., index i => 10^i th place

17 {
18  long l = fscanf(fp, "%s\n", buffer);
19  if (!l)
20  {
21  perror("Error reading line.");
22  return -1;
23  }
24  // printf("Number: %s\t length: %ld, %ld\n", buffer, strlen(buffer), l);
25 
26  long L = strlen(buffer);
27 
28  for (int i = 0; i < L; i++)
29  {
30  if (buffer[i] < 0x30 || buffer[i] > 0x39)
31  {
32  perror("found inavlid character in the number!");
33  return -1;
34  }
35  else
36  {
37  out_int[L - i - 1] = buffer[i] - 0x30;
38  }
39  }
40 
41  return 0;
42 }
L
Definition: list.h:8