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.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick The Programming Process rUse an editor to create a program file (source file). l contains the text of.
Advertisements

C++ Basics Variables, Identifiers, Assignments, Input/Output.
Chapter 3: Beginning Problem Solving Concepts for the Computer Programming Computer Programming Skills /1436 Department of Computer Science.
ECE 103 Engineering Programming Chapter 11 One Minute Synopsis Herbert G. Mayer, PSU CS Status 7/1/2014.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Structure of a C program
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
Basic Elements of C++ Chapter 2.
Objectives You should be able to describe: Data Types
CS 192 Lecture 3 Winter 2003 December 5, 2003 Dr. Shafay Shamail.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
C Tokens Identifiers Keywords Constants Operators Special symbols.
C-Language Keywords(C99)
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
C++ Programming, Namiq Sultan1 Chapter 2 Introduction to C++ Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Copyright Curt Hill Variables What are they? Why do we need them?
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Basic Types, Variables, Literals, Constants. What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet)
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CS 161 Introduction to Programming and Problem Solving Chapter 12 C++ Statements Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied verbatim.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
C++ Lesson 1.
Asst.Prof.Dr. Tayfun ÖZGÜR
Variables, Identifiers, Assignments, Input/Output
Chapter Topics The Basics of a C++ Program Data Types
Data types Data types Basic types
Basic Elements of C++.
Introduction to C Programming
Reserved Words.
Basic Elements of C++ Chapter 2.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
C++ Basics.
Variables in C Topics Naming Variables Declaring Variables
Basics of ‘C’.
An overview of Java, Data types and variables
Introduction to C Programming
Variables, Identifiers, Assignments, Input/Output
Prof. Bhushan Trivedi Director GLS Institute of Computer Technology
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Herbert G. Mayer, PSU CS Status 7/19/2015
Module 2 Variables, Data Types and Arithmetic
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

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

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

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

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 “

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

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

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

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 ; 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 Integer decimal literals consist of any number of decimal digits ‘0’.. ‘0’, but may not have a leading ‘0’. Examples: 128, or -255

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 Upper- and lower-case are equivalent. Example: 0xff, same 0xFF, same as 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

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.: // for PI // for PI with redundant sign // negative PI E1// PI scaled by factor * E-1// PI scaled by 10 -1

Numeric Limits, from

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 -

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

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

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

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

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

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!

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

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

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

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

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

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 for ( int i = 0; i < MAX; i++ ) { list[ i ] = 0;// best not change i } //end for

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

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

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