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

Problem 8 solution More...

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

Functions

long long int get_product (FILE *fp, long start_pos, int num_digits)
 Compute the product of two numbers in a file. More...
 
int main (int argc, char *argv[])
 Main function.
 

Detailed Description

Problem 8 solution

Author
Krishna Vedala

Function Documentation

◆ get_product()

long long int get_product ( FILE *  fp,
long  start_pos,
int  num_digits 
)

Compute the product of two numbers in a file.

Parameters
[in]fppointer to file that is already open
[in]start_posline number of the first numer
[in]num_digitsnumber of digits on the line to multiply
Returns
expected product
17 {
18  char ch = ' '; /* temporary variable to store character read from file */
19  unsigned char num = 0; /* temporary variable to store digit read */
20  long long int prod = 1; /* product accumulator */
21  int count =
22  0; /* we use this variable to count number of bytes of file read */
23 
24  /* accumulate product for num_digits */
25  for (int i = 0; i < num_digits; i++, count++)
26  {
27  /* get character from file */
28  ch = getc(fp);
29 
30  /* the ASCII codes of digits is between 0x30 and 0x39.
31  * any character not in this range implies an invalid character
32  */
33  if (ch < 0x30 || ch > 0x39)
34  {
35  if (ch == EOF)
36  return 0;
37  i--;
38  continue;
39  }
40 
41  num = ch - 0x30; /* convert character digit to number */
42  if (num == 0)
43  {
44  /* If number is zero, we can skip the next 'num_digits'
45  * because this '0' will repeat in the next 'num_digit'
46  * multiplications. Hence, we also do not update the file position
47  */
48  /* NOTE: this is not needed but helps get results faster :) */
49  return 0;
50  }
51 
52  prod *= num; /* accumulate product */
53  }
54 
55  /* set file position to the next starting character + 1 */
56  fseek(fp, -count + 1, SEEK_CUR);
57 
58  return prod;
59 }