int zipcode; double weight; printf("Enter zip code: "); scanf("%d", &zipcode); printf("Enter weight: "); scanf("%lf", &weight); printf("And now both: "); scanf("%d %lf", &zipcode, &weight);
scanf
.
printf
. The formatting symbols are the same,
except double is %lf
(letter l, letter f).
#include <stdio.h> int main() { double friction, number; int numPeople; // read in some values printf("Enter the amount of friction: "); // prompt stays on line scanf("%lf", &friction ); printf("Enter the number of people:\n"); // prompt goes to next line scanf("%d", &numPeople); number = friction + 3.2 * 2; // This makes no sense printf("The final number was %f\n", number); printf("The value of \"friction\" was %f.\n", friction ); printf("There are %d people here.\n", numPeople); return 0; }
&
in front of the variable’s name tells the
program to use the variable’s address in memory rather than its value.
Address | Value |
---|---|
9278 | 00111011 |
9279 | 00000000 |
9280 | 11111110 |
9281 | 10101010 |
9282 | 01010101 |
9283 | 11110000 |
9284 | 11110000 |
9285 | 11110000 |
9286 | 00010110 |
Memory is divided into many memory locations (or cells).
Each memory cell has a numeric address, which uniquely identifies it.
Every location has a value, whether you put one there or not. The statement “there’s nothing in there” is meaningless.
#include <stdio.h> int main() { int integerType; float floatType; double doubleType; char charType; short int shortIntType; long int longIntType; long double longDoubleType; // Sizeof operator is used to evaluate the size of a variable printf("Size of char: %ld byte\n",sizeof(charType)); printf("Size of short int: %ld bytes\n",sizeof(shortIntType)); printf("Size of int: %ld bytes\n",sizeof(integerType)); printf("Size of long int: %ld bytes\n",sizeof(longIntType)); printf("Size of float: %ld bytes\n",sizeof(floatType)); printf("Size of double: %ld bytes\n",sizeof(doubleType)); printf("Size of long double: %ld bytes\n",sizeof(longDoubleType)); return 0; }
Size of char: 1 byte Size of short int: 2 bytes Size of int: 4 bytes Size of long int: 8 bytes Size of float: 4 bytes Size of double: 8 bytes Size of long double: 16 bytes
&
to designate we want the address, not the value inside
scanf
needs to know where to store them the values
printf
need the address too?
int x=3; printf("x is now %d\n", x); // No ampersand printf("Gimme: "); scanf("%d", &x); // Ampersand! printf("x is now %d\n", x); // No ampersand
If you use c11 -Wall
, it tells you when you forget the ampersand,
and when you put in an extra one. Use -Wall
!
Modified: 2017-02-24T10:47 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |
![]() |