Variables

In programming when you want to store a value for future use in your program you store it in what is called a variable. Under the hood a variable is just a name give to a specific point in the computers memory that allows us to reference that point in memory when we need it.

Creating Variables

Most programming languages follow one of two syntax. Some programming langauges require you to define the data type of your variable while other programming languages can dynamically determine what data type your variable is and won't require you to define it. First let's look at some examples of how to declare variables in languages that require you to define the data type of the variable:

  • C:

    int day = 20;
    string month = "October";
    int year = 2052;
    
    char firstInitial = 'E';
    char lastInitial = 'P';
    
  • Java:

    int day = 20;
    String month = "October";
    int year = 2052;
    
    char firstInitial = 'E';
    char lastInitial = 'P';
    

Now let's looks at some examples of programming languages that dynamically set the data type of variables:

  • Bash:

    day=20;
    month="October";
    year=2052;
    
    firstInitial='E';
    lastInitial='P';
    
  • Python:

    day = 20
    month = "October"
    year = 2052
    
    firstInitial = 'E'
    lastInitial = 'P'
    

Using Variables

Now that we have learned how to create variables let's actually use them in our programs. In most programming languages you can access the value of a variable by either calling it's name outright or by using a $ in front of the variable name. Let's see some examples:

  • Bash:

    x=5;
    y=$(($x+5));
    
    echo "$y";
    # Prints: 10
    
  • C:

    int x = 5;
    int y = x + 5;
    
    printf("%d", y);
    // Prints: 10
    
  • Java:

    int x = 5;
    int y = x + 5;
    
    System.out.println(y);
    // Prints: 10
    
  • Python:

    x = 5
    y = x + 5
    
    print(y)
    # Prints: 10
    
This page was last updated: 2023-04-12 Wed 20:27. Source