Computer Programming/Loops/C++

From Wikiversity
Jump to: navigation, search

loops.cpp[edit]

// This program displays a temperature conversion table showing Fahrenheit
// temperatures from 0 to 100, in increments of 10, and the corresponding 
// Celsius temperatures using While, For, and Do loops.

#include <iostream>

using namespace std;

void whileLoop();
void forLoop();
void doLoop();

int main()
{
    whileLoop();
    forLoop();
    doLoop();
}

void whileLoop()
{
    double f;
    double c;
    
    cout << "F°    C°" << endl;
    f = 0;
    while (f <= 100)
    {
        c = (f - 32) * 5 / 9;
        cout << f << " = " << c;
        cout << endl;
        f += 10;
    }
}

void forLoop()
{
    double f;
    double c;
    
    cout << "F°    C°" << endl;
    for (f = 0 ; f <= 100 ; f += 10)
    {
        c = (f - 32) * 5 / 9;
        cout << f << " = " << c;
        cout << endl;
    }
}

void doLoop()
{
    double f;
    double c;
    
    cout << "F°    C°" << endl;
    f = 0;
    do
    {
        c = (f - 32) * 5 / 9;
        cout << f << " = " << c;
        cout << endl;
       f += 10;
    } while (f <= 100);
}

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.

See Also[edit]