Execute Arithmetic Operations Between Integers
In this step, you will learn how to perform basic arithmetic operations between integers in C programming. We'll build upon the previous step and demonstrate addition, subtraction, multiplication, and division.
Let's modify the previous file to include arithmetic operations:
cd ~/project
nano integer_operations.c
Add the following code to the file:
#include <stdio.h>
int main() {
// Declare and initialize integer variables
int num1 = 20;
int num2 = 10;
// Addition
int sum = num1 + num2;
printf("Addition: %d + %d = %d\n", num1, num2, sum);
// Subtraction
int difference = num1 - num2;
printf("Subtraction: %d - %d = %d\n", num1, num2, difference);
// Multiplication
int product = num1 * num2;
printf("Multiplication: %d * %d = %d\n", num1, num2, product);
// Division
int quotient = num1 / num2;
int remainder = num1 % num2;
printf("Division: %d / %d = %d (Remainder: %d)\n", num1, num2, quotient, remainder);
return 0;
}
Let's break down the arithmetic operations:
+
performs addition
-
performs subtraction
*
performs multiplication
/
performs integer division
%
calculates the remainder of integer division
Compile and run the program:
gcc integer_operations.c -o integer_operations
./integer_operations
Example output:
Addition: 20 + 10 = 30
Subtraction: 20 - 10 = 10
Multiplication: 20 * 10 = 200
Division: 20 / 10 = 2 (Remainder: 0)