CPS120: Introduction to Computer Science Introduction to C++
A Simple C++ Program Comments // Simple C++ Program // // Purpose: To demonstrate the // parts of a simple C++ program Compiler Directive #include Main Functionmain ( ) Braces{ Statementscout << "This is a simple program "; return 0; }
C++ and Blank Space C++ allows for great flexibility in the spacing and layout of code Use this feature to make it easier for you as a human being to read the code
Formatting in C++ Modern programming languages are free form with delimiters instead of columns to determine the end of instructions –The ; (semi-colon) is the delimiter used in C++ Use tabs, indents, and blank lines in any manner that makes code easier to understand Many programming instructions become subordinate to other instructions due to scope and other restrictions. Formatting code to reflect this makes it easier to read
Uppercase or Lowercase Be careful to use the same combination of uppercase or lowercase lettering when you enter source code Commands and other reserved words are all lower case
Characteristics of a C++ Program Comments Compiler Directives Functions Braces Statements
Comments Explain the purpose of a program Keep notes regarding changes to source code Store details about the programmers for future reference Explain parts of the program
Comments Document what is happening, why it is happening and other issues Commentary is ignored by the compiler C++ has inline, block and documentary comments –Inline comments are within line of code Use the // symbols –Block comments are long comments delimited with /* and */
Sample Comments At the start of the program /************************************************** ** Miles Per Gallon** ** Programmer: Paul J. Millis** ** Purpose: Calculate mile per gallon and price per mile** ** given miles, gallons and gas price** *************************************************/ Within specific lines of code float PricePerMile = 0.00;//store the price per mile float MilesPerGallon = 0.0;//stores the miler per gallon achieved
Compiler Directives Instructions to the compiler rather than part of the C++ language –Most common directive is #include For Example: #include –A.h file is a header file. It serves as a link between program code and standard C++ code needed to make programs run
Functions A function is a block of code that carries out a specific task Every C++ program has a main function that executes when a program initiates –Includes open parenthesis to designate a function –Ends with a return 0; statement
Braces Mark the beginning and ending of blocks of related code –Every opening brace must have a closing brace
Statements Functions contain statements that consist of instructions or commands that make the program work
Semicolons There must be a semicolon after every statement –To tell the compiler that the statement is complete –Function definitions and compiler directives are exempt