Basic C Exercises
C program to add two numbers
Write a C program to input two numbers from user and calculate their sum. C program to add two numbers and display their sum as output. How to add two numbers in C programming.
Required knowledge
Data Types in c, Input/Output in C, C OperatorsProgram to add two numbers
/** * C program to find sum of two numbers */ #include <stdio.h> int main() { int num1, num2, sum; /* * Read two numbers from user */ printf("Enter first number: "); scanf("%d", &num1); printf("Enter second number:"); scanf("%d", &num2); /* Adding both number is simple and fundamental */ sum = num1 + num2; /* Prints the sum of two numbers */ printf("Sum of %d and %d = %d", num1, num2, sum); return 0; }
Note: You can also write the above program using single scanf() function.
/** * C program to find sum of two numbers */ #includeint main() { int num1, num2, sum; /* * Input two numbers from user */ printf("Enter any two numbers : "); scanf("%d%d", &num1, &num2); sum = num1 + num2; /* Prints the sum of two numbers */ printf("Sum of %d and %d = %d\n", num1, num2, sum); return 0; }
Note: \n is a escape sequence character used to print new line (used to move to the next line).
Output:
Enter any two numbers : 12 20 Sum of 12 and 20 = 32