CS110_02a_printfScanf - EECS 110: 2a Literals &...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: EECS 110: 2a Literals & Constants, printf() & scanf() Essentials Jack Tumblin [email protected] Types of Variables There are 4 basic `built-in' types in C: Type Integer Floating point Double Character C keyword to use: int float double char BAD: Scattered Literals /******************************************* Hydra.c -- a program with variables. *******************************************/ #include < stdio.h > main() { int heads; int eyes; heads = 3; eyes = heads * 2; integer literals; -not declared, just written directly -(no memory location; not a C variable!) /* assign a value */ /* compute a value */ printf("It has %d heads and %d eyes! \n", heads, eyes); } string literal; (includes quotes) -not declared, just written directly -(no memory location; not a C variable!) Better!: #define for Literals /******************************************* Hydra.c -- a program with variables. *******************************************/ #include < stdio.h > #define JT_HEADS #define JT_EYES_PER_HEAD main() { int heads; int eyes,hats; 3 2 preprocessor directives; -centralized location; -defined once (no scattered typos!) -can use it many times w/o error -(REMEMBER: no memory location; not a C variable!) heads = JT_HEADS; /* assign a value */ eyes = heads * JT_EYES_PER_HEAD; /* compute a value */ hats = JT_HEADS; printf("It has %d heads and %d eyes! \n", heads, eyes); printf("It needs %d hats in winter.", hats); } Better!: #define for Literals /******************************************* Hydra.c -- a program with preprocessor variables. *******************************************/ #include < stdio.h > directives; -strict substitution, -`build' does it BEFORE compiling - OK for *ANY* text in your pgm! #define JT_HEADS 3 #define JT_EYES_PER_HEAD 2 #define HAT_STRING "It needs %d hats in Winter" main() { int heads; int eyes,hats; heads = JT_HEADS; /* assign a value */ eyes = heads * JT_EYES_PER_HEAD; /* compute a value */ hats = JT_HEADS; printf("It has %d heads and %d eyes! \n", heads, eyes); printf(HAT_STRING, hats); } #define Directive: A Better Way for Literals Why? One single, central location for fixed values (prevents scattered, hard-to-find errors in literals) Works for ANY repeated text, not just numbers (string literals, even executable text statements...) How? put your #defines with other directives (e.g. #include, etc) Syntax: #define UNIQUE_NAME my_VALue42 Before compiling, `pre-processor' does find&replace on your file: every UNIQUE_NAME string replaced by my_VALue42. Convention: UNIQUE_NAME is always in UPPERCASE. CAREFUL! NOT A STATEMENT! no semicolon needed! Literals .vs. Constants A CS jargon disaster! (even your book confuses them!) `Literals'==fixed values written into the program: not declared, no address--no memory location assigned address not re-usable--written directly into each statement... no error-finding help--danger! misteaks are very hard to find) help Better Idea! use #define (C preprocessor directive) `Constants'== genuine C variables (?!?!), but set once and then FORBIDDEN TO CHANGE. CHANGE must declare, must initialize (or get errors). has a genuine address in memory (important later) re-usable in as many statements as you like. Try to change values? Reports errors `at run-time'! Literals .vs. Constants In CS jargon, constants are variables (!?!?!) whose value is found when the program runs (CS Jargon: `initialized at run-time'), that CANNOT CHANGE as program runs. (try it! you'll get an error message) How? Declare a variable, but use keyword const before variable type: const double pi = 3.1415926535897932384626433832795; (hint: Start=>Programs=>Accessories=>Calculator, View=>Scientific, PI button) All together now: Constants, Literals, #define #include<stdio.h> /*compiler directive*/ #define JT_PI 3.1415926535897932384626433832795 /*preprocessor directive*/ (hint: Start=>Programs=>Accessories=>Calculator, View=>Scientific, PI button) int main() { const double m_pi = JT_PI; /*const enforces fixed-value var*/ return (m_pi * 2.0); } ?Why is this better? Literals .vs. Constants ?Why have both? `Literals'==fixed values written into the program Value is fixed when you write the program (CS Jargon: `at compile-time') Impossible to change without re-compiling. (reliable). Hint: use #define for a central location to set value `Constants'== genuine C variables, but set once and then FORBIDDEN TO CHANGE. CHANGE Value is set as the program runs; misuse? Error msg. Value can be computed by program itself, at runtime. Has a reserved memory location: literals do not (other parts of you program can select it, copy it, etc. ) Text output: printf() printf() function will print formatted output to the screen. To print a string: printf("This is a message"); How do we print the value of a variable? Text output: printf() Use special format specifiers depending on type. To print an integer : int deg=53; printf("Today's temperature is %d degrees", deg); Specifier for "print an integer value" "Read value from this variable" Text output: printf() Essential format specifiers: %c for single characters %d for integers %f for float/double fractions: 1234.56 %e for float/double scientific: 1.23456E+3 %s for phrases or `strings' (coming soon!) more formatting details later... %x or %X for hexadecimal (base 16) : 0x14FB79E0 %o for octal (base 8): 0x14FB79E0 Keyboard input: scanf() scanf() function will scan formatted keyboard input values into your program. Uses same format specifiers as printf(), but for input To read an integer : scanf(" %d", &integer_variable_name); Specifier for "read an integer" (NEEDS the space char!) VERY IMPORTANT special symbol (pointers: you'll understand soon) Keyboard input: scanf() #include <stdio.h> int main() { int heads, eyes; printf("how many heads?:"); /* ask user */ scanf(" %d", &heads); /* read in */ eyes = heads * 2; /* compute */ printf("Watch out for %d eyes!\n",eyes); return 0; } Result: > how many heads? 3 (you type in 3) > Watch out for 6 eyes! Try it! How can we write a program to compute the area of a circle? The volume of a rectangle? The balance point for a fulcrum with two weights on each end? What happens if we MIX data types? int i,j; double fi, fj,f0,f1,f2,f3,f4; i=5; fi = 5.0; j=2; fj = 2.0; f0 f1 f2 /*** f3 = fi/ = i/ = fi/ BUT! ***/ = i/ fj; fj; fj; j; /* int, double 5 */ /* int, double 2 */ /* /* /* result: result: result: 2.5 2.5 2.5 */ */ */ /* result: 2.0 */ /* result: 2.5 */ f4 = (double)i/ (double)j; WHY?!?! See pg 114 in book... `Cast' i and j to type double ...
View Full Document

This note was uploaded on 10/05/2011 for the course COMPUTER S 110-1 taught by Professor Tumblin during the Spring '11 term at Northwestern.

Ask a homework question - tutors are online