1 / 84

Overview of the c Programming Language

An Overview of the C/C++ Programming Languages. Overview of the c Programming Language. What you MUST know before we start:. Overview of the c Programming Language. Not Much : This is the exception to the rule that everything builds on the previous topics.

Télécharger la présentation

Overview of the c Programming Language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. An Overview of the C/C++ Programming Languages Overview of the c Programming Language

  2. What you MUST know before we start: Overview of the c Programming Language • Not Much: This is the exception to the rule that everything builds on the previous topics • We do know a little about C/C++ Programming: • How to declare variables/Request Memory locations • How to assign values to variables/set the appropriate bit-sequence in RAM • We also know all about: • Bits and Bytes (Machine Architecture) • Basic Data Types (Storage in RAM) • NOW we need to learn how to operationalize our knowledege

  3. The C Programming Language Overview of the c Programming Language • Developed in 1978 at Bell Labs by Kernighan & Ritchie after A & B failed • Associated with UNIX • • Developed on UNIX Systems • • UNIX and its software are written in c • Intended as general purpose Language • Basically a primitive language: 34 (28 original) Key words: float auto default new sizeof union break do for register static unsigned case goto double release struct void char else if return switch volatile typedef const enum int short continue extern long signed while

  4. The C++ Programming Language Overview of the c Programming Language • Developed by  Bjarne Sroustrup  at Bell Labs during 1983-1985. • C++ is an extension of C. • Prior to 1983, Stroustrup added features to C and formed what he called "C with Classes". • In 1983 the use of classes and object-oriented features with the power and efficiency of C. The term C++ was first used in 1983. • Additional C++ Reserved Words and default namespace reinterpret_cast virtual and_eq not delete template wchar_t asm not_eq xor dynamic_cast this xor_eq bitand explicit operator throw export or true bitor catch false try or_eq 40 Additional; 74 Total class friend private typeid const_cast inline protected typename public using continue mutable

  5. So, master of insipidness, which language will we use ??? Overview of the c Programming Language • Mostly simple (?) C • Most of C++ consists of C • You really can’t understand C++ unless you know C first • We will use some C++ commands • Mostly for I/O activities • You will learn more about C++ in later classes

  6. So, insipidness personified, is there anything we should look out for ??? Overview of the c Programming Language • As Stroustrup remarked (I’m paraphrasing): In C, it is easy to shoot yourself in the foot. In C++, if you do, you will blow your foot off. Ouch!!! No es bueno!! No es bueno para nada !!!

  7. C/C++ Operators Overview of the c Programming Language Standard/Common Operators: Binary Operators: Operators Between Two Operands: Operator Meaning Example Definition. + Addition x = 6 + 2; Add the values on either side of + - Subtraction x = 6 - 2; Subtract right value from left value Multiplication x = 6 * 2; Subtract right hand side values * / Division x = 6/2; Divide left value by right value Dividing real numbers yields EXACT results NOTE: Dividing Integers yields TRUNCATED results % Modulus x = 6 % 2; Remainder of left divided by right What about exponentiation??? Either x = 6 ^ 2 OR x = 6 ** 2 ??? No Such Thing: You must write your own function (Or use an available one)

  8. = x = 3 Assignment Operators: Assigning Values to RAM: Overview of the c Programming Language Operator Example Definition. = x = 6 + 2; Location x will get the value 6 + 2 ( = 8) += x += 3 Same as x = x + 3: IF x contained the value 4, it now contains the value 7 Same as x = x - 3: IF x contained the value 4, it now contains the value 1 *= x *= 3 Same as x = x * 3: IF x contained the value 4, it now contains the value 12 /= x /= 3 Same as x = x / 3: IF x contained the value 4: IF x is a float (real), it now contains 1.33 IF x is an integer, it now contains the value 1 %= x %= 3 Same as x = x % 3: IF x contained the value 4, it now contains the value 1 (3 goes into 4 Once with ONE left over)

  9. Unary Operators: Operators on a single Operand: Operator Meaning Example Definition. Overview of the c Programming Language - Minus Sign x = -2; Assign a negative value + Plus Sign x = +2; Assign a Positive value ++ Increment x = ++y; Prefix Notation OR x = y++; Postfix Notation -- Decrement x = --y; Prefix Notation OR x = y--; Postfix Notation Prefix and Postfix Notation?? What’s that all About ??? Consider the following section of c code: int x,y,a,b; a = b = 1; // Initialize the variables (locations) with the value 1 x = 2 * ++a; // PREFIX Notation: First increment a by 1 (a = 2) // Then Multiply by 2 & assign to x (x=2*2) y = 2 * b++; // POSTFIX Notation: First multiply b by 2 & assign to y (y=1*2) // Then increment b by 1 (b = 2) printf("%d %d\n",x,y); // The Output would appear as:4 2

  10. There are two (2) Additional Unary Operators: sizeof Return the size of the operand (in bytes) Overview of the c Programming Language Consider the following section of c code: int i = 12; float f = -123.45; printf("%d sizeof = %d\n",i,sizeof i); // would produce: 12 sizeof = 2 printf("%7.2f sizeof = %d\n",f,sizeof f); // would produce: -123.45 sizeof = 4 (type) Convert a value to the specified data type Consider the following section of c code: int a = 4; float b = 12.245; printf("%d %ld\n",a,(long) a); // would produce: 44 printf("%d %f\n",a,(float) a); // would produce: 4 4.000000 printf("%f %d\n",b,(int) b); } // would produce: 12.24500012

  11. Relational Operators: Operators on two Operands Yielding a T/F Answer: Overview of the c Programming Language Operator Meaning Example Definition. < x < 2; False if x contains the value 2 Less Than x <= 2; True if x contains the value 2 <= Less Than OR Equal To == x = = 2; True if x contains the value 2 Equal To ! = x ! = 2; False if x contains the value 2 Not Equal To > x > 2; False if x contains the value 2 Greater than >= x >= 2; True if x contains the value 2 Greater than OR Equal To False if x contains the value 2 x > 2 && x < 4 && And | | True if x contains the value 2 x = = 2 | | x = = 4 Or ! False if x contains the value 2 Not ! (x = = 2)

  12. Order of Operations: Order Operator Overview of the c Programming Language 1 ( ) 2 + - ++ -- (unary) ! (Rel) 3 * / % 4 + - (binary) 5 < > <= >= 6 == != && 7 8 | | = 9 Given:int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8; What is the value of the statement: a = (a * ((b + c) % d) / e) - (f * g + 6) * h / 4 + 1;

  13. Given:int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8; Overview of the c Programming Language - 96 + 1 = - 95 0 - 96 = - 96 384 / 4 = 96 1 / 5 = 0 48 * 8 = 384 1 * 1 = 1 5 % 4 = 1 42 + 6 = 48 2 + 3 = 5 6 * 7 = 42 a = (a * ((b + c) % d) / e) - (f * g + 6) * h / 4 + 1;

  14. Example 2: Given:int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8; Evaluate: Overview of the c Programming Language ++a * b-- + c % d / e - f-- * g + 6 * h++ / b + h; 2 2 * 2 = 4 3 % 4 = 3 3 / 5 = 0 6 * 7 = 42 6 * 8 = 48 48 / 2 = 24 4 + 0 = 4 4 - 42 = - 38 - 38 + 24 = - 14 - 14 + 8 = - 6 Note that now: a = 2, b = 1, f = 5, h = 9

  15. Example 3: Given: int a = 1, b = 2, c = 3, d = 4; Consider the statement: Overview of the c Programming Language a > b || b < c && c == 3 || d < 4 && b != c False True False True True False True True True

  16. Printing in C: Overview of the c Programming Language • No Input/Output facilities are provided • • There are no reserved keywords for READ or WRITE • • Functions such as scanf, printf, cout and cin must be added: #include <stdio.h> // a C pre-compiler directive #include <iostream.h> // a C++ pre-compiler directive Why?? Aren’t these standard functions?? Yes, but the designers of C/C++ left I/O implementation up to compiler writers so that they could better match input and output to specific machines

  17. Conversion specifiers for scanf and printf: Overview of the c Programming Language Specifier(s) Output Example %c Single Character B %d %i Signed decimal Integer 457 %u Unsigned decimal Integer 7832 %ld %lu Signed/Unsigned long Integer -345 64 %f Signed floating-point, decimal notation -6.576 -4.5e3 2.1E-2 %e %E Signed floating-point, e or E notation -2.1 4.56E4 %g %G Use shorter or %f or %e (%f or %E) Long double floating-pt (also %LE) 7.32 -6.1e4 %Lf %Le %o Unsigned octal notation 4271 %x %X Unsigned hexadecimal notation 4d2a F6B %s Character string Hello %p Pointer (address) 4FF0: 8BC1 %% Print a % sign % Additional information about printf/scanf specifiers can be found in the Supplementary Materials Link

  18. Misusing Print Specifiers Assume the following C declarations: int a = -32, b = 6781; unsigned int c = 49216; long d = -53212; unsigned long e = 123456; Overview of the c Programming Language What would happen if we applied the following print specifier? printf("%8d %8d %8d %8d %8d\n", a, b, c, d, e); The following output would be produced: ⃞⃞⃞⃞⃞-32⃞⃞⃞⃞6781⃞⃞-16320⃞⃞⃞12324⃞⃞⃞⃞⃞⃞-1

  19. 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 Why?? Overview of the c Programming Language Some are easy to understand. Consider the declaration unsigned int c = 49216; and how it would be stored in RAM: 4921610 = 1100000001000000 (On 16-bits) Since we told the compiler to print the value as a signed int: Negative Sign Compliment: 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 Add 1 (2’s Compliment): + 1 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 = 213 + 212 + 211 + 210 + 29 + 28 + 27 + 26 = 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 = -16,320

  20. Some are a little more complex. Consider the declaration long d = -53212; and how it would be stored in RAM: Overview of the c Programming Language 5321210 = 00000000000000001100111111011100 (32-bits) -5321210 = 11111111111111110011000000100011 (1’s Comp) + 1 11111111111111110011000000100100 (2’s Comp) Taking the right-most 16-bits: = 213 + 212 + 25 + 22 = 8,192 + 4,096 + 32 + 4 (As it appeared in the output) = 12,324

  21. Other Misuses of Print Specifiers Overview of the c Programming Language Sometimes, we can misuse conversion specifiers and get lucky. We can ALWAYS represent characters as integers (since they are stored as integers on 8-bits). Consider the declaration: char c1 = ‘C’, c2 = 51; And the statement: printf(“%c %d %c %d”, c1, c1, c2, c2); C 67 3 51 The output would be: SOMETIMES, we can also print integers as characters: Given: int i1 = ‘C’, i2 = 51; printf(“%c %d %c %d”, i1, i1, i2, i2); C 67 3 51 The output would be:

  22. SOMETIMES, even though we can appear to print integers as characters, we will get strange results: Overview of the c Programming Language Given: int i = 318; printf(“%c %d”, i, i); The output would be: > 318 Why??? Once again, consider how the value is stored in RAM: 31810 = 0000000100111110 (On 16-bits) Taking the right-most 8-bits: = 25 + 24 + 23 + 22 + 21 = 32 + 16 + 8 + 4+ 2 = 62 Which is the ASCII value for the character >

  23. Generally speaking, it is best to avoid misusing specifiers: Given: int a = 317; Overview of the c Programming Language long b = 53212; float c = 43.672; long double d = 5.6E7; printf(“%d %ld %12.4f %13.4Lf”,a , a, a, a); The statement: Would Yield: -317 106233539 0.0000 -0.0000 The statement: printf(“%d %ld %12.4f %13.4Lf”,b , b, b, b); Would Yield: -12324 53212 0.0000 0.0000 The statement: printf(“%d %ld %12.4f %13.4Lf”,c , c, c, c); 0 536870912 43.6720 0.0000 Would Yield: The statement: printf(“%d %ld %12.4f %13.4Lf”,d , d, d, d); Would Yield: 0 0 -2.8220783e+10456000000.0000

  24. What if I need to print a data type using a (different) specifier? Overview of the c Programming Language Don’t forget the type (unary) operator. Using our previous variable declarations, we could print them out on different format. Given: int a = 317; long b = 53212; float c = 43.672; The statement: printf(“%ld %12.4f”, (long) a , (float) a); Would Yield: -317 -317.0000 The statement: printf(“%d %ld”,(int) c , (long) c); Would Yield: 43 43 The statement: printf(“%d %12.4f”, (int) b , (float) b); Would Yield: -12324 53212.0000 ??? Casting variable b as int yields -12324 when b = 53212 ???

  25. Remember how long d = 53212; would be stored in RAM: Overview of the c Programming Language 5321210 = 00000000000000001100111111011100 (32-bits) Taking the right-most 16-bits: The number transferred is: 1100111111011100 Which Equals: 011000000100011 Negative Compliment 1’s Compliment + 1 011000000100100 = (-) 213 + 212 + 25 + 22 = (-) 8,192 + 4,096 + 32 + 4 = -12,324 (As it appeared in the output)

  26. Printing in C++: • Printing in C++ is actually much easier than C. Overview of the c Programming Language • Once you have declared a variable (location), the cout command will automatically print using the specified data type. • The code: #include <iostream.h> //Notice that this is the C++ header file void main() { char c = 109; int i = -765; float f = 2.0445; cout << "c = " << c << " i = " << i << " f = " << f << endl; } • Produces the output:

  27. Well This is a LOT easier than C !! Why didn’t you show us this before ??? Overview of the c Programming Language No pain, no gain -- So tell me, oh master of sadism, does this mean that you can’t specify how you want the output to be displayed, as you can in C ?? Non, mon ami -- Additional information about cout and cin (the equivalent of scanf in C) specifiers can be found in the Supplementary Materials Link

  28. One C++ which is much more convenient, and we will use, is the cin command Overview of the c Programming Language • This command will get user input from the keyboard and store it in a variable location • It is similar to the scanf command in C, but much neater • As we will see when we discuss Character Arrays (Strings), the command is actually doing a lot • There may be some problems, however, so be careful with this command

  29. The Program below: Overview of the c Programming Language Produces the Output

  30. The Basic Structure of the C Programming Language • Precompiler Instructions: Overview of the c Programming Language #include <iostream.h> #define ZERO 0 (function prototypes) (external variables) Additional code/shorthand/ definitions • Main Function: (data type) main (arguments) { // begin declarations statements (return value) } // end A C program consists of one or more function. The primary function MUST be labeled main • Additional Functions: function 1 (optional) functions are the building blocks of C function n

  31. C/C++ Programming Conventions: Overview of the c Programming Language • Case Sensitive: UPPERCASE vs. lowercase • NOT Strongly typed: Checking left to Programmer • Each Statement ends with a semicolon • Elipses and Parentheses MUST match: {…. } ( …. ) • C is a translated language (vs. interpreted): Source Code Compiler Object Code Library Code Linker Start-up Code Executable Code

  32. Precompiler Directives Overview of the c Programming Language #include <header files> <stdio.h>e.g., forprintf() <stdlib.h>e.g., foratoi() <string.h>e.g., forstrcmp() “user-defined functions” e.g., “myfunction.h” #define User Defined ConstantPI 3.15149 Replace the expression PIwith 3.15149 where ever it occurs in the program. Given: float area, r; . . . . . Should a statement such as: area = PI * (r * r);occur It would be replaced with: area =3.15249* (r * r);where ever itoccurs

  33. Precompiler Directives (Continued) Overview of the c Programming Language #define User Defined MacroSQUARE (x) (x * x) Once again, Given: float area, r; . . . . . Should the statement: area = PI * SQUARE(r);occur, it would be replaced with: area = 3.15149 * (r * r); throughout the program Additional Precompiler Instructions (function prototypes) to be discussed later (external variables) to be discussed later

  34. Example Usage of Precompiler Directives Overview of the c Programming Language #include <stdio.h> // Needed for printf #define PI 3.14159 // Pi estimation #define SQUARE(x) (x*x) // a value squared int main() // main statement { // begin the function float area, r = 4.5; // declare variables area = PI * SQUARE(r); // calculate area printf("The area of the circle is: %7.3f\n",area); return(0); // return an int value } // end the function Which would print out: The area of the circle is: 63.617 Since: 4.5 * 4.5 = 20.25 * 3.14159 = 63.6171975

  35. Substitution of a Macro in a Program: Overview of the c Programming Language #include <stdio.h> // Needed for printf #define PI 3.14159 // Pi estimation #define SQUARE(x) (x*x) // a value squared int main() // main statement { // begin the function float area, r = 4.5; // declare variables area = 3.14159 * (r * r); // calculate area printf("The area of the circle is: %7.3f\n",area); return(0); // return an int value } // end the function Unlike functions, Macros are substituted throughout the code

  36. The main function Overview of the c Programming Language • MUST be labeled main • May return any standard data type: • • char main Returns a character • • int main Returns an integer value • • float main Returns a real number • • Or need not return a value: • • void main Returns a void value • • May receive arguments (parameters) of any type: • • int main (int argc, char argv) • • But usually does NOT: • • int main (void) • • void main ()

  37. Characteristics of ALL functions Overview of the c Programming Language • MUST Begin with begin character { and end with end character } void main () { . . . . } • Generally (although not always) start with variable declarations void main () { char c = ‘B’; // initialize 1-byte of RAM with 66 int i = 0, j; // initialize 2-bytes of RAM with 0 // reserve additional 2-bytes for j float real1, real2 = -32.45; // reserve 4-bytes of RAM for real1 // initialize 4-bytes RAM with -32.45 . . . . } Declarations may be made ANYWHERE in the function

  38. Characteristics of ALL functions (continued) • Generally (although not always) contain a variable number of • statements and control statements: Overview of the c Programming Language void main () { . . . . x = . . . if . . . for . . . while . . . printf . . . . . . . } { These statements will be discussed later • Should (unless void) return an appropriate value int main () { . . . . return (0); // if NOT included, results in a warning }

  39. if Statements • Branching Statement: Junction at which the program has • choice of two paths to follow. Overview of the c Programming Language • ALWAYS based on a TRUE/FALSE condition #include <stdio.h> void main () { char ch = ‘B’; if (ch % 2 == 0) printf (“The number is even\n”); } Which would yield: The number is even Since the ASCII value for ‘B’ is 66 Note that if we had initialized: char ch = ‘A’; or char ch = ‘C’; Nothing would have been printed since the ASCII value for ‘A’ is 65 and the ASCII value of ‘C’ is 67.

  40. Multi-lineif Statements Overview of the c Programming Language • IF more than one statement is to be executed in am if • statement, begin and end elipses must be included: #include <stdio.h> void main () { char ch = ‘B’; if (ch % 2 == 0) { printf (“The number is even\n”); ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch); } } Which would yield: The number is even The new character is C (or ASCII 67)

  41. OMISSION of the elipses, given the following code, would • yield: Overview of the c Programming Language #include <stdio.h> void main () { char ch = ‘C’; // NOTICE the ASCII value of C is 67 (odd) if (ch % 2 == 0) printf (“The number is even\n”); ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch); } Which would yield: The new character is D (or ASCII 68)

  42. Compoundif else Statements #include <stdio.h> void main () { char ch = ‘B’; if (ch % 2 == 0) printf (“The number is even\n”); else printf (“The number is odd\n”); } Overview of the c Programming Language Which would yield: The number is even However, the code: #include <stdio.h> void main () { char ch = ‘C’; if (ch % 2 == 0) printf (“The number is even\n”); else printf (“The number is odd\n”); } Would yield: The number is odd

  43. NOTE that multi-line statements still require elipses: { char ch = ‘B’; // include and void main() omitted to save space if (ch % 2 == 0) { printf (“The number is even\n”); ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch); } else printf (“The number is odd\n”); } Overview of the c Programming Language Would yield: The number is even The new character is C (or ASCII 67) While: { char ch = ‘C’; // include and void main() omitted to save space if (ch % 2 == 0) printf (“The number is even\n”); ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch); else printf (“The number is odd\n”); } Would yield AN ERROR MESSAGE (misplaced else)

  44. Additionalif else Statements • Suppose we wished to determine if a letter is a vowel or consonant: • a, e, i, o, u (accept y): The letter is a vowel • Otherwise: It is a consonant Overview of the c Programming Language #include <stdio.h> void main () { char letter = ‘u’; // The letter we wish to classify if ((letter == ‘a’) || (letter == ‘e’) || (letter == ‘i’) || (letter == ‘o’) || (letter == ‘u’) || (letter == ‘y’)) printf (“The letter is a vowel\n”); else printf (“The letter is a consonant\n”); } Which would yield: The letter is a vowel All of the OR operators make the statement confusing, however

  45. We COULD rewrite the program as: #include <stdio.h> void main () { char letter = ‘u’; // The letter we wish to classify if (letter == ‘a’) printf (“The letter is a vowel\n”); else if (letter == ‘e’) printf (“The letter is a vowel\n”); else if (letter == ‘i’) printf (“The letter is a vowel\n”); else if (letter == ‘o’) printf (“The letter is a vowel\n”); else if (letter == ‘u’) printf (“The letter is a vowel\n”); else printf (“The letter is a consonant\n”); } Overview of the c Programming Language

  46. The previous program uses compound if elsestatements • or uses nestedif else statements Overview of the c Programming Language • NOTICE: each elseMUST have a corresponding if statement • preceding it • If there are too many statements, the program can become ‘messy’ Alternative: #include <stdio.h> void main () { char letter = ‘u’; // The letter we wish to classify switch { case ‘a’ : printf (“The letter is a vowel\n”); break; case ‘e’ : printf (“The letter is a vowel\n”); break; case ‘i’ : printf (“The letter is a vowel\n”); break; case ‘o’ : printf (“The letter is a vowel\n”); break; case ‘u’ : printf (“The letter is a vowel\n”); break; default : printf(“The letter is a consonant\n”); } }

  47. for Statement Overview of the c Programming Language • A ‘Looping’ statement: Repetition of statements within • Similar to a PERFORM WHILE statement in COBOL • Repeats statements UNTIL a set condition is met • Consists of three (3) components: for( ; ; ) INITIALIZATION: Set initial values CONDITION TO CHECK: Evaluate to either TRUE or FALSE While TRUE: CONTINUE When FALSE: STOP UPDATING: Resetting of values

  48. Assume we wished to print out the squares of 1 through 3: Overview of the c Programming Language #include <stdio.h> void main () { int i; for (i = 1; i < 4; i++) /* the initial value of i is 1 continue while the value of i is 3 or less increment i by one until it is less than 4 */ printf (“The Square of %d is %d\n”, i, i * i); } The Output would be: The Square of 1 is 1 The Square of 2 is 4 The Square of 3 is 9

  49. 6450 6451 6450 6451 0 0 1 1 0 1 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 How does this really work??? Let’s take it line by line: Overview of the c Programming Language int i; Requests 2-bytes of contiguous storage Let’s assume at location 6450 in RAM Contents Unknown for (i = 1; i < 4; i++) INITIALIZATION: Performed ONLY One Time Set the CONTENTS of location i to 1:

  50. 6450 6451 6450 6451 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 Condition Check 1: for (i = 1; i < 4; i++) Overview of the c Programming Language Are the contents of i< 4 ??? Yes: Perform Statement printf (“The Square of %d is %d\n”, i, i * i); Output: 1 * 1 = 1 The Square of 1 is 1 i contains 2 Update #1: for (i = 1; i < 4; i++) Increment the contents of location i by 1

More Related