C program to add two numbers

Write a program in C to enter 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 first number: 20
Input second number: 10
Output: Sum = 30

Required knowledge:

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

Program:

/**
 * C program to calculate sum of two numbers
 */

#include <stdio.h>

int main()
{
    int num1, num2, sum;
    
    /*
     * Read two numbers from user
     */
    printf("Enter first number: \n");
    scanf("%d", &num1);
    printf("Enter second number: \n");
    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: The above program can also written using single scanf() function as below.


/**
 * 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 : \n");
    scanf("%d%d", &num1, &num2);
    
    sum = num1 + num2;
    
    /* Prints the sum of two numbers */
    printf("Sum of %d and %d = %d",num1, num2, sum);
    
    return 0;
} 


Note: \n is a escape sequence character used to print new line or is used to move to the next line.


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

Happy coding ;)


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
< code >< pre > -- Your source code -- < /pre >< /code > (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