Overview of a C Program Programming with C CSCI 112, Spring 2015 Patrick Donnelly Montana State University C Language Components • Preprocessor Directives • Comments • The “main” function • Variable Declarations and Data Types • Executable Statements • Reserved Words • Identifiers Programming with C (CSCI 112) Spring 2015 2 / 42 General Outline of a C Program preprocessor directives main function heading { declarations executable statements } Programming with C (CSCI 112) Spring 2015 3 / 42 Example C Program # include < stdio .h > # define KMS_PER_MILE 1.609 // printf , scanf definitions // conversion constant int main ( int argc , char ** argv ) { double miles ; // distance in miles double kms ; // equivalent distance in kilometers // get the distance in miles printf ( " Enter the distance in miles > " ); scanf ( " % lf " , & miles ); // convert the distance to kilometers kms = KMS_PER_MILE * miles ; // display the distance in kilometers printf ( " That equals % f kilometers .\ n " , kms ); return (0); } Programming with C (CSCI 112) Spring 2015 4 / 42 Anatomy of a C Program Programming with C (CSCI 112) Spring 2015 5 / 42 Example C Program: Preprocessor Directives #include <stdio.h> #define KMS PER MILE 1.609 int main ( int argc , char ** argv ) { double miles ; // distance in miles double kms ; // equivalent distance in kilometers // get the distance in miles printf ( " Enter the distance in miles > " ); scanf ( " % lf " , & miles ); // convert the distance to kilometers kms = KMS_PER_MILE * miles ; // display the distance in kilometers printf ( " That equals % f kilometers .\ n " , kms ); return (0); } Programming with C (CSCI 112) Spring 2015 6 / 42 Example C Program: Declarations # include < stdio .h > # define KMS_PER_MILE 1.609 // printf , scanf definitions // conversion constant int main ( int argc , char ** argv ) { double miles; double kms; // get the distance in miles printf ( " Enter the distance in miles > " ); scanf ( " % lf " , & miles ); // convert the distance to kilometers kms = KMS_PER_MILE * miles ; // display the distance in kilometers printf ( " That equals % f kilometers .\ n " , kms ); return (0); } Programming with C (CSCI 112) Spring 2015 7 / 42 Example C Program: Comments # include < stdio .h > # define KMS_PER_MILE 1.609 // printf, scanf definitions // conversion constant int main ( int argc , char ** argv ) { double miles ; // distance in miles double kms ; // equivalent distance in kilometers // get the distance in miles printf ( " Enter the distance in miles > " ); scanf ( " % lf " , & miles ); // convert the distance to kilometers kms = KMS_PER_MILE * miles ; // display the distance in kilometers printf ( " That equals % f kilometers .\ n " , kms ); } Programming with C (CSCI 112) Spring 2015 8 / 42 Example C Program: Executable Statements # include < stdio .h > # define KMS_PER_MILE 1.609 // printf , scanf definitions // conversion constant int main ( int argc , char ** argv ) { double miles ; // distance in miles double kms ; // equivalent distance in kilometers // get the distance in miles printf("Enter the distance in miles> "); scanf("%lf", &miles); // convert the distance to kilometers kms = KMS PER MILE * miles; // display the distance in kilometers printf("That equals %f kilometers.\n", kms); return(0); } Programming with C (CSCI 112) Spring 2015 9 / 42 Our C Program # include < stdio .h > /* lab01 . c ( name of your file ) * Philip J . Fry ( your name ) , CSCI112 , Lab 01 * 08/28/2014 ( current date ) */ int main ( void ) { printf ( " Hello World \ n " ); return (0); } Programming with C (CSCI 112) Spring 2015 10 / 42 Preprocessor Directives Definition: Preprocessor Directives Preprocessor Directives are commands that give instructions to the C preprocessor. Definition: Preprocessor The Preprocessor is a program that modifies your C program before it is compiled. Preprocessor Directives start with a “#” symbol. • #include • #define • #if • #else • #endif • #pragma Programming with C (CSCI 112) Spring 2015 11 / 42 #include #include is used to include other source files into your source file. #include gives a program access to a library/header file. • stdio.h • math.h • time.h Libraries are a collection of useful functions and symbols. Standard libraries are predefined by the ANSI C language. • You must include stdio.h if you want to use printf and scanf library functions. • “#include <stdio.h>” inserts their definitions into your program before compilation. Programming with C (CSCI 112) Spring 2015 12 / 42 #define The #define directive instructs the preprocessor to replace every occurance of a particular text with a given constant value. The replacement occurs before compilation. Your source code: #d e f i n e P I 3 . 1 4 1 5 9 #d e f i n e EULERS NUMBER 2 . 7 1 8 2 8 i n t main ( v o i d ) { d o u b l e x = 5 ∗ PI ; d o u b l e y = EULERS NUMBER ∗ 7 ; return (0); } What actually gets compiled: i n t main ( v o i d ) { double x = 5 ∗ 3.14159; double y = 2.71828 ∗ 7; return (0); } Programming with C (CSCI 112) Spring 2015 13 / 42 Constants #define Constants • Consists of 3 parts: ◦ “#define” ◦ constant name ◦ constant value • There is no “=” sign or “;” at the end # define M Y _ C O N S T A N T _N A M E 123 # define ANSWER 42 Programming with C (CSCI 112) Spring 2015 14 / 42 Comments Comments provide extra information, making it easier for humans to understand the program. These comments are completely ignored by the compiler. Comments take two forms: • /* • // */ - anything between asterisks is a comment. - anything after is a comment, but only until EOL. Comments are used for documentation that helps other programmers read and understand the program. Programs should contain a comment at the top with • the programmer’s name, • the date, and • a brief description of what the program does. COMMENT YOUR CODE! Programming with C (CSCI 112) Spring 2015 15 / 42 The “main” function The heading “int main(void)” marks the beginning of the main function where your program execution begins. Every C program has a main function. Braces/Curly brackets: { } mark the beginning and end of the body of the function. A function body has two parts: • declarations: (names of variables and data types) tell the compiler what memory cells are needed in the function and how they should be processed. • executable statements: they reflect “actions” of your algorithm. These are translated into machine language by the compiler and later executed. Programming with C (CSCI 112) Spring 2015 16 / 42 Declarations of Variables Variable: A memory cell used to store program data. • A variables value can change with time. • We use its name as a simple reference (instead of the actual address in memory). Variable declaration: Statement that communicates to the compiler the names of variables in the program and the data type they represent. Example: double miles ; This tells the compiler to create a space for a variable of type double in memory and refer to it each time we use the name miles in our program. Programming with C (CSCI 112) Spring 2015 17 / 42 Numeric Data Types Definition: Data Type Data Type: a set of values and a set of operations that can be performed on those values. Numeric Data Types: • int: Stores integer value (whole number). Examples: 65, -123 • double: Stores real number (uses a decimal point). Examples: 3.14159, 1.23e5 (123000.0) Arithmetic operations (+,-,*,/, %) can be used on ints and doubles. Programming with C (CSCI 112) Spring 2015 18 / 42 Character Data Type Character Data Type: • char: An individual character value. Examples: ‘a’, ,‘5’, ‘*’ (can be a letter, digit, or special symbol) Character Declaration • Use single quotes, NOT double quotes char my_char = ’Z ’; Comparison operations (<, >, ≤, ≥) can be used on ints, doubles and chars. Programming with C (CSCI 112) Spring 2015 19 / 42 ASCII Code ‘A’ < ‘B’ < ‘C’ < ... < ‘X’ < ‘Y’ < ‘Z’ Programming with C (CSCI 112) Spring 2015 20 / 42 Executable Statements Executable Statements: C statements used to write or code the algorithm. The C compiler translates the executable statements into machine code. Examples: • Input/Output Operations and Functions ◦ printf function ◦ scanf function • Assignment Statement (=) • return Statement/Operation Programming with C (CSCI 112) Spring 2015 21 / 42 Executable Statements: Input/Output Operations Input operation: data transfer from outside the program into computer memory that is usable by the program. Input may be received from: • A program user • An external file • Another program Output operation: program results that can be displayed to the program user. Results can be printed to: • The standard console output • An external file Programming with C (CSCI 112) Spring 2015 22 / 42 Executable Statements: Functions A function takes input parameters and produces an output. A function definition specifies the return type, the input parameters, and the body. A function call is used to call or activate a function. • Calling a function means asking another piece of code to do some work for you. Programming with C (CSCI 112) Spring 2015 23 / 42 Executable Statements: Functions - printf() By calling the printf() function, we are asking for the function to print to standard output. The first argument to printf is the formatting code (in string form), and all following arguments are the the variables to be used in the placeholders. double miles = 2.7; printf ( " That is % f miles .\ n " , miles ); Programming with C (CSCI 112) Spring 2015 24 / 42 Executable Statements: Functions - printf() Multiple placeholders can be specified, and the corresponding arguments are then provided in order. Different types of variables require different formatting codes. int a = 1; double b = 2.0; char * c = " three " ; printf ( " Easy as %d , %f , % s !\ n " , a , b , c ); Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable Statements: Functions - scanf() Reading input data in a program is done via the scanf() function. The concept is very much the same as the printf() function. In this case, the format code is just the variable code for what data will be received (%d, %c, %lf), and the following arguments are the variables that will receive the data. double miles ; scanf ( " % lf " , & miles ); The “&” is the address operator in C. The “&” operator in front of variable miles informs the scanf() function about the location of variable miles in the computer’s memory. Programming with C (CSCI 112) Spring 2015 26 / 42 printf()/scanf() statements printf()/scanf() statements Use commas to deliminate printf/scanf arguments. char a = ’! ’; int b = 7; float c = 3.7; double d = 1.5; printf ( " % c | % d | % f | % lf | % c \ n " , a , b , c , d , a ); scanf ( " % lf " , & d ); Remember that %f is for floats, %lf is for doubles • For printf(), doubles can be implicitly converted to floats printf ( " % f \ n " , & d ); printf ( " % lf \ n " , & d ); scanf ( " % lf " , & d ); Programming with C (CSCI 112) Spring 2015 27 / 42 Assignment Statements An assignment statement stores a value in a variable. • The value assigned can be the result of another computation. kms = KMS_PER_MILE * miles ; The above assigns a value (content) to the variable kms. The value assigned in this case is the result of the multiplication of the constant KMS PER MILE by the variable miles. We should interpret an assignment statement: value = expression as: value ← expression This should be read as “becomes”, “gets”, or “takes the value of” rather than “equals”. Programming with C (CSCI 112) Spring 2015 28 / 42 Assignment Statements Effect of kms = KMS PER MILE * miles; Programming with C (CSCI 112) Spring 2015 29 / 42 Assignment Statements “=” is NOT an algebraic operator. Consider the following: sum = sum + item ; This is obviously not a correct algebraic equation (if item 6= 0). This statement instructs the computer to add the current value of sum to the value of item. Afterward the result is stored back into sum. Equality: To test for equality, use the “==” operator. Be sure to keep these concepts separate. Remember! Every variable has contents, even before assignment. Programming with C (CSCI 112) Spring 2015 30 / 42 Assignment Statements Effect of sum = sum + item; Programming with C (CSCI 112) Spring 2015 31 / 42 Arithmetic Operators Operator + Meaning addition Examples 5+2=7 5.0 + 2.0 = 7.0 − subtraction 5 −2 = 3 5.0 −2.0 = 3.0 * multiplication 5 * 2 = 10 5.0 * 2.0 = 10.0 / division 5.0 / 2.0 = 2.5 5/2=2 % remainder (mod) 5%2=1 5/2=2 Programming with C (CSCI 112) Spring 2015 32 / 42 Expression Example Area of a Circle a = πr 2 can be written in C as: area = PI * radius * radius ; where PI is a constant macro set to 3.14159. Programming with C (CSCI 112) Spring 2015 33 / 42 Expression Evaluation Programming with C (CSCI 112) Spring 2015 34 / 42 Expression Example 3 Evaluation Tree and Evaluation for v = (p2 - p1) / (t2 t1); Programming with C (CSCI 112) Spring 2015 35 / 42 Expression Example 4 Evaluation Tree and Evaluation for z - (a + b / 2) + w * -y; Programming with C (CSCI 112) Spring 2015 36 / 42 The “return” statement In your main() function, the return statement will transfer control from your program to the operating system. “return(0);” returns a 0 to the operating system, which indicates that the program executed without error. • This means that the end of the program was reached. • It does not mean that the program did what it was supposed to do. There still may have been logical errors. Other functions also have return statements, which can return error codes, data, or nothing at all. Programming with C (CSCI 112) Spring 2015 37 / 42 Punctuation & Special Symbols Semicolons: ; Mark the end of a statement (which may take more than one line). Curly Braces: { } Mark the beginning and end of the body of a function. Mathematical Symbols: *,/,+,Are mainly used to compute numeric values. Note that some have additional meaning. In particular, we will talk about * later. Programming with C (CSCI 112) Spring 2015 38 / 42 Reserved Words A reserved word is a word that has special meaning to C and can not be used for other purposes. These are words that C reserves for its own uses. They are often necessary for the compiler to analyze the language’s grammar and to understand what the programmer wants to do (declaring variables, controlling data flow, etc). • In example, you cannot have a variable named “return” or “if”. Reserved words are always lowercase. See your book or the reference links on the website for a complete list of reserved words. Programming with C (CSCI 112) Spring 2015 39 / 42 Standard Identifiers An identifier is a name given to a variable or an operation. • This is just a formal term for function names and variable names. A standard identifier is an identifier that is defined in the standard C libraries and has special meaning in this standard (such as ANSI C). • Examples include printf and scanf • Unlike reserved words, you can re-define a standard identifier • It is not recommended to use standard identifiers in a non-standard way, especially when linking to other code that uses these standards. Programming with C (CSCI 112) Spring 2015 40 / 42 User Defined Identifiers Variables: We choose our own identifiers to name memory cells that will hold data. Functions: We choose our own identifiers to name operations that we define. Common Rules for Naming Identifiers: • May consist only of letters, digits, and underscores • cannot begin with a digit • reserved words cannot be used • standard identifiers should not be redefined Valid Identifers: var1, inches, KM PER MILE Invalid Identifiers: 1var, the*var, return Programming with C (CSCI 112) Spring 2015 41 / 42 Identifier Naming Guidelines Some compilers only recognize the first 31 characters of identifier names, so avoid long identifiers. Compilers are case-sensitive. • Aviod very similar names (differ by case, or a single letter) • ITEM is different than Item is different than item • Note that conventional C code uses lowercase and underscores for variables (as opposed to camel-case used in Java) ◦ miles ◦ vehicle speed Constants and Macros usually use all uppercase ◦ KMS PER MILE is a defined constant Choose meaningful identifiers that are easily understood. • distance = velocity * time is more intelligible than x = y * z. Programming with C (CSCI 112) Spring 2015 42 / 42
© Copyright 2025 Paperzz