C Program to Add Two Numbers

Introduction

Adding two numbers is one of the basic operations in programming. This guide will show you how to write a simple C program to add two numbers provided by the user and display the result.

Problem Statement

Create a C program that:

  • Prompts the user to enter two numbers.
  • Adds the two numbers.
  • Displays the sum of the two numbers.

Example:

  • Input: 5 and 3
  • Output: Sum: 8

Solution Steps

  1. Include the Standard Input-Output Library: Use #include <stdio.h> to include the standard input-output library, which is necessary for using printf and scanf functions.
  2. Write the Main Function: Define the main function, which is the entry point of every C program.
  3. Declare Variables: Declare variables to store the two numbers and the sum.
  4. Input the Numbers: Use scanf to take input from the user for the two numbers.
  5. Add the Numbers: Calculate the sum of the two numbers.
  6. Display the Sum: Use printf to display the sum.

C Program

#include <stdio.h>

/**
 * C Program to Add Two Numbers
 * Author: https://www.javaguides.net/
 */
int main() {
    // Step 1: Declare variables to hold the numbers and the sum
    int num1, num2, sum;

    // Step 2: Prompt the user to enter the first number
    printf("Enter the first number: ");
    scanf("%d", &num1);

    // Step 3: Prompt the user to enter the second number
    printf("Enter the second number: ");
    scanf("%d", &num2);

    // Step 4: Calculate the sum of the two numbers
    sum = num1 + num2;

    // Step 5: Display the result
    printf("Sum: %d\n", sum);

    return 0;  // Step 6: Return 0 to indicate successful execution
}

Explanation

Step 1: Declare Variables

  • Variables num1, num2, and sum are declared as integers to hold the two input numbers and their sum, respectively.

Step 2: Input the First Number

  • The program prompts the user to enter the first number using printf. The scanf function then reads the input and stores it in the variable num1.

Step 3: Input the Second Number

  • Similarly, the program prompts the user to enter the second number, which is stored in the variable num2.

Step 4: Calculate the Sum

  • The sum of the two numbers is calculated by adding num1 and num2, and the result is stored in the sum variable.

Step 5: Display the Sum

  • The calculated sum is displayed to the user using the printf function.

Step 6: Return 0

  • The return 0; statement indicates that the program executed successfully.

Output Example

Example:

Enter the first number: 5
Enter the second number: 3
Sum: 8

Conclusion

This C program demonstrates how to add two numbers provided by the user and display the result. It covers basic concepts such as taking user input, performing arithmetic operations, and outputting results, making it a useful example for beginners learning C programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top