C Program to Subtract Two Numbers

1. Introduction

Arithmetic operations are foundational in programming, serving as an excellent starting point for newcomers to grasp basic coding concepts. In this tutorial, we will learn how to write a simple C program to subtract two given numbers.

2. Program Overview

Our program's workflow is as follows:

1. Prompt the user to input two numbers.

2. Read and store the numbers.

3. Subtract the second number from the first.

4. Display the result.

3. Code Program

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

int main() {  // This is where our program begins its execution

    double num1, num2, difference;  // Declare three variables of type double: two for the user's numbers and one for the result

    // Ask the user to input their numbers
    printf("Enter the minuend (number to be subtracted from): ");
    scanf("%lf", &num1);  // Capture and save the first number

    printf("Enter the subtrahend (number to subtract): ");
    scanf("%lf", &num2);  // Capture and save the second number

    difference = num1 - num2;  // Perform the subtraction operation

    printf("The difference between %.2lf and %.2lf is: %.2lf\n", num1, num2, difference);  // Showcase the result

    return 0;  // Denotes successful execution
}

Output:

Enter the minuend (number to be subtracted from): 20
Enter the subtrahend (number to subtract): 12
The difference between 20.00 and 12.00 is: 8.00

4. Step By Step Explanation

1. #include <stdio.h>: By adding this, we integrate the standard input/output library, essential for functions such as printf and scanf.

2. int main(): Recognized as the program's entry point, every C program springs to life from the main function.

3. double num1, num2, difference;: In this segment, we're reserving space for three variables of the double type. These will store our two numbers and the resulting difference.

4. The printf function: Primarily for showing prompts and messages to the user.

5. The scanf function: It's pivotal for reading user input. We use %lf since we're working with the double type. The ampersand (&) denotes the memory address of our variable, specifying where to store the input.

6. difference = num1 - num2;: Here, the subtraction takes place.

7. return 0;: A common convention, this indicates that the program ended without any hitches.

This basic program serves as a stepping stone, introducing fundamental concepts of C programming, especially regarding user interactions and arithmetic operations.

Comments