in Programming in C
328 views
1 vote
1 vote

Hi friends, In the following program when I am using '-'  in the expression "ndigit[c - '0'];" I am getting correct result but wen I am using + then I am not getting the answer, am I missing something, please answer.

 


#include <stdio.h>

int main()
{
    int c,i;
    int ndigit[10];
    
    
    for(i=0;i<10;++i)
        ndigit[i]=0;
        
        while((c=getchar())!=EOF)
        {
            
            
          if (c>='0' &&  c<='9')
          ++ndigit[c - '0'];
          
        }  
        
    printf("digits=");
    for(i=0;i<10;i++)
       printf("%d",ndigit[i]);
       
      }

in Programming in C
328 views

4 Comments

you are getting character by getchar(), But you want, integers to store.

when you enter 0 as i/p, it takes it as character 0

Character 0 has ascii value 48 ( ascii value is integer )

Character 1 has ascii value 49

.

.

Character 9 has ascii value 57

 

What this expression doing c - '0' ?

subtracting 48 from c ====> if you entered character 2 ===> 50

By that expression you are subtracting 48 from character 2===> 50-48=2 which is integer

 

If you replace it by c + '0' what happened ?

50+48 = 98 which is integer, but your array is size of 10

1
1

Hello Shaik Mastan boss, I understood everything now, I was having a misconception......

What this expression doing c - '0' ?............this sets the array subscript to that particular index position, if 0 is encountered then it would increament ndigit[0] .....as the arithmetic expression of character constants is integer value.

0
0

What this expression doing c - '0' ?............this sets the array subscript to that particular index position, if 0 is encountered then it would increament ndigit[0] .....as the arithmetic expression of character constants is integer value.

i didn't get why you added this point.... i hope i misused the terms

it's actually,

How this expression c-'0'  is evaluating 

0
0
btw....thanks boss
0
0

Please log in or register to answer this question.

Related questions