Sunday 14 October 2012

Exercises of "C" language book by K&R

Exercise 1-1 and 1-2 : 

#include <stdio.h>

/* printing hello world in different ways -
 * Studying Dennis Ritchie's The "C" Porgramming language second edition
 */


/* Example 1: Print Helloworld 10 times as executed below. */
int main()
    {
        int i;
        for( i=1 ; i<=10 ; i++)
        {
            printf ("Helloworld\n");
        }
        return 0;
    }


/*
Example 2: Print "Hello World" string through a const char  pointer.
  int main()
    {
        char string[] = "Hello world";
        printf("%s\n",string);
        return 0;
    }    

*/

/*
*Exercise 1-1:
*Scan an integer from keyboard and print it back to the console
*/
/*
int main()
{
    int i;
    char c[] = "1"; 
    /* Test the error message we get, if we pass integer in place of a
    * string constant to printf function as an argument
    *<Error message>  integet pointer is converted to string with out any cast.
    */
   
    /* printf(c); this is a valid input argument as , c is a string whose value is "1" 
    printf ("Enter a number from keyboard:");
    scanf("%d",&i);
    printf ("Entered number is:%d",i);
    return 0;
}
*/

/*
*Exercise 1-2:
*Last test to give \c in place of \n and see what happens */


/*
int main()
{
    printf ("hello,");
    printf ("world");
    printf ("\t");
}
*/

Exercise 1-3 and 1-4 : Temperature conversion with heading of the table,  FH to CL and CL to FH 

/* Objective: Print fahrenhiet-Celsius table for fahrenhiet = 0,20 .. 300
*<Sriram> : Directly writing the Fahrenhiet to Celsusis in floating point output
*as given by Dennis ritchie in his modified version of the program.
*This program covers Exercise 1-3 and 1-4 from the "C" book by Ritchie and kernigan
*/

int main()
{
    float fh, fh_low, fh_step,fh_up , cel , cel_low ,cel_step;
    /* Now implement the physics formula of fh to celsius conversion as: c = (5/9) * (fh - 32)
    */
    fh_step = 20; /* increment fh by 20 */
    fh_low = 0; /* initializing the loer value */
    fh_up = 300; /* max FH value to be calculated */
    printf ("FahrenHiet to Centigrade Table from 0 degree FH to degree Centigrade\n");
    fh = fh_low;
    cel_low = -17.8 ;
    cel = cel_low;
    /* cel_step = 11 */
    while (fh <= fh_up)
    {
        cel = (5.0/9.0) * (fh - 32.0) ; 
        printf ("%3.0f\t%6.2f\n", fh,cel);
        fh = fh + fh_step ;       
               
    }
    printf ("Centigrade to Fahrenhiet Table from degree Centigrade to 0 degree FH\n");

    while (fh_up >= fh_low)
    {
        cel = (5.0/9.0) * (fh_up - 32.0) ;
        printf ("%3.2f\t%6.2f\n", cel , fh_up) ;
        fh_up = fh_up - fh_step ;     
    }
    return 0;
}

 

Exercise 1-5: Printing FH to CEL in reverse order 
/* Objective: Print fahrenhiet-Celsius table for fahrenhiet = 300,280,...20,0. Reverse Order
*<Sriram> : Directly writing the Fahrenhiet to Celsusis in floating point output
*as given by Dennis ritchie in his modified version of the program.
*/


int main()
{
    float fh, fh_low, fh_step,fh_up , cel , cel_low ,cel_step;
    /* Now implement the physics formula of fh to celsius conversion as: c = (5/9) * (fh - 32)
    */
    fh_step = 20; /* increment fh by 20 */
    fh_low = 0; /* initializing the loer value */
    fh_up = 300; /* max FH value to be calculated */
    printf ("FahrenHiet to Centigrade Table from 300 degree FH to x degree Centigrade\n");
    fh = fh_low;
    cel_low = -17.8 ;
    cel = cel_low;
    /* cel_step = 11 */
    while (fh_up >= fh_low)
    {
        cel = (5.0/9.0) * (fh_up - 32.0) ; 
        printf ("%3.0f\t%6.2f\n", fh_up,cel);
        fh_up = fh_up - fh_step ;       
               
    }
   
    return 0;
   
}


Exercise 1-4: Use symbolic constants instead of writing and assigning 300, 0 and 20 to a variable.This will give more readability and avoid unintentional errors
I have attempted to assign some other value to a symbolic constant.C compiler immediately threw an error that, lvalue should not be a constant for the "=" operator. 

 #include <stdio.h>
/*Objective: this program is to define 300, 0 numbers as symbolic constants to increase
the readibility of the program as these constants never change through out hte program */

#define FH_LOWER 0
#define FH_UPPER 300
#define FH_STEP 20
#define CEL_LOW -17.8
/* Exercise 1-5a: Printing FH to CEL in reverse order */
int main()
{
    float cel;
    /* Now implement the physics formula of fh to celsius conversion as: c = (5/9) * (fh - 32)
    */
    /* fh_step = 20; increment fh by 20
    * fh_low = 0;  initializing the loer value
    *fh_up = 300;  max FH value to be calculated
    */
    float fh_up = FH_UPPER; /* <Sriram> Assigned Symbolic Constant to fh_up as this value
     * changes until fh_up reaches to 0 */
    printf ("FahrenHiet to Centigrade Table from 300 degree FH to x degree Centigrade\n");
    /* cel = cel_low;
     cel_step = 11 */
    while (fh_up >= FH_LOWER)
    {
        cel = (5.0/9.0) * (fh_up - 32.0) ;
        printf ("%3.0f\t%6.2f\n", fh_up,cel);
        /* fh_up = fh_up - fh_step ; */
        fh_up = fh_up - FH_STEP;
        /* FH_UPPER = FH_UPPER - FH_STEP; */
        /* <Sriram> : the above line throws the following error, if symbolic constants are attempted
        to modify their value.
        Symbolic_Constants.c:26:12: error: lvalue required as left operand of assignment
        *left side of "=" operator is a constant.So,a constant cannot be modified through the program.*/
                      
    }
  
    return 0;
  
}

  

Exercise 1-6: get a character from keyboard and print it on console:

#include <stdio.h>
main()  /* Removing int from main() as K&R removed.So,I need not return
 * the program with
 * return 0; */
{
    short c; /* K&R says use int "C" to hold the "EOF" value returned by getchar function */
    while ( (c=getchar()) != EOF )
        putchar(c);
        return 0;
   
}


Exercise 1-6a: Verify whether getchar() !=EOF is 0 or 1 ?

 #include <stdio.h>
main()  /* Removing int from main() as K&R removed.So,I need not return
 * the program with
 * return 0; */
{
    short c; /* K&R says use int "C" to hold the "EOF" value returned by getchar function */
    short e; /* hold getchar return integer value 0 or 1 */
    while ( (c=getchar()) != EOF )
    {
        putchar(c);
        /* Exercise 1-6a: Verify whether getchar() !=EOF is 0 or 1 ? */
        e = (getchar() != EOF);
        if ( e = 0 )
        {
            printf ("Characters did not match with end of line i.e EOF value \\n %d\n",EOF);   
        }
        else if ( e = 1)
        {
            printf ("getchar reached end of line or end of file EOF whose real value is %d\n",EOF) ;
         }   

    }
}

Exercise 1-7: Program to print the value of EOF:

#include <stdio.h>

main()
{
    int c;
    while ( (c = getchar()) != EOF )
    {
        putchar(c);
        printf ( "My EOF constant value is %d\n", EOF );
    }
}
Exercise 1-7a: Program to count the characters of a string or a paragraph as well as number of lines in the paragraph or string.
<Sriram> This exercise is given as example in K&R,but i wanted to combine two programs into one for my understanding.

#include <stdio.h>

/* This programs gives the length of a string or full sentence before the EOF is reached.
 * If a new line is given as the input.. It will count number of new lines as well.That means,we
 * can get line counting in the same program.Let's do that: */
main()
{
    double nc; /* count the number of characters in a string */
    int nl=0; /* Count the number of lines in a paragraph */
    int c=0; /* declaring c as integer to hold any value from getchar function */
   
    for (nc=0;getchar() != EOF ; ++nc)
        ;
   
    printf("Length of String is %.0f\n",nc);
   
    /* print the number of lines now with in a paragraph , basically number of new lines*/
    while( (c=getchar())  != EOF )
    {
        if ( c =='\n')
            ++nl;
    }
    printf("Total Number of lines are %d\n",nl);
   
}
/* <Sriram> : for and if controls can be written in short form as Sir Dennis Ritchie said.But, for
my understanding, i am writing it in a proper for and if syntax.*/

Important Note: K&R discussed about string constants and character constants at this point before Exercise 1-8. 

When '\n' is given like this in single quotes and is assigned to an integer,then ASCII value of '\n' will be assigned to the operand.
For example,
int c;
c = '\n';
printf ("New line character's ASCII value is %d\n", c);
<Sriram> Note that, first argument to printf above viz. string constant with in double quotes " " keeps the meaning of '\n' as it is and it takes the new line after printing the above statement. 
 To illustrate this example,I have rewritten  Exercise 1-7a as Exercise 1-7b:

Exercise 1-7b: Program to print total number of characters in a string and total number of lines in a paragraph.I have practiced once again to print the new line character's ASCII value along with the actual output given be Exercise 1-7a.

#include <stdio.h>

/* This programs gives the length of a string or full sentence before the EOF is reached.
 * If a new line is given as the input.. It will count number of new lines as well.That means,we
 * can get line counting in the same program.Let's do that: */
main()
{
    double nc; /* count the number of characters in a string */
    int nl,c; /* Count the number of lines in a paragraph */
             /* declaring c as integer to hold any value from getchar function */
    int newlinechar;
    for (nc=0;getchar() != EOF ; ++nc)
        ;
    printf("Length of String is %.0f\n",nc);
   
    /* print the number of lines now with in a paragraph , basically number of new lines*/
    nl = 0;
    while( (c=getchar())  != EOF )
    {
        if ( c =='\n')
            {
                ++nl;
            }
        else if ( c == EOF )
            {
                c = '\n';   
                printf ("New line char's ASCII value is %d\n" , c);       
            }
    }
    printf("Total Number of lines are %d\n",nl);
   
}
/* <Sriram> : for and if controls can be written in shortform as Dennis Ritchie said.But, for
my understading, i am writing it in a proper for and if syntax.*/

Important Note: Now, i feel it is important to have a look at  ASCII characters and their acronyms.
http://en.wikipedia.org/wiki/ASCII#ASCII_control_charactersASCII character Set

This wiki page cleary explains about EOF (ASCII value is ' -1' decimal), which is not present and considers Ctrl-Z (ASCII value is '26' decimal)  as End of Alphabet. Ctrl-C(ASCII value is '3' decimal) is for End of Text. 
Similary, Line Feed '\n'  character's ASCII value is '10' decimal and Carriage return '\r' character's ASCII value is '13' decimal and so on...

Exercise 1-8: Prorgram to print total count of blanks,tabs and newlines in a paragraph entered from stdin.

#include <stdio.h>
/* Exercise 1-8: Program to count blanks,tabs and newlines from a large string or paragraph*/
#define NEWLINE 10 /* defining NEWLINE character constant as '\n' viz.. 10 ASCII */
#define HT  9   /* defining horizontal tab character constant as '\t' viz.. 9 ASCII */ 
#define NULL 0  /* defining blank space character constant as '\0' viz.. 0 ASCII */ 

main()
{
    double nb; /* count the number of blanks in a string */
    int nt,nl,c; /* Count the number of tabs and newlines in a paragraph */
    nt=0;
    nl=0;
    c=0;
    while ( (c = getchar() ) != EOF )
    {
        if ( c == '\n' )
            ++nl;
        else if ( c == '\t' )
            ++nt;
        else if ( c == ' ' ) /* C literal is ' ' for blanks or white space, NUL is end of sring i.e decimal 0 or C-literal '\0' */
            ++nb;
    }
    /* print the number of blanks,tabs and newlines */
    printf("Total Number of Tabs   is %d\n",nt);
    printf("Total Number of newlines  is %d\n",nl);
    printf("Total Number of Blanks is %.0f\n",nb);
   
}








No comments:

Post a Comment

Tweets by @sriramperumalla