How to Take Input in Competitive Programming
This guide shows how to read input using C++, C, Python and Java. We’ll use the following example problem:
Read an integern
, then read inn
names. For each name, printHello <name>!
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 0; i < x; ++i) {
string name;
cin >> name;
cout << "Hello " << name << "!" << '\n';
}
return 0;
}
C
#include <stdio.h>
int main() {
int x;
scanf("%d", &x);
for (int i = 0; i < x; ++i) {
char name[100]; // Ensure name array is large enough
scanf("%s", name);
printf("Hello %s!\n", name);
}
return 0;
}
Python (3.x)
a = int(input())
for i in range(a):
z = input()
print("Hello " + z + "!") # can also do print(f"Hello {z}!")
Additionally, if there are several space-separated integers in the input (e.g. 1 2 3 4
), then you can extract it as follows:
nums = list(map(int, input().split()))
# Print the contents of nums:
for n in nums:
print(n)
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int i = 0; i < a; i++) {
String name = sc.next();
System.out.println("Hello " + name + "!");
}
}
}
Sample Input
3
Adelaide
Toronto
Singapore
Sample Output
Hello Adelaide!
Hello Toronto!
Hello Singapore!
You may output at any point of the program. Your full output will be compared against the expected output.