CS156

CS156: Intro to C, Part I

Fall 2017

IO

See this page as a slide show

CS156 IO: Input/Output

Reading input

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);

Example reading in from stdin

#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; 
} 

What is this &?

Memory

AddressValue
927800111011
927900000000
928011111110
928110101010
928201010101
928311110000
928411110000
928511110000
928600010110

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.

Memory by type

#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

Address

scanf reads values IN …

Stress the ampersand

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 CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building