Structured Programming II
Case sensitivity—An identifier is a series of characters consisting of letters, digits, and underscores(_) that does not begin with a digit. C++ is case sensitive—uppercase and lowercase letters are different, a1 and A1 are different identifiers. When spelling the keyword while with an uppercase W as in while is a syntax error all reserved keywords contain only lowercase letters.
#include Libraries—Lines beginning with # are processed by the preprocessor before the program is compiled. This specific line tells the preprocessor to include in the program the contents of the input/output stream header file iostream.h The file must be included for any program that outputs data to the screen or inputs data from the keyboard.
Main as a function—int main() is a part of every c++ program The parentheses after main indicate that main is a program building block called a function If the program only contains one function the program normally begins executing at function main, even if main is not the first function in the program. The keyword int to the left of main indicates that main "returns" an integer (whole number) value.
Comments--\\ indicating that the remainder of each line is a comment. Comments document programs and improve program readability. Comments also help other people read and understand you program. The computer does not perform any action on them.
Statements—Every statement must end with a semicolon ( a statement terminator). Statements tell the compiler what action is to be taken depending on keywords used within the statement.
Grouping of statements--<< in a single statement is referred to as concatenating, chaining or cascading stream insertion operations. Mathematical Operators have an order or precedence. () first, *,/, or % second, + - third.
== equal, != not equal, > is greater than < is less than >== is greater than or equal to, <= is less than or equal to. () left to right, * / % left to right, +- left to right, << >> left to right < <= > >= left to right == != left to right = assignment right to left.
If ( num1==num2 )
Programmers concentrate on writing function, groups of actions that perform some common task are formed into functions and functions are grouped to form programs. The if statement allows a program to make a decision when a certain condition is met. If (condition)
Statement; placing a semicolon immediately after the right parenthesis after the condition in an if structure is often a logic error. The if structure itself would perform no action regardless of whether or not its condition is true. Indent the statement in the body of an if structure to make the body of the structure stand out and to enhance program readability. There should be no more than one statement per line in a program. A length statement may be spread over several lines.
If statement—The if selection structure either performs an action of a condition is true or skips the action of the condition if false.
The if/else selection structure performs an action if a condition is true and performs a different action of the condition is false. The switch selection structure performs one of many different actions depending on the value of an expression. The if selection structure is called a single-selection structure because it selects or ignores a single action. The if/else selection structure is called a double-selection structure is called a multiple-selection structure because it selects the action to perform from many different action. Repetition structures, namely while, do/while and for. Expression evaluates to zero, it is treated as false. If ( grade >= 60 ); cout << "passed"; If ( grade >= 60 ) cout << "Passed"; else cout << "Failed"; conditional operator ?: cout << ( grade >= 60? "Passed"; "Failed");
While is a repetition structure this action will be performed repeatedly while the condition remains true. While ( product <= 1000 )
Product = 2 * product;
The for repetition structure handles all the details of counter-controlled repetition. For ( int counter = 1; counter <+ 10; counter++ )
The switch structure consists of a series of case labels, and an optional default case. This is used when a series of decision in which a variable or expression is tested separately for each of the constant integral values it may assume, and different actions are taken. Switch ( grade ) {
Case ‘A’:
Casea’a’:
The switch structure is different from all other structures in that braces are not required around multiple actions in a case of a switch. A switch can only be used for testing a constant integral expression. The general switch multiple-selection structure (using a break in each case causes control to immediately exit the switch structure. The break statement when executed in a while, for, do/while, or switch structure, causes immediate exit from that structure. The continue statement, when executed in a while, for, or do/while structure skips the remaining statements in the body of that structure, and proceeds with the next iteration of the loop. The do/while repetition structure tests the loop-continuation condition at the end of the loop so the body of the loop will be executed at least once. Do
Statement
While (condition );
A local variable is known only in a function definition. Functions aren’t allowed to know the implementation details of any other function (including local variables).
Function definition is:
return-value-type function-name( parameter-list )
{
declarations and statements
}
A function prototype declares the return-type of the function and declares the number, the types, and order of the parameters the function expects to receive. Function prototypes enable the compiler to verify that functions are called correctly. The compiler ignores variable names mentioned in the function prototype.
Coercion of arguments—An important feature of function prototypes it is the forcing of arguments to the appropriate type.
Enum declaration—An enumeration, introduced by the keyword enum and followed by a type name, is a set of integer constants represented by identifiers. The values of these enumeration constants start at 0, unless specified otherwise, and are incremented by 1. The identifiers in an enum must be unique, but separate enumeration constants can have the same integer value. Any enumeration constant can be explicitly assigned an integer value in the enumeration definition. Enum Status {continue, won, lost};
Scope rules. An identifier’s scope is where the identifier can be referenced in a program. The four scopes for an identifier are function scope, file scope, block scope, and function prototype scope. Labels such as start: are the only identifiers with function scope. Identifiers declared inside a block have block scope. Block scope begins at the identifiers’ declaration and ends at the terminating right brace} of the block.
Void a ( void );
Void b( void );
Inline functions eliminate function-call overhead. The programmer uses the keyword inline to advise the compiler to generate function code in line (when possible) to minimize function calls. The compiler may choose to ignore the inline advice.
Inline float cube( const float s ) { return s * s * s; }
This ensures that the value of s is not changed by the function before the calculation is performed.
Call by reference—uses reference parameters. To indicate that a function parameter is passed by reference, follow the parameter’s type in the function prototype by an & In the function call, mention the variable by name and it will be passed call-by-reference. In the called function, mentioning the variable by its local name actually refers to the original variable in the calling function. The original variable can be modified directly by the called function. When an argument is passed call-byvalue, a copy of the argument’s value is made and passed to the called function. Call-by-reference is good for performance reason because it eliminates the overhead of copying large amounts of data. Int &count count is a reference to an int.
Default arguments—Function calls may commonly pass a particular value of an argument. When a default argument is omitted in a function call, the default value of that argument is automatically inserted by the compiler and passed in the call. Default arguments must be the rightmost arguments in a function’s parameter list.
Declaration of an array—An array is a consecutive group of related memory location. These locations are related by the fact that they all have the same name and the same type. To refer to a particular location or element within the array, we specify the name of the array and the subscript.intb[ 100 ], x[ 27 ];
Initializing an array—The elements of an array can also be initialized in the declaration by following the declaration with an equal sign and a coma-separated list (enclosed in braces) of initializers. Int n[ 10 ] = { 0 };
Const variable—Constant variables must be initialized with a constant expression when they are declared and cannot be modified thereafter. Constant variables are also called named constants or read-only variables. Constant variables can be placed anywhere a constant expression is expected. Int j, s[ arraySize ]; Using constant variables to specify array sizes makes programs more scalable.
Static array initialization—Arrays that are declared static are initialized when the program is loaded. If the programmer does not explicitly initialize a static array, that array is initialized to zero by the compiler. Void staticArrayInit( void )
{
static int array1[ 3 ];
Sorting Arrays—placing the data into some particular order such as ascending or descending is one of the most important computing applications. A bubbles sort is when the smaller values gradually "bubble" their way upward to the top of the array like air bubbles rising in water, while the larger values sink to the bottom of the array. The chief virtue of the bubble sort is that it is easy to program, however, it runs slowly. On each pass, successive pair of elements are compared, resulting in several passes to sort the data.
Search—The process of finding a particular element of an array is called searching. Linear search is a simple search technique. The more efficient binary search is the most commonly used. The linear searching method works well for small arrays or for unsorted arrays. The linear search compares each element of the array with the search key. The binary search algorithm eliminates one half of the elements in the array being searched after each comparison. The algorithm locates the middle element of the array and compares it to the search key. If they are equal, the search key is found and the array subscript of that element is returned. The searching of an array of 1024 elements will take only 10 comparisons using a binary search. Where one billion element array, in a linear search could average 500 million comparison.
Multi-dimensional arrays—A common use of multiple-subscripted arrays is to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two subscripts: The first (by convention) identifies the element’s row, and the second( by convention) identifies the element’s column. These are known as double-subscripted arrays. C—compilers support at least 12 array subscripts. A[ I ][ j ]