Function that adds digits of a number - C++

Asked

Viewed 51 times

0

Good evening guys, I’m working on a program that generates a 10x10 matrix, with numbers between 100 and 999, and finally that I make the sum of the digits of each generated number, ex: if it came out 350, 3+5+0=8, if it comes out 495, 4+5+9=18 and so on, that is to add the digits of the 100 elements of this matrix individually, however I can not generate the part of the sum at all, follow the code below to help.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void gen( int [][10] );
void prn( int [][10] );
void sel( int [][10] );
int main()
{
    int n[ 10 ][ 10 ];
    gen( n );
    prn( n );
    sel( n );
    return 0;
} 
void gen( int g[][10] )
{
    srand(time(0));
    for( int i = 0 ; i < 10 ; i++ )
        for( int j = 0 ; j < 10 ; j++ )
            g[ i ] [ j ]= 100+ rand()%899 + 1 ;
}
void prn( int p[][10] )
{
    for( int i = 0 ; i < 10 ; i++ )
    {
        for ( int j = 0 ; j < 10 ; j++ )
            cout << p[ i ][ j ] << '|';
        cout << endl;
    }
void sel( int s[][10] )
{
    for( int i = 0 ; i < 10 ; i++)
        for()
}    
}

  • I suggest lowering the scope of the question to something like 'function' that adds the digits of a number'.

  • you wrote a program in C. Just switched the headers. It was really a program in C?

1 answer

2

You can create a function that computes the sum of the digits of a number and apply this function to all elements of your matrix. Your job would be something like:

int raizDigital(int n) {
    int soma = 0;

    // Cria uma cópia do parâmetro `n` para manipular ao longo da função
    int x = n;

    // Repete o procedimento seguinte enquanto houverem dígitos a serem somados
    while (x > 0) {
        // Adiciona à variável `soma` o dígito atual de `x`
        // Essa operação é equivalente ao resto da divisão de `x` por 10 (32 % 10 = 2)
        soma += x % 10;

        // Avança o dígito atual de `x` em uma casa para a esquerda
        // Essa operação é equivalente à divisão de `x` por 10 (32 / 10 = 3)
        x /= 10;
    }

    return soma;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.