1.07k likes | 1.21k Views
Learning the C++ language 3. The Nuts and Bolts of C++. What you have learned last week?. Built (compiling and linking) a simple C++ program under the Visual Studio environment. Source code, object code, and executable code Encountered syntax errors. Compile-time errors are useful.
E N D
What you have learned last week? • Built (compiling and linking) a simple C++ program under the Visual Studio environment. • Source code, object code, and executable code • Encountered syntax errors. • Compile-time errors are useful. • Run-time errors • Debugging process • Debugging all kinds of errors
What you have learned last week? • Executed the program in the “console mode.” • Many command-line applications are known as console applications. • Installed Visual Studio at your own PC. • Reading
A simple program #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; }
Elements of a C++ program • A main() function • A program consists of many functions. • It is expected to return an integer value. • Inputs and outputs • Standard output stream (std::cout) • Standard input stream (std::cin) • Insert a new-line character (std::endl) • Standard library • It is a collection of classes and functions, such as iostream. • Data type: character strings and the new-line character • Operators: << is an insertion operator. • Statements
Preprocessor and Program Codes #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } Preprocessor The actual program • Preprocessor: • Instruct the compiler on how to compile the program • Will NOT generate machine codes • Start with a pound (#)symbol Read before compiling • Actual program: • Every C++ program must have the main() function • It is the beginning point of every C++ program
Preprocessor #include <iostream> • When compiling a file, we need to obtain the definitions of some terms in the program codes • These definitions are recorded in some header files • These files are shipped with the compiler or other resources • #include tells the compiler where to find the header files and insert this file to that location of the program • e.g. #include <iostream>tells the compiler it should get the file iostreamthrough the default path • e.g. #include "myfile"tells the compiler it should get the file myfilein the current folder.
Program Codes Think from the point of view of the compiler. • The basic element of a program isfunction • A function is composed of: 1. Return Type 2. Function name int main() { std::cout << "Hello World!" << std::endl; return 0; } 3. Input parameters 4. Program codes enclosed by the opening and closing braces Note: The meaning ofstd::coutis checked in the file iostream in the preprocesor.
Themain()function is thebeginning pointof a program • When executing a program, the operating system will firstcallthemain()function of this program • If the above main()function executes successfully, it shouldreturn an integer 0 to the operating system Callmain() main() Return 0 Means everything fine on executing main()as it is the last statement.
Program Codes Send the stringHello World! to std::cout – the standard output, defined in iostream int main() { std::cout << "Hello World!" << std::endl; return 0; } Return an integer 0 to the operating system • In console mode, thestandard outputis theconsole, i.e. theCommand promptwindow • In C++,character stringis represented by a sequence of characters enclosed by " " • std::endlmeansnewline (or Enter),also defined iniostream
Namespaces • std::cout andstd::endl means that we are referring to the cout andendl of the stdnamespace • Thestdnamespace is defined in iostream • Namespace– A new feature of C++ • Design to help programmers develop new software components without generating naming conflicts • Naming conflict– A name in a program that may be used for different purposes by different people • cout andendl areNOTa part of C++, people can use these two names for any purpose; not necessarily referring to standard output and newline. Folders and files concept in Windows
We can have our own coutby putting it in a namespace defined by ourselves #include <iostream> namespace myns { int cout=0;//Integer variable }//No semi-colon int main() { std::cout << myns::cout << std::endl; return 0; } This coutrefers to the number 0 This coutrefers to the standard output • In fact, another definition of cout can be found iniostream • The result of this program is a number 0 shown on the standard output.
That’s why using coutwithout the associate namespace is an error since the system does not know which coutyou are referring to #include <iostream> namespace myns { int cout=0; } int main() { std::cout << cout << std::endl; return 0; }
It may be a bit cumbersome to write the namespace of names every time • A short form is to use theusingstatement All names that are NOT a part of C++ will belong to the namespace std, unless otherwise stated #include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; return 0; } No need to put std in front of cout and endl
We can also print integers, floating- point numbers or even combination of string and integers in standard output #include <iostream> using namespace std; int main() { cout << "Hello there.\n"; cout << "Here is 5: "<< 5 << "\n"; cout << "endl writes a new line to the screen."; cout << endl; cout << "Here is a very big number:\t" << 70000 << endl; cout << "Here is the sum of 8 and 5:\t" << 8+5 << endl; cout << "Here's a fraction:\t\t" << (float) 5/8 << endl; cout << "And a very very big number:\t"; cout << (double) 7000*7000 << endl; //casting integer to double cout << "Replace Frank with your name...\n"; cout << "Frank is a C++ programmer!\n"; return 0; } \n- Another way to show newline escape sequence \t - Add a tab character Another line Ex. 3.1a
Comments • A program needs to be well commented to explain the important points of the program • Adding comments in the program will not affect the program execution but improve readability • Comments can be added in two ways: • Comments can be added in two ways: #include <iostream> using namespace std; int main() { /* Text between these two marks are comments */ cout << "Hello World!\n"; return 0; // Text after that are also comments }
Exercise 3.1a p.16 • a. Build the program in p.16. Note the output on the console. • b. Add one statement to the program which will show your name and age in a single sentence. The nameshould be shown as acharacter string. The ageshould be shown as an integer. • c. Use the comment symbols /*and */to comment the statements from line 4 to line 8 (inclusive). Is there any change to the results output? Ex 3.1b
More on Functions • Although a single main()function is enough for any C++ program, it’s a bad habit to do everything by a single function • C++ allows nesting of functions to facilitate "divide and conquer" of jobs • The function main()can callother functions to help it complete a task • When a function is called, the program branches off from the normal program flow • When the function returns, the program goes back to where it left before.
Mr. A wants to decorate his house 2 Call his friend B to help mowing 1 Call his friend C to help painting Return him the mowed lawn Return him the painted house 3 Call a function is just similar to asking somebody to help!
Return nothing They must be the same A function is defined A function is called #include <iostream> using namespace std; //function DemonstrationFunction() // show a useful message voidDemonstrationFunction() { cout << "In Demonstration Function\n"; cout << "Print one more line\n"; } //function main - prints out a message, then //calls DeomonstrationFunction, then shows //the second message. int main() { cout << "In main\n"; DemonstrationFunction(); cout << "Back in main\n"; return 0; }
#include <iostream> using namespace std; //function DemonstrationFunction() // show a useful message void DemonstrationFunction() { cout << "In Demonstration Function\n"; cout << "Print one more line\n"; } //function main - prints out a message, then //calls DeomonstrationFunction, then shows //the second message. int main() { cout << "In main\n"; DemonstrationFunction(); cout << "Back in main\n"; return 0; } The execution sequence is like that
Passing Parameters to Function • To let the called function really help the main(), sometimes parameters are passed from main()to the called function • After finishing the computation, the function should pass back the results to main() • It can be achieved by the returnstatement. function(a,b) Branch to function(a,b) main() return c
Mr. A wants to decorate his house Call his friend B to help mowing and give him a mowing machine 2 1 Call his friend C to help painting and give him the paint brush Return him the mowed lawn Return him the painted house If you want your friend to help, you'd better give him the tool! 3
#include <iostream> using namespace std; int Add (int x, int y) { cout << "In Add(),received "<<x<<" and "<<y<<"\n"; return(x+y); } int main() { cout << "I'm in main()!\n"; inta,b,c; cout << "Enter two numbers: "; cin >>a; cin >> b; cout << "\nCalling Add()\n"; c = Add(a,b); cout << "\nBack in main().\n"; cout << "c was set to " << c; cout << "\nExiting...\n\n"; return 0; } Input parameters need to declare type - the same as those in the calling function Add()returns an integer x+y back to main() Add()is called with two parameters c holds the return value of Add()
Exercise 3.1b • a. Build the program in the last slide. Note the output on the console. • b. Modify main()to calculate the square ofc. Add one more function called Square()to achieve this. The Square()function will take the square of the parameter that is passed to it. It will return the result in the form of an integer back to the calling function.
Variables and Memory • A variable is actually a place to store information in a computer • It is a location (or series of locations) in the memory • The nameof avariable can be considered as a label of that piece of memory Variableschar aint bshort int cbool d Memory 10 0A 21 3A 51 44 20 00 in hex Address 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 in bin One address for one byte, i.e.8 bits.
Size of Variables • In memory, all data are groups of '1' and '0', byte by byte • Depending on how we interpret the data, different types of variables can be identified in the memory p.35 Type bool unsigned short int short int unsigned long int long int unsigned int int char float double Size 1 byte 2 bytes 2 bytes 4 bytes 4 bytes 4 bytes 4 bytes 1 byte 4 bytes 8 bytes Values true or false (1 or 0) 0 to 65,535 (i.e. 216-1) -32,768 to 32,767 0 to 4,294,967,295 (i.e. 232-1) -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 -2,147,483,648 to 2,147,483,647 256 character values (+/-)1.2e-38 to (+/-)3.4e38 (+/-)2.2e-308 to (+/-)1.8e308 p.34
Exercise 3.2a a. Build the project and note the results. b. Add lines for bool, unsigned int, unsigned long int, and unsigned int. #include <iostream> using namespace std; int main() { cout << "The size of an int is:\t\t" << sizeof(int) << " bytes.\n"; cout << "The size of a short int is:\t" << sizeof(short) << " bytes.\n"; cout << "The size of a long int is:\t" << sizeof(long) << " bytes.\n"; cout << "The size of a char is:\t\t" << sizeof(char) << " bytes.\n"; cout << "The size of a float is:\t\t" << sizeof(float) << " bytes.\n"; cout << "The size of a double is:\t" << sizeof(double) << " bytes.\n"; return 0; }
Declaring Variables • Before we use a variable, we need to declare its type so that the compiler can reserve suitable memory space for it • Variables are declared in this way: • It defines myVariableto be an integer. Hence 4 bytes will be reserved for its storage in memory • The name of the variable is case sensitive, hence • myVariableis NOT the same as myvariable int myVariable;
Declaring Variables • We can declare one or more variables of the same type at once • It defines myVar1, myVar2, yourVar1, yourVar2are all integers • Some names are keywords of the C++ language that cannot be used as variable names • e.g.return, while, for, if, etc. • We can even initialize the value of the variables when making the declaration int myVar1, myVar2, yourVar1, yourVar2; int myVar1 = 10, myVar2, yourVar1, yourVar2 = 5; Does an uninitialized variable have a value?
Maximum and Minimum p.30 • Each data type has its own maximum and minimum limits • When the value goes beyond those limits, unexpected behavior may result #include <iostream> using namespace std; int main() { unsignedshort intsmallNumber; smallNumber = 65535; // 1111 1111 1111 1111 = 65535 cout << "small number:" << smallNumber << endl; smallNumber++;//1 0000 0000 0000 0000 = 0 cout << "small number:" << smallNumber << endl; smallNumber++; // 0000 0000 0000 0001 = 1 cout << "small number:" << smallNumber << endl; return 0; }
Maximum and Minimum p.30 • Signed integers do NOT behave in the same way #include <iostream> using namespace std; int main() { short intsmallNumber; smallNumber = 32767; // 0111 1111 1111 1111 = 32767 cout << "small number:" << smallNumber << endl; smallNumber++; // 1000 0000 0000 0000 = -32768 cout << "small number:" << smallNumber << endl; smallNumber++; // 1000 0000 0000 0001 = -32767 cout << "small number:" << smallNumber << endl; return 0; }
Characters • Besides numbers, C++ also has a data type called char, i.e. character • If a variable is declared as char, the compiler will consider the variable as an 8-bitASCII character #include <iostream> using namespace std; int main() { // ASCII code of '5' is 53 charc = 53, d = '5'; // They are the same int e = 53; cout << "c = " << c << endl; // c = 5 cout << "d = " << d << endl; // d = 5 cout << "e = " << e << endl; // e = 53 return 0; }
ASCII Table decimal Details of the table can be found in many places, for instance, http://web.cs.mun.ca/~michael/c/ascii-table.html
Special Printing Characters • C++ compiler recognizes some special charactersforoutput formatting • Start with an escape character \(e.g. \nmeans new line) Character \n \t \b \" \' \? \\ What it Means new line tab backspace double quote single quote question mark backslash escape sequence in a string
Constants • Unlike variables, the values of constants cannot be changed • The value of a constant will be fixed until the end of the program • There are two types of constants • Literal Constants - come with the language • e.g. a number 39(you cannot assign another value to 39) • Symbolic Constants- • Like variables, the user define a special name as a label to it • Unlike variables, its value cannot be changed once it is initialized.
Defining Symbolic Constants • A symbolic constant can be defined in two ways • 1. Old way - use the preprocessor command #define • No type needs to be defined for studentPerClass • The preprocessor just replaces the word studentPerClasswith 87 wherever it is found in the source program • 2. A better way- use the keywordconst • The data studentPerClassnow has a fixed value 87 • It has a type now. This feature helps the compiler to debugthe program. #define studentPerClass 87 const unsigned short intstudentPerClass = 87;
Why do we need Constants? • Help debugging the program • Compiler will automatically check if a constant is modified by the program later (and reports it as an error if modified.) • Improve readability • Give the value a more meaningful name; e.g. rather than writing 360, we can use degreeInACircle • Easy modification • If a constant really needs to be changed, we only need to change a single line in the source program.
#include <iostream> using namespace std; int main() { const inttotalStudentNumber = 87; // Student no. num must < 87 int num; cout << "Enter a student number: "; cin >> num; if(num > totalStudentNumber) cout << "\n Number not valid!!!\n"; cout << "\n There are " << totalStudentNumber << " student in this class\n"; return 0; } • Give better readability • Modify once and apply to whole program
Enumerated Constants • Enumerated constants allow one to create a new type that contains a number of constants • Makes COLORthe name of the new type • Set RED = 0, BLUE = 1, GREEN = 2, WHITE = 3, BLACK = 4 • Another example • Makes COLOR2the name of the new type • Set RED = 100, BLUE = 101,GREEN = 500,WHITE = 501,BLACK = 700 enum COLOR { RED, BLUE, GREEN, WHITE, BLACK}; enum COLOR2 {RED=100, BLUE, GREEN=500, WHITE, BLACK=700};
Exercise 3.2 #include <iostream> using namespace std; int main() { const int Sunday = 0; const int Monday = 1; const int Tuesday = 2; const int Wednesday = 3; const int Thursday = 4; const int Friday = 5; const int Saturday = 6; int choice; cout << "Enter a day (0-6): "; cin >> choice; if (choice ==Sunday||choice==Saturday) cout << "\nHave a nice weekend!\n"; else cout << "\nToday is not holiday yet.\n"; return 0; } a. Build the project and note the result b. Use enumerated constantsmethod to simplify the program Ex.3.3
A Typical Program #include <iostream> int abc (...) { ... ; return ... ; } int cde (...) { ... ; return ... ; } int main() { ...; return 0; } function statements function function
Statements • A C++ program comprises a number of functions • A function comprises a number of statements • A statement can be as simple as • It can be as complicated as • A statement must end with a semicolon; • In a statement, space carries nearly no information x = a + b; • if (choice ==Sunday ||choice ==Saturday) • cout << "\nYou're already off on weekends!\n"; x = a + b; x = a + b ;
Expressions • A statement comprises one or manyexpressions • Anything that returns a value is an expression, e.g. • 3.2;// Returns the value 3.2 • studentPerClass;// Returns a constant, say 87 • x = a + b;// Here, TWO expressions • // Return a + b, return the value of a variable x • Since x = a + b is an expression (i.e. return a value) , it can certainly be assigned to another variable, e.g. • y = x = a + b;/* Assign to y the value of x whichis equal to the sum of a and b */
Operators • An expression often comprises one of more operators • The assignment operator'=' assigns a value or constant to a variable, e.g.x = 39; • Several mathematical operators are provided by C++ • Let abe 3, bbe 4and xis declared as an integer, OperatorsMeaning + Add - Subtract *Multiply / Divide %modulus Examples x = a + b; // x = 7 x = a - b; // x = -1 x = a * b; // x = 12 x = a / b; // x = 0 (why?) x = a % b; // x = 3 (why?) 3 modulo 4 is 3
Integer and Floating Point Divisions x, y of main() are not x, y of intDiv(int, int) #include <iostream> using namespace std; void intDiv(int x, int y) { int z = x/y; cout << "z: " << z << endl; } void floatDiv(int x, int y) { float a = (float)x; // old style float b = static_cast<float>(y); // ANSI style float c = a/b; cout << "c: " << c << endl; } int main() { int x = 5, y = 3; intDiv(x,y); floatDiv(x,y); return 0; } Casting Ask the compiler to temporarily consider xas a floating point no., i.e. 5.0 in this case Only give integer division result, i.e. 1 Give floating point division result, i.e. 1.66...