# From For-Loop to Formula

*Task 3 of 5 · [Hello, Kernel](https://gpu.rocks/learn/hello-kernel-f1399353.md) · GPU.js Learn*

Here's the payoff of the thread index. On the CPU you'd sample a sine wave like
this:

```js
for (let i = 0; i < 64; i++) {
  wave[i] = Math.sin(i / 64 * 2 * Math.PI);
}
```

On the GPU, the loop **disappears** — the 64 iterations become 64 threads,
and the loop variable `i` becomes `this.thread.x`. The body of the loop
is your kernel body, unchanged. (`Math.sin` and `Math.PI` work inside
kernels, along with most of `Math`.)

## Figures

- **same body, new address — the loop unrolls into threads**

## Goal

**Goal:** sample one full sine cycle across 64 threads — thread
`x` returns `Math.sin(x / 64 * 2 * Math.PI)`.

## Requirements

- Keep `output: [64]` — one thread per sample
- Use `this.thread.x` where the CPU loop used `i`
- Return one sine sample per thread — the CPU loop body, unchanged except for the index

## Hint 1 — the translation rule

Take the CPU loop body, delete the loop, and substitute
`this.thread.x` for `i`. That mechanical rewrite is how most
for-loops become kernels.

## Hint 2 — the body

```js
return Math.sin(this.thread.x / 64 * 2 * Math.PI);
```

## Same idea elsewhere

This loop-body-becomes-kernel-body rewrite is called an *embarrassingly
parallel map*, and it's the bread and butter of GPGPU: the same move turns a pixel loop
into a Metal fragment shader, a physics update into a CUDA kernel, or an array transform
into a WebGPU compute pass.

## Starter code

```js
// The for-loop is gone — 64 threads each compute one sample.
const gpu = new GPU({ mode });

// CPU version, for reference:
//   for (let i = 0; i < 64; i++) wave[i] = Math.sin(i / 64 * 2 * Math.PI);

const wave = gpu.createKernel(function () {
  // TODO: one sample of a sine wave — i is this.thread.x now
  return 0;
}, { output: [64] });

const samples = await wave();
console.log(samples);
```

---

Interactive version: https://gpu.rocks/learn/hello-kernel-f1399353/3

[Previous task](https://gpu.rocks/learn/hello-kernel-f1399353/2.md) · [Next task](https://gpu.rocks/learn/hello-kernel-f1399353/4.md)
