9. Exercises – Modern C++ for Absolute Beginners: A Friendly Introduction to C++ Programming Language and C++11 to C++20 Standards

© Slobodan Dmitrović 2020
S. DmitrovićModern C++ for Absolute Beginnershttps://doi.org/10.1007/978-1-4842-6047-0_9

9. Exercises

Slobodan Dmitrović1 
(1)
Belgrade, Serbia
 

9.1 Standard Input

Write a program that accepts an integer number from the standard input and then print that number.
#include <iostream>
int main()
{
    std::cout << "Please enter a number: ";
    int x;
    std::cin >> x;
    std::cout << "You entered: " << x;
}

9.2 Two Inputs

Write a program that accepts two integer numbers from the standard input and then prints them.
#include <iostream>
int main()
{
    std::cout << "Please enter two integer numbers: ";
    int x;
    int y;
    std::cin >> x >> y;
    std::cout << "You entered: " << x << " and " << y;
}

9.3 Multiple Inputs

Write a program that accepts three values of type char, int, and double respectfully from the standard input. Print out the values afterward.
#include <iostream>
int main()
{
    std::cout << "Please enter a char, an int and a double: ";
    char c;
    int x;
    double d;
    std::cin >> c >> x >> d;
    std::cout << "You entered: " << c << ", " << x << ", and " << d;
}

9.4 Inputs and Arithmetic Operations

Write a program that accepts two int numbers, sums them up, and assigns a result to a third integer. Print out the result afterward.
#include <iostream>
int main()
{
    std::cout << "Please enter two integer numbers: ";
    int x;
    int y;
    std::cin >> x >> y;
    int z = x + y;
    std::cout << "The result is: " << z;
}

9.5 Post-Increment and Compound Assignment

Write a program that defines an int variable called x with a value of 123, post-increments that value in the next statement, and adds the value of 20 in the following statement using the compound assignment operator . Print out the value afterward.
#include <iostream>
int main()
{
    int x = 123;
    x++;
    x += 20;
    std::cout << "The result is: " << x;
}

9.6 Integral and Floating-point Division

Write a program that divides numbers 9 and 2 and assigns a result to an int and a double variable. Then modify one of the operands, so that is of type double and observe the different outcomes of a floating-point division where at least one of the operands is of type double. Print out the values afterward.
#include <iostream>
int main()
{
    int x = 9 / 2;
    std::cout << "The result is: " << x << '\n';
    double d = 9 / 2;
    std::cout << "The result is: " << d << '\n';
    d = 9.0 / 2;
    std::cout << "The result is: " << d;
}