The following program does a simple calculation using the values of the variables:
// Simple calculations #include <stdio.h> int main(void) { int total;/* w ww .j a va 2 s. c om*/ int cats; int dogs; int bugs; int others; // Set the number of each kind of pet cats = 2; dogs = 1; bugs = 1; others = 5; // Calculate the total number of pets total = cats + dogs + bugs + others; printf("We have %d pets in total\n", total); // Output the result return 0; }
You first define five variables of type int:
int total; int cats; int dogs; int bugs; int others;
the variables are given specific values in these four assignment statements:
cats = 2; dogs = 1; bugs = 1; others = 5;
at this point the variable total doesn't have an explicit value set.
It will get its value as a result of the calculation using the other variables:
total = cats + dogs + bugs + others;
in this arithmetic statement, you calculate the sum of all your pets on the right of the assignment operator by adding the values of each of the variables together.
this total value is then stored in the variable total that appears on the left of the assignment operator.
printf() statement presents the result of the calculation by displaying the value of total:
printf("We have %d pets in total\n", total);