Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 161 Introduction to Programming and Problem Solving Chapter Hello World Program in C++ And Lexical Rules Herbert G. Mayer, PSU Status 10/18/2014.

Similar presentations


Presentation on theme: "CS 161 Introduction to Programming and Problem Solving Chapter Hello World Program in C++ And Lexical Rules Herbert G. Mayer, PSU Status 10/18/2014."— Presentation transcript:

1 CS 161 Introduction to Programming and Problem Solving Chapter Hello World Program in C++ And Lexical Rules Herbert G. Mayer, PSU Status 10/18/2014

2 Syllabus Lexical Rules Identifiers Keywords Literals Scopes Numeric Limits, from Hello World in C and C++ Some Data For Loops in C++

3 Lexical Rules A C program is an ASCII text files ASCII: American Standard Code for Information Interchange This includes white space, such as blanks ‘ ‘, tabs, carriage return, line-feed, etc. Meaningful parts consist of letters, digits, and special symbols, such as ‘+’ or ‘/’ This sequence of (usually) visible characters. Named the source program, is logically partitioned into tokens A token is a complete lexeme in the C language, i.e. one single part of a C program

4 Lexical Rules Sometimes the C rules for composing lexical elements, are sufficient to separate one from another token, e.g. min = 100; consists of 4 tokens: identifier min, special symbol =, decimal integer literal 100, and special symbol ; It could also be written correctly as min=100; Other times a deliberate separation of one token from another is needed, done via white space, e.g. a blank character A C token must fit onto a single line, with the exception of string literals, enclosed in a pair of “

5 Lexical Rules: Identifiers Identifiers, AKA user-defined identifiers in C are composed of letters, digits, and underscore characters ‘_’ Must begin with a letter or underscore Are case sensitive; i.e. the 3 legal C identifiers MaxValue, Maxvalue, maxvalue are all 3 distinct names Reserved keywords are symbols that adhere to the lexical rules of identifiers, but are reserved, with predefined meanings, and cannot be be used as identifiers

6 Lexical Rules: Reserved Keywords All keywords reserved in the C programming language are also carried over into C++. There are 32 such inherited reserved words: auto const double float int short struct unsigned break continue else for long signed switch void case default enum goto register sizeof typedef volatile char do extern if return static union while

7 Lexical Rules: Reserved Keywords There are 30 additional C++ reserved keywords that are not part of C, hence new in C++. See below: asm dynamic_cast namespace reinterpret_cast try bool explicit new static_cast typeid catch false operator template typename class friend private this using const_cast inline public throw virtual delete mutable protected true wchar_t

8 Lexical Rules: Literals There are octal, decimal and hexadecimal numeric literals, bool, char, and string literals in C++ Integer numeric literals of base 8, octal numbers, are introduced via the leading ‘0’ digit, followed by any number of octal digits ‘0’.. ‘7’. Example: 0177, same as 127 10 ; note that overflow can occur, if the resulting number is greater than the maximum integral number the machine can handle Integer numbers may have an optional negative sign, e.g. -077 Integer decimal literals consist of any number of decimal digits ‘0’.. ‘0’, but may not have a leading ‘0’. Examples: 128, or -255

9 Lexical Rules: Literals Integer numeric literals of base 16, hexadecimal numbers, are introduced via the leading ‘0x’, followed by any number of hex digits ‘0’.. ‘9’, and ‘a’..’f’, or ‘A’..’F’. Here ‘a’ stands for the digit of value 10 10, ‘and ‘f’ stands for the digit of value 15 10. Upper- and lower-case are equivalent. Example: 0xff, same 0xFF, same as 255 10 The boolean literals are true and false Literals of type char are embedded in a pair of single quotes, like ‘z’ Some char type literals are not printable, thus they are encoded via an escape mechanism, introduced by the \ followed by the desired symbol. E.g. ‘\n’ stands for carriage return, and ‘\t’ for horizontal tab

10 Lexical Rules: Floating-Point Literals Float (AKA floating-point) literals are numeric literals with a possible fraction. They can have integer and fractional parts, be signed, and be scaled; e.g.: 3.142592// for PI +3.142592// for PI with redundant sign -3.142592// negative PI 0.3142592E1// PI scaled by factor * 10 31.42592E-1// PI scaled by 10 -1

11 Numeric Limits, from

12 11 Lexical Rules: Special Symbols as Operators LDescriptionOperatorAssociativityLDescriptionOperatorAssociativity 1 Function call ( ) left-to-right 5 Bitwise left shift << left-to-right Array subscript [ ] Bitwise right shift >> Struct member. 6 Less than < left-to-right Struct dereference -> Greater than > Increment (post) expr++ LT or equal to <= Decrement (post) expr-- GT or equal to >= 2 Indirection * right-to-left 7 Equal to == left-to-right Reference (addr) & Not equal to != Unary plus + 8Bitwise AND & left-to-right Unary minus - 9Bitwise XOR ^ left-to-right Logical negation ! 10Bitwise OR | left-to-right Bitwise NOT ~ 11Logical AND && left-to-right Increment (pre) ++expr 12Logical OR || left-to-right Decrement (pre) --expr 13Conditional ? : right-to-left Cast ( type ) 14Assignment = += -= *= /= %= >>= <<= &= ^= |= right-to-left Size in bytes sizeof 3 Multiplication * left-to-right 15Comma, left-to-right Division / Highest precedence is Level 1. Lowest precedence is Level 15. Use parentheses () to alter the order of evaluation. Modulo % 4 Addition + left-to-right Subtraction -

13 Hello World Program We’ll write and discuss a very simple source programs Tongue-in-cheek known as the hello world program We briefly contrast C and C++, then we cover more advanced C++ for loops This famous hello world program does nothing except to print “Hello” on the standard output device

14 Hello World in C #include void main( ) { // main printf( “Hello World!\n” ); // no return value given; should be 0 } // end main

15 Hello World in C #include provides to the programmer a so-called library: stdio.h stdio.h makes available standard input and output functions, for example printf(), without programmers having to code them main() identifies a select C function, always to be provided in a complete C source program main() is always the first function to be executed All work to be done by the main() function is enclosed between the { and } braces, as has to be done for every other C function

16 Hello World in C #include directive to include libraries specifies library to be included void reserved keyword, specifies type of function main reserved keyword, naming a special function ( ) are special symbols, enclosing formal parameters { } special symbols, enclosing body of function // is start of line comment printf user-defined function name from stdio.h “Hello World!\n” string literal to be printed ; special symbol, ending statement

17 Hello World in C++ #include int main( void ) { // main cout << ”Hello World!” << endl; // endl is \n return 0; } // end main

18 Hello World in C++ C++ also provides the same common input- and output-functions of C, but typical C++ IO uses a new IO format, available in iostream.h main() again identifies the starting point of execution Like in C, all work to be done by the C++ main() function is enclosed between the { and } brackets Instead of a magic symbol ‘\n’ to identify a “carriage- return and line-feed” to be output, C++ specifies a symbolic, fictitious character, named: endl The << operators define elements to be output If there are no errors, C++ returns error code 0 to say: All is OK!

19 Some Data #include int main( void ) { // main int i;// we don’t use i!!! int year = 2014;// initialized year float pi = 3.141592;// should be constant printf( ”year = %d\n”, year ); // old C cout << “year = “ << year << endl; // C++ return 0; } // end main

20 Some Data The reserved C keyword int defines a datum, by the name i, and another by the name year The former is left uninitialized, the latter receives an initial value, 2014 Both options are allowed in C Line “float pi” defines a datum of a different type, called a floating-point value. This type permits fractional values, but not all possible values in the numeric range are representable on a computer The printf() argument enclosed in a pair of “ is printed, unless it is a % character, in which data and format interpretation takes place

21 Some Data Interpretation of data to be printed depends on the characters after the % Here the %d means: Find another argument after the “ pair, and print it as an integer value, to base 10; i.e. a decimal integer number The special character sequence \n means: also print a carriage-return line-feed, as we saw with the hello world

22 Quick Excursion to C++ Now you now know something about arrays and while loops Arrays are composite types, AKA aggregate types Loops perform repetitive actions, so are perfectly suited to process arrays We also refer to them as iterations The for loop is the next construct you learn

23 For Loop in C++ Formally, the C++ For Loop defines 3 expressions More practically, the C++ For Loop defines an iteration variable, which progresses over a range of values This is called the iteration space The first expression defines an iteration variable, initialized to a defined start value of scalar type; may be integer or any other scalar type The second expression tests a boolean condition; if true, the progression continues; practically the iteration variable is checked, whether it has reached a final value The third expression defines a change to the iteration variable, executed at the end of the loop body

24 For Loop in C++ The 3 expressions are enclosed in a pair of ( and ) parens, each separated from the next by a ; Then comes a statement, which is executed iteratively, based on the iteration space It is common to refer to the iteration variable inside the body of the for loop Here an example: #define MAX 10... for ( int i = 0; i < MAX; i++ ) { list[ i ] = 0;// best not change i } //end for

25 For Loop in C++ A for loop executes, as long as the boolean expression 2 yields true When the expression is false, the for loop ends, and the operation after the for is executed next Note that the boolean condition could be false at the start, in which case the for loop would be empty, i.e. executed 0 times

26 Simple For Loop in C++ // declaration of some array #define TEN 10 char digits[ TEN ]; // loop to initialize digits[] for( int i = 0; i < TEN; i++ ) {) { digits[ i ] = ‘0’ + i++; } //end for // no compound { and } needed, but is a good habit

27 More Complex For Loop in C++ // declaration of 2-Dim matrix mat[][] #define MAX_ROW 50 #define MAX_COL 50 float mat[ MAX_ROW ][ MAX_COL }; // initialize matrix mat[][] for( int row = 0; row < MAX_ROW; row++ ) { for( int col = 0; col < MAX_COL; col++ ) { mat[ row ][ col ] = 0.0; } //end for // no compound needed, but is a good habit


Download ppt "CS 161 Introduction to Programming and Problem Solving Chapter Hello World Program in C++ And Lexical Rules Herbert G. Mayer, PSU Status 10/18/2014."

Similar presentations


Ads by Google