Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

2.3. Another Simple C Program: Adding Two Integers

Our next program uses the Standard Library function scanf to obtain two integers typed by a user at the keyboard, computes the sum of these values and prints the result using printf. The program and sample output are shown in Fig. 2.5. [In the input/output dialog of Fig. 2.5, we emphasize the numbers entered by the user in bold.]

Fig. 2.5. Addition program.

 1   // Fig. 2.5: fig02_05.c
 2   // Addition program.
 3   #include <stdio.h>
 4
 5   // function main begins program execution
 6   int main( void )
 7   {
 8      int integer1; // first number to be entered by user 
 9      int integer2; // second number to be entered by user
10      int sum; // variable in which sum will be stored        
11
12      printf( "Enter first integer\n" ); // prompt
13      scanf( "%d", &integer1 ); // read an integer
14
15      printf( "Enter second integer\n" ); // prompt
16      scanf( "%d", &integer2 ); // read an integer
17
18      sum = integer1 + integer2; // assign total to sum
19
20      printf( "Sum is %d\n", sum ); // print sum
21   } // end function main

The comment in line 2 states the purpose of the program. As we stated earlier, every program begins execution with main. The left brace { (line 7) marks the beginning of the body of main, and the corresponding right brace } (line 21) marks the end of main.

Variables and Variable Definitions

Lines 8–10

int integer1; // first number to be entered by user     
int integer2; // second number to be entered by user    
int sum; // variable in which sum will be stored        

are definitions. The names integer1, integer2 and sum are the names of variables—locations in memory where values can be stored for use by a program. These definitions specify that variables integer1, integer2 and sum are of type int, which means that they’ll hold integer values, i.e., whole numbers such as 7, –11, 0, 31914 and the like.

All variables must be defined with a name and a data type before they can be used in a program. For readers using the Microsoft Visual C++ compiler, note that we’re placing our variable definitions immediately after the left brace that begins the body of main. The C standard allows you to place each variable definition anywhere in main before that variable’s first use in the code. Some compilers, such as GNU gcc, have implemented this capability. We’ll address this issue in more depth in later chapters.

The preceding definitions could have been combined into a single definition statement as follows:

int integer1, integer2, sum;

but that would have made it difficult to describe the variables with corresponding comments as we did in lines 8–10.

Identifiers and Case Sensitivity

A variable name in C is any valid identifier. An identifier is a series of characters consisting of letters, digits and underscores (_) that does not begin with a digit. C is case sensitive—uppercase and lowercase letters are different in C, so a1 and A1 are different identifiers.

Syntax Errors

We discussed what syntax errors are in Chapter 1. Recall that the Microsoft Visual C++ compiler requires variable definitions to be placed after the left brace of a function and before any executable statements. Therefore, in the program in Fig. 2.5, inserting the definition of integer1 after the first printf would cause a syntax error in Visual C++.

Prompting Messages

Line 12

printf( "Enter first integer\n" ); // prompt

displays the literal "Enter first integer" and positions the cursor to the beginning of the next line. This message is called a prompt because it tells the user to take a specific action.

The scanf Function and Formatted Inputs

The next statement

scanf( "%d", &integer1 ); // read an integer

uses scanf (the “f” stands for “formatted”) to obtain a value from the user. The function reads from the standard input, which is usually the keyboard. This scanf has two arguments, "%d" and &integer1. The first, the format control string, indicates the type of data that should be entered by the user. The %d conversion specifier indicates that the data should be an integer (the letter d stands for “decimal integer”). The % in this context is treated by scanf (and printf as we’ll see) as a special character that begins a conversion specifier. The second argument of scanf begins with an ampersand (&)—called the address operator—followed by the variable name. The &, when combined with the variable name, tells scanf the location (or address) in memory at which the variable integer1 is stored. The computer then stores the value that the user enters for integer1 at that location. The use of ampersand (&) is often confusing to novice programmers or to people who have programmed in other languages that do not require this notation. For now, just remember to precede each variable in every call to scanf with an ampersand. Some exceptions to this rule are discussed in Chapters 6 and 7. The use of the ampersand will become clear after we study pointers in Chapter 7.

When the computer executes the preceding scanf, it waits for the user to enter a value for variable integer1. The user responds by typing an integer, then pressing the Enter key to send the number to the computer. The computer then assigns this number, or value, to the variable integer1. Any subsequent references to integer1 in this program will use this same value. Functions printf and scanf facilitate interaction between the user and the computer. Because this interaction resembles a dialogue, it’s often called interactive computing.

Line 15

printf( "Enter second integer\n" ); // prompt

displays the message Enter second integer on the screen, then positions the cursor to the beginning of the next line. This printf also prompts the user to take action.

Line 16

scanf( "%d", &integer2 ); // read an integer

obtains a value for variable integer2 from the user.

Assignment Statement

The assignment statement in line 18

sum = integer1 + integer2; // assign total to sum

calculates the total of variables integer1 and integer2 and assigns the result to variable sum using the assignment operator =. The statement is read as, “sum gets the value of integer1 + integer2.” Most calculations are performed in assignments. The = operator and the + operator are called binary operators because each has two operands. The + operator’s two operands are integer1 and integer2. The = operator’s two operands are sum and the value of the expression integer1 + integer2.

Printing with a Format Control String

Line 20

printf( "Sum is %d\n", sum ); // print sum

calls function printf to print the literal Sum is followed by the numerical value of variable sum on the screen. This printf has two arguments, "Sum is %d\n" and sum. The first argument is the format control string. It contains some literal characters to be displayed, and it contains the conversion specifier %d indicating that an integer will be printed. The second argument specifies the value to be printed. Notice that the conversion specifier for an integer is the same in both printf and scanf—this is the case for most C data types.

Calculations in printf Statements

Calculations can also be performed inside printf statements. We could have combined the previous two statements into the statement

printf( "Sum is %d\n", integer1 + integer2 );

The right brace, }, at line 21 indicates that the end of function main has been reached.

  • + Share This
  • 🔖 Save To Your Account