Solutions

5. if and for Statements

Exercise 1:

#include <iostream>
using namespace std;

int main()
{
    for(double i=1; i<=20; i++)
        cout << "The square of " << i << " is " << i*i << endl;
}

Exercise 2:

#include <iostream>
using namespace std;

int main()
{
    double n=0;
    cin >> n;
    
    for(double i=1; i<=n; i++)
        cout << "The square of " << i << " is " << i*i << endl;
}

Exercise 3:

#include <iostream>
using namespace std;

int main()
{
    double a=0;
    cin >> a;
    double b=0;
    cin >> b;
    
    if (a<b)
        cout << "The smaller number is " << a << endl;
    else
        cout << "The smaller number is " << b << endl;        
}

Exercise 4:

#include <iostream>
using namespace std;

int main()
{
    double num1=0;
    double num2=0;
    double num3=0;
    cout << "Type in three different numbers: " << endl;    
    cin >> num1;
    cin >> num2;
    cin >> num3;
    
    if (num1<num2 && num1<num3)
        cout << "The smallest one is " << num1 << endl;
    if (num2<num1 && num2<num3)
        cout << "The smallest one is " << num2 << endl;
    if (num3<num1 && num3<num2)
        cout << "The smallest one is " << num3 << endl;    
}

Note: A much better solution of this problem can be written by using functions.

Exercise 5:

#include <iostream>
using namespace std;

int main()
{
    cout << "Type in a natural number: " << endl;
    double n=0;
    cin >> n;    
    
    if (n>=10 && n<100)
        cout << "The given number has exactly two digits." << endl;
    else
        cout << "The given number doesn't have exactly two digits." 
             << endl;
}

Exercise 6:

#include <iostream>
using namespace std;

int main()
{
    cout << "Type in the annual income of a company:" << endl;
    double income=0;
    cin >> income;    
    cout << "Type in the annual expenses of a company:" << endl;
    double expenses=0;
    cin >> expenses;    
    
    double tax=0;
    if (income > expenses)
        tax = (income - expenses)*0.2;
    cout << "Profit tax: " << tax << endl;    
}

Back to exercises