Programming With Integers - A Simple program to add up two numbers

Chapter chap2 section 2

A simple C program that reads in two numbers, stores them and prints out the sum is listed below.

/*	A program to read in two numbers
	and print their sum
*/
main()
{
	int	x,y;	/* places to store numbers */
	printf("Enter x ");
	scanf("%d",&x);
	printf("Enter y ");
	scanf("%d",&y);
	printf("The sum of x and y was %d\n",x+y);
}
After compiling the program the following dialogue is typical of operation of the program.
Enter x 4
Enter y 5
The sum of x and y was 9

There are a number of features of this program that require further explanation. If you have had any experience of programming you will probably guess the following points. The code on line 6 reserves and names places to store the numbers. The library function scanf() used on lines 8 and 10 reads from the keyboard. The addition of the two stored numbers is done on line 11 by calculating the value of x+y. Even if you have had programming experience you may well be puzzled by the percent (%) and ampersand (&) symbols appearing on lines 8, 10 and 11.


Storing Numbers