Like Tree6Likes

I cant figure out why my simple program is not working!

This is a discussion on I cant figure out why my simple program is not working! within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> Code: int main() { int p; int n; int d; int q; int sum; int x,y,z,s; float ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    10

    I cant figure out why my simple program is not working!

    Code:
     
    #include <stdio.h>
    Code:
    
    int main()
    {
        int p;
        int n;
        int d;
        int q;
        int sum;
        int x,y,z,s;
    float r;
        
        
        
    printf("enter number of pennies:");
        scanf("%d",&p);
        x=p;
        
    printf("enter number of nickels:");
        scanf("%d",&n);
        y=(n*5);
        
    printf("enter number of dimes:");
        scanf("%d",&d);
        z=d*10;
        
    printf("enter number of quarters:");
        scanf("%d",&q);
        s=(q*25);
        
        r=(((x+y+z+s)%100)/100);
        sum=((x+y+z+s)/100)-r;
        
        scanf("%d %f",&sum,&r);
    printf("you have" sum,r "dollars");
        
    getchar();
    return0;
        
        
    }
    /*this will be a coin counting program please someone help me this to work it will be my first program my own */

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,837
    Please post your error messages, exactly as they appear in your development environment. These messages have important information to aid in locating and fixing these errors.

    You may also want to review the documentation for printf() and see if you can determine why this line is incorrect:
    Code:
    printf("you have" sum,r "dollars");
    Jim

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    Why, after doing the work to compute values of r and sum, do you immediately read in new values for them?

    The last printf() statement is invalid. Read the documentation on printf() to work out how to fix it.
    Right 98% of the time, and don't care about the other 3%.

  4. #4
    Registered User
    Join Date
    Oct 2012
    Posts
    22
    Your primary issues were:
    1) Failed to initialize your variables, when you create a variable memory is allocated for that variable by the operating system, there is however no guarantee that the value in that memory is 0 (Thus why you have to initialize your variables to zero) this ensures you don't get crazy numbers from your arithmetic.

    2) Indentation, remember that you indent when you enter a new code block and when you have to much to fit on one line. You also dropped a space between return and 0.

    3) Arithmetic, you had some botched arithmetic, you didn't need to use the modulus operator at all (thats the % sign).

    4) Botched printf (I use linux man to lookup most function definitions:
    printf(3): formatted output conversion - Linux man page

    5) Unnecessary scanf, after entering all of your monetary values you accidentally read new values in to sum and r.

    Hopefully I've been concise in my explanations, if you need any further clarification I'll be glad to assist.

    Best of luck!

    Here's the fixed code:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        /* Remember to initialize variables to zero
         * as you cannot depend on having zero-ed memory */
        int p = 0,n = 0,d = 0,q = 0;
        double sum = 0;
        /* You didn't need the additional variables,
         * everything you wanted to do can be done with the variables 
         * you already made */
    
        printf("enter number of pennies:");
        scanf("%d",&p);
        
        printf("enter number of nickels:");
        scanf("%d",&n);
        /* Multiply number of nickels by 5,
         * Note: n*=5 is the same thing as n = n * 5 */
        n *= 5;
    
        printf("enter number of dimes:");
        scanf("%d",&d);
        /* Multiply number of dimes by 10,
         * Note: d*=10 is the same thing as d = d * 5 */
        d *= 10;
    
        printf("enter number of quarters:");
        scanf("%d",&q);
        // Do the same thing for quarters
        q *= 25;
    
        /* Because money has decimal points we need more precision
         * This means we need to cast our integers to doubles (or floats)
         * to ensure we don't lose the decimal points 
         * (An integer divided by an integer is an integer) */                                       
        sum=(double)(n+d+q+p)/100;
    
        // Print the value of sum;
        // Note: .2f is a format specifiers it tells printf you print
        // 2 decimal places.
        printf("you have %.2f dollars",sum);
    
        return 0;
    }
    Adak likes this.

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    Quote Originally Posted by Tomwa View Post
    1) Failed to initialize your variables, when you create a variable memory is allocated for that variable by the operating system, there is however no guarantee that the value in that memory is 0 (Thus why you have to initialize your variables to zero) this ensures you don't get crazy numbers from your arithmetic.
    Not relevant in this case, since the first operation involving all variables is either reading a value (using scanf()) or setting a value.

    Your advice is only relevant if the first operation on any variable after its declaration involves accessing its value (as accessing the value of an uninitialised variable yields undefined behaviour).

    Of course, it is necessary to check the return value from scanf(), in case the reading fails.
    Right 98% of the time, and don't care about the other 3%.

  6. #6
    Registered User
    Join Date
    Oct 2012
    Posts
    22
    Quote Originally Posted by grumpy View Post
    Not relevant in this case, since the first operation involving all variables is either reading a value (using scanf()) or setting a value.

    Your advice is only relevant if the first operation on any variable after its declaration involves accessing its value (as accessing the value of an uninitialised variable yields undefined behaviour).

    Of course, it is necessary to check the return value from scanf(), in case the reading fails.
    Ah you've got me there! It's still a good practice though.

    I also want to point out that I accidentally dropped the getch() keeping the console window open so the OP needs to amend that into the program.
    Last edited by Tomwa; 01-05-2013 at 09:14 PM.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    Quote Originally Posted by Tomwa View Post
    Ah you've got me there! It's still a good practice though.
    I disagree on that. In my experience, such techniques serve to obscure more bugs than they eliminate - while giving a false sense of confidence and complacency that problems have been eliminated.

    Better to avoid declaring/defining a variable before it is needed, even if that means a need to break code into smaller functions. That way, if a variable is not initialised on definition, the first operation on it is to assign it a value.

    getch() is a non-standard function too.
    Right 98% of the time, and don't care about the other 3%.

  8. #8
    Registered User
    Join Date
    Oct 2012
    Posts
    22
    The OP didn't specify whether or not he wanted to comply with any standard and as his original post contained getch I assume he accepts it as reasonable (Thought pointing out that it is non-standard is nothing but informative).

    As far as initializing variables go a large number of bugs can be avoided by simply initializing data, the risks of unintended values from uninitialized data can be easily be avoided with one statement, a simple initialization can save you tons of debugging later especially since the program may very well work at some times and not at others (depending on if the memory allocated for the data is already the value anticipated).
    Last edited by Tomwa; 01-05-2013 at 10:02 PM.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,993
    Quote Originally Posted by Tomwa
    The OP didn't specify whether or not he wanted to comply with any standard and as his original post contained getch I assume he accepts it as reasonable
    The original post contain getchar -- which is standard -- not getch.

    Quote Originally Posted by Tomwa
    As far as initializing variables go a large number of bugs can be avoided by simply initializing data, the risks of unintended values from uninitialized data can be easily be avoided with one statement, a simple initialization can save you tons of debugging later especially since the program may very well work at some times and not at others (depending on if the memory allocated for the data is already the value anticipated).
    That is only true if the value used in the initialisation is intended. Otherwise, one invalid value is as bad as another (though admittedly having a null pointer is typically somewhat better than a garbage pointer), regardless of whether you explicitly initialised or just access garbage.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    That's the slavish response, which people follow without thought.

    It is a technique that was originally formulated to cope with another bad practice, such as
    Code:
    void some_function()
    {
      int x;
    
         /*    Several pages of code here that don't touch x */
    
      something_that_accesses_value_of(x);
    }
    Now, the thing is, that type of code is usually a sign of a function with convoluted logic that is hard to get right. The problem with initialising x to zero (or any other value, unless it has meaning relevant to the function) is that it encourages programmers to assume there are no bugs before the value of x is accessed. Those sorts of bugs - which programmers assume do not exist, so do not look for - are much more problematical in team environments than any inconvenience caused by x having an unpredictable value. Unfortunately, it is a fact of life that programmers tend to hack out such code when under time constraints, and assume it works without testing it.

    Not to mention the fact that virtually every compiler over the last decade or two can be configured to give a diagnostic about code that accesses the value of uninitialised variables. Initialising variables slavishly stops compilers diagnosing such things. It is true that some compilers can also be configured to give a diagnostic about a variable initialisation that is not used (eg a variable initialised to zero, then set to 1, with nothing in between that uses the value of zero) but not all compilers - because it is harder to avoid false positives in complex code.

    For small projects, by a single person, what you say sometimes works. In team environments, on larger projects, it obscures bugs more effectively than not.
    Right 98% of the time, and don't care about the other 3%.

  11. #11
    Registered User
    Join Date
    Oct 2012
    Posts
    22
    @grumpy the largest part of your example tends to lean toward code which isn't properly factored and has the definitions extremely far from their usage (Ideally it wouldn't be more than a few lines). But that is was an insightful read none the less though I've always had people push me toward the initialization side of things, I never really thought about the other side so it's interesting to discuss it (Though we are totally derailing this thread). I believe you are correct about the usage in team applications.

    @laserlight, you are indeed right I believe the fact that I'm losing my ability to read means I need to go to bed (I've got a project I'm working on and I wanted to make some more progress, though I believe I've become more of a deficit than an asset). No more caffeine for the night, night all. On the concept of initialization, initializing a variable to an incorrect value is a typographical mistake or a logical one that can be debugged and the behavior will be the same each time (since it's initialized), it'd be like if i did
    Code:
    int i = 2;
    while(i < 10)
    {
        i++;
        printf("%d\n",i);
    }
    and wondered why it was skipping 1.
    Last edited by Tomwa; 01-05-2013 at 11:47 PM.

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,993
    Quote Originally Posted by Tomwa
    On the concept of initialization, initializing a variable to an incorrect value is a typographical mistake or a logical one that can be debugged and the behavior will be the same each time
    If there is no correct initial value at that point, then there is no correct initialisation (or any initialisation, or no initialisation, is correct). The appropriate solution is to declare the variable near to first use, or in such cases, near to where they will be provided with an appropriate initial value. Just initialising the variable for the sake of initialisation will not cut it, and in fact can mislead the reader into thinking that the initialisation is appropriate.

    EDIT:
    Quote Originally Posted by Tomwa
    it'd be like if i did
    Consider this code:
    Code:
    int i = 0;
    for (i = 2; i < 10; ++i)
    {
        printf("%d\n", i);
    }
    Is the assignment of 2 to i a bug or was it intentional? If it was intentional, why was i initialised to 0 instead of 2? Now consider this code:
    Code:
    int i = 0;
    scanf("%d", &i);
    printf("%d\n", i);
    When run with certain user input, the program prints "2". Was the initialisation of i with 0 a bug or was it intentional? If it was intentional, why was i not used before the scanf?
    Last edited by laserlight; 01-05-2013 at 11:56 PM.
    iMalc, stahta01 and grumpy like this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    Quote Originally Posted by Tomwa View Post
    @grumpy the largest part of your example tends to lean toward code which isn't properly factored and has the definitions extremely far from their usage
    That is true, but I can provide other examples. Similarly, a fair proportion of examples I've seen used to justify advocating initialisation like you describe have significant separation between where a variable is defined, and the point of first use.

    While the notion of "good practice" is subjective, such examples suggest that the "initialise everything" approach is actually papering over deficiencies with other techniques.

    And I do advocate managing the lifetime of a variable (eg with scope, placing all code which uses it in a separate function, etc) a better alternative than some blanket notion of "initialise on definition". After all, if a variable is not in scope, it cannot be accessed - regardless of how or if it is initialised.

    Simply because, if a variable is not in scope, any attempt to access it (retrieve its value, set it) always yields a compilation error. And, if a variable is being accessed when it shouldn't, it needs to be asked why it is in scope - and being accessed - in the first place.

    Quote Originally Posted by Tomwa View Post
    I believe you are correct about the usage in team applications.
    I can't say I've seen formal studies on such things, but my views are based on experience leading teams of various sizes, and also providing independent review of work performed by other teams.
    Right 98% of the time, and don't care about the other 3%.

  14. #14
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    407
    It seems like the entire debate is subjective. I believed staunchly in one side of the debate because I was told so at the initialization of my learning to program and then over years people have defined new behaviors at which I've wondered why I was initialized to initialize at all times. There seems to be ways in which any unknowledgable programmer can accidently poke holes in either style.

    At this point I've honestly given up in believing there is any difinitive answer other than knowing what you are programming, and controlling all aspects of how the user can provide input. If everything isn't anticipated a bug will arrive and if everything is anticipated a bug will arrive. You take the most well developed commercial games of our generations and we still see multiple bugs in all of them. You take the least well developed games of our generation and .... well no one played them... but I am sure they had bugs in them as well.

    Is there really any answer in programming style that substitutes knowledge of what you are doing? I highly doubt it.

    And I guess that is why Grumpy and Laser seem to lean towards initializing or declaring based upon its nearest usage point because it encourages understanding of the need for the variable.
    Last edited by Lesshardtofind; 01-06-2013 at 01:47 AM.

  15. #15
    Registered User
    Join Date
    Jan 2013
    Posts
    10
    Quote Originally Posted by jimblumberg View Post
    Please post your error messages, exactly as they appear in your development environment. These messages have important information to aid in locating and fixing these errors.

    You may also want to review the documentation for printf() and see if you can determine why this line is incorrect:
    Code:
    printf("you have" sum,r "dollars");
    Jim
    Allright Jim, I will do that from now on.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Why is this simple c program not working ?
    By TexasKid in forum C Programming
    Replies: 5
    Last Post: 04-23-2012, 06:27 AM
  2. Simple program not working, don't know why
    By Bakster in forum C Programming
    Replies: 11
    Last Post: 01-29-2009, 12:56 PM
  3. Simple program not working
    By oobootsy1 in forum C# Programming
    Replies: 1
    Last Post: 08-10-2005, 02:20 AM
  4. can't figure out simple program
    By blight2c in forum C++ Programming
    Replies: 4
    Last Post: 03-16-2002, 04:17 PM
  5. simple program not working
    By Unregistered in forum Windows Programming
    Replies: 2
    Last Post: 03-04-2002, 10:36 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21