Ibtro to c++

¡Supera tus tareas y exámenes ahora con Quizwiz!

What is machine language?

>Set of Instruction executed directly by a computer's CPU >Machine language is machine-dependent. Strings of numbers giving machine specific instructions Example: +1300042774 +1400593419 +1200274027

Control structure

A control statement and the statements whose execution it controls. a control statement is any statement that alters the linear flow of control of a program. C++ examples include: if-else, while, for, break, continue and return statement Sequential execution: Statements executed in order Transfer of control: The next statement to be executed may be other than the next one in sequence.

What is an algorithm?

A step-by-step procedure for solving a problem or accomplishing some task, especially by means of a computer. The algorithm provides a blueprint for writing a program to solve a particular problem. It is considered to be an effective procedure for solving a problem in a finite number of steps. A well-defined algorithm always provides an answer and is guaranteed to terminate.

while loop syntax

Action repeated while some condition remains true. When an action must be repeated a loop is used. While loop syntax while (boolean expression is true) { statements to repeat ; //braces are required for compound statement statements to repeat ;. } While (boolean expression is true) statement to repeat; // no braces are required for single statement

Describe the characteristics of an algorithm

Algorithm must possess the following characteristics: Be precise Be unambiguous Not even a single instruction must be repeated infinitely. After the algorithm gets terminated, the desired result must be obtained.

Example of an algorith

An Algorithm to add two numbers. Step 1: Input the first number as A. Step 2: Input the second number as B. Step 3: Set Sum = A+ B Step 4: Print Sum Step: End

Declaration of Arrays

An array must be declared before being used. Declaring an array means specifying three things: Data Type: what kind of value it can store, for example, int, float , char , double. Name: to identify the array. Size: the maximum number of values that the array can hold. Arrays are declared using the following syntax: Type name[size]; For example : int marks[10]; declares a marks variable to be an array containing 10 elements. C++ does not allow declaring an array whose number of elements is not known at the compile time.

Operators in C++

An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables" Ex: a+b

Types of Recursion

Any recursive function can be characterized based on the following: 1.Whether the function calls itself directly or indirectly.(direct or indirect recursion) 2.Whether any operation is pending at each recursive call.(tail - recursive or not) 3.The structure of the calling pattern .(linear or tree recursive)

What is assembly language?

Assembly languages English-like abbreviations representing elementary computer operations (translated via assemblers) Example: LOAD BASEPAY ADD OVERPAY STORE GROSSPAY Translator programs called assembler were developed to convert assembly language programs to machine language programs at computer speed.

Function Declaration

Before using the function, the compiler must know about the number and type of parameters that the function expects to receive and the data type of the value that it will return to the calling program. Placing the function declaration statement prior to its use enables the compiler to make a check on the arguments used while calling that function. The general format for declaring a function that accepts some arguments and returns some value as a result can be given as : return_data_type function_name(data_type variable 1, data_type variable2,.......) Here, function_name is a valid name for function. Naming a function follows the same rules as naming variable. A function should have a meaningful name that must clarify the task that it will perform.

Boolean Expressions

Boolean expressions are expressions that are either true or false comparison operators such as '>' (greater than) are used to compare variables and/or numbers - (grade >= 60) Including the parentheses, is the boolean expression from the grade example - A few of the comparison operators that use two symbols (No spaces allowed between the symbols!) > greater than != not equal or inequality == equal or equivalent <= less than or equal to etc

What is increment and decrement?

C++ supports 2 useful operators namely Increment ++ Decrement-- operators The ++ operator adds a value 1 to the operand The -- operator subtracts 1 from the operand ++a or a++ --a or a--

Compiling and Executing C++ Programs

Compilation before execution: Source File + Library Files >Pre Processor > Compiler > Object Files + Library Files > Linker > Executable File

Describe computer languages

Computer languages are divided into three types: 1)Machine languages 2)Assembly languages 3) High level languages

Equality and Relational operators

Conditions in if structures can be formed by using the equality and relational operators Equality operators: Same level of precedence Associated left to right. Relational operators: Same level of precedence. Associated left to right. Equality operators precedence is lower then precedence of relational operators.

Nested control structure

Control structure that rests entirely within another control structure

Do-While Loop vs. While Loop

Do: POST-TEST loop (exit-condition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. While: PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all.

How does the ? operator work?

Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated and this becomes the value of the expression, If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the expression Ex: m=2; n=3 r=(m>n) ? m : n;

Rules of a switch

Expression (variable in braces after switch) must be of type integer or character. It is the controlling expression of switch statement The keyword case must be followed by a constant break statement is required unless you want all subsequent statements to be executed.

What is a flowchart?

Flowchart is a graphical or symbolic representation of a process. It is basically used to design and document virtually complex processes to help the viewers to visualize the logic of the process to gain a better understanding of process and find flaws

Operations that can be performed on Arrays

Following operations can be performed on arrays: 1.Traversal 2.Insertion 3.Search 4.Deletion 5.Merging

Avoiding Common Pitfalls with if Statements

Forgetting that C++ is case sensitive Assuming that indentation has a logical purpose Adding an unwanted semicolon Forgetting curly braces Using = instead of == (explained with example on next) Making unnecessary comparisons

Hardware vs. Software

Hardware: >Physical part of the computer >Various devices comprising a computer Examples: keyboard, screen, mouse, disks, memory, CD-ROM, and processing units Software: A collection of computer programs, procedures, and documentation that performs some tasks on a computer system Example: programs that run a computer

Example of structured programming

Imagine that your institute wants to create a program to manage the names and addresses of a list of students. Let's program is break down into following modules: 1.Enter new name and addresses. 2.Modify existing entries. 3.Sort entries. 4.Print the list.

Function with Default Parameters

In C++ programming, we can provide default values for function parameters. 1.If a function with default arguments is called without passing arguments, then the default parameters are used. 2.However, if arguments are passed while calling the function, the default arguments are ignored.

Decision making structure/ selection structure

Selection structure/decision structure allows the program to make a decision or comparison and then select one of two paths, depending on the result of the comparison.

Compound Statement

Set of statements within a pair of braces also known as BLOCK if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n";} Without braces, cout << "You must take this course again.\n"; always executed

What are computer programs?

Sets of instructions that control a computer's processing of data

What are high level languages? (the third type of computer language)

Similar to everyday English, uses mathematical notations (translated via compilers) Example: grossPay = basePay + overTimePay C, C++ are the most widely used high level languages. Some other examples are: FORTRAN (formula translator) (Used in scientific and engineering applications) COBOL (common business oriented language. Used to manipulate large amounts of data) Pascal (Used to teach structured programming)

Files in a C++ Program

Source File Header File Object File Executable File

If Selection Structure

The primary C++ selection structure statement used to perform a single-alternative selection. Choose among alternative courses of action If the condition is true: statement Print statement executed, program continues to next If the condition is false: Print statement ignored, program continues

Explain tokens

The smallest individual units of a program are called tokens. 1.Constants 2.Variables 3.Keywords 4.Data Types A C++ program is written using these tokens, white spaces, and the syntax of the language.

Function Call

The two types of function call: •Call by value •Call by reference Arguments can generally be passed in one of the two ways: 1. Sending the values of the arguments In this method, value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method changes made to the formal arguments in the called function have no effect on the values of the actual arguments. 2. Sending the address of the arguments The address of the actual arguments in the calling function are copied into formal arguments of the called function.This

disadvantages of goto

The use of goto statement is highly discouraged as it makes the program logic very complex. use of goto makes the task of analyzing and verifying the correctness of programs (particularly those involving loops) very difficult. Use of goto can be simply avoided using break and continue statements. Using goto statement violates the rules of structured programming.

Condition

condition is a logical expression that evaluates to true or false. It could be a relational or Boolean expression. In other words: Specifies the decision you are making Must result in either a true or false answer

SYNTAX

do { Statement } while (Expression) ; //note semi colon Loop body statement can be a single statement or a block

If the value of a formal argument s changed in the called function.....

the corresponding change does not take place in the calling function. When values are passed to a called function the value present in the actual arguments are not physically moved to the formal arguments, just a photocopy of values in actual argument is made into formal arguments.

Following points should be kept in mind about function declaration:

•After the declaration of every function , there should be a semicolon. If the semicolon is missing, the compiler will generate an error message. •A function cannot be declared with in the body of another function. •A function having void as its return type cannot return any value. •A function having void as its parameter list cannot accept any value.

Basics of a typical C++ environment

•Phases of C++ Programs to be executed -Edit (Program is created in the editor and stored on disk.) -Preprocess (Preprocessor program processes the code.) -Compile (Compiler creates object code and stores it on disk.) -Link (Linker links the object code with the libraries, creates .exe and stores it on disk) -Load (Loader puts program in memory.) - Execute (CPU takes each instruction and executes it, possibly storing new data values as the program executes.)

The do-while Statement

•Syntax do action while (condition) •How it works: -execute action -if condition is true then execute action again -repeat this process until condition evaluates to false. •action is either a single statement or a group of statements within braces

valid return statements:

•return(x); •return (0); •return 1; •return 12.5; A function can return only one value at a time . Thus , the following statements are invalid. return(a , b); return(x,12);

//program to calculate the sales commission

#include <iostream> using namespace std; int main() { float sales, commission; cout<<"enter the sales"<<endl; cin>>sales; if (sales>1500) commission = sales*0.2; else commission = sales*0.1; cout<<"commission is"<<commission; return 0; }

If/else selection structure

(Different actions if conditions true or false) Syntax: A single statement for each alternative if (Boolean_expression) yes_statement; else no_statement; A sequence statement for each alternative if (Boolean_expression) { yes_statement1; yes_statement2; yes_statement last; } else { no_statement1; no_statement2; no_statement last; }

Call By reference

1.A function call passes arguments by value . 2.The called function creates a new set of variables and copies the value of arguments into them. 3.The function doesn't have access to the actual variables in the calling program and can only work on the copies of value. 4.This mechanism is fine if function does not need to alter the values of the original variables in the calling program . 5.But there may arise situation where we would like to change the values of variables in the calling program. 6.Reference variables in C++ permits us to pass parameters to the function by reference. 7.When we pass arguments by reference the formal arguments in the calling function become aliases to the actual arguments in the calling function. 8.This means that when the function is working with its own arguments it is actually working on the original data.

What is a computer?

>A device capable of performing computations and making logical decisions >A machine that manipulates data according to a list of instructions. >A programmable device that can store, retrieve, and process data.

Converting Recursive functions to tail Recursive

1.A non tail recursive function can be converted into a tail-recursive function by using an auxiliary parameter as in case of factorial function. 2.The auxiliary parameter is used to form the result. 3.When we use such a parameter , the pending operation is incorporated into the auxiliary parameter so that recursive call is no longer has a pending operation. 4.We generally use auxiliary function while using auxiliary parameter. 5. This is done to keep the syntax clean and to hide the fact that auxiliary parameters are needed.

Arrays

1.An array is a collection of similar data elements have the same data type. 2.The elements of array are stored in consecutive memory locations and are referenced by an index (also known as subscript). 3.Subscript indicates an ordinal number of the elements counted from the beginning of the array. Examples: •List of temperatures recorded on everyday of the month. •List of employee in a company. •List of students in a class. •List of products sold. •List of customers.

1.//program to determine if user is ill

1.#include <iostream> 2.using namespace std; 3.int main() 4.{ 5. const double NORM = 98.6; // degree Fahranheit; 6. double temperature; 7. cout<<"Enter your temperature\t"; 8. cin>>temperature; ● 9. if (temperature>NORM) //if temperature is greater than NORM print following statement 10. cout<<"\n\nYou are sick\n"<<"take rest and drink lots of fluids"; 11. else //if temperature is <= NORM print following statement 12. cout<<"\n\nYou are perfectly fine"; ● 13. return 0; }

Calculating the Address of Array Elements

1.Array name is symbolic reference for the address to the first byte of the array. When we use the array name, we are actually referring to the first byte of array. 2.An array stores all its elements in consecutive memory locations . So, storing just the base address, i.e. the address of the first element in the array is sufficient. 3.The address of other data elements can simply be calculated using the base address.

Reference Variable

1.C++ introduces a new kind of variable known as reference variable. 2.A reference variable provides an alias(alternate name) for a previously defined variable. 3.e.g. if we make a variable sum a reference to total, then sum and total can be used interchangeably to represent that variable. 4.A reference variable is created as follows: data-type & variable-name = variable name; Example: float total = 100; float &sum=total; total is a float type variable that has already been declared, sum is alternative name declared to represents the variable total. Both the variables refer to the same data object in the memory. cout<<total; cout<<sum;

Accessing Elements of the Array

1.For accessing the individual element of the array, the array subscript must be used. e.g. to access the fourth element of the array, we must write arr[3]. 2.Subscript index must be an integral value or an expression that evaluates to integral value. 3.To access all the elements of the array, we must use a loop.

Some of the situations where inline expansion may not work are:

1.For functions returning values , if a loop, a switch or a goto exists. 2.If function contains static variables. 3.If inline functions are recursive. Remember that inline keyword merely send a request not a command, to compiler. The compiler may ignore this request if the function definition is too long or too complicated and compile the function as normal function.

Type Casting (char <> int <> float)

1.It is possible to store char values in integer variables (an important feature of C++) 2.Characters are represented as 1-byte integer in computers so we can treat a character as either char or int depending on its use int value = 'A'; //65 is ASCII for A 4. value will contain an integer representing 'A' i.e. value = 65. 5.Similarly ,It is possible to store int values in char variables char letter=97 //97 is numerical representation of lower case a (ASCII) Result of the above statement is letter = a Use single quotes to get numerical representation of a character cout << "The character (" << 'a' << ") has the value " << ( int ) ( 'a' ) << endl; Prints The character (a) has the value 97 ASCII (American Standard Code For Information Interchange)

Function Overloading

1.Overloading refers to the use of same thing for different purpose. 2.C++ permits overloading of functions. 3.same function name may be used to create functions that perform a variety of different tasks. 4.The correct function to be invoked is determined by checking the number and type of arguments but not on the function type.

Unary Scope Resolution Operator

1.Same variable name can be used to have different meanings in different blocks. 2.The scope of variable extends from the point of its declaration till the end of the block containing the declaration. 3.A variable declared inside a block is said to be local to that block.

basic steps of a recursive program:

1.Specify the base case which will stop the function from making a call to itself. 2.Check to see whether the current value being processed matches with the value of base case. If yes, process the return value. 3.Divide the problem into smaller or simpler sub-problem. 4.Call the function from sub problem. 5.Combine the results of sub-problems. 6.Return the result of entire problem.

Using multiple variables in for loop

1.There may be several variables in the for structure that must be initialized and updated (e.g. incremented or decrement) 2.Coma operator is used to enable the programmer to use multiple initialization and increment expressions -For multiple variables, use comma-separated lists example for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl;

How many logical units are there?

6

Direct Recursion

A function is said to be directly recursive if it explicitly calls itself. int func(int n) { if(n==0) return n; else return (func(n-1)) } Here, the func() calls itself for all positive values of n, so it is said to be directly recursive.

Indirect recursion

A function is said to be indirectly recursive if it contains a call to another function which ultimately calls it. Following functions are indirectly recursive as they both call each other: int func1(int n) { if(n==0) Return n; else return func2(n); } int func2(int x) { return func1(x-1); }

A number of conclusions can be drawn regarding functions:

A number of conclusions can be drawn regarding functions: •Any C++ program contains at one function. •If a program contains only one function, it must be main(). •In a C++ program if there are more than one function present, the one (and only one) of these functions must be main(). •There is no limit on the number of functions that might be present in a C++ program. •Each function in a program is called in a sequences specified by the function calls in main(). •After each function has complete its execution control returns to main().

Recursive Functions

A recursive function is defined as a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. Every recursive solution has two major cases, they are: Base Case: program is simple enough to be solved directly without making any further calls to the same function. Recursive Case: 1.The problem at hand is divided into simpler sub parts. 2.The function calls itself but with sub parts of the problem obtained in the first step. 3.result is obtained by combining the solutions of simpler sub parts.

Tail Recursion

A recursive function is said to be tail recursive if no operations are pending to be performed when the recursive function returns to its caller . When the called function returns, the returned value is immediately returned from the calling function. Tail recursive functions are highly desirable because they are much more efficient to use as the amount of information that has to be stored on the system stack is independent of the number of recursive calls.

Describe every logical units function

Input unit: Obtains information (data and computer programs) from input devices (keyboard, mouse) Output unit: Outputs information to the output device (screen, printer) or to control other devices. Memory unit: Rapid access, low capacity, stores input information Arithmetic and logic unit (ALU): Performs arithmetic calculations and logic decisions Central processing unit (CPU): Supervises and coordinates the other sections of the computer Secondary storage unit: Cheap, long-term, high-capacity storage, stores inactive programs

loop continuation test

Is a Boolean expression Expression contains the final value of the control variable for which the condition is true e.g. counter <= 10; Loop continuation test evaluates to true or false If true body of for is executed, else exit for loop Notice that there is also a semi colon after loop condition test Update Specifies how to update condition After the execution of the body of the loop, the condition of the loop is updated e.g. counter ++ Notice that there is no semi colon after updat_action Example for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; Prints integers from one to ten

Explain keywords

Keywords implement specific C++ language features. They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements.

Confusing Equality (==) and Assignment (=) Operators

L-values Expressions that can appear on left side of equation Can be changed (I.e., variables) x = 4; R-values Only appear on right side of equation Constants, such as numbers (i.e. cannot write 4 = x;) L-values can be used as R-values, but not vice versa

What is pseudocode?

Pseudocode is an outline of a program that can easily be converted into programming statements. They consist of short English phrases that explain specific tasks within a program's algorithm.

Calculating the Length of the Array

Length of the array is given by the number of elements stored in it. The general formula to calculate the length of the array is, Length = upper bound - lower bound + 1 Where upper bound is the index of the last element And lower bound is the index of the first element in the array.

Example of decrement/increment

Let the value of a =5 and b=++a then a = b =6 Let the value of a = 5 and b=a++ then a =6 but b=5 i.e.: 1. a prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left 2. a postfix operator first assigns the value to the variable on left and then increments the operand.

repetition structure

Many application require certain operations to be carried out more than once. Such situations require repetition in control flow. C++ has three types while, do/while, for While Selection Structure: An action to be repeated while some conditions remains true. Do/While Selection Structure: . Similar to while structure. Tests the loop continuation after the loop body is performed. while structure the loop continuation condition is tested at the beginning of the loop before the body of loop is performed.

The return statement serves two purposes :

On executing the return statement it immediately transfers the control back to the calling program. It returns the value present in the parenthesis after return, to the calling program.in the above program value of the sum of three numbers is being returned. 1.There is no restriction on the number of return statements that may be present in a function. Also, the return statement need not always be present at the end of the called function. 2.Whenever control returns from a function some value is definitely returned. If a meaningful value is returned then it should be acceptable in calling program by equating the called function to some variable. For example: Sum = calsum(a,b,c);

IF Structure

One statement or a block of statement enclosed in braces {} i.e. (compound statement), to be processed If condition met otherwise it is skipped. Uses equality and relational operators

What are the rules for naming identifiers?

Only alphabetic characters digits and underscores are permitted. The name cannot start with a digit. Uppercase and Lowercase letters are distinct A declared keyword cannot be used as a variable name.

if and if-else

Perform an action if condition is true. Skip the action if condition is false. If/else Selection Structure Perform an action if condition is true. Performs a different action if the condition is false.

Function Templates

Suppose we want to write a function that returns the minimum of two numbers. ordinarily this function would be written for a particular data type. For example: int min(int a, int b) { return (a<b)?a:b; } If we want to find a minimum of two long ints-we would be required to write a completely new function . Similarly to find minimum of two floats or two doubles or two chars it is required to write separate versions of the same function. These are given below: //min for ints int min(int a,int b) { return (a<b)?a:b; } //min for longs long min (float a, float b) { return (a<b)?a:b; }

switch (Selection structure)

Switch is typically a selection structure and an alternative to the long string of ifs Tests variables for multiple values Consists of a series of case labels and an optional default case General format: switch ( variable ) { case value1: // taken if variable == value1 statements break; // necessary to exit switch case value2: case value3: // taken if variable == value2 or == value3 statements break; default: // taken if variable matches no other cases statements break;}

how does do while work

Syntax: do action while (condition) How it works: execute action if condition is true then execute action again repeat this process until condition evaluates to false. action is either a single statement or a group of statements within braces Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while (Expression) ; //note semi colon Loop body statement can be a single statement or a block.

Conditional operators

Syntax: exp1 ? exp2 : exp3 Where exp1,exp2 and exp3 are expressions

Selection structure

To use the selection structure to choose among the alternative actions if selection statement Double Selection (if else ) statements Nested Selection statements

Constants , Identifiers and Keywords

The alphabets, numbers, and special symbols when properly combined form constants, identifiers, and keywords. Constant: a constant is a quantity that does not change. This can be stored at a location in memory of the computer. Variable(identifiers): is considered as a name given to the location in memory where this constant is stored. Naturally, the contents of the variable can change. There is a fundamental requirement of any language. Each language has its own rules for naming these identifiers.

break and continue Statements

The break and continue statements alter the flow of control break statement Causes immediate exit from while, for, do/while or switch structure Program execution continues with first statement after structure Common uses Escape early from a loop Skip the remainder of switch structure continue statement Used in while, for, do/while Skips remainder of loop body Proceeds with next iteration of loop

What is structured programming?

The goal of structured programming is to write correct programs that are easy to understand and modify. A structured program takes less time to write than other programs. Modules or procedures written for one program can be reused in another program also

goto statement

The goto statement is used for transferring the control of a program to a given label. Used to transfer control to a specified label. Label is an identifier that specifies the place where branch is to be made. Label is placed immediately before the statement where the control has to be transferred.

Arithmetic Expressions in for Structure

The initialization, loop-continuation condition and increment portions of a for structure can contain arithmetic expressions Example Assume x = 2, y = 10 If x and y are not modified in loop body, the statement for (int j = x; j <= 4*x*y; j+=y/x ) Is equivalent tt the statement for (int j = 2; j <= 80; j+=5) As 4*x*y = 4*2*10 = 80 and y/x = 10/2 = 5

Rules for ++ & -- Operators

They require variables as their operands. When postfix either ++ or -- is used with the variable in a given expression, the expression is evaluated first and then it is incremented or decremented by one. When prefix either ++ or - is used with the variable in a given expression, it is incremented or decremented by .one first and then the expression is evaluated with the new value

Have we gained anything by writing these overloaded functions?

This results into following disadvantages: 1.Rewriting the same function body over and over for different types is time consuming. 2.Program consumes more disk space. It would be nice if we could write such a function just once, and make it work for many different data types. This is exactly what function templates do for us.

example of calculating factorial of a number.

To calculate !n , we have to multiply the number with factorial of the number that is one less than the number. In other words: !n = n*!n-1 Let us assume we need to find the value of !5 !5 = 5*4*3*2*1=120 This can be written as !5=5*!4, where !4=4*3*2*1 For the factorial function Base Case: when n=1, because if n=1, the result will be 1 as !1=1 Recursive Case: factorial function will call itself but with a smaller value of n , this case be given as: factorial(n) = n*factorial(n-1)

Inline Function

To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. An inline function is a function that is expanded in line when it is invoked that is compiler replaces the function call with the corresponding function code. The inline functions are defined as follows: inline function header { Function-body } Example: Inline double cube(double a) { return a*a*a; }

Tower of Hanoi algorithm

To summarize , the solution to our problem of moving n rings from A to C using B as spare can be given as: Base case: If n=1 Move the rings from A to C using B as spare. Recursive case: 1.Move (n-1 ) rings from A to B using C as spare. 2.Move the one ring left on A to C using B as spare. 3.Move (n-1 ) rings from B to C using A as spare.

Tower of Hanoi

Tower of Hanoi is also called as Tower of Brahma or Lucas Tower. It is one of the most popular problem which makes you understand the power of recursion. Tower of Hanoi is a mathematical puzzle which consist of 3 poles and number of discs of different sizes. Initially all the discs will be places in the single pole with the largest disc at the bottom and smallest on the top. We need to move all the disc from the first pole to the third pole with the smallest disc at the top and the largest at the bottom under the below conditions 1.Only one disc can be moved at a time. 2.Larger disc cannot be placed on a smaller disc.

What is a compiler?

Translator programs called Compilers converts high-level language programs into machine language

Functions Definition

When a function is defined space is allocated for that function in the memory. A function definition comprises two parts: •Function Header •Function Body The Syntax of function definition can be given as: Return-type function_name(data type variable1, data_type variable2........) { ....... Statements ..... .... Return variable; }

Storing Values in Arrays

When we declare and define an array , we are just allocating space for the elements, no values are stored in array. To store values in the array, there are three ways: 1.Initialize the elements 2.Input values for the elements 3.Assign values to the elements

for and while and do syntax

for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); // you can put more statements. } while(condition) { while(condition) { statement(s); } statement(s); // you can put more statements. } do { statement(s); // you can put more statements. do { statement(s); } while( condition ); } while( condition );

for Repetition Structure

for loop is used when the number of times to be repeated is fixed/known It handles all the details of the counter controlled repetition Execution continues as long as the Boolean expression is true General format of the for loops: for (initialization; Loop Continuation Test; update) { statement block; } Initialization action Done only once at the start Initialization expression initialize and declare the loop's control variable e.g. int counter = 1; Notice that there is a semi colon after initialization statement

C++ code

if ( grade >= 90 ) // 90 and above cout << "A"; else if ( grade >= 80 ) // 80-89 cout << "B"; else if ( grade >= 70 ) // 70-79 cout << "C"; else if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F"; if grade>=90, first four conditions will be true. But only the cout statement after the first test will be executed. After that cout is executed, the else part of the outer if/else statement is skipped.

Nested if/else structure

if structure that rests entirely within another if structure, within either the if or the else clause One inside another, test for multiple cases Once condition met, other statements skipped

Example:

int sum ( int a = 0, int b = 10, int c =5) { return a+b+c; } y = sum(1,6); // returns 12 y = sum(); // returns 15 y = sum(6,1); // returns 12 y = sum (2,3,4); // returns 9 Can be provided for trailing arguments only Examples: int f1 ( int a, int b = 1, int c = 5); // OK int f2 (int a = 2, int b = 1, int c); // Error int f3 (int a = 2, int b, int c = 5); // Error


Conjuntos de estudio relacionados

Geometry B, Assignment 1. Symmetry

View Set

AP Econ Fall FInal Review Unit 8

View Set

Fitness Wellness and Stress Management

View Set

L1.1. Long-Term Insurance Coverages

View Set