Created
October 25, 2022 07:50
-
-
Save shramee/51af12434b922a71e863cd88f6852362 to your computer and use it in GitHub Desktop.
Loops with jmp in Cairo (Starknet).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dynamic allocation in Cairo is done using the `alloc` function, | |
// which itself is implemented in Cairo using the | |
// [segments](https://www.cairo-lang.org/docs/how_cairo_works/segments.html) mechanism. | |
// Thanks to this mechanism, `alloc` allocates an array of an arbitrary size, | |
// which does not need to be specified in the call. | |
// | |
// The function `sqr_array` should compute and return an array | |
// of the square values of a given array. | |
// Write the body of `sqr_array` using the given helper function | |
// `_inner_sqr_array` and check that the program output | |
// is 1, 4, 9, 16. | |
// `sqr_array` should allocate the new array it returns. | |
// Use the output builtin. | |
%builtins output | |
from starkware.cairo.common.alloc import alloc | |
from starkware.cairo.common.serialize import serialize_word | |
func sqr_array(array: felt*, length: felt) -> (new_array: felt*) { | |
alloc_locals; | |
// Allocate a new array. | |
let (local new_array) = alloc(); | |
tempvar i = length - 1; | |
myLoop: | |
assert [new_array + i] = [array + i] * [array + i]; | |
if ( i == 0 ) { | |
return (new_array=new_array); | |
} | |
tempvar i = i - 1; | |
jmp myLoop; | |
} | |
func main{output_ptr: felt*}() { | |
alloc_locals; | |
// Allocate a new array. | |
let (local array) = alloc(); | |
// Fill the new array with field elements. | |
assert [array] = 1; | |
assert [array + 1] = 2; | |
assert [array + 2] = 3; | |
assert [array + 3] = 4; | |
let (new_array) = sqr_array(array=array, length=4); | |
serialize_word([new_array]); | |
serialize_word([new_array + 1]); | |
serialize_word([new_array + 2]); | |
serialize_word([new_array + 3]); | |
return (); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment