Write a simple c program that will add 2 numbers and display the result on linux?

Certainly! Below is a simple C program that adds two numbers and displays the result. You can compile and run this program on a Linux system.

add_numbers.c

#include <stdio.h>

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

    // Ask user for input
    printf("Enter first number: ");
    scanf("%f", &num1);
    
    printf("Enter second number: ");
    scanf("%f", &num2);
    
    // Calculate sum
    sum = num1 + num2;

    // Display the result
    printf("Sum: %.2f\n", sum);

    return 0;
}

Steps to Compile and Run the Program

  1. Open a Terminal on your Linux system.

  2. Create a new file named add_numbers.c using a text editor, such as nano or vim.

    nano add_numbers.c
    
  3. Copy and paste the code above into the file and save it. In nano, you can save the file by pressing CTRL + O, then Enter, and exit with CTRL + X.

  4. Compile the program using gcc (GNU Compiler Collection).

    gcc add_numbers.c -o add_numbers
    
  5. Run the compiled program.

    ./add_numbers
    
  6. Follow the prompts to enter the numbers to be added.

Example Output

Enter first number: 5
Enter second number: 10.5
Sum: 15.50

This program uses float to allow for decimal number input as well. You can change float to int if you only want to work with integer values.

Have your own question?

Ask the AI now