CS156: Intro to C, Part I

Spring 2018

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

int i;
float f;
double d;
char c;
short int si;
long int li;
long double ld;

// sizeof operator gives the size of a variable
printf("char: %zu byte\n",         sizeof(c));
printf("short int: %zu bytes\n",   sizeof(si));
printf("int: %zu bytes\n",         sizeof(i));
printf("long int: %zu bytes\n",    sizeof(li));
printf("float: %zu bytes\n",       sizeof(f));
printf("double: %zu bytes\n",      sizeof(d));
printf("long double: %zu bytes\n", sizeof(ld));
char: 1 byte
short int: 2 bytes
int: 4 bytes
long int: 8 bytes
float: 4 bytes
double: 8 bytes
long double: 16 bytes

But they’re not the same everywhere!

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!

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-03-08T23:08

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building