C Program Declarations – How to Assign Variables?
The below C Program shows and example of typical declarations, assignments and values stored in various types of variables.
C Program Declarations with Examples
The variables x and p have been declared as floating-point variables. Note that the way the value of 1.234567890000 that we assigned to x is displayed under different output formats. The value of x is displayed as 1.234567880630 under %.12lf format, while the actual value assigned is 1.234567890000. This is because the variable x has been declared as a float that can store values only upto six decimal places.
main() { /*..........Declarations............................*/ float x, p ; double y, q ; unsigned k ; /*..........Declarations and Assignments............*/ int m = 54321 ; long int n = 1234567890 ; /*..........Aasignments.............................*/ x = 1.234567890000 ; y = 9.87654321 ; k = 54321 ; p = q = 1.0 ; /*..........Priniting................................*/ printf("m = %d\n", m) ; printf("n = %ld\n", n) ; printf("x = %.12lf\n", x) ; printf("x = %f\n", x) ; printf("y = %.12lf\n",y) ; printf("y = %lf\n", y) ; printf("k = %u p = %f q = %.12lf\n", k, p, q) ; }
Output:
m = -11215 n = 1234567890 x = 1.234567880630 x = 1.234568 y = 9.876543210000 y = 9.876543 k = 54321 p = 1.000000 q = 1.000000000000
C Program Typical declarations, assignments and values
The variable m that has been declared as int is not able to store the value 54321 correctly. Instead, it contains some garbage. Since this program was run on a 16-bit machine, the maximum value that an int variable can store is only 32767. However, the variable k (declared as unsigned) has stored the value 54321 correctly. Similarly, the long int variable n has stored the value 1234567890 correctly.
The value 9.87654321 assigned to y declared as double has been stored correctly but the value is printed as 9.876543 under %lf format. Note that unless specified otherwise, the printf function will always display a float or double value to six decimal places. We will discuss later the output formats for displaying numbers.
Let me know if you find any difficulty in understanding this example and I would be glad to explain it further.