C Program to add two Numbers

Here's a step-by-step description of adding two numbers in C :


How to Add Two Numbers in C

Adding two numbers in C is one of the simplest programs for beginners to learn. Here's a step-by-step guide to implement this:


Step 1: Understand the Problem

Before diving into the code, understand that the program will:

  1. Accept two numbers as input from the user.
  2. Add them together.
  3. Display the result.

Step 2: Set Up Your Development Environment

  1. Install a C compiler, such as GCC, or use an online compiler.
  2. Open a text editor or an Integrated Development Environment (IDE) like Visual Studio Code, Code::Blocks, or Dev-C++.

Step 3: Write the Program

Here’s a simple C program for adding two numbers:

#include <stdio.h>

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

// Input two numbers from the user
printf("Enter the first number: ");
scanf("%d", &num1);

printf("Enter the second number: ");
scanf("%d", &num2);

// Perform addition
sum = num1 + num2;

// Display the result printf("The sum of %d and %d is %d.\n", num1, num2, sum); return 0; // End of program
}

Step 4: Break Down the Code

  1. Header File:

    • The #include <stdio.h> statement includes the standard input-output library for using functions like printf and scanf.
  2. Main Function:

    • The int main() function is where the program begins execution.
  3. Variable Declaration:

    • int num1, num2, sum; declares three integer variables: two for input and one for storing the result.
  4. Taking Input:

    • The printf statements prompt the user to enter values.
    • The scanf function reads the user's input and stores it in num1 and num2.
  5. Performing Addition:

    • sum = num1 + num2; adds the two numbers and stores the result in sum.
  6. Displaying Output:

    • The printf function displays the sum in a formatted manner.
  7. Returning 0:

    • The return 0; statement indicates successful program termination.

Step 5: Compile and Run the Program

  • Press F9 (shortcut for "Build and Run").
  • Alternatively, go to the Build menu at the top and select Build and Run.
  • Code::Blocks will use the GCC compiler to compile the code automatically.
  • After successful compilation, Code::Blocks will execute the program.
  • A terminal window will open, prompting you to enter input values for your program.


Step 6: Example Execution

Here’s how the program might look in action:

Enter the first number: 5
Enter the second number: 10
The sum of 5 and 10 is 15.

Step 7: Enhance Your Program

To make the program more versatile:

  1. Add error handling for invalid input.
  2. Support floating-point numbers using float instead of int.

This video explain in detail the practical demonstration to add two numbers in a C program using Code::Block:


Comments