C Addition of Two Numbers
In C language, a program to add two numbers involves taking two numbers as input from the user, performing the addition, and then printing the result. Here's a step-by-step explanation and a sample code for the program:
Steps for Addition of Two Numbers:
- Include Header Files: You need to include the
stdio.h
library, which is required for input and output functions likeprintf
andscanf
. - Declare Variables: Define variables that will store the numbers to be added and the result of their sum.
- Take Input: Use the
scanf
function to take input from the user for the two numbers. - Perform Addition: Add the two numbers and store the result in another variable.
- Display Output: Use
printf
to display the sum of the numbers.
Program:
Explanation:
#include <stdio.h>
: This includes the Standard Input Output library, which contains functions likeprintf
(for output) andscanf
(for input).Variables:
int num1, num2, sum
: Three variables are declared of typeint
.num1
andnum2
will store the numbers entered by the user, andsum
will store the result of their addition.
Input:
printf("Enter two integers: ");
prompts the user to enter two numbers.scanf("%d %d", &num1, &num2);
reads two integers entered by the user and stores them in the variablesnum1
andnum2
.
Addition:
sum = num1 + num2;
calculates the sum of the two numbers.
Output:
printf("Sum of %d and %d is: %d\n", num1, num2, sum);
prints the result, showing the sum of the two numbers.
Sample Output:
Key Points:
%d
is used as a format specifier for integers.scanf
uses&
to pass the address of variables where the input values will be stored.- The program adds the two integers entered by the user and prints their sum.
This is a simple and effective program to get started with user input, variable handling, and performing basic arithmetic operations in C.