Recommended reading:
Stanek, William R 2004. Microsoft Windows
Command-Line Administrator's Pocket Consultant. Microsoft Press.
[Stanek, William R 2005. Microsoft Windows parancssor.
A rendszergazda zsebkönyve. Bicske: Szak K.]
2nd Edition: Microsoft Press, 2008.⇒
command line interface (desktops, laptops)
We can use a script language in MS DOS batch (.bat) files. A batch file contains a set of DOS commands that can be executed sequentially by the OS in a command prompt window (CMD.EXE). The simplest way to create batch files is to use the Notepad.
The syntax of the script language can be described in the BNF (Backus-Naur Form) metalanguage or its extended form. It uses the following symbols:
- ::=
- abc
- <...>
- [...]
- {...|...}
- ...
Batch files behaves like they were DOS commands. We can run batch files or issue DOS commands separately in a command prompt (CMD) window. In the CMD window the previously issued commands can always be recalled and edited by pressing the up (↑) and down (↓) arrows in the keyboard. Pressing the 'Esc' key erases the command line.
- some commands are internal (built into COMMAND.COM; note that the former 16-bit DOS commands are not available on 64-bit editions of MS Windows)
- some commands can be considered as external commands stored on disk, mostly in the c:\windows\system32 folder (e.g. ping, tracert, ipconfig etc.; notepad, mspaint etc.)
The operation of the DOS commands can be modified by various switches which follow the commands after a slash (/) character. The DOS commands contain a built-in help which can be be activated by using the /? switch (e.g. dir /?; note that 'help dir' can also be used). The 'help >help.txt' command can be especially useful because it lists the available internal DOS commands (in this case redirected into the help.txt file).
DOS and OS commands I.
Basic DOS and OS commands:
- help
- cls
- dir
- dir "c:\Program Files"
- dir ..\p*
- dir *.txt
- tree
- cd xyz
- md xyz
- ren xyz pqr
- rd xyz
- copy or xcopy
- copy abc.txt xyz
- xcopy xyz uwz
- copy *.txt all.txt
- copy /b *.mpg all.mpg
- copy con abc.txt
- (enter text)
- CTRL Z (Enter)
- copy abc.txt con
- ren abc.txt uvz.txt
- del
- move
- type abc.txt
- type abc.txt | more
(you can always break the execution by the CTRL C hotkey combination)- type abc.txt | sort
- type abc.txt | sort /r
(/r means sorting in reverse order)- type help.txt | find "DIR"
- type help.txt | find /i "dir"
- findstr
- findstr /is "hello" *.txt
- findstr /ims "h[ae]llo" *.txt
- fc temp1.txt temp2.txt
- comp /a/l temp1.txt temp2.txt
- attrib abc.txt
- attrib help.txt +r
- assoc
assoc | find ".txt"
Redirection of the standard input and output
The standard input (con, 0), the standard output (con, 1), and the standard error text output (2) can be redirected by the following operators:
- > or 1>
(redirection of the standard output; e.g. help >help.txt or type help.txt | find "DIR" 1>temp.txt)- >> or 1>>
(redirection of the standard output by appending the content of the output to the given file; e.g. type help.txt | find "TREE" >>temp.txt)- 2>
(redirection of the error text output; e.g. dir /b abc 2>errlog.txt; if 'abc' does not exist, 'errlog.txt' will contain the "File not found." message)
- type abc
echo %errorlevel%
(the system variable 'errorlevel' (or ERRORLEVEL) contains the error or return code of the previous command (it is usually 0 if the command has been executed normally); in this case, if the 'type' command fails then the value of 'errorlevel' will be 1)- |
(creating a pipe of two commands, i.e. redirecting the standard ouput of the first command to the standard input of the second command; e.g. type help.txt | find "DIR")- < or 0<
(redirection of the standard input; e.g. find "DIR" <help.txt or find /i "dir" 0<help.txt)Note that the 'nul' output will hide either the standard output or the standard error output (e.g. the command 'dir xxx.abc 2>nul' hides the 'File not found.' error message if the file 'xxx.abc' does not exist)
further reading:
SS64: Command redirection, Pipes etc.⇒
DOS and OS commands II.
DOS and OS commands to display or modify system information:
- ver
- winver
- path
(displaying current paths)- set
(displaying all environmental variables)
- set PATH=c:\temp;%PATH%
(adding 'c:\temp' to the paths; note that in case the current paths (i.e. %PATH%) contain a space, as in 'c:\Program Files\...', then we get an error message)- prompt $P$G
(note that the order of the parameters beginning with the $ sign is important)- title uvz
- ftype
(lists all registered file types and the executables that are associated with them, along with the switches and command line parameters which will be used when opening a given file)- color
- date
- time
- vol
- label
DOS and OS commands III.
Other DOS or OS commands:
- start cmd (or simply 'cmd')
- ...
- tasklist >tasklist.txt
- systeminfo >systeminfo.txt
- driverquery
- sc
- ...
- tar /?
- tar --help
(to get detailed help in Unix style)- ...
- ping dom.name
- tracert dom.name
- ipconfig
- ...
- exit
DOS and OS commands IV.
Various commands that can be used primarily in batch files
I. handling variables
- REM or ::
- @
- echo
- @echo off
- echo:
(displaying a new line)- echo %%1=%1
(displaying the first command-line parameter in %1=... format; note that there can be a maximum of nine such parameters from %1 to %9, and the %0 parameter corresponds to the name of the batch file where it is referred to)- shift
echo %%9=%9
(displaying the tenth command-line parameter)- set
- set i=Hello, World!
echo %i%
(note that variables are not case sensitive)- set cp=%cd% (assigning the current path to the 'cp' variable)
- set /p HELLO=
(the value of the 'HELLO' environmental variable can be entered using the keyboard)- set /p HELLO=<hello.txt
(the value of the 'HELLO' environmental variable is set from the first line of the file 'hello.txt')- set xxx=123456789
echo %xxx%
set x=%xxx:~0,3%
echo %x%
(the second 'echo' command displays only 3 characters of the content of the variable 'xxx' starting with the character at position 0 (that is, the result will be '123'); the result will be 'cde' because the position of the first character is 0; when the given number of characters is greater than the length of the string (or just the starting position is given), all characters will be displayed from the starting position)- set xxx="123456789"
echo %xxx%
set x=%xxx:~1,-1%
echo %x%
(the second 'echo' command displays the content of the variable 'xxx' omitting the first and the last characters (that is, the result will be '123456789'); the negative number shows the number of characters to be omitted from the right of the content)- set /a x=8 (only integers are allowed; both positive and negative numbers can be used; although the effect of the command 'set x=8' is the same but /A declares that the type of the variable 'x' is integer)
- set /a x=%x% + 1 (or x+=1)
- set /a x=%x% - 1 (or x-=1)
- set /a x=%x% * 2 (or x*=2)
- set /a x=%x% / 2 (or x/=2; note that 3/2 equals 1 etc.)
- set /a x=%x% % 2 (or x%=2; note that 7/2 equals 1 etc.)
- echo %x%
- set /a s=%~z1
echo the size of file '%1' is %s%
(assuming that %1 is the first command line parameter or argument (or that of a 'call' function) which points to an existing file)
- we can get other characteristics of a given file, e.g. the path name (%~f1), file name (%~n1), file extension (%~x1) etc.
II. control structures
- if ... else ...
- if EXIST hello.txt (
echo 'hello.txt' exists
del hello.txt
) else (
echo 'hello.txt' does not exist
)- if NOT EXIST "%1" (
echo file '%1' does not exist
) else (
echo file '%1' exists
)
(note that the parameter '%1' should be closed in parentheses in the condition of the 'if' statement)- if /i %1==hello (
echo the first command line parameter is 'hello'
goto :eof
)
echo the first parameter is not 'hello'
(note: instead of the operator == we can use the EQU, NEQ, LSS, LEQ, GTR, GEQ operators; /i (or /I) means 'hello' can be in either lowercase or in uppercase)- if "%1"=="" (
echo the first command line parameter is missing
goto :eof
)- @echo off
set a=Hello!
if NOT DEFINED a (
echo 'a' is not defined
) else (
echo %a%
)- set /a x=%1
set /a y=%2
if %x% LSS %y% (
echo %x%^<%y%
) else (
echo %x%^>^=%y%
)
(note that '^<', '^>' and '^=' are the escape sequences of '<', '>' and '=', respectively)- goto
- type %1
if NOT ERRORLEVEL 1 goto :cont
echo ERRORLEVEL=%ERRORLEVEL%
goto :eof
:cont
...- for ... in ... do⇒
- for %a in (*.txt) do @dir /b %a
- set list=1 2 3 4
for %%a in (%list%) do (
echo %%a
)
(note that '%%' is the escape sequence of '%')- for /L %%n in (0,1,5) do (
echo %%n
)
(the switch /L (or /l in lowercase) introduces a loop statement which initializes the loop variable %n with 0, sets the increment or step value in each loop to 1, and sets the last value of the loop variable to 5)- call proc1
- call :sub
...
:sub
...
exit /b
...- call :sub 1 2
...
:sub
echo %1
echo %2
...
exit /b
...- setlocal ... endlocal
- pause
Always be careful when you modify the value of variables within the 'if' or 'for' blocks. The modified values are hidden within the block and they become visible only outside the block. This "delayed" evaluation mechanism should always be taken into consideration.further reading:
Wikipedia: cmd.exe
Wikipedia: List of DOS commands
Tutorialspoint: Batch Script - Commands⇒
SS64: An A-Z Index of Windows CMD Commands⇒
Applications of the 'if' command in batch files
examine the first command line argument (firstpar.txt)
@echo off cls echo --- the previous value of 's' is s=%s% --- echo: if "%1"=="" ( echo missing command line parameter ^('%1'^) set s=null ) else ( echo first command line parameter: %1 if NOT EXIST "%1" ( echo the file '%1' does not exist set s=null ) else ( set /A s=%~z1 echo the size of '%1' in the 'if' block is s=%s% ) ) echo: echo --- the real size of '%1' is s=%s% ---
examine the default path and add new paths (exampath.txt)
@echo off IF EXIST temp.txt ( del temp.txt ) set x=c:\temp\gcc\bin; set x=c:\temp\jdk_22\bin;%x% set x=c:\Windows\Microsoft.NET\Framework64\v4.0.30319;%x% echo %x% PATH | find "gcc" >temp.txt call :sizeof temp.txt IF %size% LSS 10 ( set PATH=%x%;%PATH% ) path del temp.txt goto :eof :sizeof set size=%~z1 echo %size% exit /bNote that if the current path contains a special character (e.g. a space, as in 'Program Files') then the %PATH% reference will cause an error message.
Applications of the 'for' command in batch files I.
display the number of command line arguments (args.txt)
@echo off set /A a=0 for %%i in (%*) do ( echo %%i set /A a+=1 ) echo Number of arguments: %a%Although we have only nine default variables for the command line arguments (i.e. %1, %2, ..., %9) the args.bat batch program will list all the arguments.
another version of displaying the command line arguments (args1.txt)
@echo off set /A a=0 :cont if "%1"=="" goto :disp set /A a+=1 if %a% LEQ 9 ( echo %%%a%=%1 ) else ( echo ^<%%%a%^>=%1 ) shift goto :cont ) :disp echo Number of arguments: %a%
display the name of the files in the current directory (fnames.txt)
@echo off for %%f in (*) do ( echo %%f )
display the name and path of the directories (or folders) located in the C:\temp directory (dnames.txt)
@echo off for /R C:\temp /D %%n in (*) do ( echo %%n )Note that the recursive 'for' command without the /D switch
for /R C:\temp %n in (.) do echo %n
has almost the same effect (because '.' refers to itself in each directory).
display the name of all files that can be found in the directory tree starting from the current directory (tnames.txt)
@echo off set cp=%cd% set /A i=0 for %%f in (*) do ( echo %%f set /A i+=1 ) for /R /D %%n in (*) do ( cd %%n for %%f in (*) do ( echo %%f set /A i+=1 ) ) echo %i% file(s) listed cd %cp%
display the first three words of each line of a given text file (token.txt)
@echo off for /F "tokens=1-3* delims=,; " %%a in (%1) do ( echo %%a echo %%b echo %%c echo ...%%d )
Applications of the 'for' command in batch files II.
List the natural numbers from 1 to a specified number given by the first command line argument (numbers.txt).
@echo off if "%1"=="" goto error_1 set /a n=%1 if %n% GEQ 1 ( goto :cont ) else ( goto :error_2 ) :cont for /l %%i in (1,1,%n%) do ( echo %%i ) goto :eof :error_1 echo missing argument goto :eof :error_2 echo invalid or not a number (NaN) error
Now list 'n' elements of the Fibonacci sequence (fibonacci.txt).
@echo off if "%1"=="" goto error_1 set /a n=%1 if %n% GEQ 1 ( goto :cont ) else ( goto :error_2 ) :cont set /a s1=0 echo %s1% set /a s2=1 for /l %%i in (2,1,%n%) do ( call :subroutine ) rem be careful with assignment sentences in the loop :-( goto :eof :error_1 echo missing argument goto :eof :error_2 echo invalid or not a number (NaN) error goto :eof :subroutine echo %s2% set /a t1=%s1% set /a t2=%s2% set /a s2=%t1%+%t2% set /a s1=%t2% exit /b
The assignment sentences within the loop are executed only after the 'for' statement has been finished. Therefore the 'echo' commands can display the previously assigned values of the variables (i.e. their modified values cannot be temporarily accessed). Run this batch file and analyse the problem (errpow.txt):
@echo off set /A %a=1 set /A %n=0 for /L %%x in (1,1,5) do ( echo 2 raised to %n% equals %a% set /A n=%%x set /A a*=2 ) echo ----------------------- echo 2 raised to %n% equals %a%Using the 'call' command inside the 'for' loop, we could modify the above batch program to display the powers of 2 correctly (errpow1.txt):
@echo off set /A %a=1 set /A %n=0 for /L %%x in (1,1,5) do ( call :pow2 %%x ) echo ----------------------- echo 2 raised to %n% equals %a% goto :eof :pow2 echo 2 raised to %n% equals %a% set /A n=%1 set /A a*=2 exit /bfurther reading:
Wikipedia: Fibonacci sequence
Applications of the command line interface I. – Say 'Hello'
(1) First, as a short reminder, let us display "Hello, World!" using a batch file (hellob.txt):
@echo off echo Hello, World!We can give a name as a command line argument as well (helloa.txt):
@echo off set name=Anonymous if "%1" NEQ "" ( set name=%1 ) echo Hello, %name%!Finally, ask for a name, and say 'Hello' to him or her (helloh.txt):
@echo off echo What is your name? set /p name= echo Hello, %name%!
Download the GNU gcc C/C++ compiler (e.g. the latest version of gcc-win64 from SourceForge). Then copy the files and folders into the c:\temp\gcc directory.
Create the 'compileC.bat' file as follows (compileC.txt):
@echo off c:\temp\gcc\bin\gcc %1.c -o %1Create the 'hello.c' file which writes the well-known message of 'Hello, World!' after the command prompt (hello.c).
#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }Open the command line window (cmd.exe), compile 'hello.c', correct the errors (if any), and then run the created 'hello.exe' file.
Create the 'args.c' file which lists the command line arguments in a console (cmd) window (args.c).
#include <stdio.h> int main(int argc, char *argv[]) { int i; for(i=0; i<argc; i++) { printf("%d. parameter: %s\n", i, argv[i]); } return 0; }Open the command line window (cmd.exe), compile 'args.c', correct the errors (if any), and then run the created 'args.exe' file with some command line parameters.
In the C language the 0th command line parameter always exists and contains the name of the source file (e.g. args in this case). Accordingly, the size or length of the array 'argv' is one larger than the number of command line parameters.
Create the 'hellon.c' file which lists the command line arguments in a console (cmd) window (hellon.c).
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { char s[128]="Anonymous"; if(argc>1) { strcpy(s,argv[1]); } printf("Hello, %s!",s); return 0; }Open the command line window (cmd.exe), compile 'hellon.c', correct the errors (if any), and then run the created 'hellon.exe' file with one command line parameter that represents your name.
Create the 'hellox.c' file which reads your name and then displays a welcome message of 'Hello, ...!' after the command prompt (hellox.c).
#include <stdio.h> int main() { char s[128]=""; /* max. 128 chars */ printf("Your name: "); gets(s); /* also try this: scanf("%s",s); */ printf("Hello, %s!",s); return 0; }Open the command line window (cmd.exe), compile 'hellox.c', and run the 'hellox.exe' file.
further reading:
Wikipedia: GNU Compiler Collection
Applications of the command line interface II. – Say 'Hello' in C#
We can easily create the 'setpath.bat' file which sets the path of the MS C# compiler located in the .NET Framework:
@echo off set PATH=c:\Windows\Microsoft.NET\Framework64\v4.0.30319;%PATH%In the following, we will use three compilers: the 'gcc.exe' for the C language, the 'csc.exe' for the C# language, and the 'javac.exe' (together with the 'java.exe' JVM) for the Java language. The easiest way to use them is to set the default search path so that we can have access to each of the compilers.Let us add two more paths to the 'setpath.bat' file which set the paths of the C and Java compilers as well (setpath.txt):
@echo off set x=c:\temp\gcc\bin set x=c:\Windows\Microsoft.NET\Framework64\v4.0.30319;%x% set x=c:\temp\jdk-22\bin;%x% set PATH=%x%;%PATH% echo new path: PATHNote that after downloading the setpath.txt file it should be renamed to setpath.bat.
Create the 'HelloWorld.cs' file written in C# language (HelloWorld.cs):
namespace Hello { class HelloWorld { static void Main(string[] args) { System.Console.WriteLine("Hello, World!"); } } }Open the command line window (cmd.exe), and then run the 'csc.exe' file by compiling the 'HelloWorld.cs' file (csc HelloWorld.cs). Correct the errors (if any), then run the created 'HelloWorld.exe' file.
Create the 'ArgsList.cs' file which lists the command line parameters (ArgsList.cs).
using System; namespace Hello { class ArgsList { static void Main(string[] args) { for(int i=0; i<args.Length; i++) { Console.WriteLine(args[i]); } } } }Open the command line window (cmd.exe), compile 'ArgsList.cs', and run the created 'Argslist.exe' file with or without command line parameters.
Create the 'HelloWorldn.cs' file which accepts your name as a command line parameter and then displays a welcome message of 'Hello, ...!' after the command prompt (HelloWorldn.cs).
using System; namespace Hello { class HelloWorldn { static void Main(string[] args) { string name="Anonymous"; if(args.Length>0) { name=args[0]; } Console.WriteLine(String.Format("Hello, {0}!",name)); } } }Open the command line window (cmd.exe), compile 'HelloWorldn.cs', and run the created 'HelloWorldn.exe' file with and without giving your name as a command line parameter.
Create the 'HelloWorldx.cs' file which reads your name and then displays a welcome message of 'Hello, ...!' after the command prompt (HelloWorldx.cs).
using System; namespace Hello { class HelloWorldx { static void Main(string[] args) { string name; Console.WriteLine("Who are you?"); name=Console.ReadLine(); if(name.Length==0) { name="Anonymous"; } Console.WriteLine(String.Format("Hello, {0}!",name)); } } }Open the command line window (cmd.exe), compile 'HelloWorldx.cs', and run the created 'HelloWorldx.exe' file.
Applications of the command line interface III – Say 'Hello' in Java
Download the newest Java JDK for Windows (e.g. the jdk-22_windows-x64_bin.zip compressed file from the Oracle website). Then copy the files and folders into the c:\temp\jdk-22 directory.
One way to compile and run a Java program is to create the compileJ.bat batch file which first try to compile the given Java program and, if it is successful, then runs the compiled '.class' file (with a maximum of five command line arguments).
@echo off c:\temp\jdk-22\bin\javac %1.java c:\temp\jdk-22\bin\java %1 %2 %3 %4 %5Another way to compile and run a Java program, which is strongly recommended, is to run the setpath.bat batch file first, and then enter two commands after the command prompt:
C:\...> javac Filename.java
C:\...> java FilenameNow create the Hello.java file which writes the well-known message of 'Hello, World!' after the command prompt (Hello.java):
public class Hello { public static void main(String[] args) { System.out.println("Hello, World!"); } }Note that the file name (Hello) and the class name (Hello) are the same.
In Java the name of the .java source file must always match the class name.Open the command line window (cmd.exe), set the default paths (→ setpath.bat; it has to be run only once), compile (→ javac Hello.java), and, if it is successful, then run (→ java Hello) the Hello.java file.
Create the Args.java file which lists the command line parameters (Args.java):
public class Args { public static void main(String[] args) { for(int i=0; i<args.length; i++) { System.out.println(args[i]); } } }Open the command line window (cmd.exe), and then compile and run the Args.java file by giving some command line parameters to test the program.
Create the HelloArg.java file which lists the command line parameters (HelloArg.java):
public class HelloArg { public static void kiir(String s) { System.out.println(s); } public static void kiir(int[] sz) { for(int i=0;i<sz.length;i++) { System.out.println(sz[i]); } } public static void main(String[] args) { if(args.length==0) { kiir("Missing parameter"); System.exit(1); // set errorlevel=1 } else { kiir("Hello, "+args[0]+"!"); System.exit(0); // set errorlevel=0 } } }Open the command line window (cmd.exe), and then compile and run the HelloArg.java file with or without some command line parameters to test the program. Note that running the HelloArg.java program without command line parameters involves to set the value of the 'errorlevel' variable to 1.
Create the 'Hellon.java' file which accepts your name as a command line parameter and then displays a welcome message of 'Hello, ...!' after the command prompt (Hellon.java):
public class Hellon { public static void main(String[] args) { String name="Anonymous"; if(args.length>0) { name=args[0]; } System.out.println("Hello, "+name+"!"); } }Open the command line window (cmd.exe), and then compile and run the Hellon.java file with or without giving your name as a command line parameter.
Create the 'Hellox.java' file which reads your name and then displays a welcome message of 'Hello, ...!' after the command prompt (Hellox.java):
import java.io.*; public class Hellox { public static void main(String[] args) throws IOException { String name; LineNumberReader in=new LineNumberReader( new BufferedReader( new InputStreamReader( System.in))); System.out.println("Who are you?"); name=in.readLine(); if(name.length()==0) { name="Anonymous"; } System.out.println("Hello, "+name+"!"); } }Open the command line window (cmd.exe), and then compile and run the Hellox.java file.
Note that the 'LineNumberReader' class can be useful if we want to use the in.getLineNumber() method to count the number of reads. For example, create the 'Helloy.java' file which reads your name again, if you did not enter a real name (Helloy.java):
import java.io.*; public class Hellox { public static void main(String[] args) throws IOException { String name; LineNumberReader in=new LineNumberReader( new BufferedReader( new InputStreamReader( System.in))); System.out.println("Who are you?"); name=in.readLine(); for(int i=1;i<=3;i++) { if(name.length()>0) { break; } System.out.println("I ask you again ("+ in.getLineNumber()+ "), who are you?"); name=in.readLine(); } if(name.length()==0) { name="Anonymous"; } System.out.println("Hello, "+name+"!"); } }Open the command line window (cmd.exe), and then compile and run the Helloy.java file.
Applications of the command line interface IV – List the elements of a series of numbers
Let sn denote the series of 'n' natural numbers (1, 2, ..., n). Enter the number of elements as a command line parameter and list the elements of the series by a C program (numa.c).
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i,s; int n=0; if(argc>1) { n=atoi(argv[1]); } if(n<1) { n=10; printf("The command line argument is invalid. Let n=%d.\n", n); } s=1; for(i=1; i<=n; i++) { printf("%d. element: %d\n", i, s); s=s+1; } return 0; }Now enter the number of the elements from the keyboard (numb.c).
#include <stdio.h> int main(int argc, char *argv[]) { int i,s; int n=0; printf("Write a number: "); i=scanf("%d",&n); if(n<1 || i<1) { n=10; printf("The number is invalid (return code: %d). Let n=%d.\n", i, n); } s=1; for(i=1; i<=n; i++) { printf("%d. element: %d\n", i, s); s=s+1; } return 0; }Compile and run the created executable files.
Let sn denote again the series of 'n' natural numbers (1, 2, ..., n). Enter the number of elements as a command line parameter and list the elements of the series by a C# program (NumArg.cs).
using System; namespace Hello { class NumArg { static void Main(string[] args) { int s; int n=0; bool b=true; if(args.Length>0) { b=int.TryParse(args[0], out n); } if(n<1 || !b) { n=10; Console.WriteLine(String.Format("The command line argument is invalid. Let n={0}.", n)); } s=1; for(int i=1; i<=n; i++) { Console.WriteLine(String.Format("{0}. element: {1}", i, s)); s=s+1; } } } }Note that the 'out' keyword in the int.TryParse(...) method results in an output parameter (that is, after 'out n' the result of the conversion will be stored in the given variable 'n').
Now enter the number of the elements from the keyboard and lists the elements of the series by a C# program (NumInp.cs).
using System; namespace Hello { class NumImp { static void Main(string[] args) { int s; int n=0; bool b=true; string ns; Console.WriteLine("Write a number: "); ns=Console.ReadLine(); b=int.TryParse(ns, out n); if(n<1 || !b) { n=10; Console.WriteLine(String.Format("The input is invalid. Let n={0}.", n)); } s=1; for(int i=1; i<=n; i++) { Console.WriteLine(String.Format("{0}. element: {1}", i, s)); s=s+1; } } } }Compile and run the created executable files.
Let sn denote again the series of 'n' natural numbers (1, 2, ..., n). Enter the number of elements as a command line parameter and list the elements of the series by a Java program (NumArg.java).
public class NumArg { public static void main(String[] args) { int s; int n=0; boolean b=true; if(args.length>0) { try { n=Integer.parseInt(args[0]); } catch(NumberFormatException ex) { n=0; } } if(n<1) { n=10; System.out.println("The command line argument is invalid. Let n="+n+"."); } s=1; for(int i=1; i<=n; i++) { System.out.println(i+". element: "+s); s=s+1; } } }Now enter the number of the elements from the keyboard and lists the elements of the series by a Java program (NumInp.java).
import java.io.*; public class NumInp { public static void main(String[] args) throws IOException { int s; int n=0; String ns; BufferedReader in=new BufferedReader( new InputStreamReader( System.in)); System.out.print("Write a number: "); ns=in.readLine(); try { n=Integer.parseInt(ns); } catch(NumberFormatException ex) { n=0; } if(n<1) { n=10; System.out.println("The input is invalid. Let n="+n+"."); } s=1; for(int i=1; i<=n; i++) { System.out.println(i+". element: "+s); s=s+1; } } }Compile and run the created class files.
Applications of the command line interface V – List the elements of the Fibonacci series
Previously we created a batch program that displayed the elements of the Fibonacci series.⇒ Now we shall create a C, Java and C# programs to do the same task.
Let sn denote the Fibonacci series (0, 1, 1, 2, 3, 5, 8, ...). Enter the number of the elements to be displayed as a command line parameter and list the elements of the series by a C program (fib.c).
#include <stdio.h> #include <stdlib.h> int s1,s2; void sub() { int t1,t2; printf("%d\n", s2); t1=s1; t2=s2; s2=t1+t2; s1=t2; } int main(int argc, char *argv[]) { int i; int n=0; if(argc>1) { n=atoi(argv[1]); } if(n<1) { n=10; printf("The command line argument is invalid. Let n=%d.\n", n); } else { printf("First %d elements of the Fibonacci series:\n", n); } s1=0; printf("%d\n", s1); s2=1; for(i=2; i<=n; i++) { sub(); } return 0; }Compile and run the created executable file.
Let sn denote again the Fibonacci series (0, 1, 1, 2, 3, 5, 8, ...). Enter the number of the elements to be displayed as a command line parameter and list the elements of the series by a Java program (Fibonacci.java).
public class Fibonacci { private static int s1,s2; private static void sub() { int t1,t2; System.out.println(s2); t1=s1; t2=s2; s2=t1+t2; s1=t2; } public static void main(String[] args) { int n=0; boolean b=true; if(args.length>0) { try { n=Integer.parseInt(args[0]); } catch(NumberFormatException ex) { n=0; } } if(n<1) { n=10; System.out.println("The command line argument is invalid. Let n="+n+"."); } s1=0; System.out.println(s1); s2=1; for(int i=2; i<=n; i++) { sub(); } } }Compile and run the created class file.
Let sn denote again the Fibonacci series (0, 1, 1, 2, 3, 5, 8, ...). Enter the number of the elements to be displayed from keyboard and list the elements of the series by a C# program (Fibonacci.cs).
using System; namespace Hello { class Fibonacci { private static int s1,s2; private static void sub() { int t1,t2; Console.WriteLine(s2); t1=s1; t2=s2; s2=t1+t2; s1=t2; } static void Main(string[] args) { int n=0; bool b=true; string ns; Console.WriteLine("Write a number: "); ns=Console.ReadLine(); b=int.TryParse(ns, out n); if(n<1 || !b) { n=10; Console.WriteLine(String.Format("The input is invalid. Let n={0}.", n)); } else { Console.WriteLine("-----"); } s1=0; Console.WriteLine(s1); s2=1; for(int i=2; i<=n; i++) { sub(); } } } }Now compile and run the created executable file.