Kombination av if och for

status: alpha
author: krm
created: 2026-06-08

1. 🪧 count and print

const print = Number(prompt("What to print?"));
const index = Number(prompt("When to print?"));
for(let i = 1; i < 5; i++) {
  if(index === i) {
    console.log(i);
  } else {
    console.log(print);
  }
}

1. 🐾 Test 1

> GG 
> 2
*
GG
*
*
*

2. 🐾 Test 2

> 1+1 
> 2
*
*
*
*
1+1

2. 🪧 Count how you like?

const step = Number(prompt("How long should a step be?"));
const max = Number(prompt("What should be max?"));
const start = Number(prompt("When to start?"));
for(let i = start; i < max; i=i+step) {
  console.log(i);
  if(max-2 === i) {
    console.log("Bang!");
  } 
}

1. 🐾 Test 1

> 10
> 40
> 10
10
20
30

2. 🐾 Test 2

> 2
> 8
> 0
0
2
4
6
Bang!

3. 🪧 To break or stop?

const stop = Number(prompt("When to stop?"));
const num = Number(prompt("When to break?"));
const step = Number(prompt("How long is a step?"));
for(let i = 1; i < stop; i=i+step) {
  if(i % num === 0) {
    break;
  } else {
    console.log(i);
  }
}

1. 🐾 Test 1

> 10 
> 5
> 2
1
3

2. 🐾 Test 2

> 30 
> 9
> 3
1
4
7
10

4. 🪧 Divided in many ways

const Start = Number(prompt("Start"));
const Stop = Number(prompt("Stop"));

let sum = 0;
for(let i = Start; i <= Stop; i++) {
  if(i % 2 === 0) {
    sum += i*2;
  } else {
    sum += i;
  }
  console.log(sum);
}

1. 🐾 Test 1

> 5 
> 7
5
17
24

2. 🐾 Test 2

> 0 
> 4
0
1
5
8
16