CodeChef Tutorial: Input and Output (I/O)

2 min read

This post will try and introduce newcomers to the first and most basic thing they need to learn before submitting programs — How to properly accept Input and print Output (I/O). I’ll start off with a few guidelines and then conclude with an example from the CodeChef site.

For all the questions on our site, the input will be given to you from standard input (stdin for C users) and the result is expected on standard output (stdout for C users). This is the same as writing a program that accepts input from the keyboard and displays the results on the screen. I’m sure most of you have been programming that way already. However, a major difference is that you don’t need to prompt the user for input, so stuff like:

“Please enter your name: ”

are a big NO NO! You need to assume that the user entering the data at the other end knows what to enter and when to enter it. Similarly, while displaying the results, you need to display it in the exact format as is specified in the problem statement.

For figuring out the format in which data will be entered (given to you) and how you should display the results, you need to refer to the “Input” and “Output” section of the problem statement respectively. Please make sure that you are following the output specification to the decimal point. If you have one character out of place, your submission will be marked as incorrect

After reading the problem statement, you will be given a sample “Input” and the resulting expected “Output” your program should submit. Typically, you will be asked to run your program against multiple test cases. The number of test cases and the format of each test case will be clearly mentioned in the problem statement’s “Input” section. More often than not, you will be required to display the result for each test case, so you will have as many results displayed as there are test cases.

Why so many test cases?

You must have studied about the different types of tests that you can run your program against in school. Some of them are:

  1. Boundary value testing
  2. Negative testing
  3. Stress testing
  4. and so on….

Now, each of these have a specific purpose, so the problem setter has kept many different types of tests to test the correctness and performance of your program for different types of inputs.

Let us move on to a specific example to see what is happening.

The problem we shall be tacking here is: Life, the Universe, and Everything

The problem statement:

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely… rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.

Input:

A list of integers separated by a new line.

Output:

All the integers before the integer ’42’.

Sample Input:
1
2
88
42
99

Sample Output:

1
2
88

Here, the constraint on the input we have is that any input number n will be such that (0 <= n < 100).

The problem statement is pretty straightforward, but for this toy program, the problem setter may construct test cases where:

  1. The 1st number is 42
  2. The last number if 42
  3. There are 10000000 numbers before 42

The first 2 tests are boundary value tests, and the 3rd one is a performance test. Generally these problems have a time limit associated with them. You are required to solve the problem with the given constraints in the given time limit. This time limit is chosen such that a good solution in any language would be accepted.If you are stuck, the answers to this problem, in over 25 programming languages can be found in our forums.

You can now go ahead and try out the problems in the easy set. If you have problems, post a message in the Forums.

Enjoy!

What Is An Integrated Development Environment?

An integrated development environment (IDE) is software that facilitates software developers in writing source code, debugging it, and providing specific tools for automation that...
jn0706
5 min read

Updates for the month of April 2022

Update on Laddus We had initiated Laddus in our system almost 8 years ago as an attempt to encourage the correct user behavior and...
surajmsharma
1 min read

The World Has A New SnackDown Champion!

Hello there! After a whole four months and just an extra few days, we finally have our new SnackDown Champion! With more than 75k+...
ganga4518
3 min read

99 Replies to “CodeChef Tutorial: Input and Output (I/O)”

  1. More often than not, your program’s output is redirected to a file. This file is diffed with an expected output file. Even a single difference in the output (say a simple whitespace) will be evaluated to ‘Wrong answer’.

    So it is important to adhere-to the output specification of the problem, literally.

    1. can any one explain what is problem in my code:

      import java.util.*;
      class InputStop
      {
      public static void main(String[] args)
      {
      Scanner in = new Scanner(System.in);
      while(true)
      {
      System.out.printf(“enter number”);
      int num = in.nextInt();
      if(num>99)
      {
      System.out.println(“sorry enter only 1 or 2 digit number”);
      }
      else
      {
      if(num==42)
      {
      System.exit(1);
      }
      else{
      System.out.println(“the input number is :”+num);
      }
      }
      }
      }
      }

      1. my solution is working check it out

        #include

        int main(){
        int number;

        while(1){
        scanf(“%d”,&number);

        if(number==42)
        {
        break;
        }
        printf(“%dn”,number);
        }}

        1. My Solution is working Check it out

          import java.io.*;

          class Codechef
          {
          public static void main (String[] args) throws java.lang.Exception
          {
          // your code goes here
          Scanner scan=new Scanner(System.in);
          while(true)
          {
          int N=scan.nextInt();
          if(N<=99)
          {
          if(N!=42)
          {
          System.out.println(N);
          }
          else
          {
          break;
          }
          }
          }
          }
          }

  2. More often than not, your program’s output is redirected to a file. This file is diffed with an expected output file. Even a single difference in the output (say a simple whitespace) will be evaluated to ‘Wrong answer’.

    So it is important to adhere-to the output specification of the problem, literally.

  3. One(coder) should take care of the input constraints before starting the code and one(problem setter) should give those explicitly, nothing can be assumed. Some languages have a good advantage over others, when it comes to reading input.
    Input Java is horrible 🙁 , aah! I remember a good old story on this ;).. –> Once a group of people were testing the programs response to the input ( knocking the door ), the program should output ( a voice says, “Hello I’m C/C++/Java/(what ever the code is written in) ), they knocked the door to check the language, it said, ” Hello I’m C “, one more time , “Hello I’m C++”, and they knocked again , shhhhhhhhh! a loong pause, they all exclaimed, “oh! ya… its Java 😛 “..

  4. One(coder) should take care of the input constraints before starting the code and one(problem setter) should give those explicitly, nothing can be assumed. Some languages have a good advantage over others, when it comes to reading input.
    Input Java is horrible 🙁 , aah! I remember a good old story on this ;).. –> Once a group of people were testing the programs response to the input ( knocking the door ), the program should output ( a voice says, “Hello I’m C/C++/Java/(what ever the code is written in) ), they knocked the door to check the language, it said, ” Hello I’m C “, one more time , “Hello I’m C++”, and they knocked again , shhhhhhhhh! a loong pause, they all exclaimed, “oh! ya… its Java 😛 “..

  5. i have posted many solutions.
    but all have errors saying cin and cout are undefined.
    y cant i use cin and cout.?
    which standard library does code chef have?

  6. i have posted many solutions.
    but all have errors saying cin and cout are undefined.
    y cant i use cin and cout.?
    which standard library does code chef have?

  7. hello folks, I have just joined this site and I’m having problems with posting the solution programs.

    I have submitted the solution to a problem, in C++.
    I have compiled it on my Computer with Turbo C++ IDE.
    It ran fine.
    But unfortunately when I submit the program in codechef it always shows an icon showing Compilation Error.

    I would appreciate any help regarding the matter, as a newcomer I dont have slightest Idea of the norms followed on CodeChef.
    Please leave a reply.

    1. Please use VS code or any other IDE because Turbo C++ is for beginner and I think you are my senior, So it is just my recommendation because a few code in Turbo C++ is different from a real IDE.

  8. hello folks, I have just joined this site and I’m having problems with posting the solution programs.

    I have submitted the solution to a problem, in C++.
    I have compiled it on my Computer with Turbo C++ IDE.
    It ran fine.
    But unfortunately when I submit the program in codechef it always shows an icon showing Compilation Error.

    I would appreciate any help regarding the matter, as a newcomer I dont have slightest Idea of the norms followed on CodeChef.
    Please leave a reply.

  9. Hi Folks..

    For this Life, the Universe, and Everything problem i believe the judge is not working properly for Java.
    Please check my two correct submissions. One of the submission checks using startsWith(“42”) but got accepted as correct but it is incorrect because even numbers like 423 will cause the program to exit.. username is : predator

  10. Hi Folks..

    For this Life, the Universe, and Everything problem i believe the judge is not working properly for Java.
    Please check my two correct submissions. One of the submission checks using startsWith(“42”) but got accepted as correct but it is incorrect because even numbers like 423 will cause the program to exit.. username is : predator

  11. It is quite possible that our tests are not covering the case you mentioned.
    Anyways, the problem above is meant to just get you familiar with the environment, and doesn’t test anything serious.

  12. To add to what dhruv.m said “Unless the judge is going to test your solution for every possible test-case (which is impossible), it is always possible to write a wrong solution which will pass the judge”. They are just part of any programming contest. It is the limitation of the world 😉
    As long as the judge is good enough to catch 99% of failed cases, it is good to go.

  13. To add to what dhruv.m said “Unless the judge is going to test your solution for every possible test-case (which is impossible), it is always possible to write a wrong solution which will pass the judge”. They are just part of any programming contest. It is the limitation of the world 😉
    As long as the judge is good enough to catch 99% of failed cases, it is good to go.

  14. Really great article, love the site. And the template is really nice – is this designed just for this site or is it a template you bought. I’m looking for a good one for one of my blogs (I have several).

  15. Really great article, love the site. And the template is really nice – is this designed just for this site or is it a template you bought. I’m looking for a good one for one of my blogs (I have several).

  16. I am noticing all the java solutions for the ByteLandian coin problem are reporting high memory usage (> 200 M) as compared to nearly zero consumption by other languages. Is there a difference between the way memory utilization inside JVM is computed as opposed to the way it is for other languages?

    The only data structure I am using in my solution is TreeMap and which has maximum of 239 entries (each entry being an integer key and a long value). I cannot believe this would even take 1 M. But the system is reporting 219 M. There definitely is something mysterious about the way memory utilization is measured. Can someone throw some light on that?

    Thanks,
    Ashutosh

  17. I am noticing all the java solutions for the ByteLandian coin problem are reporting high memory usage (> 200 M) as compared to nearly zero consumption by other languages. Is there a difference between the way memory utilization inside JVM is computed as opposed to the way it is for other languages?

    The only data structure I am using in my solution is TreeMap and which has maximum of 239 entries (each entry being an integer key and a long value). I cannot believe this would even take 1 M. But the system is reporting 219 M. There definitely is something mysterious about the way memory utilization is measured. Can someone throw some light on that?

    Thanks,
    Ashutosh

  18. One additional thought. I am guessing the solutions are run by the system by starting JVM such that it explicitly specified -Xms flag causing OS level utilities to record that as memory utilization of the program. It seems there is no easy way to record the true memory usage for the program as such.

  19. One additional thought. I am guessing the solutions are run by the system by starting JVM such that it explicitly specified -Xms flag causing OS level utilities to record that as memory utilization of the program. It seems there is no easy way to record the true memory usage for the program as such.

  20. I’ve been having major problems getting my Ruby programs to be scored properly. I keep getting NZEC (Non-Zero Exit Code) errors, even when I tried submitting a program that only contained: “exit(0)”. What’s worse, is that when I took one solution and translated it from Ruby to C (without any program/logic modifications), it worked!

    I’d really like to use Ruby here, but it’s not looking good.

    -CJ

  21. I’ve been having major problems getting my Ruby programs to be scored properly. I keep getting NZEC (Non-Zero Exit Code) errors, even when I tried submitting a program that only contained: “exit(0)”. What’s worse, is that when I took one solution and translated it from Ruby to C (without any program/logic modifications), it worked!

    I’d really like to use Ruby here, but it’s not looking good.

    -CJ

  22. Can any one tell me the name of any standard compiler for programming in C++ as is GCC compiler for programming in C.C++ programming can be done on GCC but my version is not supporting one Turbo compilers are there but it is not the standard one.PLZ reply as early as possible.

  23. Can any one tell me the name of any standard compiler for programming in C++ as is GCC compiler for programming in C.C++ programming can be done on GCC but my version is not supporting one Turbo compilers are there but it is not the standard one.PLZ reply as early as possible.

  24. Hi,

    I am trying to submit my codes in Java. Tried to submit 2 programs as of now. I keep getting a compilation error of the type.

    class “classname” is public, should be declared in a file named “classname”.java

    This happens even if my public class name is in a java file of the same name.

    Please advise.

  25. Hi,

    I am trying to submit my codes in Java. Tried to submit 2 programs as of now. I keep getting a compilation error of the type.

    class “classname” is public, should be declared in a file named “classname”.java

    This happens even if my public class name is in a java file of the same name.

    Please advise.

  26. Sup? thanks a million for the fantastic tutorial. The tutorial helped me improving my skills pretty much. It’s at all times gorgeous to get some impressive inspiration and I hope to read more of such posts here soon because no one will ever stop learning new stuff. Props

  27. Sup? thanks a million for the fantastic tutorial. The tutorial helped me improving my skills pretty much. It’s at all times gorgeous to get some impressive inspiration and I hope to read more of such posts here soon because no one will ever stop learning new stuff. Props

  28. import java.util.*;
    class main
    {public static void main(String a[])
    {int n=0;
    for(;;)
    {Scanner s = new Scanner(System.in);
    n = s.nextInt();
    if(n!=42)
    {System.out.println(n);
    }
    if(n==42)
    break;

    }

    }
    }

    1. the input and output are coming on alternate lines viz 1 input followed by same output and also the execution of program stops after user inputs 42. If you go through the problem you can see that input first enter any number of input which may or may not include 42 and only after the user is done providing the input is the output provided on the screen i.e. integers before 42 if there is any.

  29. import java.util.*;
    class main
    {public static void main(String a[])
    {int n=0;
    for(;;)
    {Scanner s = new Scanner(System.in);
    n = s.nextInt();
    if(n!=42)
    {System.out.println(n);
    }
    if(n==42)
    break;

    }

    }
    }

  30. i want to ask that is conio.h not a c header file .because without writing it my compiler is not giving output. and after writting it gives. i am using dev c++ compiler.

    1. plz…. read the problem first. It is clearly mentioned in last line of question that All numbers at input are integers of one or two digits.

  31. i am getting a runtime(NZEC) error

    my source code is

    import java.util.*;

    class Lifecc

    {

    public static void main(String args[])

    {

    ArrayList al=new ArrayList();

    int num;

    //int i;

    int flag=0;

    Scanner in=new Scanner(System.in);

    do

    {

    num=in.nextInt();

    if(num!=42 && num<99)

    {

    al.add(num);

    }

    else

    flag=1;

    }while(flag==0);

    int []arr=new int[al.size()];

    int b=arr.length;

    for(int j=0;j<b;j++)

    {

    arr[j]=al.get(j);

    }

    for(int k=0;k<b;k++)

    {

    System.out.println(arr[k]);

    }

    }

    }

    pls help

  32. #include

    void main()

    { int a;

    while(1)

    { cin>>a;

    if(a!=42&&a0)

    cout<<a<<"n";

    else

    break;}

    }

    this is my code..it works fine on my turbo and on codechef it shows compilation error if i select C++ as language and wrong answer when i choose pure text as language.

  33. Tell me about the stopping criteria. When does i stop reading elements from prompt? I can’t understand at what position i have to stop reading input

  34. #include

    using namespace std;

    int main()

    {int a[5];

    for(int i=0;i>a[i];

    int j=0;

    while(a[j]!=42)

    {cout<<a[j]<<endl;

    j++;

    }

    return 0;

    }
    getting a runtime error sigsegv

  35. #include
    using namespace std;
    int main()
    {int a[5];
    for(int i=0;i>a[i];
    int j=0;
    while(a[j]!=42)
    {cout<<a[j]<<endl;
    j++;
    }
    return 0;
    }
    GETTING RUNTIME ERROR SIGSEGV

  36. please tell me whats wrong in it
    ,,codechef says runtime error

    #include
    void main()
    {
    int a=0;
    do
    {
    scanf(“%d”,&a);
    if(a!=42)
    printf(“n%d”,a);
    }while(a!=42);
    }

  37. “Wrong answer” why anyone please ?

    #include
    int main()
    {
    int n;
    printf(“enter values:n”);
    scanf(“%d”,&n);
    if(n!=42)
    {
    printf(“%dn”,n);

    }
    return 0;
    }

      1. i have added loop but it is sayin wrong #include
        int main()
        {
        int n,i,p;
        scanf(“%d”,&n);
        for (i=1;i<n;i++)
        {
        scanf("%d",&p);
        if (p!=42)
        printf("%d",p);
        }
        return 0;
        }

  38. wrong answer
    why?
    #include
    int main()
    {
    int n,i,p;
    scanf(“%d”,&n);
    for (i=1;i<n;i++)
    {
    scanf("%d",&p);
    if (p!=44)
    printf("%d",p);
    }
    return 0;
    }

  39. can anyone please tell me why my following code is giving me wrong answer??
    #include
    using namespace std;
    int main()
    {
    int a[5];
    for(int i=0;i>a[i];
    }

    for(int i=0;i<5;i++)
    {
    if(a[i]!=42)
    {
    cout<<a[i]<<endl;
    }
    else
    {
    break;
    }
    }
    return 0;
    }

  40. I am trying to execute the following code but i am getting “wrong answer”
    although i have tried this code in IDE and it is working fine there.
    Please help as i am new to codechef
    #include

    int main()
    {
    int n=0;
    int a[100000];
    int i=0;
    scanf(“%d”,&n);
    for(i=0;i<n;i++)
    {
    scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++)
    {
    if(a[i]!=42)
    {
    printf("%un",a[i]);
    }
    else
    {
    break;
    }
    }
    return 0;
    }

  41. guys tell me what’s wrong with my program
    #include
    int main()
    {
    int a=0,b;
    while (a<1)
    {
    printf("enter the valuen");
    scanf ("%d",&b);
    if (b==42)
    break;
    else
    printf("you entered %dnn",b);
    }
    }

  42. import java.util.Scanner;
    public class JavaApplication2 {

    public static void main(String[] args) {

    Scanner s=new Scanner(System.in);

    System.out.println(“enter number of elements”);

    int n=10;

    int arr[]=new int[n];

    System.out.println(“enter elements”);

    for(int i=0;i<n;i++){//for reading array
    arr[i]=s.nextInt();

    }
    for(int i=0;i<n;i++)
    {
    if(arr[i]!=42)
    {
    System.out.println(arr[i]);
    }

    }
    }}
    *************************************************************************************
    WHY IT IS SHOWING ERROR

  43. hello, i am new to codechef. I tried the program using python 2.7 but it is still displaying all the inputs even when 42 is show. This is my code.

    vals = raw_input()
    numbers = map(int, vals.split())
    print

    for index in range(len(numbers)):
    if numbers == 42:
    break
    print numbers[index]

  44. package testing;

    import java.io.*;
    import java.util.*;
    public class Main{

    public static void main(String[] args)throws IOException {
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
    int num[]=new int[100];
    int num1[]=new int[100];
    int n,i,o;
    o=0;
    System.out.println(“Enter the number of inputs”);
    n=Integer.parseInt(x.readLine());

    System.out.println(“Enter the numbers”);
    for(i=0;i=0) && (num[i]<100))
    {
    if(num[i]==42){
    break;}
    else
    num1[i]=num[i];
    o++;

    }
    else{
    System.out.println("re enter number betwen 0 and 100");
    i–;
    }
    }
    for(i=0;i<o;i++)
    {

    System.out.println(num1[i]);
    }
    }

    }

  45. why it is wrong answer please help

    #include
    using namespace std;
    int main()
    {
    int a[1000000];
    int j,n,i=0,n1,c=0;
    while(a[i-1]!=42)
    {
    c=0;
    cin>>n;
    n1=n;
    while(n1!=0)
    {
    c++;
    n1=n1/10;
    }
    if((c==2)||(c==1))
    {
    i++;
    a[i]=n;
    }
    }
    for(j=1;j<i-1;j++)
    {
    cout<<a[j]<<endl;
    }
    return 0;
    }

  46. THERE IS A RUNTIME ERROR IN THIS SOLUTION.
    WHAT SHOULD I DO?
    i THINK I GAVE THE RIGHT SOLUTION

    import java.io.*;
    class Test
    {
    public static void main(String []ar)throws IOException
    {
    int num;
    boolean itr;
    do
    {
    System.out.println(“Enter a number”);
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    num=Integer.parseInt(br.readLine());
    if(num==48)
    itr=false;
    else
    {
    System.out.println(“Output is “+num);
    itr=true;
    }
    }
    while(itr);

    System.out.println(“n End of program”);
    }
    }

  47. I feel the and Input and Output section should be more clear. In this particular problem input is showing 99 also. But the accepted answer is…when 42 is entered the program is terminated. The inputs provided is misguiding a reader. According to accepted answer, input should not contain 99 Or according to input provided, the program should accept an array of inputs. And logic should be such that, we have to analyze the array and stop printing the elements when 42 is encountered.

  48. Hey! I’m new here.
    What’s wrong with the following code:

    #include

    int main()
    {
    int x;

    while(1)
    {
    scanf(“%d”,&x);

    if(x != 42)
    printf(“%d”,x);
    else
    break;
    }

    return 0;
    }

  49. somebody please tell me what is wrong with this code
    At submission time it said-“wrong answer”.

    import java.util.*;
    class Demo
    {
    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    int i,j,n;
    System.out.println(“enter the array lentgh”);
    n=sc.nextInt();
    int a[]=new int[n];
    System.out.println(“enter the numbers”);
    for(i=0;i<n;i++)
    {
    a[i]=sc.nextInt();
    }
    for(j=0;j<n;j++)
    {
    if(a[j]==42)
    {
    break;
    }
    System.out.println(a[j]);

    }
    }
    }

  50. what is problem in this code
    #include
    int main()
    {
    int num1[100],i,n,k;
    printf(“Enter no. of numbers you want”);
    scanf(“%d”,&n);
    printf(“Enter the numbers”);
    for(i=0;i<n;i++)
    {
    scanf("%d",&num1[i]);
    }
    for(k=0;k=0&&num1[k]<100)
    {
    if(num1[k]==42)
    break;
    else
    printf("n%d",num1[k]);
    }
    }
    return 0;
    }

  51. what is wrong with this code?
    #include
    using namespace std;

    int main() {
    int a;
    while(true){
    cin>>a;
    if(a!=42){
    cout<<a<<endl;
    } else {
    break;
    }
    }
    return 0;
    }

  52. #include
    #include
    void main()
    {
    int num[20];
    int i;
    printf(“Enter the numbers:”);
    for (i = 0; i < 5; ++i)
    {
    scanf("n%d",&num[i]);
    }
    printf("The output :n");

    for (i = 0; i < 5; ++i)
    {
    {
    if(num[i]==42) {
    break;
    }
    else
    {
    printf("%dn",num[i]);
    }
    }

    getch();
    }
    }

  53. #include

    int main(void) {

    int i,n;
    scanf(“%d”,&n);
    int arr[n];
    for(i=0;i<n;i++)
    scanf("%d",&arr[i]);

    for(i=0;i<n;i++)
    { if(arr[i]==42)
    break;
    printf("%d",arr[i]);
    printf("n");
    }

    return 0;
    }

  54. #include
    void main()
    {
    int i,a[20],n;
    printf(“Enter the no. of digits “);
    for(I=0;i<n;I++)
    {
    scanf("%d",&a[I]);
    if(i!=42)
    {
    printf("%d",a[I]);
    break;
    }
    }
    }

Leave a Reply