Unformatted text preview:

Object-Oriented Design and ProgrammingOverview of Basic C++ ConstructsOutline- Lexical Elements- The Preprocessor- Variables, Functions, and Classes- Definition and Declaration- Compound Statement- Iteration Statements- for Loop- while Loop- do while loop 1- break and continue Statements- Conditional Branching- if Statement- switch Statement- C++ Arrays- Multi-Dimensional Arrays- Pointers- Passing Arrays as Parameters- Character StringsLexical ElementsIdentifiers: A sequence of letters (including ' ') and digits. The firstcharacter must be a letter. Identifiers are case sensitive,i.e., Foo Bar1 is different from foo bar1.Reserved Words: Keywords that are not re-definable by the programmer, e.g., int, while, double, return, catch, delete. There are currently 48 C++ reserved words.Operators: Tokens that perform operations upon operands of various types. There arearound 50 operators and 16 precedence levels.Preprocessor Directives: Used for conditional compilation. Always begin with #, e.g.,#include, #ifdef, #define, #if, #endif.Comments: Delimited by either /* … */ or //, comments are ignored by the compiler. Note that comment of the same style do:#if 0: : : .#endifConstants and Literals: For strings, integers, floating point types,and enumerations, e.g., "hello world", 2001, 3.1416, and FOOBAR.The Preprocessor- Less important for C++ than for C due to inline functions andconst objects.- The C++ preprocessor has 4 major functions:1. File Inclusion:#include <stream.h>#include "foo.h"2. Symbolic Constants:#define SCREEN SIZE 80#define FALSE 03. Parameterized Macros:#define SQUARE(A) ((A) * (A))#define NIL(TYPE) ((TYPE *)0)#define IS UPPER(C) ((C) >= 'A' && (C) <= 'Z')4. Conditional Compilation:#ifdef "cplusplus"#include "c++-prototypes.h"#elsif STDC#include "c-prototypes.h"#else#include "nonprototypes.h"#endifVariables, Functions, and Classes- Variableso In C++ all variables must be declared before they are used. Furthermore, variables must be used in a manner consistent with their associated type.- Functionso Unlike C, all C++ functions must be declared before being used, their return type defaults to int. However, it is considered good style to fully declare all functions.o Use void keyword to specify that a function does not return a value.- Classeso Combines data objects and functions to provide an Abstract Data Type (ADT).Definition and Declaration- It is important in C to distinguish between variable and function declaration and definition:Definition: Refers to the place where a variable or function iscreated or assigned storage. Each external variable and function must be defined exactly once in a program.Declaration: Refers to places where the nature of the variableis stated, but no storage is allocated.Note that a class, struct, union, or enum declaration is also a definition in the sense that it cannot appear multiple times in a single compilation unit.- Variables and function must be declared for each function that wishes to access them. Declarations provide sizes and types to the compiler so that it can generate correct code.Compound Statement- General form:‘{‘[ decl-list ][ stmt-list ]‘}'- e.g.,int c = 'A'; // Global variableint main (void) {if (argc > 1) {putchar ('[');for (int c = ::c; c <= 'Z'; putchar (c++));putchar (']');}}- Note the use of the scope resolution operator :: to reference otherwise hidden global int c.Iteration Statements- C++ has 5 methods for repeating an action in a program:1. for: test at loop top2. while: test at loop top3. do/while: test at loop bottom4. Recursion5. Unconditional Branch: local (goto) and non-local (setjmp and longjmp)for Loop- _ General formfor (<initialize>; <exit test>; <increment>)<stmt>- The for loop localizes initialization, test for exit, and incrementing in one general syntactic construct.- All three loop header sections are optional, and they may contain arbitrary expressions.- Note that it is possible to declare variables in the <initialize> section (unlike C).for loop (cont'd)- _ e.g.,for ( ; ; ); /* Loop forever. *//* Copy stdin to stdout. */for (int c; (c = getchar ()) != EOF; putchar (c));/* Compute n! factorial. */for (int i = n; n > 2; n--) i *= (n - 1);/* Walk through a linked list. */for (List *p = head; p != 0; p = p->next) action (p);while Loop- General formwhile (<condition>)<stmt>- repeats execution of stmt as long as condition evaluates to non-zero- In fact, a for loop is expressible as a while loop:<initialize>while (<exit test>){<loop body><increment>}while Loop (cont'd)- e.g.,while (1); /* Loop forever. */int c;while ((c = getchar ()) != EOF)putchar (c);i = n; /* Compute n! factorial. */while (n > 0)i *= --n;/* Walk through a linked list. */p = head;while (p != 0) {action (p);p = p->next;}do while loop- General form:do <stmt> while (<condition>);- Less commonly used than for or while loops.- Note that the exit test is at the bottom of the loop, this means that the loop always executes at least once!int main (void) {const int MAX LEN = 80;char name str[MAX LEN];do {cout << "enter name (\exit" to quit)";cin.getline (name str, MAX LEN);process (name str);} while (strcmp (name str, "exit") != 0);return 0; }break and continue Statements- Provides a controlled form of goto inside loops.#include <stream.h>int main (void) {/* Finds first negative number. */int number;while (cin >> number)if (number < 0)break; cout << "number = " << number << "\n";// : : :/* Sum up all even numbers, counts total numbers readint sum, total;for (sum = total = 0; cin >> number; total++) {if (number & 1)continue;sum += number;}cout << "sum = " << sum << ", total = " << total << "\n";}Conditional Branching- There are two general forms of conditional branching statements in C++:- if/else: general method for selecting an action for conditional execution, linearly checks conditions and chooses first one that evaluates to TRUE.- switch: a potentially more efficient method of selecting actions, since it can use a “jump table."if Statement- General formif (<cond>)<stmt1>[else<stmt2>]- Common mechanism for conditionally executing a statement sequence.#include <ctype.h>char *character class (char c) {if (isalpha (c)) {if (isupper (c))return "is upper case";elsereturn "is lower case";}else if (isdigit (c))return "is a digit";else if (isprint (c))return "is a printable char";elsereturn "is an unprintable char";}switch Statement- General formswitch (<expr>) { <cases> }- switch only works for scalar variables e.g., integers,


View Full Document

UGA CSCI 2720 - C L1

Documents in this Course
Load more
Download C L1
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view C L1 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view C L1 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?