c++ programming lesson 3: adding some value to inputs and printing

So we know how to do a basic print and read on our program now, this is an excellent base skill to learn but now we need to find some ways to make it slightly more useful.

Equations and math

C++ can easily be used to create formulations and perform calculations to display on the screen.

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • division (/)

For example create a program that will take two number inputs and print out the sum of these numbers.

#include <iostream> 

using namespace std;

int main()
{
    int a, b, sum;
    cout << "Enter two numbers press enter after each number: \n";
    cin >> a;
    cin >> b;
    sum = a + b;
    
    cout << a << " + " << b << " = " << sum << endl;
    
    return 0;
}
Enter two numbers press enter after each number: 
-9999
88
-9999 + 88 = -9911

PRACTICE PROBLEMS (scroll to the end of the page for solutions)

  1. Write a program that allows a user to enter the number of 5cent, 10cent, 20cent and 50cent coins they have. And will give the total monetary value of all of their coins. (Hint: If making the sum in dollars and expecting a decimal remember to make your sum a float variable type. )
  2. Write a program that will display the multiplication, addition subtraction and division of two user inputted integers.
question 1
#include <iostream> 

using namespace std;

int main()
{
    int five, ten, twenty, fifty;
    float sum;
    
    cout << "number of five cent coins: ";
    cin >> five; 
    cout << endl << "number of ten cent coins: ";
    cin >> ten;
    cout << endl << "number of twenty cent coins: ";
    cin >> twenty;
    cout << endl << "number of fifty cent coins: ";
    cin >> fifty;
    cout << endl;
    
    sum = 0.05 * five + 0.10 * ten + 0.20 * twenty + 0.50 * fifty;
    
    cout << "Total = $" << sum << endl;
    

    
    return 0;
}
number of five cent coins: 4

number of ten cent coins: 12

number of twenty cent coins: 7

number of fifty cent coins: 34

Total = $19.8
question 2
#include <iostream> 

using namespace std;

int main()
{
    float a, b, sum, multiplication, subtraction;
    float  division;
    cout << "Enter two numbers press enter after each number: \n";
    cin >> a;
    cin >> b;
    sum = a + b;
    multiplication = a * b;
    subtraction = a - b; 
    division = a/b; 
    
    cout << a << " + " << b << " = " << sum << endl;
    cout << a << " - " << b << " = " << subtraction << endl;
    cout << a << " x " << b << " = " << multiplication << endl;
    cout << a << " / " << b << " = " << division << endl;
    
    return 0;
}
Enter two numbers press enter after each number: 
27
2
27 + 2 = 29
27 - 2 = 25
27 x 2 = 54
27 / 2 = 13.5

Leave a comment