JS FOR Loop Example PDF
Document Details
Uploaded by MagnanimousCloisonnism
Vilnius University
Justina Balsė
Tags
Summary
This document provides examples of programming concepts in JavaScript, specifically focusing on FOR loops. It demonstrates different types of loops and how they can be used to perform various actions. The examples show how to use FOR loops for tasks like calculating sums and counts in JavaScript.
Full Transcript
Programavimo pagrindai (FOR) Justina Balsė Turinys Žinomo kartojimų skaičiaus ciklas FOR; Sumos algoritmas; Kiekio algoritmas; break; continue; 2 Loop FOR | Ciklas FOR for (begin; condition; step) { Run begin //......
Programavimo pagrindai (FOR) Justina Balsė Turinys Žinomo kartojimų skaičiaus ciklas FOR; Sumos algoritmas; Kiekio algoritmas; break; continue; 2 Loop FOR | Ciklas FOR for (begin; condition; step) { Run begin //... loop body... → (if condition → run body and run step) } → (if condition → run body and run step) for (let i = 0; i < 3; i++) { → (if condition → run body and run step) // shows 0, then 1, then 2 alert(i); →... } 3 Loop FOR | Ciklas FOR for (let i = 0; i < 10; i = i + 2) { console.log(i); } // 0 2 4 6 8 let a = 10; let b = 20; for (let i = a; i < b; i++) { console.log(i); } // 10... 19 4 FOR and IF let a = 10; let b = 20; for (let i = a; i < b; i++) { if (i % 4 == 0){ console.log(i); } } // 12 16 5 Algoritmai Sumos skaičiavimo Kiekio skaičiavimo Vidurkio skaičiavimo Didžiausios/Mažiausios reikšmės paieška 6 Sumos algoritmas let sum = 0 1. sum = 0 + 1 = 1 for (let i = 1; i < 6; i++) { 2. sum = 1 + 2 = 3 sum = sum + i; 3. sum = 3 + 3 = 6 } console.log(sum); 4. sum = 6 + 4 = 10 // 15 5. sum = 10 + 5 = 15 7 Kiekio skaičiavimo algoritmas let count = 0 1. 1 % 3 == 0 ? False for (let i = 1; i < 10; i++) { 2. 2 % 3 == 0 ? False if (i % 3 == 0){ 3. 3 % 3 == 0 ? True, count = 0 + 1 = 1 count = count + 1; 4. 4 % 3 == 0 ? False 5. 5 % 3 == 0 ? False } 6. 6 % 3 == 0 ? True, count = 1 + 1 = 2; } 7. 7 % 3 == 0 ? False console.log(count); 8. 8 % 3 == 0 ? False // 3 9. 9 % 3 == 0 ? True, count = 2 + 1 = 3 8 Ciklas cikle | Nested loops for (i=1; i