Write a simple C program that adds two numbers and displays 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
-
Open a Terminal on your Linux system.
-
Create a new file named
add_numbers.cusing a text editor, such asnanoorvim.nano add_numbers.c -
Copy and paste the code above into the file and save it. In
nano, you can save the file by pressingCTRL + O, thenEnter, and exit withCTRL + X. -
Compile the program using
gcc(GNU Compiler Collection).gcc add_numbers.c -o add_numbers -
Run the compiled program.
./add_numbers -
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.
Was this answer helpful?
Thanks — your feedback improves the quality gate.