Addition of two numbers in C

Profile Picture

saxenadivya859

Wednesday, 2024-07-31



Adding two numbers in C is a fundamental operation and is quite straightforward. Here’s a simple example of how you can achieve this:


Code:

c
Copy code
#include <stdio.h>

int main() {
    int num1, num2, sum;

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

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

    // Calculate the sum
    sum = num1 + num2;

    // Display the result
    printf("The sum of %d and %d is %d\n", num1, num2, sum);

    return 0;
}


Explanation:


  1. Include the necessary header: #include <stdio.h> is used to include the standard input-output library, which allows you to use printf and scanf.
  2. Declare variables: int num1, num2, sum; are declared to store the two numbers and their sum.
  3. Get user input:
  • printf prompts the user to enter a number.
  • scanf reads the user's input and stores it in num1 and num2.
  1. Perform the addition: sum = num1 + num2; computes the sum of num1 and num2.
  2. Output the result: printf displays the result of the addition.


How did you feel about this post?

😍 πŸ™‚ 😐 πŸ˜• 😑