Imagine you are playing with blocks of different shapes and colors. You have a red square, a blue triangle, and a yellow circle. You want to make sure that whenever you put those blocks together, they always stay the same shape and color. This is what we call an invariant in computer science.
An invariant is like a rule or a condition that has to stay true no matter what happens. It is a property that doesn't change throughout the execution of a program.
Let's say you have a program that adds two numbers together. If you want to make sure that the result is always positive, you can use an invariant. You can say that the sum of two numbers always has to be greater than or equal to zero.
Invariants are useful because they help us avoid bugs and errors in our programs. They can also make it easier to understand and maintain the code, because we know that certain conditions will always be true.
To summarize, an invariant is a rule or condition that has to stay true throughout the execution of a program. It's like a promise that we make to ourselves, to make sure that things always work the way we want them to.