0

So I have declared an integer called toplam in c but did not give it a value at all. However when I opened the watches window it is shown that it has a value of 16. I used an online c compiler and copy and pasted the code into it and it ran smoothly without assigning any value to toplam unless asked. I think this is an error in Codeblocks itself but i am not sure. how do I fix this without having to subtract 16 from toplam in order for it to be 0?

int fak(int j){
    int sonuc=1;
    while(j!=0){
        sonuc = sonuc * j;
        j--;
    }

    return sonuc;
}


int main()
{
    int sayi,i,j,sonuc,toplam;
    printf("sayi giriniz: \n");
    scanf("%d",&sayi);

    for(i=1;;i*=10){
        if(sayi/i==0){
            break;
        }
        j=(sayi/i)%10;
        printf("%d\n",j);
        toplam=toplam+fak(j);
    }

    printf("%d",toplam);


    return 0;
}

this is my code. It takes the inputed number and prints out the individual numbers in it and then adds their faktorials together.

cdKm.90
  • 3
  • 1
  • 1
    As explained in the first answer to this question: https://stackoverflow.com/questions/21152138/local-variable-initialized-to-zero-in-c local variables that are not explicitely initialized have an indeterminate value, including potentially a "trap representation" that would lead to undefined behavior. If you want `toplam` to be `0`, initialize it to `0`. – Virgile Dec 02 '20 at 12:59
  • What value do you expect to see if you do not initialize? During its lifetime a variable always has a value. It cannot have no value. – Gerhardh Dec 02 '20 at 13:59
  • @Virgile yes thank you very much, I am new to coding and I didn't know that was a thing :) – cdKm.90 Dec 02 '20 at 15:40

1 Answers1

0

You just initialize toplam at 0

#include <stdio.h>

int fak(int j)
{
    int sonuc=1;
    while(j!=0)
    {
         sonuc = sonuc * j;
         j--;
    }
     return sonuc;
 }

int main()
{
    int sayi,i,j,sonuc,toplam=0;
    printf("sayi giriniz: ");
    scanf("%d",&sayi);
   for(i=1;i<=(i*10);i++)
   {
       if(sayi/i==0)
       {
           break;
       }
       j=(sayi/i)%10;
       printf("%d \n",j,fak(j));
       toplam=toplam+fak(j);
    }
    printf("%d",toplam);
    return 0;
}
MED LDN
  • 684
  • 1
  • 5
  • 10