Once we get the input(s) from the user [Tutorial 5], it is time to modify the input by performing operations on it. The basic idea of coding is to design systems which perform various functions. And a function is nothing but a machine that gives output values for various input values.
Since our basic aim is to implement functions, we need to perform operations on the inputs to get outputs. Now, suppose you had to code a basic machine that adds 5 to the input.
You will need to:
Step 1 : Get an input value from the user
Step 2 : Add 5 to the input
Step 3 : Display output to the user
Method 1 –
#include <stdio.h>
#include <conio.h>int main()
{
int x;
printf(“Enter any number\n“); /* Step 1 */
scanf(“%d“, &x);int y;
y=x+5; /* Step 2 */
printf(“The output is %d“, y); /* Step 3 */
getch();
return 0;
}
In the above method, we have used two variables. x for the input and y for the output. However, we can add 5 to change the input itself and display it as the output (this is the power of programming, the otherwise constant inputs are variables in a program)
Method 2 –
#include <stdio.h>
#include <conio.h>int main()
{
int x;
printf(“Enter any number\n“); /* Step 1 */
scanf(“%d“, &x);x=x+5; /* Step 2 */
printf(“The output is %d“, x); /* Step 3 */
getch();
return 0;
}
Now, don’t get confused when you see x=x+5; Just remember the following thumb rule :
In programming, the value on the right hand side(called the rvalue replaces the value on the left hand side(called the lvalue). In this case, (x+5) replaces x. hence, the new value of x is (x+5).
For a more elegant code, we could perform the addition in the printf function itself.
Method 3 –
#include <stdio.h>
#include <conio.h>int main()
{
int x;
printf(“Enter any number\n“); /* Step 1 */
scanf(“%d“, &x);printf(“The output is %d“, x+5); /* Steps 2 & 3 */
getch();
return 0;
}
In this case, the steps 2 and 3 can be implemented in a single line. As you will realize later, this is what programming is all about. A lot of people can program, but only a few can come up with the most elegant solution. And the most elegant one wins.
Note – in the above program, we did not have to define the “+” operator. It is one of the pre-defined C operators. C has a number of mathematical, logical and other operators. (discussed later)