C Program to Accept Two Integers and Perform All Arithmetic Operations
Introduction
Understanding arithmetic operations is one of the first steps in learning C programming. In this tutorial, we will write a simple C program to perform all basic arithmetic operations on two integers using default values (without taking user input).
Problem Statement
Question:
Write a C program to accept two integers and perform all arithmetic operations.
In this version, instead of taking input from the user, we will use default values assigned directly in the program.
The program should:
- Use two integer variables
- Perform addition, subtraction, multiplication, division, and modulus
- Display all results clearly
Logic of the Program
- Declare integer variables
num1andnum2and assign default values. - Declare result variables for storing arithmetic results.
- Perform addition, subtraction, and multiplication directly.
- Check if the second number is not zero before performing division and modulus.
- Display all results using
printf().
Source Code
#include <stdio.h>
int main()
{
// Default values
int num1 = 20;
int num2 = 4;
int sum, difference, product, division, modulus;
// Performing arithmetic operations
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
if (num2 != 0)
{
division = num1 / num2;
modulus = num1 % num2;
}
// Displaying values and results
printf("First Integer = %d\n", num1);
printf("Second Integer = %d\n", num2);
printf("\nAddition = %d", sum);
printf("\nSubtraction = %d", difference);
printf("\nMultiplication = %d", product);
if (num2 != 0)
{
printf("\nDivision = %d", division);
printf("\nModulus = %d", modulus);
}
else
{
printf("\nDivision and Modulus cannot be performed (division by zero).");
}
return 0;
}
Sample Output
First Integer = 20
Second Integer = 4
Addition = 24
Subtraction = 16
Multiplication = 80
Division = 5
Modulus = 0
Viva Questions
1. What are arithmetic operators in C?
Arithmetic operators are symbols used to perform mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
- What are arithmetic operators in C?
Answer: Arithmetic operators are symbols used to perform mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). - Why do we check
num2 != 0before division?
Answer: Division by zero is not allowed in C and causes a runtime error, so we must check that the second number is not zero. - What is the modulus operator used for?
Answer: The modulus operator (%) returns the remainder after division of two integers. - What is the purpose of
return 0;in the program?
Answer: It indicates that the program has executed successfully and returns control to the operating system. - What is the difference between using default values and user input?
Answer: Default values are assigned directly in the program, while user input allows the user to enter values during program execution.
