Increase a number?

hi.

I'm pretty new to coding and my question probably not worth asking but how can i increase some number without it affected of loop?

fn main() {
    loop {
        let x = 5;
        let y = 7;
        let z = x + y;
    }
}

z = 12 and i want z increase +12 each loop

You could do it like this, for example:

fn main() {
    let x = 5;
    let y = 7;

    let mut z = 0;

    loop {
        z += x + y;

        // break infinite loop
        if z > 100 {
            break;
        }
    }

    println!("{z}");
}

Playground.

4 Likes

Hi, and welcome.

To achieve what you want, you need to do two changes to your code:

First: You have to move z out of the loop:

fn main() {
  let z = 0;
  loop {
    let x = 5;
    let y = 7;
    z += x + y;
  }
}

If you try the snippet above, you'll notice that it doesn't compile. The reason for this is because Rust requires that you explicitly mark variables as mutable, since Rust puts explicitness above any assumption made by the compiler. To do that, you use the mut keyword:

fn main() {
  let mut z = 0;
  loop {
    let x = 5;
    let y = 7;
    z += x + y;
  }
}

Bare in mind that this program will run forever, but I guess you'll figure that out since you are just starting to learn to code.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.