Home > Back-end >  How to implement a Digital River?
How to implement a Digital River?

Time:04-29

A digital river is a sequence of numbers where every number is followed by the same number plus the sum of its digits.

I have a logical problem and I can't figure out how to loop my code so that it will do something 20 times.

First Number => KUL_digitsum = sum = 6 > KUL_NEXTRIVERNUM = 123 6 = 129 => KUL_Digitsum * 20

Exercise

#include <stdio.h>
#include "KuL_RiverFkt.h"

int main()
{
    int num;
    printf("Eingabe der Zahl: ");
    scanf("%d", &num);

    KUL_NextRiverNum(KUL_digitsum(num), num);

    for (int i=0; i<20; i  ) {
        KUL_NextRiverNum(KUL_digitsum(num), num);
        KUL_digitsum(KUL_NextRiverNum(KUL_digitsum(num), num));
    }
   
    
    return 0;
}

int KUL_digitsum(int num) 
{
    int sum = 0;
    while (num > 0) 
    {
        int digit = num % 10;
        sum = sum   digit;
        num = num/10;
    }
    printf("Die Summe der Zahl = %d\n", sum);
    return sum;
}

int KUL_NextRiverNum(int KUL_digitsum, int num)
{
    int summe = 0;
    summe = num   KUL_digitsum;
    printf("Die Nächste Riverzahl ist: %d\n", summe);
    return summe;
}

CodePudding user response:

Your code is overly complicated and you ignore the return value of KUL_NextRiverNum.

The KUL_* functions themselves are correct, but they shouldn't do any printing unless you put the printfs for debugging reasons.

You want this:

int main()
{
  int num;
  printf("Eingabe der Zahl: ");
  scanf("%d", &num);

  for (int i = 0; i < 20; i  ) {
    num = KUL_NextRiverNum(KUL_digitsum(num), num);
  }

  return 0;
}

CodePudding user response:

  • Just comment the printf() in those functions and alter the main like :
#define MAX_RIVER_TERMS 20

//    KUL_NextRiverNum(KUL_digitsum(num), num);

    for (int i=0; i < MAX_RIVER_TERMS; i  ) {
        if (i) printf (", ");
        printf ("%d", num);
        num = KUL_NextRiverNum(KUL_digitsum(num), num);
//        KUL_digitsum(KUL_NextRiverNum(KUL_digitsum(num), num));
    }
  • Use #define macro values instead of magic numbers in the sources.
  • Declare/qualify arguments as const if they're not being modified inside the function.
int KUL_NextRiverNum(const int KUL_digitsum, const int num) {}
  • Related