Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05

Similar presentations


Presentation on theme: "C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05"— Presentation transcript:

1 C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
Narrator: Lecture 5: C Programming Basics Winter Quarter Lecture 05

2 Engineering H192 Winter 2005 ENG H192 Course Web Page A web page which contains the course syllabus, updated lecture notes and other useful information may be found at: A copy of the Excel-based flowchart spreadsheet is on the Web site Narrator: As a side note, updated material may be found on the course website at the URL on this slide. Winter Quarter Lecture 05

3 C Program Basics C vs. C++
Engineering H192 Winter 2005 C Program Basics C vs. C++ C is a subset of C++. All of features in C are contained in C++ C++ adds more libraries with functions for object oriented programming C++ also adds more keywords and some added features. Instructor: C++ was developed after C and thus contains additional keywords along with the standard C keywords. This class will first learn C since it is a good basis for the fundamentals of C++. Narrator: C++ was developed after C and thus contains additional keywords along with the standard C keywords. C++ adds more libraries and support for something called object oriented programming. As a result C++ also adds more keywords and programming features. Winter Quarter Lecture 05

4 Engineering H192 Winter 2005 Keywords in C and C++ Certain words have a special meaning to the C or C++ compiler. They are called reserved words or keywords. We should not try to use these words as names of variables or function names in a program. The keyword list for C contains 32 words (D&D – Section 2.6). C++ adds 30 more keywords (D&D – Section 18.6). Instructor: Using keywords as variable or functions will cause errors in the compiler (or a program that builds programs from a user’s code), or in the rare condition that the program still compiles it may operate unpredictably. Narrator: (read text 1st paragraph). Using keywords as variable or functions will cause errors in the compiler (or a program that builds programs from a user’s code), or in the rare condition that the program still compiles it may operate unpredictably. (read text 2nd paragraph). Winter Quarter Lecture 05

5 Some Keywords in C and C++
Engineering H192 Winter 2005 Some Keywords in C and C++ switch template this throw try typedef union unsigned virtual void volatile while new operator private protected public register return short signed sizeof static struct double else enum extern float for friend goto if inline int long asm auto break case catch char class const continue default delete do Instructor/Narrator: Let’s take a moment to look over a few of these keywords. The black keywords = C, red keywords were introduced in C++. Winter Quarter Lecture 05

6 Program Structure in C EACH complete C program is composed of:
Engineering H192 Winter 2005 Program Structure in C EACH complete C program is composed of: Comment statements Pre-processor directives Declaration statements One or more functions Executable statements Instructor: These components will make more sense to the students after they are described in further slides. Narrator: (read text). Each of these components will be discussed in this lecture. Winter Quarter Lecture 05

7 Program Structure in C EACH complete C program is composed of:
Engineering H192 Winter 2005 Program Structure in C EACH complete C program is composed of: Comment statements Pre-processor directives Declaration statements One or more functions Executable statements Instructor: A complete C program will more likely contain elements in a fashion shown on this slide. Point out that there are many comment statements and that students will be expected to include many comment statements in their code. Narrator: A complete C program will more likely contain elements in a fashion shown on here. Notice that many comment statements exist, which are used by programmers as an aid when reading their code. You will be expected to also write many comment statements within your code. Winter Quarter Lecture 05

8 // Comment ….. Ends at the end of line
Engineering H192 Winter 2005 Comment Statements Formal Comments: /* Comment ….. */ Used for detailed description of functions or operations (for our benefit, not compiler’s). Can take multiple lines in source file. Informal Comments (only in C++, not C): // Comment ….. Ends at the end of line Used for quick comments like: int temp; // temporary variable for storing // the input value Instructor: Comments can take two formats (formal and informal). C style (formal) comments always begin with /* and end with */ and can contain multiple lines between the beginning and end. The comment will not end until the */ set is seen by the compiler. C++ style (informal) comments begin with // and end at the end of the line. Anything after the // set will be considered a comment by the compiler until a new line is reached. Narrator: Comments can take two formats (formal and informal). Comments are written for our benefit, to describe what the code is doing so that another programmer may easily understand what is going on without attempting to follow through the logic of a program. C style (formal) comments always surrounded by the opening and closing comment command and can contain multiple lines between the beginning and end. The comment will not end until the closing comment command is seen by the compiler. C++ style (or informal) comments begin with // and end at the end of the line. Anything after the // set will be considered a comment by the compiler until a new line is reached. Winter Quarter Lecture 05

9 Pre-Processor Directives
Engineering H192 Winter 2005 Pre-Processor Directives #include -- header files for library functions Example: #include <stdio.h> #define -- define constants and macros Examples: #define e #define pi Note Space Instructor/Narrator: Pre-Processor directives tell the compiler various things to do or things to remember before processing (or compiling) the user’s code. These are always at the beginning of a C program. The #include directive tells the program to place other files before your actual program. These other files contain various information the compiler must know about the computing environment and language before it can process the user’s code. For example the stdio.h file contains information and definitions about how to get input from the user’s keyboard or terminal and how to display it on the screen (thus stdio stands for “standard I/O”). The #define directive allows the user to create static variables to use later in his or her program. These become useful when a user wishes to use the value pi for example. Instead of typing the long decimal number for pi, he or she can simply define it once and then use the variable “pi” from then on in his or her code. Also if someone were to discover that he or she originally typed the value for pi incorrectly, it would only require a change in one location instead of multiple locations throughout the program. Note Spaces Winter Quarter Lecture 05

10 Engineering H192 Winter 2005 Declarations Declarations tell the compiler what variable names will be used and what type of data each can handle (store). Example declarations: int a, b, c ; float r, p, q ; double x, y, z ; char m, n ; Instructor/Narrator: Declarations allow the program to know what kind of variables it will be using and how much memory to reserve for each type of variable. Variables must be declared before they can be used. Some example declarations of various types are shown here. Notice multiple variables of the same type can be declared on a single line by separating them with a comma. Winter Quarter Lecture 05

11 Data Types Integer variables: int a, b ;
Engineering H192 Winter 2005 Data Types Integer variables: int a, b ; Integer variables, like a or b, store only whole numbers like 3 or 7, not 3.33 or 7.65, and only up to certain maximum values. Floating point variables: float c, d ; Floating point variables, like c or d, store rational numbers, like , but only a limited number of digits of precision. Instructor: Integer variables will only store the integer value of a number. Thus if a floating point number is stored in an integer variable the common result is the floating point portion of this number is cut off (NOT rounded up, you can think of this as always rounding down). All numbers stored in the computer only have a certain amount of precision. For floating point numbers this can be though of as cutting off the digits below a certain decimal point value. Narrator: Integer variables, like their name suggests, store integer numbers, but they will only store the integer value of a number. Thus if a floating point number is stored in an integer variable the common result is the floating point portion of this number is cut off (NOT rounded up, you can think of this as always rounding down). Floating point numbers store rational numbers, but all numbers stored in the computer only have a certain amount of precision. For floating point numbers this can be though of as cutting off the digits below a certain decimal point value. Winter Quarter Lecture 05

12 Internal Storage Representation
Engineering H192 Winter 2005 Internal Storage Representation Definitions: Binary digit -- or a "bit", is either a 0 or a 1 Byte -- usually a collection of 8 bits together Word -- often a collection of 4 bytes together On the SGI Unix system: an "int" data type takes up 4 bytes (on some systems, an "int" is only 2 bytes) a "float" data type takes up 4 bytes a "double" data type take up 8 bytes a "char" data type takes up 1 byte Instructor: Data is stored in computers in units called bits, which can only hold a value of 0 or 1 (off or on). A byte is a more common representation of computer data. 4 bytes = 32 bits 8 bytes = 64 bits The char data type is also stored as a number, with each number representing a certain character. Students may wish to visit for more information. Narrator: Data is stored in computers in units called bits, which can only hold a value of 0 or 1 (off or on). A byte, or 8 bits of data together, is a more common representation of computer data. A word is a collection of 4 bytes together. On various computer systems the data types will require different amounts of memory. For the SGI UNIX system an int requires 4 bytes (on some systems int is less precise, only using 2 bytes). Float also requires 4 bytes, and a double precision variable, as might be expected by its name, requires 8 bytes. The char data type, which stores characters or text, requires a single byte. As for this type each number represents a certain character. This number to character conversion is standardized and known as the ASCII table. Winter Quarter Lecture 05

13 Programs Have One or More Functions
Engineering H192 Winter 2005 Programs Have One or More Functions Even the main program is a function. The body of each user-written function is enclosed in braces, { } (or curly brackets) The syntax of a function is: <function type> function_name (arg. list) { /* beginning of function */ } /* end of function */ Instructor: Programs are written in the form of functions. Functions are contained within the braces. The syntax of any function is given. A common example is: void main() { } void = function type (what the function returns to whatever called the function) main = function name (the name it can be called as) () = argument list (a list of variables the function begins with given to it by whatever program called the function, in this case empty) Narrator: Every program has at least one function, that being the main function. The body of every function is enclosed in braces, otherwise known as curly brackets. The general syntax of a function is shown. The function type is basically what the function returns once it completes. This can be any of the data types we mentioned before (be it int, float, char, etc.) or it can also be “void,” meaning the function returns no value to whatever program called it. The function name is, of course, the name that is called to execute the function, except in the case of main, which is automatically executed when a program is run. The argument list follows in parentheses. This contains any values that are passed to the function for it to operate on. In the case of most of our main() functions the argument list will be empty, meaning the function doesn’t require any input. Finally the braces enclose all commands of the function. We’ll look more closely at this syntax later. Winter Quarter Lecture 05

14 Executable Statements
Engineering H192 Winter 2005 Executable Statements Simple Declaring variables int temp ; char a ; Assigning Values temp = 5 ; temp is assigned the value of 5 Complex, i.e., Calling Functions plotxy (x, y) ; Calculations x = (5. / 2 + 6) * 7 ; Instructor/Narrator: Executable statements actually perform the operations in a program. They can be anything from declaring variables, assigning values to variables, to performing calculations. Other functions can also be called. In this case the function called fubar is called, with two variables (x and y) passed to it as arguments. From here we would expect fubar to complete some operation with the variables x and y. Winter Quarter Lecture 05

15 Arithmetic Operators * multiply + add / divide - subtract
Engineering H192 Winter 2005 Arithmetic Operators * multiply + add / divide - subtract % remainder, where: x = 13 % 5 ; /* x will be equal to */ An expression can be used almost anywhere a variable of the same type can be used. Ex. expressions: num + 3, a * d - 5, ... Instructor: Students may be unfamiliar with the remainder operator. Explain that the resultant is not stored anywhere and the purpose of this function is to calculate only the remainder (what is left over by the operation). Examples of where this is useful will be given later in the quarter. Narrator: All the standard arithmetic operators are available for use. The remainder operator may be new, though. This operator returns the ONLY the remainder of a division instead of a standard floating point result. The quotient is thrown away with this operator. Also note that variables can be used anywhere in expressions where a number would normally exist, for example num+3, or a*d-5. This allows us to complete any algebraic expression. Winter Quarter Lecture 05

16 Arithmetic Operators – Order of Evaluation
Engineering H192 Winter 2005 Arithmetic Operators – Order of Evaluation Parentheses: () – Evaluate from the inside out Multiplication, Division, and Remainder: *, /, and % Addition and Subtraction: + and - NOTE: Multiple occurrences of operations with the same precedence evaluate from left to right. (D&D – Section 2.4) Instructor notes: It’s important to inform students that there is a definite order of events when it comes to evaluating mathematical operations. The contents of parentheses are first with the default order of events taking place within the parentheses. Multiplication, Division and Remainder are second. Addition and Subtraction are third. When multiple occurrences of equal precedence operations occur on the same line, the equal precedence operations are evaluated from left to right. Winter Quarter Lecture 05

17 Arithmetic Operators – Order of Evaluation
Engineering H192 Winter 2005 Arithmetic Operators – Order of Evaluation For example: x = 2 * 3 - (4 + 5) + 8 % 7; x = 2 * % 7; x = % 7; x = ; x = ; x = -2; Instructor notes: In this slide we see how the original equation would evaluate step by step to get the final result of -2. Values given in red indicate which value was solved for on each step. First, the contents of the parentheses are solved for because it has the highest precedence. Next we see that 2*3 and 8%7 have equal precedence, but 2*3 comes first in a left to right reading, so 2*3 is solved for. Following this, 8%7 has the highest remaining precedence, so it is solved for to give 1. Finally, all that remains is addition and subtraction, which have equal precedence, so the subtraction is done to give -3 and then the addition is done to give the final result. Winter Quarter Lecture 05

18 Arithmetic Operators – Order of Evaluation
Engineering H192 Winter 2005 Arithmetic Operators – Order of Evaluation Another example: x = 6 / * 4; x = 33; x = 6 / (2 + 1) - (3 + 8) * 4; Instructor notes: Here we have two similar equations that give wildly different results merely because of the placement of parentheses. The equations will be shown first and upon subsequent mouse clicks the results will appear giving students a chance to think about possible solutions. x = -42; Winter Quarter Lecture 05

19 Engineering H192 Winter 2005 Mixed Mode Arithmetic When performing arithmetic operations, the "mode" will one of: Floating point, if both operands are floating point Integer, if both operands are integer Mixed, if one operand in integer and the other is floating point -- the result is floating point Integer operations produce integer results (remember how you first learned to to division?) Instructor: An integer and floating point may differ by the decimal point at the end of a number. For example: 5 is an integer 5. is a floating point Narrator: It would be expected that at some point arithmetic involving both floating point and integer numbers will occur, but what will the result of this arithmetic be? Let’s say we are solving a simple equation with two variables. If both of these variables are floating point, then the result will also be floating point. If both variables are integer, then the result will also be integer. If one is an integer and the other a floating point, the result will be a floating point. To summarize, whenever a floating point variable exists in an equation, the result will also be a floating point. One case you may expect otherwise is the division of two integers where the result isn’t a whole number, but these rules still hold true. If you remember back when you first learned division, you were first taught to only find the largest whole number result, and forget about the remainder. An integer-integer division will operate in this manner. Winter Quarter Lecture 05

20 Assignment Operators Operator: Example: Meaning: = x = 5 ; x = 5 ;
Engineering H192 Winter 2005 Assignment Operators Operator: Example: Meaning: = x = 5 ; x = 5 ; += x += 5 ; x = x + 5 ; –= x –= 5 ; x = x – 5 ; /= x /= 5 ; x = x / 5 ; *= x *= 5 ; x = x * 5 ; %= x %= 5; x = x % 5 ; Instructor: Most of these operators were introduced by programmers to reduce the number of keystrokes needed for simple mathematical operations. Narrator: C also includes what are called assignment operators. They are a shorthand method of completing simple mathematical equations and assigning the result to the variable on the left hand side of the equation. For example the meaning of x += 5 is simply to add 5 to x, then place the result back in x. The constant 5 can be replaced by any variable or expression that returns a numerical result. Winter Quarter Lecture 05

21 Assignment Operators Example of assignment operators:
Engineering H192 Winter 2005 Assignment Operators Example of assignment operators: int a = 4, b = 2, c = 36 ; a += b ; /* This adds b to a, a = ? */ c /= a + b ; /* What is value of c now? */ Instructor: The next 2 slides contain the answers to the two questions. These are assumed to be two consecutive operations (a doesn’t re-initialize to 2 after the first operation). Narrator: Now let’s look at some more examples of the assignment operators. Here we have declared three integer variables and assigned them initial values. When we perform the operation a+=b what will the result be? Take a few seconds and come up with the result on paper or in your head. Winter Quarter Lecture 05

22 Assignment Operators Example of assignment operators:
Engineering H192 Winter 2005 Assignment Operators Example of assignment operators: int a = 4, b = 2, c = 36 ; a += b ; /* This adds b to a, a = ? */ [ Answer: a = a + b, so a = or a = 6 ] c /= a + b ; /* What is value of c now? */ Narrator: Breaking down this operation into longhand form we’d have a=a+b, so replacing the a and b variables on the right hand side with their values we have 4+2, or 6. So a will now contain the value 6. What is the result of the second operation? Take into account that a is now 6. Winter Quarter Lecture 05

23 Assignment Operators Example of assignment operators:
Engineering H192 Winter 2005 Assignment Operators Example of assignment operators: int a = 4, b = 2, c = 36 ; a += b ; /* This adds b to a, a = ? */ [ Answer: a = a + b, so a = or a = 6 ] c /= a + b ; /* What is value of c now? */ [ Answer: c = c / (a + b), and a = 6 now, so c = 36 / (6 + 2), so c = 36 / 8 or c = 4 ] Narrator: Again the longhand format of this equation will be c=c/(a+b) in this case, since the assignment operator will divide the left hand side by the ENTIRE right hand side. Replacing the variables with values on the right hand side and completing some arithmetic yields the result of 4, so the answer is c=4. Winter Quarter Lecture 05

24 Increment/Decrement Operators
Engineering H192 Winter 2005 Increment/Decrement Operators Operator: Meaning: When? count++ ; count = count + 1 ; After use ++count ; count = count + 1 ; Before use count-- ; count = count - 1 ; After use --count ; count = count - 1 ; Before use Instructor/Narrator: These are more shortcuts developed by programmers since variables often are incremented or decremented by 1. It is important to remember when each of these operations occur. As you may notice when the operator is included before the variable, the operation occurs BEFORE it is used. Conversely when the operator is included after the variable, the operation is completed after it is used. These operations are executed independent of the mathematical operation they may be included in. Winter Quarter Lecture 05

25 Increment/Decrement Operators
Engineering H192 Winter 2005 Increment/Decrement Operators Examples of increment and decrement operators: int a = 4, b = 2, c; c = ++a + b-- ; /* What are the values of a, b, c now? */ c = b a ; /* What are the values of a, b, c now? */ Instructor: The answers to the two questions are contained on the next two slides. Have the students attempt to calculate the answers before they are displayed. Narrator: Let’s look at some examples of the increment and decrement operators. Again we have three integer variables, some with initialized values. Spend some time looking at the first mathematical equation and determine an answer. Remember when the increment and decrement occurs is determined by where the operator is located. Winter Quarter Lecture 05

26 Increment/Decrement Operators
Engineering H192 Winter 2005 Increment/Decrement Operators Examples of increment and decrement operators: int a = 4, b = 2, c; c = ++a + b-- ; /* What are the values of a, b, c now? */ (Answers: a = 5, b = 1, c = 7) c = b a ; /* What are the values of a, b, c now? */ Narrator: In this equation we have an increment and decrement operator. The ++a will occur before a is used in this equation, so a is incremented from 4 to 5. Since b-- is decremented after use we will look at this after the equation is computed. We can now compute c=a+b with a=5 and b=2. The result which c is assigned is then 7. After the equation is complete we can then look for post-equation increments and decrements. b-- will now be completed, decrementing b from 2 to 1. So the final result is a=5, b=1, and c=7. With these new values of a, b, and c attempt to solve this second equation. We will look at the results in a minute. Winter Quarter Lecture 05

27 Increment/Decrement Operators
Engineering H192 Winter 2005 Increment/Decrement Operators Examples of increment and decrement operators: int a = 4, b = 2, c; c = ++a + b-- ; /* What are the values of a, b, c now? */ (Answers: a = 5, b = 1, c = 7) c = b a ; /* What are the values of a, b, c now? */ (Answers: a = 6, b = 0, c = -5) Narrator: In this case we increment a again before the equation, so a is now 6. Now that no more preceding operations exist, solving the equation b-a with b=1 and a=6 results in c=-5. Finally we can now decrement b again, resulting in b=0. In summary we have a=6, b=0, and c=-5. Winter Quarter Lecture 05

28 Relational Operators Operator: Meaning: > Greater Than
Engineering H192 Winter 2005 Relational Operators Operator: Meaning: < Less Than > Greater Than <= Less Than or Equal To >= Greater Than or Equal To == Exactly Equal To != Not Equal To Instructor: Relational operators will be used in decision-making structures. Other languages such as MATLAB differ mainly in the Not Equal operator C: != MATLAB: ~= Some others: <> Narrator: To solve yes or no questions we must be able to compare variables to each other. Thus we have these relational operators available for use. Pay close attention to the “exactly equal to” operator. It is important to not confuse this with the assignment operator, the single =. Another operator to pay close attention to is the not equal operator. In other languages this will vary the most. For example when we take a look at MATLAB you will notice the operator is ~=. Winter Quarter Lecture 05

29 Relational Operators Used for asking questions like:
Engineering H192 Winter 2005 Relational Operators Used for asking questions like: Is x bigger than 10? In C, the value of 1 stands for true and 0 stands for false. But C will recognize any non zero value as true. NOTE: "==" is NOT same as "=" Instructor: Point out the fact that it is very important when programming to use == and = correctly, or the program will operate unexpectedly. == is used to determine a relation = is used to assign Narrator: Relational operators allow the computer to ask questions and determine results of these questions. In C the result will be a 1 or 0. The 1 stands for true and a 0 stands for false. In the case of C, though, it will actually recognize any non-zero value as true. Also remember == is not the same as =. == is used to determine a relation between two variables, or ask a QUESTION. = is used to assign, or make a STATEMENT. Winter Quarter Lecture 05

30 Logical Operators ! (not) Ex: a != b is true if a and b are not equal
Engineering H192 Winter 2005 Logical Operators ! (not) Ex: a != b is true if a and b are not equal && (and) Ex: 5<6 && 7>4 is true, but 5>6 && 7>4 is not true (i.e., false) || (or) Ex: 5>6 || 7>4 is true 5<6 || 7<4 is also true Narrator: Along with relational operators, C also has logical operators. These are used in conjunction with the relational operators to create Boolean statements which the computer can then evaluate to true or false. The ! is the NOT operator. For example, for a!=b to be true, a and b cannot be equal. AND is used to check for more than one expression being true. It will only return true if all the expressions ANDed together are true. The OR operator will return true if at least one of the expressions ORed together is true. Notice in the given example how the first expression is true for both AND and OR since both of the expressions are true (5 is less than 6 AND 7 is greater than 4). The second expression on the other hand doesn’t contain all true statements, so the AND example will return false (5 is greater than 6 AND 7 is greater than four is not a true statement). On the other hand “5 is less than 6 OR 7 is less than 4” contains one true statement, which satisfies this expression and the result is true. Winter Quarter Lecture 05

31 Exponentiation Operations
Engineering H192 Winter 2005 Exponentiation Operations Exponentiation is not written as x**2 or x^2 C does not have an exponentiation operator. You can use the math function pow (a, b) which raises a to the b power. You must put a #include <math.h> in your source code and you might need the -lm switch in your compile command when on some UNIX systems, for example: >g++ -o myprog.out myprog.cpp -lm Note that g++ on Linux does not need the "-lm". Instructor: A common error for students when compiling their programs is they forget the math.h header in their program. This will cause the compiler to display an error that it does not understand the pow() function. The second common error is for students to forget the –lm option. This will not cause a problem on a certain line so it is more difficult to locate. Remind students to check for both of these conditions if they get errors in their programs. Narrator: C doesn’t have a shorthand method of completing exponentiation, or powers. Instead you must use the math function pow(a,b) which raises a to the b power. To use this function you must include another library, in this case <math.h> along with <stdio.h>. This is also a special case in that when you compile your program with the math library you must also add a –lm to the end of the compilation command as shown. Winter Quarter Lecture 05

32 Skeleton Program /**************************************/
Engineering H192 Winter 2005 Skeleton Program /**************************************/ /* Name: Brutus Buckeye */ /* Seat No. 0, Instr: W. Hayes */ /* Program progname */ #include <stdio.h> #include <stdlib.h> #include <math.h> int main ( ) { statements ; } Instructor: Point out each of the following lines: Comments Pre-processor directives Functions (in this case main()) Statements (There are no declarations shown in this example, they would be part of the statements) Narrator: Shown here is a simple skeleton program you may wish to use when writing your programs. The first three lines are comments which contain in this case some information about yourself and the program. The next three lines are pre-processor directives, in this case #include statements for three different libraries. One function exists in this program, in this case main() which would then include statements within its braces including variable declarations. Altogether this is what is necessary to complete a simple program in C. Winter Quarter Lecture 05


Download ppt "C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05"

Similar presentations


Ads by Google