250 likes | 338 Views
L ecture 2. Input-Process-Output The Hello-world program A Feet-to-inches program Variables, expressions, assignments & initialization printf() and scanf() #include Readings: Chapter 1 Section 2 to 6. The traditional first C program. /* The traditional first program in honor of
E N D
Lecture 2 • Input-Process-Output • The Hello-world program • A Feet-to-inches program • Variables, expressions, assignments & initialization • printf() and scanf() • #include • Readings:Chapter 1 Section 2 to 6
The traditional first C program /* The traditional first program in honor of Dennis Ritchie who invented C at Bell Labs in 1972 */ #include <stdio.h> int main() { printf("Hello, world!\n"); return 0; }
Program Structure • Comments begin with /* and end with */ • anything between the delimiters is ignored • “#include…” - called include directives, tells the compiler to include the header file <stdio.h>into the program • Every program must have amain function where program execution begins; inside the main function is a sequence of statementsspecifying the actions to be done.
Some Syntax Rules • C is case-sensitive • Thus, “main” is not the same as “Main” • All keywords used in C are in lower-case • Syntax of preprocessing directives: • # must start at leftmost margin • no space after < and before > • no semi-colon at the end, each include directive must be on its own line
Some Syntax Rules (cont’d) • Syntax of Statements: • most statements are ended with semicolons • spacing is not important • programmer can put in suitable spacing and indentation to increase readability
The printf() function • printf() is a library function • It resides in the library with header file stdio.h • It outputs data to the screen • “Hello, world!\n” is the string to be printed; ‘\n’ represents a newline character • non-printable characters are preceded by \ in C
The return statement • return signifies the end of a function • The number after the keyword return is sent back as the return value of the function main() • A return value of 0 usually means that the execution of the function is successful
/* To convert length in feet to inches */ #include <stdio.h> int main(void) { int inches, feet; scanf(“%d”, &feet); inches = 12 * feet; printf(“%d feet is equivalent to %d inches”, feet, inches); return 0; } A Feet-to-inches program
Program dissection 1 • int inches, feet; • Defineinches and feet as integer variables • Variables must be defined before they are referred • scanf(“%d”, &feet); • The statement causes the computer to input an integer from keyboard and store it in variable feet • The first string is called a control string / formatter string • The formatter %d indicates that an integer is expected
Program dissection 2 • inches = 12 * feet; • It is NOT an equality statement • It is an assignment statement, which assigns the value of expression12 * feet to the variable inches • The asterisk “*” stands for the multiplication operation • printf(“%d feet is equivalent to %d inches”, feet, inches); • The first string is a control or formatter string • The formatter %d in the control string causes the two parameters after the string to be printed as an integer
/* comments */ #include <stdio.h> int main() { statement-1 statement-2 statement-3 . . . return 0; } Layout of a simple C program
Variables • To store data (e.g. user input, intermediate result) • Implemented as memory bytes • Each variable must have a name and a type
Variable Names • A variable name consists of a sequence of letters, digits and underscores, but must not begin with a digit • As a convention, user-defined variables always start with a lower-case letter • Certain reserved words (keywords) are used by C and cannot be used as variable names, e.g. int, return, etc.
Data Types • There are 3 major data types in C: • int e.g. 12 • float e.g. 2.54 • char e.g. ‘A’, ‘e’, ‘#’, ‘ ’ • Data of different types are stored using different encoding schemes and require different number of memory bytes • Exact schemes differ from system to system
Typical Encoding Schemes • int • 2’s complement • 4 bytes (32 bits) • [-231, 231-1] = [-2147483648, 2147483647] • float • Floating point representation • 4 bytes • 3.4 x 1038 (7 decimal places of accuracy) • char • ASCII • 1 byte
Variable Definitions • All variables should be defined (and initialized) before they are referenced • The purpose is to tell the computer the names and types of the variables so that • sufficient memory bytes are allocated for the variables; and • content in these memory bytes are interpreted appropriately.
Expression • An expression is a meaningful combination of constants, variables and operators (e.g., +, -, *, /) • Constants are the simplest expressions, e.g., 7, ‘A’ and “Hello World\n” • Some operators only work on certain types of variables, e.g., ‘A’ * ‘B’ doesn’t make much sense
Assignment • A variable is assigned (given) a value using the assignment operator“=” • An assignment expression consists of an =, a variable on its left and an expression on its right. E.g. inch = 12*feet • An assignment expression followed by a semi-colon is called an assignment statement. E.g. inch = 12*feet; • Some illegal assignment statements: a + b = c;/* illegal */ 12 = a;/* illegal */
Variable Initialization • When variables are defined, they may also be initialized, e.g., char grade = ‘A’; int k = 10; • Only fathoms is initialized to 7 below int inches, feet, fathoms = 7; • Both inches and fathoms are initialized below int inches = 8, feet, fathoms = 7;
The use of printf() • The first argument of printf() is a control string which may contain k formatters for the second to (k+1)-st arguments of printf(), e.g., printf(“%s attained %d courses\nAverage” “ mark is %f\nOverall grade is %c\n”, “Jimmy Liu”, 4, 66.5, ‘B’); The output is Jimmy Liu attained 4 courses Average mark is 66.500000 Overall grade is B
The use ofprintf() (cont’d) • printf() conversion characters (see p.16 of [Kelly & Pohl 2001]) c as a character d as a decimal integer e as a floating point number in scientific notation (float or double) f as a floating point number (float or double) g in the e-format or f-format, whichever is shorter (float or double) s as a string
The use ofprintf() (cont’d) • The field width and the precision (for floating point number only) of an output data can be controlled, e.g., %5.2f means the field width is 5 (including the decimal point) with 2 decimal places • What will happen when the field width is too long or too short for the output data?
The use of scanf() • scanf() is to read input from keyboard • Like printf(), the first argument is a control string, which is followed by an arbitrary number of arguments (and those arguments are addresses of data items that store the input) • Address operator is represented by an ampersand &, e.g., int feet; scanf(“%d”, &feet);
The use ofscanf() (cont’d) • scanf() conversion characters (see p.18 of [Kelly & Pohl 2001]) c as a character d as a decimal integer f as a floating point number (float) lf as a floating point number (double) Lf as a floating point number (long double) s as a string
The use ofscanf() (cont’d) • When reading in numbers, scanf() will skip white space (blanks, newlines and tabs) • scanf() ends when • the input does not match the corresponding formatter in the control string • an end-of-file signal (EOF) is detected • Keyboard inputs are stored in keyboard buffer and they are “consumed” by scanf(); excessive data inputs will be left in the buffer for subsequent scanf() statements