Add Two Numbers
Add two integers entered by user
This program takes two integers as input from the user and displays their sum. It's a fundamental program that teaches variable declaration, user input, arithmetic operations, and formatted output.
📚 What You'll Learn
- •Declaring integer variables with
int - •Reading integers using
scanf()with%d - •Using the address-of operator
& - •Performing arithmetic operations
C Program to Add Two Numbers
1#include <stdio.h>23int main() {4 // Declare variables to store numbers and result5 int num1, num2, sum;6 7 // Get first number from user8 printf("Enter first number: ");9 scanf("%d", &num1);10 11 // Get second number from user12 printf("Enter second number: ");13 scanf("%d", &num2);14 15 // Calculate sum16 sum = num1 + num2;17 18 // Display the result19 printf("%d + %d = %d\n", num1, num2, sum);20 21 return 0;22}Enter first number: 25
Enter second number: 17
25 + 17 = 42
Detailed Code Explanation
int num1, num2, sum;Declares three integer variables. Memory is allocated for each variable.
Variable Declaration Syntax:
data_type variable_name;Multiple variables of same type can be declared in one line, separated by commas.
scanf("%d", &num1);Reads an integer from user and stores it in num1.
| Part | Meaning |
|---|---|
| %d | Format specifier for integer (decimal) |
| &num1 | Address of num1 (where to store the value) |
⚠️ Important: The & (address-of) operator is required for scanf() with basic data types like int, float, char. It tells scanf WHERE to store the input.
sum = num1 + num2;The + operator adds the values and = stores the result.
Arithmetic Operators in C:
+-*/%printf("%d + %d = %d\n", num1, num2, sum);Multiple format specifiers are replaced by corresponding arguments in order:
First %d → num1, Second %d → num2, Third %d → sum
Step-by-Step Execution:
Memory allocated for num1, num2, and sum (each 4 bytes for int)
printf displays "Enter first number: "
User types 25, scanf stores it at address of num1
printf displays "Enter second number: "
User types 17, scanf stores it at address of num2
sum = 25 + 17 = 42
printf shows "25 + 17 = 42"
Memory Visualization
Alternative Methods
Without Using Third Variable
1printf("Sum = %d\n", num1 + num2); // Direct calculation in printfReading Both Numbers at Once
1printf("Enter two numbers: ");2scanf("%d %d", &num1, &num2); // Space-separated input⚠️ Common Mistakes to Avoid
- • Forgetting &:
scanf("%d", num1)❌ crashes! Usescanf("%d", &num1)✓ - • Wrong format specifier: Using
%ffor integers - • Integer overflow: Adding very large numbers exceeds int range
📝 Key Takeaways
int stores whole numbers%d format specifier for integers& is required in scanf for variables+ operator adds two numbersRelated Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials