In this example, we will ask users to input two integer numbers and display the sum of these numbers.
To understand this example you should have a basic understanding of C Language topics such as Operators, Inputs & Outputs, Variables, and Data types.
#Program to add two numbers
Below is the complete program but don’t look at it now as we will understand it steps by step.
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum of %d and %d is %d\n", num1, num2, sum);
return 0;
}
#Sample Output
Enter the first number: 5
Enter the second number: 10
The sum of 5 and 10 is 15
#Step 1: Write the basic C Program
First, create a new C program file and write the basic C code to get started, as given below.
#include <stdio.h>
int main() {
// your code here
return 0;
}
#Step 2: Declare the variables
int num1, num2, sum;
These are the variables you will use in your program. num1
and num2
are the two numbers that you want to add, and sum
will store the result of the addition.
#Step 3: Get the numbers from the user
#Get the first number
printf("Enter the first number: ");
scanf("%d", &num1);
The printf
function displays the prompt “Enter the first number: ” on the screen. The scanf
function is used to read the input from the user and store it in the num1
variable. The &
symbol is used to pass the address of the num1
variable to scanf
, so that scanf
can store the input in that location.
#Get the second number
printf("Enter the second number: ");
scanf("%d", &num2);
This is similar to the previous step, except that the prompt is “Enter the second number: ” and the input is stored in the num2
variable.
#Step 4: Add the two numbers
sum = num1 + num2;
This line adds the values stored in num1
and num2
and stores the result in the sum
variable.
#Step 5: Display the result
printf("The sum of %d and %d is %d\n", num1, num2, sum);
This line uses the printf
function to display the result of the addition. The %d
is a placeholder for an integer value, and the values of num1
, num2
, and sum
are printed in the corresponding order. The \n
at the end is a special character that represents a new line, so the output will be displayed on a new line.
Your complete program should look like this
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum of %d and %d is %d\n", num1, num2,
Happy Coding/:)