0
0
C++programming~5 mins

Why input and output are required in C++

Choose your learning style9 modes available
Introduction

Input and output let a program talk with people. Input lets the program get information from users, and output shows results back to them.

When you want to ask a user for their name and greet them.
When you need to get numbers from a user to do math.
When you want to show the result of a calculation on the screen.
When your program needs to read data from a file or keyboard.
When you want to save results or messages for the user to see.
Syntax
C++
#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: "; // output
    std::cin >> number;               // input
    std::cout << "You entered: " << number << std::endl; // output
    return 0;
}

std::cout is used to show output on the screen.

std::cin is used to get input from the user.

Examples
This example asks for a name and then greets the user.
C++
#include <iostream>
#include <string>

int main() {
    std::string name;
    std::cout << "What is your name? ";
    std::cin >> name;
    std::cout << "Hello, " << name << "!" << std::endl;
    return 0;
}
This example gets two numbers and shows their sum.
C++
#include <iostream>

int main() {
    int a, b;
    std::cout << "Enter two numbers: ";
    std::cin >> a >> b;
    std::cout << "Sum is: " << (a + b) << std::endl;
    return 0;
}
Sample Program

This program asks the user for their age and then shows it back to them.

C++
#include <iostream>

int main() {
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;
    std::cout << "You are " << age << " years old." << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Without input, programs cannot get information from users.

Without output, users cannot see what the program did.

Input and output make programs interactive and useful.

Summary

Input lets programs receive data from users.

Output lets programs show results to users.

Both are needed for programs to communicate with people.