dareesome
dareesome

Reputation: 133

How to print variable's new value after it has been changed

If I have a program where x = 2 and I subtracted x by 1, making x = 1. Is there any way to make it so that whenever x will be printed in the program, it will print 1?

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 2;
            Console.WriteLine(x-1);
            Console.WriteLine(x); //make x's new value 1
        }

    }
}

Upvotes: 0

Views: 539

Answers (3)

ADyson
ADyson

Reputation: 61849

Write

x--; 
Console.WriteLine(x);

That's how you change the value of a variable - you have to assign it a new value.

Alternatively you can write x = x - 1; longhand instead of using the decrement (--) operator.

What you did in your version was to create some output which was the result of x-1, but that doesn't change the original value of x, it just uses x in another calculation.

Upvotes: 0

Nico Walsemann
Nico Walsemann

Reputation: 190

You are Displaying the Correct answer. 2 - 1 will Display 1. But u arent changing the Variable or even touching it. You are just using it for a Reference to Calculate what is x - 1? Displaying only X now will Display 2 as it has NOT been changed.

Setting (Changing the Value of a Variable) is not (normaly) possible inside a Function. There are Functions which take ref params. Which will work with its memory.

You simply need a one-liner. x = x - 1 translated the value of x is set to the value of x - 1.

it seems much for a simple calculation to require a whole line as it is. But programming will always be one of these things where u have to think literall

This whole problem is a great example for Rubberducking. think about it literall... line for line what exactly happens and why should it not work?

Upvotes: 0

Vilsad P P
Vilsad P P

Reputation: 1559

you need to store the calculation to the variable

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 2;
            Console.WriteLine(x);//will print 2
            x = x-1; //applying calculation and storing to same variable
            Console.WriteLine(x); //make x's new value 1 : Done
        }

    }
}

Upvotes: 2

Related Questions