2. Perulangan Nested FOR
Berikutnya adalah bentuk Nested For atau For dalam For. Bentuk umum
Nested For adalah:
for(kondisi 1)
{
Pernyataan_1;
for(Kondisi 2)
{
Pernyataan_2;
}
}
3. Perulangan Nested FOR
Bentuk umum pengulangan bersarang for adalah sebagai berikut :
for(Inisialisasi_1; Kondisi/penghenti_1; penaik_1)
{
Pernyataan_1;
for(Inisialisasi_2; Kondisi/penghenti_2; penaik_2)
{
Pernyataan_2;
}
}
9. Contoh lain
int main()
{
int x, j;
char f='A';
for(x=1; x<=3; x++)
{
for(j=1; j<=x; j++)
{
cout<< f;
f++;
}
cout<<"n";
}
Matrix 3 x 5
A
B C
D E F
G H I J
K L M N O
Hasil Program
10. Perulangan Nested While
Bentuk umum pengulangan bersarang while adalah sebagai berikut :
Inisialisasi_1;
while(kondisi_1)
{
Pernyataan_1;
Inisialisasi_2;
while(kondisi_2)
{
Pernyataan_2;
Penaik_2;
}
Penaik_1;
}
11. Contoh Lagi
int main()
{
int b, x, j;
cout <<" masukan bilangan : "; cin>>b ;
x=1;
while(x<=b)
{
j=1;
while(j<=x)
{
cout<<" * ";
j++;
}
x++;
cout<<"n";
}
return 0;
}
12. Perulangan Nested do-While
Bentuk umum pengulangan bersarang do-while adalah sebagai berikut :
Inisialisasi_1;
do
{
Pernyataan_1;
Inisialisasi_2;
do
{
Pernyataan_2;
Penaik_2;
}
while(kondisi_2);
Penaik_1;
} while(kondisi_1);
13. Contoh Nested do-While
int main()
{
int b, x, j;
cout <<" masukan bilangan : "; cin>>b ;
x=1;
do
{
j=1;
do
{
cout<<" * ";
j++;
}
while(j<=x);
x++;
cout<<"n";
}while(x<=b);
return 0;
}
14. Contoh Nested For
int main(){
int x, y, i,j;
cout<<"Masukkan Alas Segitiga Sama Sisi : ";
cin>>x;
for(y=1;y<=x/2+1;y++)
{
for(i=x/2+1;i>=y;i--)
{ cout<<" "; }
for(j=0;j<y;j++)
{ cout<<"*"; }
for(j=1;j<y;j++)
{cout<<"*";
}
cout<<" "<<endl;
}
return 0;
}
15. APAKAH FOR BISA DIPAKAI UNTUK MEMBALIK TULISAN SEPERTI
“SELAMAT” MENJADI “TAMALES”?
#include <iostream>
#include <string>
using namespace std;
int main () {
string teks;
cout << "masukan suatu string: "; getline (cin, teks);
for (int i = teks. size () -1; i >= 0 ; i --)
{
cout << teks . at (i);
cout<< endl; // pindah baris
}
return 0;
}
16. Contoh lain
#include <iostream>
#include <string>
using namespace std;
int main(){
string kata;
cout<<"Masukkan Kata: ";cin>>kata;
for(int a=0; a<=kata.length(); a++)
{
cout<<kata.substr(a,kata.length() -a)<<endl;
}
return 0;
}
String terbaca mundur
17. Contoh lain bilangan Prima
#include <iostream>
using namespace std;
int main() {
int x,a,b,cek;
cout<<"Masukan batasan suku ke-n prima : "; cin>>x;
cout<<"================================================"<<endl;
cout<<"Cetak bilangan prima dari batasan yang dimasukan"<<endl;
for (a = 2; a<=x; a++)
{ cek = 0;
for (b = 2; b < a; b++)
{ if (a % b == 0)
{ cek = 1; }
} if (cek == 0)
{ cout<<a<<" "; }
}
cout<<endl;
cout<<"================================================"<<endl;
return 0;
}
18. TUGAS
Buat Bintang Segitiga
Kotak dengan bintang
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15
1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
A
B C D
E F G H I
J K L M N O P
Q R S T U V W X Y
A B C D E
F G H I
J K L
M N
O