Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C: Adding Two Numbers

In this program, two numbers are accepted from the user, and their addition is stored in another variable, which is then displayed on the screen.


First of all, lets get the headers out of the way.
//WinterNurf Productions

#include <stdio.h>

#include <conio.h>

Now, we declare three variables. Two of these will be used to hold the numbers accepted from the user, and the third will hold their sum. The identifier names are self explanatory.
int main()
{
        //Declare three variables

        int nValue1, nValue2, nSum;

Next, we accept two numbers from the user using the scanf_s() (or scanf()) function.
        //Accept their values from the user
        Printf ("\n  Enter first number: ");
        scanf_s ("%i", &nValue1);
        printf ("  Enter second number: ");

        scanf_s ("%i", &nValue2);

Now, we add the two numbers and store it in the third variable. To add the numbers, we simply use the + operator.
        //Add the two numbers

        nSum = nValue1 + nValue2;

Finally, we display the value of the third variable (which is the addition of the two variables accepted by the user) and end the program.
        //Display the result
        printf ("  The sum of the two numbers is: %i", nSum);

        _getch();
        return 0;

}

Here is the full code.
//WinterNurf Productions

#include <stdio.h>
#include <conio.h>

int main()
{
        //Declare three variables
        int nValue1, nValue2, nSum;

        //Accept their values from the user
        printf ("\n  Enter first number: ");
        scanf_s ("%i", &nValue1);
        printf ("  Enter second number: ");
        scanf_s ("%i", &nValue2);

        //Add the two numbers
        nSum = nValue1 + nValue2;

        //Display the result
        printf ("  The sum of the two numbers is: %i", nSum);

        _getch();
        return 0;

}

This program has been written in Microsoft Visual Studio for Desktop. It may not work in older compilers. However, simple editing will make the code compatible.


This post first appeared on Code Walk, please read the originial post: here

Share the post

C: Adding Two Numbers

×

Subscribe to Code Walk

Get updates delivered right to your inbox!

Thank you for your subscription

×