Escolar Documentos
Profissional Documentos
Cultura Documentos
Programming Principle
LECTURE: TUAN HAJI HANNES BIN MASANDIG SECTION: SECTION 4
STUDENTS NAME
MATRIX NUMBER
AA120114
Assignment 2
The following is the keywords list for C/C++; each keywords are being studied,given the definition and the example of code. bool, break, case, char, const, continue, do, default, double, else, extern, false, float, for, if, int, long, namespace, return, short, static, struct, switch, typedef, true, unsigned, void, while
Keyword bool
Description of usage
Example of code
The Boolean data type is #include <iostream> used to declare a variable using namespace std; whose value will be set as // returns true if x and y are equal true (1) or false (0). To { return // use equality declare such a value, you operator to(x == y);equal test if use the bool keyword. The } variable can then be int main()
{ cout << "Enter a value: "; int x; cin >> x; cout << "Enter another value: "; int y; cin >> y; bool bEqual = IsEqual(x, y); if (bEqual) cout << x << " and " << y << " are equal"<<endl; else cout << x << " and " << y << " are not equal"<<endl; return 0; } #include <cstdio> // for getchar() bool IsEqual(int x, int y)
initialized with the starting value. A Boolean constant is used to check the state of a variable, an
break
Although you have already #include <iostream> seen the break statement in using namespace std; the context of switch int main()
{ // count how many spaces the user has entered int nSpaceCount = 0;
can be used with other types of loops as well. The break statement
causes a switch statement, while loop, do while loop, or for loop to terminate. In the context of a switch statement, a break is
// loop 80 times for (int nCount=0; nCount < 80; nCount++) { char chChar = getchar(); // read a char from user // exit loop if user hits enter if (chChar == '\n') break; // increment count if user entered a space if (chChar == ' ') nSpaceCount++; }
typically used at the end of each case to signify the case is finished (which prevents fall-through):
case
switch simple:
statements the
is
switch
expression is evaluated to produce a value, and each case label is tested against this value for equality. If a case label matches, the statements after the case label are executed. If no case label matches the switch expression, the
case 1: // Does not match -- skipped cout << 1 << endl; break; case 2: // Match! Execution begins at the next statement cout << 2 << endl; // Execution begins here break; // Break terminates the switch statement case 3: cout << 3 << endl; break; case 4: cout << 4 << endl; break; default: cout << 5 << endl; break; } // Execution resumes here
code under the default label is executed (if it exists). Following the switch
use labels to define all of the values we want to test for equality. There are two kinds of labels. The first kind of label is the case label, which is declared the case keyword, using and
evaluates to a constant value in other words, either a literal (such as 5), an enum (such or as a
COLOR_RED),
constant integral variable (such as nX, when nX has been defined as a const int).
char
Even though the char data #include "iostream"; type is an integer (and thus int main() follows all of the normal integer rules), we typically work with chars in a "; different way than normal integers. Characters can hold either a small number or a letter from the ASCII character set. ASCII stands for
{ using namespace std; char chChar; cout << "Input a keyboard character: cin >> chChar; cout << chChar << " has ASCII code " << (int)chChar << endl;
keyboard and a number between 1 and 127 (called a code). For instance, the character a is mapped to code 97. b is code 98. Characters placed quotes. continue The continue statement int nPrinted = 0; provides a convenient way for (int iii=0; iii < 100; iii++) to jump back to the top of a loop earlier than normal, which can be used to bypass the remainder of the loop for an iteration.
} cout << nPrinted << " numbers were found" << endl; { // if the number is divisible by 3 or 4, skip this iteration if ((iii % 3)==0 || (iii % 4)==0) continue; cout << iii << endl; nPrinted++;
are
always single
between
do
One
interesting
about the while loop is that int main() if the loop condition is false, the while loop may not execute at all. It is sometimes the case that we want a loop to execute at
using namespace std; // nSelection must be declared outside do/while loop int nSelection; do { cout << "Please make a selection: cout << "1) Addition" << endl; cout << "2) Subtraction" << endl; cout << "3) Multiplication" <<
least once, such as when " << endl; displaying a menu. Thus, To facilitate this, C++ endl; offers the do while loop
cout << "4) Division" << endl; cin >> nSelection; } while (nSelection != 1 &&
nSelection != 2 && nSelection != 3 && nSelection != 4); // do something with nSelection here // such as a switch statement return 0; } switch (2) { case 1: // Does not match -- skipped cout << 1 << endl; case 2: // Match! Execution begins at the next statement cout << 2 << endl; // Execution begins here case 3: cout << 3 << endl; // This is also executed case 4: cout << 4 << endl; // This is also executed default: cout << 5 << endl; // This is also executed }
the default keyword. The code under this label gets executed if none of the cases match the switch expression. The default
label is optional. It is also typically declared as the last label in the switch block, though this is not strictly necessary. One of the trickiest things about case statements is the way in which
execution proceeds when a case is matched. When a case is matched (or the default is executed),
execution begins at the first statement following that label and continues until one of the following conditions is true:
block 2) A
is return
reached statement
occurs
double dPi #include <iostream> { using namespace std; double dValue = 1000000.0; cout << dValue << endl; dValue = 0.00001; cout << dValue << endl; return 0; }
in int main()
which the type and/or scope of a variable is used as a naming prefix for that variable. Double or double, d is the type prefix indicates the data type of the variable in the Hungarian notaion. else We can additionally
specify what we want to void main() happen if the condition is not fulfilled by using the keyword else. Its form
unsigned int Miles; const double LessThan100 = 0.25; const double MoreThan100 = 0.15; double PriceLessThan100, PriceMoreThan100, TotalPrice; cout << "Enter the number of miles: "; cin >> Miles; if(Miles <= 100) { PriceLessThan100 LessThan100; PriceMoreThan100 } else { PriceLessThan100 LessThan100; PriceMoreThan100
= Miles * = 0;
* MoreThan100; } TotalPrice = PriceLessThan100 + PriceMoreThan100; cout << "\nTotal Price = $" << TotalPrice << "\n\n"; }
externally. A common use of the extern modifier is with the DllImport attribute when you are using
extern "C" { void f(); // extern "C++" { void g(); // extern "C" void h(); void g2(); // } extern "C++" void k();// void m(); // }
Interop services to call into unmanaged code The extern keyword can
possible
component from within a single assembly. For more information, see extern
alias (C# Reference). false The keyword is one of the two values for a variable of type bool or a
class TestClass { static void Main() { bool a = false; Console.WriteLine( a ? "yes" : "no" ); } } // Output: no
now
a true Boolean
assigns false to i. float The float keyword signifies a simple type that stores 32-bit floating-point values. Float is short for floating point and is a fundamental (i.e. built into the compiler)type used to define numbers with fractional parts. The float type can represent values ranging from approximately 1.5 1045 to 3.4 1038with a precision of 7 digits. There is also a double. Numbers without fractional parts can be stored in ints.
#include <iostream> int main() { using namespace std; float fValue; fValue = 1.222222222222222f; cout << fValue << endl; fValue = 111.22222222222222f; cout << fValue << endl; fValue = 111111.222222222222f; cout << fValue << endl; }
for
int nValue = 1; for (int iii=0; iii < nExp; iii++) nValue *= nBase; return nValue;
evaluates
to false. }
The for loop is useful for iterating over arrays and for sequential processing. if The if statement selects a statement for
#include <iostream> int main() using namespace std; cout << "Enter a number: "; int nX; cin >> nX;
execution {
example,
the Boolean variable result is set to true and then checked the if statement. in The
if (nX > 10) cout << nX << "is greater than 10" << endl; else cout << nX << "is not greater than 10" << endl; return 0; }
output is: The variable is set to true. If the expression in the parenthesis is evaluated to be true, then the Console.WriteLine("T he variable is set to true."); statement is executed. After executing the if statement, control is transferred to the next statement. The else is not executed in this example. If you wish to execute more than one statement, multiple statements can be conditionally executed by including them into blocks
using {} as in the example above. The statement(s) to be executed upon testing the condition can be of any kind, including another if statement nested into the original if statement. In nested if statements, theelse clause belongs to the last if that does not have a corresponding else.
int
Int is a fundamental (i.e. built into the compiler) type used to define numericvariables holding whole numbers. Int is short for integer. As only whole numbers can be stored in an Int variable. 7, 4908 or -6575 are ok. 5.6 is not. Numbers with fractional parts requires a float type variable. The size of number that can be stored in an int
// operating with variables #include <iostream> using namespace std; int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; }
depends on the hardware. Usually, but not always it is 32 bits so the range of values is from 2,147,483,648 to 2,147,483,647.
long
#include <iostream>
Type long (or long int) is #include <iomanip> an integral type that is int main()
{
Objects of type long can sizeof(*arr); for (size_t i = 0; i < n; ++i) be declared as signed long or unsigne d long. Signed long is synonym for long. namespac e, A namespace declaration identifies and assigns a unique name to a userdeclared namespace. Such namespaces are used
// namespace_declaration3.cpp namespace A { // declare namespace A variables int i; int j; } namespace B { } return 0;
to solve the problem of namespace A name collision in large { programs and libraries. can to use }
{
Programmers namespaces
with existing components. A namespace declaration, whether it involves a new namespace, an unnamed namespace, or an extended namespace definition,
must be accompanied by a namespace body enclosed within curly brace. return The expression clause, if present, is converted to the type specified in the function declaration, as if an initialization were being performed. Conversion from the type of the expression to the return type of the function can create temporary objects. The value of the expression clause is returned to the calling function. If the expression is omitted, the return value of the function is undefined. Constructors and destructors, and functions of type void, cannot specify an expression in
} int* AllocateArray(int nSize) { return new int[nSize]; } int main() { int *pnArray = AllocateArray(25); // do stuff with pnArray delete[] pnArray; return 0;
the return statement. Functions of all other types must specify an expression in the return statement. When the flow of control exits the block enclosing the function definition, the result is the same as it would be if a return statement without an expression had been executed. This is invalid for functions that are declared as returning a value. A function can have any number of return statements.
an {
integral type that is larger than or equal to the size of type char, and shorter than or equal to the size of type int. Objects of type short can be declared
using namespace std; unsigned short x = 65535; // largest 2-byte unsigned value possible cout << "x was: " << x << endl; x = x + 1; // We desire 65536, but we get overflow! cout << "x is now: " << x << endl; }
as signed short or unsigne d short. Signed short is a synonym for short. static The static keyword can be used to declare variables, functions, class data members and class functions. By default, an object or variable that is defined outside all blocks has static duration and external linkage. Static duration means that the object or variable is allocated when the program starts and is deal located when the program ends. External linkage means that the name of the variable is visible from outside the file in which the variable is declared. Conversely, internal linkage means that the name is not visible outside the file in which the variable is declared.
} class Something { private: static int s_nIDGenerator; int m_nID; public: Something() { m_nID = s_nIDGenerator++; } int GetID() const { return m_nID; } }; int Something::s_nIDGenerator = 1; int main() { Something cFirst; Something cSecond; Something cThird; using namespace std; cout << cFirst.GetID() << endl; cout << cSecond.GetID() << endl; cout << cThird.GetID() << endl; return 0;
switch
The expression must be of an integral type or of a class type for which there is an unambiguous conversion to integral type. Integral promotion is performed as described inIntegral Promotions. The switch statement body consists of a series of case labels and an optional default label. No two constant expressions in case statements can evaluate to the same value. The default label can appear only once. The labelled statements are not syntactic requirements, but the switch statement is meaningless without them. The default statement need not come at the end; it can appear anywhere in the body of the switch statement. A case or
void PrintColor(Colors eColor) { using namespace std; switch (eColor) { case COLOR_BLACK: cout << "Black"; break; case COLOR_WHITE: cout << "White"; break; case COLOR_RED: cout << "Red"; break; case COLOR_GREEN: cout << "Green"; break; case COLOR_BLUE: cout << "Blue"; break; default: cout << "Unknown"; break; } }
default label can only appear inside a switch statement. The constant-expression in each case label is converted to the type of expression and compared with expression for equality. Control passes to the statement whose case constantexpression matches the value of expression. The resulting behaviour is shown in the following table.
typedef
You can use typedef declarations to construct shorter or more meaningful names for types already defined by the language or for types that you have declared. Typedef names allow you to encapsulate implementation details that may change. In contrast to the class, struct, union,
#ifdef INT_2_BYTES typedef char int8; typedef int int16; typedef long int32; #else typedef char int8; typedef short int16; typedef int int32; #endif
and enum declarations, ty pedef declarations do not introduce new types they introduce new names for existing types. Typedef names share the name space with ordinary identifiers. Therefore, a program can have a typedef name and a local-scope identifier by the same name.
true This keyword is one of the two values for a variable of type bool or a
// bool_true.cpp #include <stdio.h> int main() { bool bb = true; printf_s("%d\n", bb); bb = false; printf_s("%d\n", bb); }
true; assigns true to i. unsigned An unsigned integer is one that can only hold positive values. To declare a variable as unsigned, use the unsigned keyword:
#include <iostream> int main() { using namespace std; unsigned short x = 65535; // largest 2-byte unsigned value possible cout << "x was: " << x << endl; x = x + 1; // We desire 65536, but we get overflow! cout << "x is now: " << x << endl; }
1 2 3 4
unsigned char chChar; unsigned short nShort; unsigned int nInt; unsigned long nLong;
void
When used as a function return type, the void keyword specifies that the function does not return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal." If a pointer's type is void *, the pointer can point to any variable that is not declared with the const or volatile keyw ord. A void pointer cannot be dereferenced unless it is cast to another type. A void pointer can be converted into any other
// void.cpp void vobject; // C2182 void *pv; // okay int *pint; int i; int main() { pv = &i; // Cast optional in C required in C++ pint = (int *)pv; }
type of data pointer. A void pointer can point to a function, but not to a class member in C++.
// while_statement.cpp #include <string.h> #include <stdio.h> char *trim( char *szSource ) { char *pszEOS = 0; // Set pointer to character before t erminating NULL pszEOS = szSource + strlen( szSource ) - 1; // iterate backwards until non '_' i s found while( (pszEOS >= szSource) && (*pszE OS == '_') ) *pszEOS-- = '\0'; return szSource; } int main() { char szbuf[] = "12345_____"; printf_s("\nBefore trim: %s", szbuf); printf_s("\nAfter trim: %s\n", trim(s zbuf)); }