0

I am practising on an online compiler. I have to write the factorial program that, given a number n from STDIN, it prints out the factorial of n to STDOUT:

I have written this

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        int result=1;
        int fact = int.Parse(args[0]);
        
        if(fact==0)
        {
            Console.WriteLine(result);
        }
        else
        {
            for(int i=fact;i>=1;i--)
                result = i*result;
        }
        Console.WriteLine(result);
    }
}

I know in C, we use atoi. I also tried using simple Console.ReadLine() but it simply fails the test case.

Currently, I am getting the following error -

Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0 
Anonymous
  • 113
  • 1
  • 2
  • 13
  • 3
    To read a string from STDIN, call `Console.ReadLine()`. `args` are the command-line parameters passed to the executable. These are different things. – Matthew Watson Sep 15 '21 at 11:38
  • Either your program itself promts for user-input - which you'd achieve using `Console.ReadLine()`, or you put the args from **outside** into your program using the command-args. Seems like the latter case here, so you have to call your program using some args, e.g. `MyProgram 1 2 3 7 5345`. – MakePeaceGreatAgain Sep 15 '21 at 11:44
  • 1
    [What is "args" in Main class for?](https://stackoverflow.com/questions/552796/what-is-string-args-in-main-class-for) - [C# Console receive input with pipe](https://stackoverflow.com/questions/199528/c-sharp-console-receive-input-with-pipe) – gunr2171 Sep 15 '21 at 11:50

0 Answers0