C Program to Add Two Numbers

1. Introduction

One of the most fundamental operations in any programming language is arithmetic. Today, we'll create a simple C program that adds two numbers. While it sounds elementary, this exercise will familiarize beginners with important concepts like variable declaration, taking user input, and displaying output.

2. Program Overview

Our program will do the following:

1. Prompt the user to enter two numbers.

2. Read and store these numbers.

3. Add the two numbers.

4. Display the sum.

3. Code Program

#include <stdio.h>  // Including the Standard I/O library for input and output functions

int main() {  // Entry point of the program

    double num1, num2, sum;  // Declare three variables of type double for storing two numbers and their sum

    // Prompting the user for input
    printf("Enter first number: ");
    scanf("%lf", &num1);  // Read and store the first number

    printf("Enter second number: ");
    scanf("%lf", &num2);  // Read and store the second number

    sum = num1 + num2;  // Compute the sum of the two numbers

    printf("The sum of %.2lf and %.2lf is: %.2lf\n", num1, num2, sum);  // Display the sum

    return 0;  // Indicate successful termination
}

Output:

If the user enters 5 and 6.5:
Enter first number: 5
Enter second number: 6.5
The sum of 5.00 and 6.50 is: 11.50

4. Step By Step Explanation

1. #include <stdio.h>: This includes the standard input/output library, which gives us access to functions like printf and scanf.

2. int main(): This is the starting point of our program. Every C program begins its execution from the main function.

3. double num1, num2, sum;: Here, we declare three variables of the double data type to store two numbers and their resulting sum.

4. printf function: Used for displaying prompts to the user. It sends formatted output to the screen.

5. scanf function: Allows us to read formatted input. We use %lf as the format specifier because we're dealing with double data types. The & symbol is used to get the address of the variable, i.e., where the inputted value will be stored in memory.

6. sum = num1 + num2;: This line performs the arithmetic addition operation.

7. return 0;: This returns an exit status. A return of 0 from the main indicates successful completion.

With this program, beginners get an introduction to user input, arithmetic operations, and displaying results in C programming.

Comments