LINFO

How to Create C Programs on Linux

Third Lesson: Calculation and Comments


This lesson explains how to write C programs that perform simple calculations. Such programs are very easy to write and only require a few lines of source code in addition to that presented in the previous lesson, which covered incorporating user feedback into programs.

The following is a simple program that requests that the user type in two numbers, reads in those numbers, stores them, calculates their sum, and displays the sum on the monitor screen:

#include <stdio.h>

main() {
  int x,y;
  printf("Enter a number: ");
  scanf("%d",&x);
  printf("Enter a second number: ");
  scanf("%d",&y);
  printf("The sum is %d\n",x+y);
}

It will be recalled from the previous lesson that the first line is the preprocessor directive. It causes the file named stdio.h to be copied into the source code of the program. That file resides in glibc (i.e., the GNU project's implementation of the standard C library) and provides the basic input and output facilities for C. The preprocessor directive is followed by a blank line, as is good style (but not absolutely necessary).

It will also be recalled that the main() function, which begins on the third line in this example, is where the program starts execution (i.e., running). It performs some operation(s) and returns a single value to the program. In this case, main() contains six statements within its curly brackets, each on a separate line. A statement is an instruction to a program; each statement always ends with a semicolon.

The first statement declares two variables named x and y as the data type called int (i.e., integer, which is any whole number). A variable can be thought of as a container for a certain type of value. In C, each variable must be declared before it can be used. This is accomplished by stating its type followed by its name.

The second statement, which begins with the printf() function, then writes what is enclosed in quotation marks in its parenthesis to standard output, which, by default, is the display monitor. That is, it causes the phrase Enter a number: to be displayed on the screen.

The scanf() function in the third statement reads formatted data from standard input, which by default is text typed in at the keyboard. The %d inside of its parenthesis is a placeholder that reads the integers typed in at the keyboard and places their value in the variable x. The ampersand attached to the beginning of the x, referred to as the address operator, tells the program to store the result of its scanning operation in the variable that follows it; it is necessary for proper operation of the program.

The fourth statement is essentially the same as the second statement. The only difference is what it writes on the screen (i.e., it asks the user to enter a second number).

Likewise, the fifth statement is basically the same as the third statement. The only difference is that it saves the input from the user in variable y instead of variable x.

The final statement calculates the sum of the two variables. It then replaces the %d by this sum and writes the phrase that is in quotation marks on the display screen.

The program can be easily compiled (i.e., converted to its final, ready-to-run form) using the C compiler in the GCC (GNU Compiler Collection), which is included in most distributions (i.e., versions) of Linux. All that is necessary is to copy and save it with a text editor and, assuming that this file is named aveg.c and that the final program is to be named aveg, run the following command:

gcc -o aveg aveg.c

The resulting program can be run by merely typing in its name preceded by a dot and a forward slash and then pressing the ENTER key as follows:

./aveg


Adding Comments

Comments are commonly used in source code in order to make it easier to understand by noting such things as what specific parts of the program are intended to do, problems with the code and suggestions for future work on it. In addition to making complex code more understandable by programmers other than the author, comments can also serve as a reminder for the author as to what was done years ago. Although, at first, comments can make code seem more complex, once one becomes used to them, well written comments can play an important role in making code easier to understand. Comments are ignored by compilers and thus do not affect the working of programs.

There are two ways to indicate comments in C. One is to use two forward slashes in succession. Anything following these slashes on the same line becomes part of the comment.

In addition to these single-line comments, multi-line comments are also available. They begin with a forward slash followed by an asterisk, and they are terminated by an asterisk followed by a forward slash.

The following is an example of how the above code would appear with several comments added to it (although they are not really necessary or useful for such a short and simple program):

/*A program that reads in two numbers and prints their sum. This is a multi-line comment.*/

#include <stdio.h>   // preprocessor directive

main() {   // main() function
  int x,y;   // declare variables
  printf("Enter a number: ");
  scanf("%d",&x);
  printf("Enter a second number: ");
  scanf("%d",&y);
  printf("The sum of the two numbers is %d\n",x+y);
}   // final bracket for main() function


A Slightly More Complex Calculation

It is easy to modify C programs to perform other types of calculations. The following is a modification of the above program (including elimination of most of the comments) in an attempt to calculate the average of three numbers entered by the user:

/*A program that reads in three numbers and prints their average*/

#include <stdio.h>

main() {
  int x,y,z;
  printf("Enter a number: ");
  scanf("%d",&x);
  printf("Enter a second number: ");
  scanf("%d",&y);
  printf("Enter a third number: ");
  scanf("%d",&z);
  printf("The average is %d\n", (x+y+z)/3);
}

The key difference is that the final statement calculates the average of the input numbers rather than just their sum. It does this by first adding the three variables and then dividing the total by the number 3.

Upon compiling and running this program, however, it will soon become apparent that something is not quite right. It is that the calculated average is not exact, but only approximate. This is because the numbers used are integers. Fortunately, however, this can be easily solved by changing the data type from integer to float, which can represent floating point numbers (i.e., numbers that contain a decimal point).

Thus, in the above example it would would be necessary to both change the initial declaration for x, y and z and then to replace all four instances of the %d placeholder with the %f (which represents floating point numbers) placeholder, as follows:

/*A program that reads in three numbers and prints their average*/

#include <stdio.h>

main() {
  float x,y,z;
  printf("Enter a number: ");
  scanf("%f",&x);
  printf("Enter a second number: ");
  scanf("%f",&y);
  printf("Enter a third number: ");
  scanf("%f",&z);
  printf("The average is %f\n", (x+y+z)/3);
}

After recompiling the program, it can be seen that the average will now be provided with much more precision, that is, to several decimal places.


Experiments

There are many instructive experiments that can be performed based on this program. They include changing the number of inputs and what is calculated from them. For example, the program could be revised to calculate the product of the entered numbers, the square of each number, the square of the average of the numbers or the result of dividing one number by another.

Another instructive type of experiment is to input very large (e.g., numbers in the millions or billions) or very small (i.e., tiny fractions) numbers into the above programs to see how they affect the results. This can be followed by changing the data types and see how they affect the results for calculations with very large and very small numbers.

The next lesson will show how to use conditionals to greatly increase the flexibility of programs. Future lessons will show how to use C's built-in math functions to perform much more complex calculations.






Created September 5, 2006.
Copyright © 2006 The Linux Information Project. All Rights Reserved.