Ciklusok átírása

Ciklusok átírása

do-while -> while

Írjuk át az alábbi do-while ciklus while-ra úgy, hogy ne változzon a viselkedése:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    do {
        cout << n << endl;
        n = n + 1;
    } while (n < 10);

    return 0;
}

Megoldás:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    cout << n << endl;
    n = n + 1;
    while (n < 10) {
        cout << n << endl;
        n = n + 1;
    }

    return 0;
}

Tehát a ciklus belsejét leírtuk a while elé is, hogy szimuláljuk azt, amit a do-while végrehajtana (egyszer mindenképp lefut az a kód).

while -> do-while

Írjuk át az alábbi while ciklust do-while-ra úgy, hogy ne változzon a viselkedése:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    while (n < 10) {
        cout << n << endl;
        n = n + 1;
    }

    return 0;
}

Megoldás:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    if (n < 10) {
        do {
            cout << n << endl;
            n = n + 1;
        } while (n < 10);
    }

    return 0;
}

Tehát a while feltételét leírjuk a do-while elé egy if-be, mert abban az esetben, ha az n már kezdetben nagyobb, vagy egyenlő, mint 10, a while nem hajtotta volna végre egyszer sem a ciklustörzset!

Feladatok

1. Végezzük el a következő átírásokat:

a. while -> do-while

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    while (n >= 3) {
        cout << n << endl;
        n = n / 5;
    }

    return 0;
}

b. do-while -> while

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;

    do {
        cout << a << endl;
        a = a + 2;
    } while (a < b);

    return 0;
}

c. for -> while

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    for (int i = 0; i < 3*n; i += 8) {
        cout << i << endl;
        cout << 2*i << endl;
    }

    return 0;
}

d. while -> for

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
    int n;
    cin >> n;

    int i = 2*n;
    while (i > n) {
        cout << i << endl;
        i -= 5; 
    }

    return 0;
}

2. Adott n term szám esetén írjuk ki, hogy hány számjegye van! (Itt előnyösebb a do-while ciklus, mint a while, mert az n = 0 esetet is alapból jól oldja meg.)

    Pl. n = 5    -> 1
        n = 1234 -> 4
        n = 0    -> 1