Topic Overview

Welcome back, coding explorer! Today, we're taking a new turn — mastering Input/Output, arithmetic expressions, and variable applications in C++. These skills are stepping stones to creating programs that interact with users. Brace yourself for our journey!

  • First, we'll explore the lands of Input/Output in C++.
  • Next, our mission will be collecting user inputs and displaying outputs.
  • Then, we'll dig into the treasure trove of arithmetic expressions.
  • Finally, we'll learn to apply variables within these expressions.

By the end of our journey, you'll wield the prowess of basic forms of Input/Output in C++, crafting arithmetic expressions, and using variables within them.

Understanding Input/Output in Programming

Imagine programming as a river with two streams: std::cin and std::cout. std::cin pours data into your program, and std::cout drains data from your program to the user.

Think of std::cin and >> as a way to gather user input, and std::cout and << as the microphone for your program to speak to users. However, due to platform constraints, we'll use constants instead of std::cin in our examples.

Taking User Input in C++

In a typical programming environment, std::cin >> couples with a variable to take user input.

int userAge;
std::cin >> userAge;

After the execution, userAge will contain the value inputted from the console.

Displaying Output with `std::cout`

To output data to the user, we invoke the std::cout << mantra:

#include <iostream> 

int main() {
   std::cout << "Hello, programming apprentice!";
   
   return 0;
}

But what about personalizing outputs? Just involve variables in your mantra:

#include <iostream> 

int main() {
   int userAge = 15;

   // The below line will print "You entered age as 15 years."
   std::cout << "You entered age as " << userAge << " years.";

   return 0;
}

In this snippet, we combine a string and a variable to display a tailored message to the user!

Understanding Expressions in C++

Now, let's unveil arithmetic expressions — they are simply mathematical formulas operating on variables and values. Take a glimpse of this mathematical wizardry:

#include <iostream> 

int main() {
   int x = 10;
   int y = 5;

   std::cout << x * y;  // prints 50

   return 0;
}

Here, we've used a multiplication operation x * y, and std::cout << delivers the result as 50!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal