C Program to Calculate Sum using only One Variable


As we also talked before that the less numbers of variables in the program means less memory used by the program and in return the program also run faster. So it;s always best to reduce the number of variables used in the program, as to increase the execution time of the program.

In this post we are going to make the program to calculate sum of two integers using only a single variable. We will achieve this by making a function.

Let’s have ah Look The Program ►►

#include<stdio.h>
#include<conio.h>
 
long int sum( );

void main()
{
clrscr();

printf("Enter the Numbers to calculate their Sum : ");

printf("\nSum = %ld",sum() + sum() );

getch();
}

long int sum( )
{
long int c;

scanf("%ld",&c);

return(c);
}

Explanation ►►

Here what we only did is call the function in printf that return a long value. Printf() first call the first right side sum() call and then second. In function sum() we declare a long variable c and store the user input in the variable and then return that value, stored in c and finally in printf() both returned values got add and using %ld format specifier the calculated sum is printed on the screen.

NOTE : We must use the long int variable because the limit of int variables -32768 to 32768 is short in many cases. (As if user entered 40000)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s