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:

  1. Include Header Files: You need to include the stdio.h library, which is required for input and output functions like printf and scanf.
  2. Declare Variables: Define variables that will store the numbers to be added and the result of their sum.
  3. Take Input: Use the scanf function to take input from the user for the two numbers.
  4. Perform Addition: Add the two numbers and store the result in another variable.
  5. Display Output: Use printf to display the sum of the numbers.

Program:

#include <stdio.h> int main() { int num1, num2, sum; // Declare variables for two numbers and the result // Ask the user to enter the two numbers printf("Enter two integers: "); // Read the input from the user and store them in num1 and num2 scanf("%d %d", &num1, &num2); // Add the two numbers sum = num1 + num2; // Display the result of the addition printf("Sum of %d and %d is: %d\n", num1, num2, sum); return 0; }

Explanation:

  1. #include <stdio.h>: This includes the Standard Input Output library, which contains functions like printf (for output) and scanf (for input).

  2. Variables:

    • int num1, num2, sum: Three variables are declared of type int. num1 and num2 will store the numbers entered by the user, and sum will store the result of their addition.
  3. 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 variables num1 and num2.
  4. Addition:

    • sum = num1 + num2; calculates the sum of the two numbers.
  5. 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:

Enter two integers: 12 25 Sum of 12 and 25 is: 37

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.