Arithmetic Operators
Part of the Fundamentals section of Coddy's C journey — lesson 16 of 63.
Arithmetic operators in C are used to perform basic mathematical operations. The most common arithmetic operators are:
+(addition)-(subtraction)*(multiplication)/(division)
Here's how you can use these operators:
int a = 10;
int b = 5;
int sum = a + b; // sum is 15
int difference = a - b; // difference is 5
int product = a * b; // product is 50
int quotient = a / b; // quotient is 2Note that when dividing two integers, the result will be an integer (fractional part is truncated). For example:
int result = 7 / 2; // result is 3, not 3.5To get a floating-point result, at least one of the operands should be a float:
float result = 7.0 / 2; // result is 3.5Challenge
EasyWrite a C program that performs the following operations:
- Declare two integer variables
num1andnum2and initialize them with values 15 and 4 respectively. - Calculate and store the sum of
num1andnum2in a variable calledsum. - Calculate and store the difference between
num1andnum2in a variable calleddifference. - Calculate and store the product of
num1andnum2in a variable calledproduct. - Calculate and store the quotient of
num1divided bynum2in a variable calledquotient. - Print all results using
printf()in the following format:
Sum: [value of sum]
Difference: [value of difference]
Product: [value of product]
Quotient: [value of quotient]Cheat sheet
Arithmetic operators in C perform basic mathematical operations:
+(addition)-(subtraction)*(multiplication)/(division)
int a = 10;
int b = 5;
int sum = a + b; // sum is 15
int difference = a - b; // difference is 5
int product = a * b; // product is 50
int quotient = a / b; // quotient is 2Integer division truncates the fractional part:
int result = 7 / 2; // result is 3, not 3.5For floating-point division, use at least one float operand:
float result = 7.0 / 2; // result is 3.5Try it yourself
#include <stdio.h>
int main() {
// Declare and initialize variables here
// Perform calculations
// Print results
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge