C program to add two numbers

Previous Exercise Next Program

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.

Example

Input

Input first number: 20 
Input second number: 10

Output

Sum = 30

Required knowledge

Fundamentals of C, Data types, Taking user input in C

Program 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 We can also write the above program using single scanf() function.
/**
 * C program to find sum of two numbers
 */

#include <stdio.h>

int main()
{
    int num1, num2, sum;
    
    /*
     * Read 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).

Before you move on to the next exercise you may also want to check out - C program to find sum of two numbers using pointers.

Output
Enter any two numbers : 12
20
Sum of 12 and 20 = 32

Happy coding ;)

Recommended post

Previous Exercise Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

1 comment:

  1. Basic C Program for Computer Programmer who want to learn. If you have simple wish you may visit. To get all update stay with us.
    Outline:
    • Language: C and Simscript.
    • if (Condition) statement and Nested if statement is used to determine the given number is positive, negative, even or odd. Another way we solve this program using if-else-if ladder.
    • When the given condition or expression is true the statement associated with it executed.
    To know details:
    http://www.secufoon.com/write-a-c-program-for-determining-a-number-is-positive-negative-even-or-odd/

    ReplyDelete