SlideShare a Scribd company logo
What is the general format for a Try-Catch block? Assume that
amt l and amt 2 are integers which have some values in them.
Write a try-catch block that will try to divide amt I by amt 2
and put the result into a variable named quotient. If an
Arithmetic Exception occurs, print a message saying "Invalid
data" and set quotient to 0. What are command line arguments
and how can the program access them? Write a program that
will accept a list of strings as command line arguments. It will
step through these strings, convert each one to an integer and
add them to a total. Finally, it will print the total. Write some
instructions that will write an error message if there are no
command line arguments for a program.
Solution
1 answer:
The catch Blocks
You associate exception handlers with a try block by providing
one or more catch blocks directly after the try block. No code
can be between the end of the try block and the beginning of the
first catch block.
Each catch block is an exception handler that handles the type
of exception indicated by its argument. The argument type,
ExceptionType, declares the type of exception that the handler
can handle and must be the name of a class that inherits from
the Throwable class. The handler can refer to the excepti on with
name.
The catch block contains code that is executed if and when the
exception handler is invoked. The runtime system invokes the
exception handler when the handler is the first one in the call
stack whose ExceptionType matches the type of the exception
thrown. The system considers it a match if the thrown object
can legally be assigned to the exception handler's argument.
Example::
2answer
3answer:
Like UNIX commands, shell scripts also accept arguments from
the command line.
They can, therefore, run non interactively and be used with
redirection and
pipelines.
Positional Parameters:
Arguments are passed from the command line into a shell
program using the
positional parameters $1 through to $9. Each parameter
corresponds to the
position of the argument on the command line.
The first argument is read by the shell into the parameter $1,
The second
argument into $2, and so on. After $9, the arguments must be
enclosed in
brackets, for example, ${10}, ${11}, ${12}.Some shells
doesn't support this
method. In that case, to refer to parameters with numbers
greater than 9, use
the shift command; this shifts the parameter list to the left. $1
is lost,while
$2 becomes $1, $3 becomes $2, and so on. The inaccessible
tenth parameter
becomes $9 and can then be referred to.
Example:
#!/bin/bash
# Call this script with at least 3 parameters, for example
# sh scriptname 1 2 3
echo "first parameter is $1"
echo "Second parameter is $2"
echo "Third parameter is $3"
exit 0
Output:
[root@localhost ~]# sh parameters.sh 47 9 34
first parameter is 47
Second parameter is 9
Third parameter is 34
[root@localhost ~]# sh parameters.sh 4 8 3
first parameter is 4
Second parameter is 8
Third parameter is 3
In addition to these positional parameters, there are a few other
special
parameters used by shell.Their significance is noted bellow.
$* - It stores the complete set of positional parameters as a
single string.
$@ - Same as $*, But there is subtle difference when enclosed
in double quotes.
$# - It is set to the number of arguments specified.This lets you
design scripts
that check whether the right number of arguments have been
entered.
$0 - Refers to the name of the script itself.
Setting Values of Positional Parameters
You can't technically call positional parameters as shell
variables because all
variable names start with a letter. For instance you can't assign
values to $1,
$2.. etc. $1=100 or $2=venu is simply not done. There is one
more way to assign
values to the positional parameters, using the set command.
$ set Helping hands are holier than praying lips
The above command sets the value $1 with “Helping” , $2 with
“hands” and so on.
To verify, use echo statement to display their values.
$ echo $1 $2 $3 $4 $5 $6 $7
Helping hands are holier than praying lips
You can simply use $* or $@
$ echo $*
Helping hands are holier than praying lips
$ echo $@
Helping hands are holier than praying lips
Using Shift on Positional Parameters
We have used set command to set upto 9 words. But we can use
it for more.
$ set A friend who helps when one is in trouble is a real friend
$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11
A friend who helps when one is in trouble A0 A1
Observe that last two words in the output. These occurred in
the output because
at a time we can access only 9 positional parameters. When we
tried to refer to
$10 it was interpreted by the shell as if you wanted to out put
the value of $1
and a 0. Hence we got A0 in the output.
Does that mean the words following the ninth word have been
lost? No. If not,
then where have they gone?. They are very much there, safe
with the shell But to
reach them we must do the following.
$shift 4
$ echo $1 $2 $3 $4 $5 $6 $7 $8 $9
when one is in trouble is a real friend
Now where have the first seven words gone? They have been
shifted out.The first
four words lost for ever, as we did not take the precaution to
store them else-
where. What should we have done is:
$ set A friend who helps when one is in trouble is a real friend
$ a=$1
$ b=$2
$ c=$3
$ d=$4
$ shift 4
$ echo $a $b $c $d $1 $2 $3 $4 $5 $6 $7 $8 $9
A friend who helps when one is in trouble is a real friend
Note:In the Korn and bash shells you can refer directly to
arguments where
n is greater than 9 using braces. For example, to refer to the
57th positional
parameter, use the notation ${57}.some shells may not support
this method.
$ set A friend who helps when one is in trouble is a real friend
$ echo ${12}
real
$ echo ${13}
friend
Bracket notation for positional parameters leads to a fairly
simple way of
referencing the last argument passed to a script on the
command line.
$ echo ${!#}
friend
$* and $@
Let us look at the subtle difference between $* and $@.
First create three files fileA, fileB, “file temp”
cat > fileA
I LOVE INDIA
Ctrl+d
cat > fileB
HELLO WORLD
Ctrl+d
cat > temp file
This file name contains blank space
Ctrl+d
Example:
#!/bin/bash
# Usage: sh arguments.sh fileA fileB temp file
echo -e "033[1mDisplay files content using $* 033[0m"
cat $*
echo -e "033[1mDisplay files content using $@ 033[0m"
cat $@
exit 0
Run the script with file names as arguments.
Output:
[root@localhost ~]# sh arguments.sh fileA fileB temp file
Display files content using $*
I LOVE INDIA
HELLO WORLD
cat: temp: No such file or directory
cat: file: No such file or directory
Display files content using $@
I LOVE INDIA
HELLO WORLD
cat: temp: No such file or directory
cat: file: No such file or directory
So there is no difference between cat $* and cat $@.
Modify arguments.sh script as
#!/bin/bash
# Usage: sh arguments.sh fileA fileB temp file
echo -e "033[1mDisplay files content using "$*"
033[0m"
cat "$*"
echo -e "033[1mDisplay files content using "$@"
033[0m"
cat "$@"
exit 0
Now again run the script with file names as arguments.
Output:
[root@localhost ~]# sh arguments.sh fileA fileB temp file
Display files content using "$*"
cat: fileA fileB temp file: No such file or directory
Display files content using "$@"
I LOVE INDIA
HELLO WORLD
This file name contain blank space
Now there is a difference, the two cat commands would
become:
cat “fileA fileB temp file”
cat fileA fileB 'temp file'
On execution, the first of these commands would give an error
since there does
not exist a file with the name “fileA fileB temp file”. As
against this, the
second cat command would display the contents of the files
fileA, fileB and
“temp file”. So what you observed ,when not enclosed within
"double quotes"
$* and $@ behaves exactly similarly, and when enclosed in
"double quotes" there
is a subtle difference.
Purpose of command line arguments
This is instead of having a dialog with the user such as:
How to use command line arguments
To use command line arguments, we use a different first line of
the main program:
Instead of:
int main()
we use:
int main(int argc, char *argv[])
Examples:
command line
argc
argv[0]
argv[1]
argv[2]
argv[3]
argv[4]
argv[5]
argv[6]
Converting command line arguments to int or double values
When accessing command line arguments that are integers or
floating-point numbers, we typically need to use atoi() or atof().
For example consider the code listed below, especially the part
in bold
(the full program is available at raiseToPower.c):
4.answer
When accessing command line arguments that are integers or
floating-point numbers, we typically need to use atoi() or atof().
#include <iostream>
#include <cstdlib>
int main(int argc, char **argv)
{
double sum=0;
int i=0;
if(argc>1)
{
for(i=1;i<argc;i++)
/* Conversion string into int by using atoi command*/
sum+= atoi(argv[i]);
std::cout<< "The sum is " << sum;
}
else
std::cout<< “arguments supplied”;
}
In c:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int i=0;
int sum=0;
printf(" cmdline args count=%d", argc);
/* First argument is executable name only */
printf(" exe name=%s", argv[0]);
for (i=1; i< argc; i++)
{
printf(" arg%d=%s", i, argv[i]);
/* Conversion string into int */
sum = sum+atoi(argv[i]);
printf(" sum is=%d",sum);
}
return 0;
}
5answer:
Command line arguments:
Command line arguments allow us to provide input to a C
program through the command line.
For example, instead of typing
./gameScore
to run the program foo.c, we type:
./gameScore Steelers 30 Dolphins 20
and the values "Steelers" "30" "Dolphins" and "20" will
be available inside the C program—we don't have to use scanf
to prompt for them.
Here's how it works:
Purpose of command line arguments
-bash-3.2$ ./areaOfSquare 3
The area is 9
-bash-3.2$
This is instead of having a dialog with the user such as:
-bash-3.2$ ./areaOfSquare
Please enter the value of one side of the square: 3
The area is 9
-bash-3.2$
How to use command line arguments
To use command line arguments, we use a different first line of
the main program:
Instead of:
int main()
we use:
int main(int argc, char *argv[])
Checking argc before accessing argv
If we have defined argc and argv by putting int main(int argc,
char *argv[]) as the first line of our main, then argc is always at
least 1, and argv[0] always exists and is the name of the
program (as typed on the Unix command line.)
However, argv[1], argv[2], don't necessarily exist, unless there
are sufficient items on the command line.
So, before accessing the value of argv[1], argv[2], etc. it is
necessary to always first check the value of argc.
command line
argc
argv[0]
argv[1]
argv[2]
argv[3]
argv[4]
argv[5]
argv[6]

More Related Content

PPTX
Shell scripting
PPT
1 4 sp
PDF
Bash production guide
PDF
Shell Script
PPT
390aLecture05_12sp.ppt
PPT
Shell Scripting
PDF
Unix shell scripting tutorial
PPT
Shell scripting
1 4 sp
Bash production guide
Shell Script
390aLecture05_12sp.ppt
Shell Scripting
Unix shell scripting tutorial

Similar to What is the general format for a Try-Catch block Assume that amt l .docx (20)

PPTX
Chapter 2: Introduction to Bash Scripting
PPT
Unix And Shell Scripting
PPTX
Introduction to shell
PPT
Spsl by sasidhar 3 unit
PPTX
shellScriptAlt.pptx
PPTX
Linux System Administration
PDF
Shell Programming_Module2_Part2.pptx.pdf
PPT
Shell programming
PPT
34-shell-programming asda asda asd asd.ppt
PDF
Shell scripting1232232312312312312312312
PDF
Shell-Scripting-1.pdf
PDF
Unix Shell Scripting
PDF
Essential Techniques for Mastering Command Line Arguments in C From NareshIT.pdf
PPTX
Shell Scripting and Programming.pptx
PPTX
Shell Scripting and Programming.pptx
PPTX
Hxjd djdidjdjdLBQ-Udemydhdudje dhdudb.pptx
PPTX
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
PPT
ShellProgramming and Script in operating system
PPTX
Unix - Shell Scripts
PPTX
Productive bash
Chapter 2: Introduction to Bash Scripting
Unix And Shell Scripting
Introduction to shell
Spsl by sasidhar 3 unit
shellScriptAlt.pptx
Linux System Administration
Shell Programming_Module2_Part2.pptx.pdf
Shell programming
34-shell-programming asda asda asd asd.ppt
Shell scripting1232232312312312312312312
Shell-Scripting-1.pdf
Unix Shell Scripting
Essential Techniques for Mastering Command Line Arguments in C From NareshIT.pdf
Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptx
Hxjd djdidjdjdLBQ-Udemydhdudje dhdudb.pptx
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
ShellProgramming and Script in operating system
Unix - Shell Scripts
Productive bash

More from ajoy21 (20)

DOCX
Please complete the assignment listed below.Define and explain, us.docx
DOCX
Please cite sources for each question. Do not use the same sources f.docx
DOCX
Please choose one of the following questions to answer for this week.docx
DOCX
Please check the attachment for my paper.Please add citations to a.docx
DOCX
Please answer to this discussion post. No less than 150 words. Refer.docx
DOCX
Please attach Non-nursing theorist summaries.JigsawExecutive .docx
DOCX
Please answer the question .There is no work count. PLEASE NUMBER .docx
DOCX
Please answer the following questions. Please cite your references..docx
DOCX
Please answer the following questions.1.      1.  Are you or.docx
DOCX
Please answer the following question with 200-300 words.Q. Discu.docx
DOCX
Please answer the following question Why do you think the US ha.docx
DOCX
Please answer the following questions. Define tunneling in the V.docx
DOCX
Please answer the following questions1. How can you stimulate the.docx
DOCX
Please answer the following questions very deeply and presicely .docx
DOCX
Please answer the following questions in an informal 1 ½ - 2-page es.docx
DOCX
Please answer the following questions in a response of 150 to 200 wo.docx
DOCX
Please answer these questions regarding the (TILA) Truth in Lending .docx
DOCX
Please answer the following question pertaining to psychology. Inc.docx
DOCX
Please answer the following questions in a response of 250 to 300 .docx
DOCX
Please answer the three questions completly. I have attached the que.docx
Please complete the assignment listed below.Define and explain, us.docx
Please cite sources for each question. Do not use the same sources f.docx
Please choose one of the following questions to answer for this week.docx
Please check the attachment for my paper.Please add citations to a.docx
Please answer to this discussion post. No less than 150 words. Refer.docx
Please attach Non-nursing theorist summaries.JigsawExecutive .docx
Please answer the question .There is no work count. PLEASE NUMBER .docx
Please answer the following questions. Please cite your references..docx
Please answer the following questions.1.      1.  Are you or.docx
Please answer the following question with 200-300 words.Q. Discu.docx
Please answer the following question Why do you think the US ha.docx
Please answer the following questions. Define tunneling in the V.docx
Please answer the following questions1. How can you stimulate the.docx
Please answer the following questions very deeply and presicely .docx
Please answer the following questions in an informal 1 ½ - 2-page es.docx
Please answer the following questions in a response of 150 to 200 wo.docx
Please answer these questions regarding the (TILA) Truth in Lending .docx
Please answer the following question pertaining to psychology. Inc.docx
Please answer the following questions in a response of 250 to 300 .docx
Please answer the three questions completly. I have attached the que.docx

Recently uploaded (20)

PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PPTX
History, Philosophy and sociology of education (1).pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PPTX
Introduction to Building Materials
PDF
Hazard Identification & Risk Assessment .pdf
PPTX
Virtual and Augmented Reality in Current Scenario
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
20th Century Theater, Methods, History.pptx
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
B.Sc. DS Unit 2 Software Engineering.pptx
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
David L Page_DCI Research Study Journey_how Methodology can inform one's prac...
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
History, Philosophy and sociology of education (1).pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Introduction to Building Materials
Hazard Identification & Risk Assessment .pdf
Virtual and Augmented Reality in Current Scenario
TNA_Presentation-1-Final(SAVE)) (1).pptx
Share_Module_2_Power_conflict_and_negotiation.pptx
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
20th Century Theater, Methods, History.pptx
Unit 4 Computer Architecture Multicore Processor.pptx
Computing-Curriculum for Schools in Ghana
FORM 1 BIOLOGY MIND MAPS and their schemes

What is the general format for a Try-Catch block Assume that amt l .docx

  • 1. What is the general format for a Try-Catch block? Assume that amt l and amt 2 are integers which have some values in them. Write a try-catch block that will try to divide amt I by amt 2 and put the result into a variable named quotient. If an Arithmetic Exception occurs, print a message saying "Invalid data" and set quotient to 0. What are command line arguments and how can the program access them? Write a program that will accept a list of strings as command line arguments. It will step through these strings, convert each one to an integer and add them to a total. Finally, it will print the total. Write some instructions that will write an error message if there are no command line arguments for a program. Solution 1 answer: The catch Blocks You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block. Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the excepti on with
  • 2. name. The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument. Example:: 2answer 3answer: Like UNIX commands, shell scripts also accept arguments from the command line. They can, therefore, run non interactively and be used with redirection and pipelines. Positional Parameters: Arguments are passed from the command line into a shell program using the positional parameters $1 through to $9. Each parameter corresponds to the position of the argument on the command line. The first argument is read by the shell into the parameter $1,
  • 3. The second argument into $2, and so on. After $9, the arguments must be enclosed in brackets, for example, ${10}, ${11}, ${12}.Some shells doesn't support this method. In that case, to refer to parameters with numbers greater than 9, use the shift command; this shifts the parameter list to the left. $1 is lost,while $2 becomes $1, $3 becomes $2, and so on. The inaccessible tenth parameter becomes $9 and can then be referred to. Example: #!/bin/bash # Call this script with at least 3 parameters, for example # sh scriptname 1 2 3 echo "first parameter is $1" echo "Second parameter is $2" echo "Third parameter is $3"
  • 4. exit 0 Output: [root@localhost ~]# sh parameters.sh 47 9 34 first parameter is 47 Second parameter is 9 Third parameter is 34 [root@localhost ~]# sh parameters.sh 4 8 3 first parameter is 4 Second parameter is 8 Third parameter is 3 In addition to these positional parameters, there are a few other special parameters used by shell.Their significance is noted bellow. $* - It stores the complete set of positional parameters as a
  • 5. single string. $@ - Same as $*, But there is subtle difference when enclosed in double quotes. $# - It is set to the number of arguments specified.This lets you design scripts that check whether the right number of arguments have been entered. $0 - Refers to the name of the script itself. Setting Values of Positional Parameters You can't technically call positional parameters as shell variables because all variable names start with a letter. For instance you can't assign values to $1, $2.. etc. $1=100 or $2=venu is simply not done. There is one more way to assign values to the positional parameters, using the set command. $ set Helping hands are holier than praying lips The above command sets the value $1 with “Helping” , $2 with “hands” and so on. To verify, use echo statement to display their values.
  • 6. $ echo $1 $2 $3 $4 $5 $6 $7 Helping hands are holier than praying lips You can simply use $* or $@ $ echo $* Helping hands are holier than praying lips $ echo $@ Helping hands are holier than praying lips Using Shift on Positional Parameters We have used set command to set upto 9 words. But we can use it for more. $ set A friend who helps when one is in trouble is a real friend $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 A friend who helps when one is in trouble A0 A1
  • 7. Observe that last two words in the output. These occurred in the output because at a time we can access only 9 positional parameters. When we tried to refer to $10 it was interpreted by the shell as if you wanted to out put the value of $1 and a 0. Hence we got A0 in the output. Does that mean the words following the ninth word have been lost? No. If not, then where have they gone?. They are very much there, safe with the shell But to reach them we must do the following. $shift 4 $ echo $1 $2 $3 $4 $5 $6 $7 $8 $9 when one is in trouble is a real friend Now where have the first seven words gone? They have been shifted out.The first four words lost for ever, as we did not take the precaution to store them else- where. What should we have done is: $ set A friend who helps when one is in trouble is a real friend
  • 8. $ a=$1 $ b=$2 $ c=$3 $ d=$4 $ shift 4 $ echo $a $b $c $d $1 $2 $3 $4 $5 $6 $7 $8 $9 A friend who helps when one is in trouble is a real friend Note:In the Korn and bash shells you can refer directly to arguments where n is greater than 9 using braces. For example, to refer to the 57th positional parameter, use the notation ${57}.some shells may not support this method. $ set A friend who helps when one is in trouble is a real friend $ echo ${12} real
  • 9. $ echo ${13} friend Bracket notation for positional parameters leads to a fairly simple way of referencing the last argument passed to a script on the command line. $ echo ${!#} friend $* and $@ Let us look at the subtle difference between $* and $@. First create three files fileA, fileB, “file temp” cat > fileA I LOVE INDIA Ctrl+d cat > fileB
  • 10. HELLO WORLD Ctrl+d cat > temp file This file name contains blank space Ctrl+d Example: #!/bin/bash # Usage: sh arguments.sh fileA fileB temp file echo -e "033[1mDisplay files content using $* 033[0m" cat $* echo -e "033[1mDisplay files content using $@ 033[0m" cat $@ exit 0 Run the script with file names as arguments. Output:
  • 11. [root@localhost ~]# sh arguments.sh fileA fileB temp file Display files content using $* I LOVE INDIA HELLO WORLD cat: temp: No such file or directory cat: file: No such file or directory Display files content using $@ I LOVE INDIA HELLO WORLD cat: temp: No such file or directory cat: file: No such file or directory So there is no difference between cat $* and cat $@. Modify arguments.sh script as #!/bin/bash # Usage: sh arguments.sh fileA fileB temp file echo -e "033[1mDisplay files content using "$*" 033[0m" cat "$*" echo -e "033[1mDisplay files content using "$@" 033[0m"
  • 12. cat "$@" exit 0 Now again run the script with file names as arguments. Output: [root@localhost ~]# sh arguments.sh fileA fileB temp file Display files content using "$*" cat: fileA fileB temp file: No such file or directory Display files content using "$@" I LOVE INDIA HELLO WORLD This file name contain blank space Now there is a difference, the two cat commands would become: cat “fileA fileB temp file” cat fileA fileB 'temp file' On execution, the first of these commands would give an error since there does not exist a file with the name “fileA fileB temp file”. As
  • 13. against this, the second cat command would display the contents of the files fileA, fileB and “temp file”. So what you observed ,when not enclosed within "double quotes" $* and $@ behaves exactly similarly, and when enclosed in "double quotes" there is a subtle difference. Purpose of command line arguments This is instead of having a dialog with the user such as: How to use command line arguments To use command line arguments, we use a different first line of the main program: Instead of: int main() we use: int main(int argc, char *argv[]) Examples: command line argc argv[0] argv[1] argv[2] argv[3] argv[4]
  • 14. argv[5] argv[6] Converting command line arguments to int or double values When accessing command line arguments that are integers or floating-point numbers, we typically need to use atoi() or atof(). For example consider the code listed below, especially the part in bold (the full program is available at raiseToPower.c): 4.answer When accessing command line arguments that are integers or floating-point numbers, we typically need to use atoi() or atof(). #include <iostream> #include <cstdlib> int main(int argc, char **argv) { double sum=0; int i=0; if(argc>1) { for(i=1;i<argc;i++) /* Conversion string into int by using atoi command*/ sum+= atoi(argv[i]); std::cout<< "The sum is " << sum; } else
  • 15. std::cout<< “arguments supplied”; } In c: #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int i=0; int sum=0; printf(" cmdline args count=%d", argc); /* First argument is executable name only */ printf(" exe name=%s", argv[0]); for (i=1; i< argc; i++) { printf(" arg%d=%s", i, argv[i]); /* Conversion string into int */ sum = sum+atoi(argv[i]); printf(" sum is=%d",sum); } return 0; } 5answer: Command line arguments: Command line arguments allow us to provide input to a C program through the command line. For example, instead of typing
  • 16. ./gameScore to run the program foo.c, we type: ./gameScore Steelers 30 Dolphins 20 and the values "Steelers" "30" "Dolphins" and "20" will be available inside the C program—we don't have to use scanf to prompt for them. Here's how it works: Purpose of command line arguments -bash-3.2$ ./areaOfSquare 3 The area is 9 -bash-3.2$ This is instead of having a dialog with the user such as: -bash-3.2$ ./areaOfSquare Please enter the value of one side of the square: 3 The area is 9 -bash-3.2$ How to use command line arguments To use command line arguments, we use a different first line of the main program: Instead of: int main() we use: int main(int argc, char *argv[]) Checking argc before accessing argv
  • 17. If we have defined argc and argv by putting int main(int argc, char *argv[]) as the first line of our main, then argc is always at least 1, and argv[0] always exists and is the name of the program (as typed on the Unix command line.) However, argv[1], argv[2], don't necessarily exist, unless there are sufficient items on the command line. So, before accessing the value of argv[1], argv[2], etc. it is necessary to always first check the value of argc. command line argc argv[0] argv[1] argv[2] argv[3] argv[4] argv[5] argv[6]