Chapter-01 A Sample C++ Program
// Fig. 1.2: fig1_02.cpp // A first program in C++ #include <iostream.h> int main() { cout << "Welcome to C++!\n"; return 0; // indicate that program ended successfully }
C++ Comments Multiline comments: /* -------------------------------------- can not be nested. -------------------------------------- */ Single line comment: // can be nested in multiline comments. // --------------------------------------- Conditional Compile: #if 0 can be nested. --------------------------------------- #endif
Multifile C++ Programs C++ programs often consist of several different files with extensions such as .h and .cpp related typedef statements, const values, enum type declarations, and similar items are often placed in user-written header files by using the #include preprocessor directive the contents of these header files are inserted into any program file that uses them Bazlur Rasheed
Inserting Header Files #include <iostream.h> #include “school.h” int main ( ) { enum SchoolType { PRE_SCHOOL, . ELEM_SCHOOL, . MIDDLE_SCHOOL, . HIGH_SCHOOL, COLLEGE } ; } include contents of I/O stream header file needed to use the objects cout and cin Bazlur Rasheed
A C++ program is a collection of one or more functions there must be a function called main( ) execution always begins with the first statement in function main( ) any other functions in your program are subprograms and are not executed until they are called
Program With Several Functions main function square function cube function
Shortest C++ Program int main ( ) { return 0; } type of returned value name of function
What is in a heading? int main ( ) type of returned value name of function says no parameters int main ( ) Bazlur Rasheed
Every C++ function has 2 parts int main ( ) heading { body block return 0; } Bazlur Rasheed
Block (Compound Statement) a block is a sequence of zero or more statements enclosed by a pair of curly braces { } SYNTAX { Statement (optional) ; . }
cout << "Welcome to C++!\n"; The entire line is a C++ statement. Output and input in C++ is accomplished with streams of characters. When this statement is executed: the stream of characters Welcome to C++! goes to the standard output stream object cout, which is the screen. << is the stream insertion operator. \n escape sequence means newline
Some Escape Sequences \n Newline (Line feed in ASCII) \t Horizontal tab \b Backspace \a Alert (bell or beep) \\ Backslash \’ Single quote (apostrophe) \” Double quote (quotation mark) \0 Null character (all zero bits) \ddd Octal equivalent (3 octal digits) \xddd Hexadecimal equivalent (1 or more hex digits for integer value of character) Bazlur Rasheed
Output of program Welcome to C++!
return 0; When this statement is executed: the value 0 is returned to the operating system, indicating that the program has terminated successfully.