Page 58 - Programming Microcontrollers in C
P. 58

Program Flow and Control       43

                   {
                       int c,nn,no;
                       no=0;
                       nn=0;
                       while((c=getchar())!=EOF)
                          if(c>=’0'&&c<=’9')
                              nn++;
                       else
                          no++;
                       printf(“Digits=%d and other characters=%d\n”,nn,no);
                       return 0;
                   }
                          The statement

                   int c,nn,no;
                          declares the three variables c, nn, and no to be integers. You may
                          declare as many variables as you wish with a single declaration state­
                          ment. The next statements

                   no=0;
                   nn=0;

                          initialize the values of no and nn to 0. Variables declared with the
                          above sequence of instructions are automatic variables. These vari­
                          ables are not initialized by the compiler, and the programmer must
                          initialize them to a required value. Otherwise the variables will con­
                          tain garbage.
                              The code sequence
                   while((c = getchar()) !=EOF)
                       if(c>=’0' && c<=’9')
                          nn++;
                   else
                          no++;
                          comprise the while and its following statement. The if portion of
                          the statement tests the value of c and determines if it is a digit. A
                          character constant is identified as a specific value by placing the char­
                          acter value in single quotes. Therefore, the expression c>=’0'
                          determines if the character in the location c is greater than or equal
   53   54   55   56   57   58   59   60   61   62   63