Thread: I'm I programming right?

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    17

    I'm I programming right?

    Hi,

    I'm learning C from Mark Virtue's cds chapter3 . I have completed the tasks both work as they should but they are very different from Marks soluations. I would to know if there is a problem with the way i'm learning to program?

    My 1st soluation
    Code:
    /*
     * input frist name
     * input second name 
     * output fullname with a space 
     * output the length of the name including the space 
     */ 
    
    #include <stdio.h>
    main()
    {
             char	name[15];
             char	s_name[15];
             int    length;
             
             printf("Enter your first name: ");
       	     scanf("%s", name);
       	     printf("Enter your second name: ");
       	     scanf("%s", s_name);
       	     printf("Your name is %s %s\n", name, s_name); 
             
                 length = strlen("%[^\n] %s %s"); 
                 printf("The length of this string >>%s %s<< is %d characters\n", 
                                                             name, s_name, length);	     
                 fflush(stdin);
          	     getchar();
    }
    Marks Soluation
    Code:
    /*
     *  fullname.c
     *
     *  Solution to the name exercise from Chapter 3.
     *  Ask for a user's first name and surname as two separate questions
     *  and output the result as a concatenated string (plus the length of the
     *  name).
     *
     *  by Mark Virtue, 2001.
     */
    #include <stdio.h>
    
    main()
    {
        char    first[31];
        char    sur[31];
        char    result[62];
    
        /*
         *  First, get the names from the keyboard
         */
        printf("Please enter your FIRST name: ");
        scanf("%[^\n]", first);
        printf("Please enter your LAST name:  ");
        fflush(stdin);
        scanf("%[^\n]", sur);
    
        /*
         *  Concatenate them together into "result" with a space between
         */
        strcpy(result, first);
        strcat(result, " ");
        strcat(result, sur);
    
        /*
         *  Output the result
         */
        printf("Your FULL name is %s (length %d)\n", result, strlen(result));
    
        fflush(stdin);
        getchar();
    }
    My 2nd Soluation
    Code:
    /*
     * Celsius to Fahreneit
     * 
     */ 
    
    #include <stdio.h>
    
    main()
    {
          float cel;
          double fah;
                
          printf("Enter a Celsius to convert to Fahreneit: ");
          scanf("%f", &cel);
          fah = cel * 9 /5 + 32;
          
          printf("Fahreneit = %.2f\n", fah);
         
          fflush(stdin);
          getchar();
    }
    Marks Soluation
    Code:
    /*
     *  temperature.c
     *
     *  Solution to the Celsius to Fahrenheit exercise from Chapter 3.
     *  Ask for a temperature in degrees Celsius and output the corresponding
     *  Fahrenheit value to two decimal places.
     *
     *  by Mark Virtue, 2001.
     */
    #include <stdio.h>
    
    main()
    {
        int     celsius;
        double  fahr;
    
        /*
         *  First, get the Celsius value from the keyboard
         */
        printf("Please enter a temperature in degrees Celsius: ");
        scanf("%d", &celsius);
    
        /*
         *  Perform the conversion  F = 32 + C * 9/5
         */
        fahr = 32 + (double)celsius * 9 / 5;
    
        /*
         *  Output the result
         */
        printf("%d degrees Celsius = %.2f degrees Fahrenheit\n",
                            celsius, fahr);
    
        fflush(stdin);
        getchar();
    }
    Thanking you in advance for any of your time helping me.


    Nurofen
    Last edited by nurofen; 03-15-2008 at 10:03 AM. Reason: character missing from title

  2. #2
    and the hat of copycat stevesmithx's Avatar
    Join Date
    Sep 2007
    Posts
    587
    strlen() function seems to be logically incorrect in your 1st program.
    Not everything that can be counted counts, and not everything that counts can be counted
    - Albert Einstein.


    No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes.
    - Herbert Mayer

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I say, get yourself a better book.
    main() should always return int; not nothing.
    Reading strings with scanf is tricky and mark is better at than you, but still negliges to do it correctly.
    This is important. Read http://cboard.cprogramming.com/showp...37&postcount=9
    Also, fflush(stdin) is undefined. Bad. So don't do that either.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I have completed the tasks both work as they should but they are very different from Marks soluations.
    Your first program does not work as it should. For example, it will claim that the length of the string is 11 characters, regardless of long the string really is.

    I would to know if there is a problem with the way i'm learning to program?
    Attempting to write your own programs and then comparing with a model solution is a good idea, unless the model solution is horrible. So far Mark Virtue's examples appear well formatted, clearly presenting the solution with suitable comments. The rather unfortunate part is that he uses fflush(stdin), which is undefined and should be avoided. There is also a pitfall to using scanf() in the way he demonstrates, but perhaps he will explain the problem in a later chapter (think of what happens if you enter a long string).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Quote Originally Posted by nurofen View Post
    Hi,

    My 1st soluation
    Code:
             char	name[15];
             char	s_name[15];
    ...
       	     scanf("%s", name);
       	     scanf("%s", s_name);
                 fflush(stdin);
    Your call to scanf ignores the buffer size.
    Calling fflush(stdin) is best to be avoided. Why.
    Marks Soluation
    Code:
        char    first[31];
        char    sur[31];
        char    result[62];
    ...
        scanf("%[^\n]", first);
        fflush(stdin);
        scanf("%[^\n]", sur);
    }
    Pretty bad for a solution for reasons already explained.
    The proper way to scanf is:
    Code:
        char first[31];
        char *newLine;
        scanf("%s30[^\n]", first); /* Leave room for scanf to put a '\0' in first */
        /* But it is sometimes clearer to use: */
        fgets(first, sizeof(first), stdin);
        /* However the above call, has the \n as the last character in buffer if there is one. */
        newLine = strchr(first, '\n');   /* Is there a newline in the first buffer ? */
        if(newLine)
            *newLine = '\0';   /* Remove it */
    My 2nd Soluation
    ...
    Appart from the fflush part ok for starters.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  6. #6
    Registered User
    Join Date
    Mar 2008
    Posts
    17
    laserlight, Elysia, xuftugulus

    Thank you for taking time to explaining and pointing out what i had done wrong.
    I'll need to read up on defining before continue with the cd's to get a better understaing.

    not sure why it's only showing 11 characters, my name is 11 character long so I thought i had it in the bag. Will have to go back over that.


    Thank you again for you help and your time

    Nurofen
    Last edited by nurofen; 03-15-2008 at 10:36 AM. Reason: adding text

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    not sure why it's only showing 11 characters, my name is 11 character long so I thought i had it in the bag. Will have to go back over that.
    strlen("&#37;[^\n] %s %s") returns the length of the string "%[^\n] %s %s".
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Mar 2008
    Posts
    17
    Thank you all again for your help.

    I have decided to put Mark Virtue's cds aside as from your feedback they are not teaching me a good foundation for learning C. I will go for one of the books from the C Book Recommendations section..

    Beginning C
    From Novice to Professional,
    Fourth Edition
    Ivor Horton

    Thanks again for you help

    Nurofen

  9. #9
    Registered User
    Join Date
    Oct 2006
    Location
    Omaha, Nebraska
    Posts
    116
    Look into The C Programming language by Brian Kernighan and Dennis Ritchie.
    I swear by it, but that's my opinion.

  10. #10
    Registered User
    Join Date
    Mar 2008
    Posts
    17
    Which should I use all the time?

    Ivor Horton book shows :

    Code:
    int main(void)
    {
    
    return 0;
    }
    Brian Kernighan and Dennis Ritchie shows

    Code:
    main()
    {
    
    }
    Again thank you for taking time to help me

    Nurofen

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The first.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Mar 2008
    Posts
    17
    Elysia,

    Thank you

    Nurofen

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    K&R2 also casts the return value of malloc() which is also generally considered a bad idea.

    Casting malloc

  14. #14
    Registered User
    Join Date
    Mar 2008
    Posts
    17
    Hi,

    I trying to to understand what kind of programs are created in the real world by programmers in C.

    What I guess I'm trying to ask is what can I do with my skill? What are the options? Do you have to learn a special skill set with in C itself to do a job?


    Thank you for any advise and guidence

    Nurofen

  15. #15
    Registered User
    Join Date
    Mar 2008
    Posts
    17
    Is this right?

    Exercise 2-1. Write a program that prompts the user to enter a distance in inches and then
    outputs that distance in yards, feet, and inches.

    Code:
    /* This program converts inches into feet and yards */
    
    #include <stdio.h>
    
    int main(void)
    {
    
    	int inches = 0;
    	int feet = 0;
    	int yards = 0;
    		
    	printf("Enter Inches as a whole number please: ");
    	 scanf("%d", &inches);
    
    	feet = inches/12;
    	yards = inches/36;
    
    	printf("\n %d Yards \n %d Feet \n %d Inches", yards, feet, inches);
    	return 0;
    }
    Exercise 2-2. Write a program that prompts for input of the length and width of a room in feet
    and inches, and then calculates and outputs the floor area in square yards with two decimal
    places after the decimal point.

    Code:
    /* This program allows you to enter the length and width of a 
     * room in feet and inches then calculates the area in square feet
     */
    
    #include <stdio.h>
    
    int main(void)
    {
    
    	float length_feet_inches = 0.0f;
    	float width_feet_inches = 0.0f;
    	float sq_feet = 0.0f;
    
    	printf("Enter the length of the room in feet and inches: ");
    	 scanf("%f", &length_feet_inches);
    	
    	printf("Enter the width of the room in feet and inches: ");
    	 scanf("%f", &width_feet_inches);
    	
    
    	sq_feet =  length_feet_inches*width_feet_inches;
    
    	printf("\nThe floor are in square feet is %.2f", sq_feet);
    
    	return 0;
    }
    Thank you for your time

    Nuofen

Popular pages Recent additions subscribe to a feed