Add two number in c program

Add Two Numbers in C - Explanation

Add Two Numbers in C - Program and Explanation

Program:

#include <stdio.h>

int main() {
    // Declare variables
    int num1, num2, sum;

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

    printf("Enter 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:

#include <stdio.h>: This line includes the standard input/output library in C, which allows you to use the printf and scanf functions.

int main(): This is the main function where the execution of the program begins. The int before main() indicates that this function returns an integer value.

int num1, num2, sum;: Declares three integer variables to store the two numbers and their sum.

printf("Enter first number: ");: This line prompts the user to enter the first number.

scanf("%d", &num1);: This line reads the user's input and stores it in the num1 variable.

printf("Enter second number: ");: This line prompts the user to enter the second number.

scanf("%d", &num2);: This line reads the user's input and stores it in the num2 variable.

sum = num1 + num2;: Adds the two numbers and stores the result in sum.

printf("The sum of %d and %d is %d\\n", num1, num2, sum);: This line prints the sum of the two numbers to the console. The \\n at the end adds a new line after the output.

return 0;: Indicates that the program has ended successfully. Returning 0 is a convention in C that signifies successful execution.

Comments

Popular Posts