Loops in Carbon Language – while, for, break, continue, return

Total
0
Shares
loops in carbon language - for while break continue return

We can use for and while loops in carbon language. Within a loop the break and continue statements can be used for flow control.

while Loop

while loop in carbon is similar to that of any other language. It runs till the loop condition returns True.

Code Example –

var x: i8 = 0;
while (x < 3) {
  Print(x);
  ++x;
}
Print("Done!");

// Output: 0 1 2 Done!

In this code example, we have declared a 8 bit integer variable x and assigned it a value of 0.

Then, we are using while loop to run till value of x is less than 3 and printing the value. Along with it, we are incrementing the value of x using ++ increment operator.

After the loop finished, it will print Done.

for Loop

for loop in carbon works like foreach loop in javascript by supporting range-based looping. It will loop over all the values of a provided array or range.

Code Example –

var names: [String;] = ("Ironman", "Thor", "Hulk");

for (var name: String in names) {
  Print(name);
}

In this code we are using for loop to access all the values of names array. The for structure is –

for ( var declaration in expression ) { statements }

var name: String – Variable declaration which will hold single value of an array.

names – array of names.

break

Like any other language, break is used to halt the execution of loops.

Code Example –

var i: i8 = 0;

while(i < 10) {
    if(i == 5) {
       break;
    }
    Print(i);
    ++i;
}

// Output: 0, 1, 2, 3, 4

continue

continue statement skips the current cycle of the loop and start the next cycle.

Code Example –

var i: i8 = 0;

while(i < 10) {
    if(i == 5) {
       continue;
    }
    Print(i);
    ++i;
}

// Output: 0, 1, 2, 3, 4, 6, 7, 8, 9

return

return statement is used to end the flow of functions.

Code Example –

fn checkReturn() {
  var i: i8 = 0;
  while(i < 8) {
    if(i == 3) continue;
    if(i == 6) return;

    Print(i);
    ++i;
  }

  Print("I will never reach");
}

// Output: 0 1 2 4 5

Conclusion

Loops are the integral part of any programming language. We use for and while loops in Carbon whose implementation is similar to other programming languages.

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
functions in carbon language

Functions in Carbon Language

Table of Contents Hide IntroductionCode Example –Conclusion Functions in carbon language has the same role as in C, Php or any other functional language. It is used to separate a…
View Post
introduction to carbon language - what and why it is created

Introduction to Carbon Language

Table of Contents Hide IntroductionFeatures of Carbon LanguageWhy developed Carbon? Why not upgraded C++?Where Carbon could be used?Carbon is written in which language?Code Example Carbon Language is the successor to…
View Post