C Programming — Adding Two Integers

C Programming — Adding Two Integers

A basic C example that reads two integers from the keyboard, adds them and prints the result.

The first example only printed text to the screen, which is an output device. This example reads two numbers from the keyboard, adds them and prints the result.

#include <stdio.h>
#include <conio.h>
int main()
{
int number1, number2, total;
printf("Enter the first number: ");
scanf("%d", &number1);
printf("Enter the other number: ");
scanf("%d", &number2);
total = number1 + number2;
printf("Total: %d", total);
getch();
return 0;
}
  • The int expression on the first line specifies the data type; the comma-separated expressions that follow are variables.
  • Variables must first be declared. Three integer variables are declared here.
  • The printf() function prints “Enter the first number:” on the screen.
  • As shown in scanf("%d", &number1);, the function receives two parameters, although it can receive more.
  • The first parameter (%d) indicates that the input is a decimal integer.
  • Notice the ampersand (&) before the second parameter. In this context, the operator refers to an address.
  • In brief, &number1 passes the address of number1 to the function.

References

  • **[1]** Brian W. Kernighan; Dennis M. Ritchie. (1988). The C Programming Language, Second Edition. Prentice Hall.
  • **[2]** International Organization for Standardization. (2011). ISO/IEC 9899:2011 - Programming Languages - C. ISO.
QR code for this page