Home > Software engineering >  Please correct my Code program C language
Please correct my Code program C language

Time:12-13

// Program jumlahBilangan.c
#include <stdio.h>

int jumlahDigit();

int jumlahDigit(int bilangan)
{
    if (bilangan == 0){
        return 0;}
    

bilangan = 10;
    }
    

int main()
{
    int bilangan, hasil;
    printf("Masukkan angka bilangan bulat: \n");
    scanf("%d", &bilangan);
    hasil = jumlahDigit(bilangan);
    printf("Jumlah digit angka bilangan: %d\n", hasil);
    return 0;
}

fix the program code, for example, enter the number 7631, then the function of the program will return the value 17 which is the number of digits of the number. The value 17 is the result of the addition (7 6 3 1)

CodePudding user response:

The question as asked cannot be answered, because there is insufficient explanation of how an input of 17 should arrive at an output of 7631.

However, in the spirit of How do I ask and answer homework questions? I will comment on the shown code, to enable the asker to improve to a point where the question can be focused on the correct algorithm.

// Program jumlahBilangan.c
#include <stdio.h>

int jumlahDigit(/* put at least int here, to match the function definition below */);

int jumlahDigit(int bilangan)
{
    if (bilangan = 0){ /* attention, =  is assignment, you most likely want == */
        return 0; /* at this point the function is left */
        bilangan = 10; /* this is never executed, even with == above) */
    }
    /* you probably want an else {...} here */
    /* with the "..." being something involving bilangan =10; */
    /* in the end please make sure that you always end in a return statement */
}

int main(/* better add void here */)
{
    int bilangan, hasil; /* better initialise both variables here */
    printf("Masukkan angka bilangan bulat: \n");
    scanf("%d", &bilangan); /* consider not ignoring the return value here ... */
    hasil = bilangan; /* if scan fails, both are still not cleanly initialised, UB */

    /* somewhere here I expect a call to int jumlahDigit(int bilangan) */
    /* maybe replace above line by hasil = jumlahDigit(bilangan),
       but make sure to have return statements in all possible outcomes
       of that function */
    printf("Jumlah digit angka bilangan: %d\n", hasil);
    return 0;
}

CodePudding user response:

#include <stdio.h>
int jumlahDigit();
int jumlahDigit(int bilangan){
if(bilangan==0) {
return 0; }
else
{
int hasil = 0;
while(bilangan != 0)
{
hasil = hasil   bilangan % 10;
bilangan = bilangan / 10;
}
return hasil;
}
}
int main()
{
int hasil, bilangan;
printf("Masukkan angka bilangan bulat: \n");
scanf("%d", &bilangan);
hasil = jumlahDigit(bilangan);
printf("Jumlah digit angka bilangan: %d\n", hasil);
return 0;
}

so, when I input for example the number 7631 then the question will produce a value of 17 . 17 is the result of the sum of the values ​​I input (7 6 3 1 = 17)

  •  Tags:  
  • c
  • Related