Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find sum and difference of two numbers
In C programming, finding the sum and difference of two numbers is a fundamental operation. This program demonstrates how to perform arithmetic operations on different data types and handle the output formatting correctly based on the operands' types.
Syntax
// For integer arithmetic int result = num1 + num2; int result = num1 - num2; // For floating-point arithmetic float result = num1 + num2; float result = num1 - num2;
Example 1: Sum and Difference of Integer Numbers
This example shows basic arithmetic operations on integer values −
#include <stdio.h>
int main() {
int a = 15, b = 8;
printf("First number: %d
", a);
printf("Second number: %d
", b);
printf("Sum: %d + %d = %d
", a, b, a + b);
printf("Difference: %d - %d = %d
", a, b, a - b);
return 0;
}
First number: 15 Second number: 8 Sum: 15 + 8 = 23 Difference: 15 - 8 = 7
Example 2: Sum and Difference of Floating-Point Numbers
This example demonstrates arithmetic operations on floating-point values −
#include <stdio.h>
int main() {
float c = 6.32, d = 8.64;
printf("First number: %.2f
", c);
printf("Second number: %.2f
", d);
printf("Sum: %.2f + %.2f = %.2f
", c, d, c + d);
printf("Difference: %.2f - %.2f = %.2f
", d, c, d - c);
return 0;
}
First number: 6.32 Second number: 8.64 Sum: 6.32 + 8.64 = 14.96 Difference: 8.64 - 6.32 = 2.32
Example 3: Mixed Data Type Operations
This example shows arithmetic operations between integer and floating-point numbers −
#include <stdio.h>
int main() {
int a = 5, b = 58;
float c = 6.32, d = 8.64;
printf("Integer operations:
");
printf("a + b = %d
", a + b);
printf("b - a = %d
", b - a);
printf("\nFloat operations:
");
printf("c + d = %.6f
", c + d);
printf("d - c = %.6f
", d - c);
printf("\nMixed operations:
");
printf("a + c = %.6f
", a + c);
printf("b - d = %.6f
", b - d);
return 0;
}
Integer operations: a + b = 63 b - a = 53 Float operations: c + d = 14.960001 d - c = 2.320000 Mixed operations: a + c = 11.320000 b - d = 49.360001
Key Points
- When adding integers, use
%dformat specifier for output. - When adding floats, use
%for%.nf(where n is decimal places) format specifier. - Mixed operations (int + float) automatically promote the integer to float, requiring
%ffor output. - Floating-point arithmetic may introduce small precision errors due to binary representation.
Conclusion
Arithmetic operations in C are straightforward, but proper format specifiers must be used based on data types. Mixed operations automatically promote integers to floating-point for accurate results.
Advertisements
