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.
Carbon Language Series
- Introduction to Carbon Language.
- How to define variables in Carbon.
- Primitive Types – Bool, Int, Float, String
- Tuple in Carbon
- Struct in Carbon
- Pointers in Carbon
- Operators in Carbon Language
- Conditions & Control Flow in Carbon
- Ternary Operator (if expression) in Carbon
- Switch conditional in Carbon using Match
- Loops in Carbon
- Functions in Carbon