The purpose of this section is to get you up and running ready to write very quick C routines to perform arithmetic tasks. In each case, a program that obtains the input for you can be created by editing the previous program, and then all you need to do is fill in the C code to implement the desired functionality.
Some may appear overly simplistic, but stay with the tasks and you should find you gain some valuable experience and insights.
First a note about commandline arguments. After you compile a program from file foo.c into an executable called foo (or, in the case of Windows foo.exe) via the command gcc -o foo foo.c, you run the program simply by typing, at the unix prompt:
> fooIf, instead, you type
> foo 3 7 xyz 21then the 3, 7, xyz and 21 are all called commandline arguments. C gives you access to them via two variables:
So now you know also why argc is one more than the number of commandline arguments.
Like Java, C chooses to regard all commandline arguments as strings. The reason for this is that anything that strings are sufficiently versatile to contain representations of ints, floats, chars, and, of course, strings. A small proviso is in order: C does not actually admit a string data type. argv is declared via:
char *argv[ ];Technically, argv is a pointer to an array of character strings, and we will understand it better shortly when we study arrays and pointers. For now, the best thing is just to accept that this is how C accesses its commandline arguments.
Just to test that you have got the hang of it, let's write a program to print out all the commandline arguments each on its own line. We'll even print out argv[0] the name under which the program is invoked. The code is in here. Grab it, compile it, and test it.
Sometimes, you want to treat a commandline argument as a number. In that case C has a nice library function called atoi. If you want to place the first commandline argument into an int variable, you get the value as atoi(argv[1]). For example here is a program to print double the value of its first commandline argument.
> addargs 17 25 42
> addargs 17.6 25.3
Now let's do the same program in Java. The file, which this time absolutely positively must be called AddArgs.java is in here.
Study it. Compile it via javac AddArgs.java. Run it via java AddArgs 17 25. (Do you remember all that Java?)
> java AddArgs 17.2 25.1
Back to C. Instead of adding the two numbers what happens if you & them?
What's going on? If you're not sure, try
Let's finish with a few more exercises:
> printem 5 1 2 3 4 5
> printsqs 5 1 4 9 16 25
Here is a program to tell you if the int at argv[1] is prime. Several things to note:
> prime 42 2 3 5 7 11 13 17 19 23 29 31 37 41