Input and Output in Programming
Input and Output (I/O)
I/O stands for Input and Output.
Input is how a program receives data (for example, from the user), and output is how a program shows data (for example, printing to the screen).
Every program usually needs some form of input and output.
Basic Output
Output means displaying data to the screen. All programming languages have a way to do this:
print("Hello World!")
console.log("Hello World!");
System.out.println("Hello World!");
cout << "Hello World!";
Try it Yourself »
Basic Input
Input means letting the user type something into the program. The program then stores that input in a variable.
name = input("Enter your name: ")
print("Hello, " + name)
// In browsers, prompt() can be used:
const name = prompt("Enter your name:");
console.log("Hello, " + name);
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
}
}
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " + name;
return 0;
}
Real-Life Example
Here is a simple program that asks the user for their age, and then prints out the year when they will turn 100 years old:
age = int(input("Enter your age: "))
year_to_turn_100 = 2025 + (100 - age)
print("You will turn 100 in the year", year_to_turn_100)
const age = Number(prompt("Enter your age:"));
const yearToTurn100 = 2025 + (100 - age);
console.log("You will turn 100 in the year " + yearToTurn100);
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
int yearToTurn100 = 2025 + (100 - age);
System.out.println("You will turn 100 in the year " + yearToTurn100);
}
}
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
int yearToTurn100 = 2025 + (100 - age);
cout << "You will turn 100 in the year " << yearToTurn100;
return 0;
}
Note: Input methods are different in every language. For example, input()
works in Python, while cin
is used in C++. In many cases, input is always stored as text first, and may need type casting to be used as numbers.