Redefining a Variable but using the same name? (Beginner question)

This is a discussion on Redefining a Variable but using the same name? (Beginner question) within the C Programming forums, part of the General Programming Boards category; Hi. Is it true that when you redefine a variable using the same name, the new redefinition of the variable ...

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    23

    Redefining a Variable but using the same name? (Beginner question)

    Hi. Is it true that when you redefine a variable using the same name, the new redefinition of the variable is not valid?

    For example, in this code, where I'm trying to output the lowest number of change needed for an user input (example: if the user inputs .26, I need to output 2 [one quarter, one penny]).

    Code:
    #include <cs50.h>
    #include<stdio.h>
    
    int main(void)
    {
        // get an input from user
        printf("How much change?: ");
        float change = GetFloat();
    
        int Change = round(change * 100);
    
        // how many quarters are needed
        while (Change >= 25)
        {
            quarters = (Change / 25);
            Change = (Change%25);
            // HERE IS MY QUESTION! I want to make Change (on the left) be Change%25 (on the right).  In the next while loop (to count dimes), is the (Change >= 10) using my new definition of Change (which is Change%25)?
        }  
        // how many dimes are needed 
        while (Change >=10)
        {
            dimes = (Change / 10);
            Change = (Change%10);
         }
        // there's more code concerning how many nickels and pennies are needed, but I deleted that to be concise in this question
    
        return 0;
    }
    Thank you!

  2. #2
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,501
    I'm not too sure what you are asking.

    One thing I did notice is that should not be a while statement, it should be an if statement - This is because you don't need it to loop.
    Fact - Beethoven wrote his first symphony in C

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,220
    1. I assume you realize that change and Change are two different names in C, so they are not in any way related.
    2. In your while loop, if you modify Change, then it happens immediately. It is "visible" throughout its entire scope. The scope of a local variable is within the curly braces in which it appears.

    Code:
    {
        int x = 123;
        //...
        {
            int y = 456;
            // ...
        }
    }
    y is visible only within the inner braces, while x is visible in both sets.

  4. #4
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Quote Originally Posted by Rubik View Post
    Code:
            Change = (Change%25);
            // HERE IS MY QUESTION! I want to make Change (on the left) be Change%25 (on the right).  In the next while loop (to count dimes), is the (Change >= 10) using my new definition of Change (which is Change%25)?
    The answer is yes. The variable Change is assigned(=) the expression on the right. Change%25 is just an expression which has a value with no side-effects. Using the assignment operator, '=', has the side effect of modifying the left-side's value.

    It is poor practice to have variables whose only difference in name is their case. I presume you will declare quarters and dimes as some type of variable?

  5. #5
    Registered User
    Join Date
    Feb 2013
    Posts
    23
    @click_here: Thank you for catching that!

    @c99tutorial and Tclausex: Thank you for answering; I have one follow-up question:

    Under my first loop (for how many quarters are needed), I define Change = Change(%25). Let's call this redefinition of Change "X" (in other words, X is Change(%25). On the next while loop (for how many dimes are needed), is the Change in while (Change >= 10) X?

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    1,220
    The way you phrase the question is like variables are some sort of conceptual thing. In programming, variables are not like mathematics, variables are basically just a spot where a value may be stored.

    Change = 27;

    So just imagine that you have a chalkboard called `Change' and that line simply writes the number 27 onto the chalkboard.

    Change = Change % 25;

    This line will look at what is on the chalkboard and do the calculation, then "overwrite" what is on the Change chalkboard with the new answer.

    So in summary, yes, you make the modification "right away". To demonstrate this fact more obviously you would be better to try a standard loop like this

    Code:
    int i=0;
    while (i < 100) {
       printf("i is currently %d\n", i);
       i++;
    }

  7. #7
    Registered User
    Join Date
    Feb 2013
    Posts
    23
    @c99tutorial:

    Thank you. It makes sense that you can redefine the value of a variable that has the same name as an old variable, but the reason I don't understand why this works is because in the code I'm writing, when I run the program, the output is completely wrong.

    what I have is:

    Code:
    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {    
        // get an input from user
        printf("How much change?: ");
        float change = GetFloat();
    
        int Change = round(change * 100);
        int quarters, dimes, nickels, pennies;
    
        // how many quarters are needed
        if (Change >= 25)
            quarters = (Change / 25);
        Change = (Change%25);
       
        // how many dimes are needed
        if (Change >=10)
            dimes = (Change / 10);
        Change = (Change%10);
    
        if (Change >= 5)
            nickels = (Change / 5);
        Change = (Change%5);
    
       if (Change >= 1)
            pennies = (Change / 1);
    
        int x = (quarters + nickels + dimes + pennies);
        printf("%i, is the answer\n", x);
        return 0;
    }
    I don't understand what I'm doing wrong.
    Last edited by Rubik; 02-18-2013 at 06:39 PM. Reason: Wrong Code

  8. #8
    Registered User
    Join Date
    Feb 2013
    Posts
    23
    Also, about the visibility of a scope of a local variable,

    in the code at [C] CS50 / greedy.c - Pastebin.com , near the end when it says "printf("Here's how many coins I gave you: %d\n", coins);", the variable coins within the curly brackets of inner loops seem to carry over -- how is that possible if the scope of the variable coins in the while loop is only contained within the curly brackets of the while loop?

    Thank you so much!

  9. #9
    Registered User
    Join Date
    Nov 2012
    Posts
    1,220
    Consider a simple case: you enter 0.01 at the prompt. What should the answer be? According to your program

    int x = (quarters + nickels + dimes + pennies);

    But the only variable which you've assigned a value to is pennies (because Change is 1). The rest of the values are undefined, so your answer in x is also undefined.

  10. #10
    Registered User
    Join Date
    Feb 2013
    Posts
    23
    c99tutorial, thanks for pointing that out!

    However, I'm confused because
    1. When I input 0.37 (which technically should work, I get a number like 218741571). Why doesn't it work when I input 0.37?

    2. Why doesn't the computer give me an error code telling me my values are undefined?

    3. Sorry if I'm really slow at this, but does all this basically mean that I can't use IF to write the code for this?

  11. #11
    Registered User
    Join Date
    Nov 2012
    Posts
    1,220
    It's normally the responsibility of the programmer to define the values for local variables, so it is not an "error" not to define them. However, if you turn on warnings in your compiler they will normally tell you. For example if you're using gcc you type

    gcc -Wall -Wextra -Werror -pedantic -std=c99 [......]

    This gives you the highest level of warnings

  12. #12
    Registered User
    Join Date
    Feb 2013
    Posts
    23
    Thanks, that makes more sense. However, I cannot, for the life of me, figure out why when I input something like 0.38, the code below doesn't work:

    Code:
    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {    
        // get an input from user
        printf("How much change?: ");
        float change = GetFloat();
    
        int Change = round(change * 100);
        int quarters, dimes, nickels, pennies;
    
        // how many quarters are needed
        if (Change >= 25)
            quarters = (Change / 25);
        Change = (Change%25);
       
        // how many dimes are needed
        if (Change >=10)
            dimes = (Change / 10);
        Change = (Change%10);
    
        if (Change >= 5)
            nickels = (Change / 5);
        Change = (Change%5);
    
       if (Change >= 1)
            pennies = (Change / 1);
    
        int x = (quarters + nickels + dimes + pennies);
        printf("%i, is the answer\n", x);
        return 0;
    }


    I tried using a while loop, but I have no idea why that doesn't work either:
    Code:
    #include <cs50.h>
    #include <stdio.h>
    
    int main(void)
    {    
        // get an input from user
        printf("How much change?: ");
        float change = GetFloat();
    
        int Change = round(change * 100);
        int coins;
    
        // if quarters are needed
        while (Change >= 25)
        {       
            Change = (Change - 25);
            coins++;
        }
        Change = (Change%25);
       
        // how many dimes are needed
        while (Change >=10)
        {       
            Change = (Change - 10);
            coins++;
        }
        Change = (Change%10);
    
        if (Change >= 5)    
        {       
            Change = (Change - 5);
            coins++;
        }
        Change = (Change%5);
    
       if (Change >= 1)
       {       
            Change = (Change - 1);
            coins++;
        }
    
        printf("%i, is the answer\n", coins);
        return 0;
    }
    Can you please enlighten me?

  13. #13
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,501
    "Doesn't work" doesn't help us

    Looking at your second code, run through what happens to the "coins" variable, it won't tell you what change you need, only the amount of coins needed - It is also not initialised.

    Your best bet is to use a debugger.

    [edit]

    Also, the 'Change % n' is useless, because the while loop keeps executing until the value is less than n

    [/edit]
    Last edited by Click_here; 02-18-2013 at 09:58 PM.
    Fact - Beethoven wrote his first symphony in C

  14. #14
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,501
    Also, what is "GetFloat" returning? Have you checked the value?
    Fact - Beethoven wrote his first symphony in C

  15. #15
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    It makes sense that you can redefine the value of a variable that has the same name as an old variable
    It's not the same name as the old variable, it IS the old variable. Remember, at the most basic, a variable is a place that stores a particular type of value - you're not creating a new variable (a new storage place), you're replacing what is stored inside the existing variable.

    As to why your last code isn't working - you need to explicitly initialize your variables to 0 before you start incrementing them. This code results in an undefined result because you have an undefined input:

    Code:
        int coins;  // Here, coins has some unknown value between INT_MIN and INT_MAX
     
        // if quarters are needed
        while (Change >= 25)
        {      
            Change = (Change - 25);
            coins++;  // Now you've incremented an unknown number to be one higher, but you could still have any number in coins because you don't know what your starting value was.
        }
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

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

Similar Threads

  1. Unused Variable - Beginner Question
    By intex in forum C Programming
    Replies: 4
    Last Post: 11-24-2012, 07:25 PM
  2. Beginner, help with loop and variable
    By keeganstarr in forum C Programming
    Replies: 16
    Last Post: 05-28-2012, 08:31 PM
  3. Replies: 10
    Last Post: 03-28-2010, 02:35 AM
  4. Question about redefining functions in derived class
    By Sharke in forum C++ Programming
    Replies: 2
    Last Post: 08-05-2009, 12:48 PM
  5. Replies: 4
    Last Post: 11-15-2005, 02:13 PM

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