Programming in C++ Structure of main() function

Size: px
Start display at page:

Download "Programming in C++ Structure of main() function"

Transcription

1 1 Programming in C++ A C++ program is a collection of one or more functions (or procedures) Functions (in C++ program) are very much like functions in mathematics A function is like a black box There must be a function called main( ) in every executable C++ program Execution always begins with the first statement in the function main( ) Any other functions in your program are sub-programs and are not executed until they are called (either from main() or from functions called by main()) 2 Structure of main() function

2 3 Preprocessor and Program Codes std::cout << "Hello World!" << std::endl; preprocessor The actual program Preprocessor: Run before compiling Instruct the compiler on how to compile the program Will not generate machine codes Start with a pound (#) symbol Actual program: Every C++ program must have the main() function It is the beginning point of every C++ program 4 Preprocessor Preprocessor is called automatically each time you run the compiler The preprocessor looks for lines that begin with the # symbol If the line is found then the preprocessor modifies the code The compiler will compile the modified codes In addition to #include, there is also #define, #if etc

3 5 Preprocessor 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. tells the compiler it should get the file iostream through the default path e.g. #include "myfile" tells the compiler it should get the file myfile in the current folder. 6 Program Codes The basic element of a program is function A function is composed of: Return Type Function name std::cout << "Hello World!" << std::endl; Input parameters Think from the point of view of the compiler Program codes enclosed by by the opening and closing braces Note: The meaning of std::cout is checked in iostream

4 7 Themain() function is the beginning point of a program When executing a program, the operating system will first call the main() function of this program If the above main() function executes successfully, it should return an integer 0 to the operating system Call main() main() Return 0 Means everything fine on executing main()as it is the last statement 8 Program Codes std::cout << "Hello World!" << std::endl; Send the string Hello World! to to std::cout the standard output, defined in in iostream Return an an integer 0 to to the operating system In console mode, the standard output is just the console, i.e. the Command prompt window In C++,character string is represented by a sequence of characters enclosed by " " std::endl means newline (or Enter), also defined in iostream

5 9 Namespaces std::cout and std::endl means that we are referring to the cout and endl of the std namespace Thestd namespace is defined in iostream Namespace A new feature of C++ Folders and files concept in XP 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 purpose by different people cout and endl are not a part of C++, people can use these two names for any purpose; not necessarily referring to standard output and newline. 10 namespace myns int cout=0; //Integer variable //No semi-colon This cout refers to to We can have our own cout by putting it it in in a namespace defined by ourselves the standard output std::cout << myns::cout << std::endl; This cout refers to to the number 0 In fact, another definition of cout can be found in iostream The result of this program is a number 0 shown on the standard output.

6 11 namespace myns int cout=0; That s why using cout without the associate namespace is is an error since the system does not know which cout you are referring to to std::cout << cout << std::endl; 12 It may be a bit cumbersome to write the namespace of names every time A short form is to use the using statement cout << "Hello World!" << endl; All names that are not a part of of C++ will belong to to the namespace std, unless otherwise stated No need to to put std in in front of of cout and endl

7 13 We can also print integers, floatingpoint numbers or or even combination of of string and integers in in standard output \n \n--another way to to show newline cout << "Hello there.\n"; escape sequence cout << "Here is 5: "<< 5 << "\n"; cout << "endl writes a new line to the screen."; cout << \t Add a tab character Another line endl; cout << "Here is a very big number:\t" << << endl; cout << "Here is the sum of 8 and 5:\t" << 8+5 << endl; cout << "Here's a fraction:\t\t" << 5.0/8 << endl; cout << "And a very very big number:\t"; cout << *7000 << endl; // (double) 7000 casting integer to double cout << "Replace Frank with your name...\n"; cout << "Frank is a C++ programmer!\n"; \t Add a tab character 14 Result

8 15 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 only improve readability Comments can be added in two ways: /* Text between these two marks are comments */ cout << "Hello World!\n"; // Text after that are also comments 16 Hello.cpp Preprocessor directives Function named main() indicates start of program // Program: Display Hello world // Author(s): ENG2002 // Date: 28/8/2013 Comments Provides simple access otherwise, std::cout cout << "Hello world!" << endl; Ends execution of main() which ends program Insertion statement Program

9 17 Exercise 3.1a a. Build the program in p.13. 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 name should be shown as a character string. The age should be shown as an integer. c. Use the comment symbols /* and */ to comment the statements from line 5 to line 9 (inclusive). Is there any change to the results output? 18 Function main is a function What is a function? A collection of C++ statements to carry out a specific task! You can have more functions in your program! How to declare a function? A proper name must be unique Return type The function body

10 19 Example of a function Function body Return type Function name /* Text between these two marks are comments */ cout << "Hello World!\n"; // Text after that are also comments 20 The Function DEFINITION The mathematical definition of the function f(x) = 5x 3 The C++ programmatic definition would be: int f(int x) int y = 5*x 3; return y; //return 5*x 3;

11 21 Function Definition ReturnDataType FunctionName ( Parameter List ) Statement(s)... int Cube ( int n ) return n * n * n ; header body 22 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 call other 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.

12 23 They must be be the same //function DemonstrationFunction() // show a useful message void DemonstrationFunction() cout << "In Demonstration Function\n"; cout << "Print one more line\n"; A function is is defined //function main - prints out a message, then //calls DeomonstrationFunction, then shows //the second message. cout << "In main\n"; DemonstrationFunction(); cout << "Back in main\n"; Return nothing A function is is called 24 The execution sequence is like that //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. cout << "In main\n"; DemonstrationFunction(); cout << "Back in main\n";

13 25 cout << "In main\n"; DemonstrationFunction(); cout << "Back in main\n"; //function DemonstrationFunction() void DemonstrationFunction() cout << "In Demonstration Function\n"; cout << "Print one more line\n"; Can you write your program like this? 26 Function prototype A prototype looks like a header but must end with a semicolon; and its parameter list just needs to contain the type of each parameter. int Cube( int ); // prototype

14 27 Function prototype void DemonstrationFunction(); This the function prototype Put this before main then your function declaration can be written after main void DemonstrationFunction() cout << "In Demonstration Function\n"; cout << "Print one more line\n"; 28 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 return statement. main() function(a,b) return c Branch to function(a,b)

15 29 Function with input parameters Two input parameters of type integer int Add (int x, int y) cout << "In Add(),received "<<x<<" and "<<y<<"\n"; return(x+y); Now inside the function Add, the name x refers to the first input parameter, and y refers to the second parameter 30 int Add (int x, int y) cout << "In Add(),received "<<x<<" and "<<y<<"\n"; return(x+y); cout << "I'm in main()!\n"; int a,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"; Input parameters need need to to declare type type-the - the same as as those in in the the calling function Add() will will return an an integer x+y x+yback to to main() Add() is is called with with two two parameters c holds the the return value of of Add()

16 31 Exercise 3.1b a. Build the program in the last slide. Note the output on the console. b. Modify main() to calculate the square of c. 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. 32 Variable Concepts Variables Variable names (identifiers) correspond to locations in the computer's memory Every variable has a name, a type, a size and a value Whenever a new value is placed into a variable, it replaces (and destroys) the previous value. (Destructive write) Reading variables from memory does not change them int i = 45; i 45 int bytes variable value datatype address size

17 33 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 name of a variable can be considered as a label of that piece of memory Variables char a int b short int c bool d Memory Address 10 0A 21 3A One address for one byte, i.e. 8 bits. in hex in bin 34 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 Type Size bool 1 byte unsigned short int 2 bytes short int 2 bytes unsigned long int 4 bytes long int 4 bytes unsigned int 4 bytes int 4 bytes char 1 byte float 4 bytes double 8 bytes Values true or false (1 or 0) 0 to 65,535 (2 16-1) -32,768 to 32,767 0 to 4,294,967,295 (2 32-1) -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295-2,147,483,648 to 2,147,483, character values (+/-)1.40x10-45 to (+/-)3.40x10 38 (+/-)4.94x to (+/-)1.80x unsigned long long 8 bytes 0 to (2 64-1) long long 8 bytes to (2 63-1)

18 35 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: int myvariable; It defines myvariable to be an integer. Hence 4 bytes will be reserved for its storage in memory The name of the variable is case sensitive, hence myvariable is NOT the same as myvariable 36 Variable Declarations type v 1,v 2,v 3,, v n Example: int count; int j; float k; double area; char c; short int x; long int y; unsigned int z; int a1;

19 37 Declaring Variables We can declare one or more variables of the same kind at once int myvar1, myvar2, yourvar1, yourvar2; It defines myvar1, myvar2, yourvar1, yourvar2 are 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 Does an uninitialized variable have a value? int myvar1 = 10, myvar2(10), yourvar1, yourvar2 = 5; 38 Variable Initialization If a variable is not initialized, the value of variable may be either 0 or garbage depending on the storage class of the variable. int count = 5; // int count(5); double length = 1.23; char c = A ; // char c; c = A ; int i = 1, j, k = 5; char c1 = B, c2 = 66; float x = 1.23, y = 0.1;

20 39 Maximum and Minimum Each data type has its own maximum and minimum limits When the value goes beyond those limits, unexpected behavior may result unsigned short int smallnumber; smallnumber = 65535; // = cout << "small number:" << smallnumber << endl; smallnumber++; // = 0 // smallnumber = smallnumber + 1; cout << "small number:" << smallnumber << endl; smallnumber++; // = 1 cout << "small number:" << smallnumber << endl; 40 Maximum and Minimum Signed integers do NOT behave in the same way short int smallnumber; smallnumber = 32767; // = cout << "small number:" << smallnumber << endl; smallnumber++; // = cout << "small number:" << smallnumber << endl; smallnumber++; // = cout << "small number:" << smallnumber << endl;

21 41 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-bit ASCII character // ASCII code of '5' is 53 char c = 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 = ASCII Table decimal : A 6 6 B 6 7 C 6 8 D 6 9 E : 7 0 F 7 1 G 7 2 H 7 3 I 7 4 J 9 7 a 9 8 b 9 9 c d e Details of the table can be found in many places, for instance, f g h i j

22 43 Special Printing Characters C++ compiler recognizes some special characters for output formatting Start with an escape character \ (e.g. \n means new line) Character \n \t \b \" \' \a \\ What it Means new line tab backspace double quote single quote bell backslash escape sequence //using goto, not recommended int i = 0; char c = i; beg: // label for goto 44 cout << "[ " << c << " ] = " << i << endl; i = i + 1; c = i; // c = ++i; if (i < 256) goto beg; c = 'A'; cout << "c = " << c << endl; c = 65; cout << "c = " << c << endl; i = 'A'; cout << "i = " << i << endl; // A == 65 cin.get();

23 45 Floating-point numbers Floating-point number (real number): zero or any positive or negative number containing a decimal point Examples: No special characters are allowed Three floating-point data types in C++: float (single precision) 7 significant digits 1.2F double (double precision) 15 significant digits 1.2 long double (same as double for Visual C++) 1.2L 46 Exponential Notation Floating point numbers can be written in exponential notation, where e or E stands for exponent 6.25E

24 47 //Comparing int, double and float int main () cout.precision(20); cout << "1/3 = " << 1/3 << endl << endl; cout << "1.0/3 = " << 1.0/3 << "\n"; cout << "(double)1/3 = " << (double)1/3 << "\n\n"; cout << "(float)1/3 = " << (float)1/3 << "\n1.0f/3 = " << 1.0F/3 << "\n\n"; cout << "int size = " << sizeof(int) << " bytes\n"; cout << "double size = " << sizeof(double) << " bytes\n"; cout << "float size = " << sizeof(float) << " bytes\n"; cin.get(); 48 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, users define a special name as a label to it Unlike variables, its value cannot be changed once it is initialized.

25 49 Defining Symbolic Constants A symbolic constant can be defined in two ways 1. Old way - use the preprocessor command #define #define studentperclass 87 No type needs to be defined for studentperclass Preprocessor just replaces the word studentperclass with 87 whenever it is found in the source program 2. A better way - use the keyword const const int studentperclass = 87; Variable studentperclass now has a fixed value 87 It has a type now. This feature helps the compiler to debug the program. 50 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 if modified.) Improve readability Give the value a more meaningful name e.g. rather than writing 360, 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.

26 51 const int totalstudentnumber = 87; // Student no. must < 87 int num; cout << "Enter a student number: "; cin >> num; if (num > totalstudentnumber) cout << "\n Number not valid!!!\n"; Give better readability Modify once and apply to to whole program cout << "\n There are " << totalstudentnumber << " student in this class\n"; 52 Enumerated Constants Enumerated constants allow one to create a new type that contains a number of constants enum COLOR RED, BLUE, GREEN, WHITE, BLACK; Makes COLOR the name of the new type Set RED = 0, BLUE = 1, GREEN = 2, WHITE = 3, BLACK = 4 enum RED, BLUE, GREEN, WHITE, BLACK; Another example enum COLOR2 RED=100, BLUE, GREEN=500, WHITE, BLACK=700; Makes COLOR2 the name of the new type Set RED = 100, BLUE = 101, GREEN = 500, WHITE = 501, BLACK = 700

27 53 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; Exercise 3.2 a. Build the project and note the result b. Use enumerated constants method to simplify the program if (choice == Sunday choice == Saturday) cout << "\nhave a nice weekend!\n"; else cout << "\ntoday is not holiday yet.\n"; 54 A Typical Program function function function int abc (...)... ; return... ; int cde (...)... ; return... ;...; statements

28 55 Statements A C++ program comprises a number of functions A function comprises a number of statements A statement can be as simple as x = a + b; It can be as complicated as if (choice == Sunday choice == Saturday) cout << "\nyou're already off on weekends!\n"; A statement must end with a semicolon ; In a statement, space carries nearly no information x = a + b; x = a + b ; 56 Expressions A statement comprises one or many expressions Anything that returns a value is an expression Examples of expressions 3.2 // Returns the value 3.2 studentperclass // Returns a constant, say 87 x = a + b // Here, two expressions // Return a + b and 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 For example, y = x = a + b; // assign y to the value of x which // is equal to the sum of a and b

29 57 Operators Any expression can be an operand An expression often comprises one of more operators The assignment operator '=' assigns a value to a variable or constant, e.g. x = 39; Several mathematical operators are provided by C++ Let a be 3, b be 4 and x is declared as an integer, Operators Meaning + Add - Subtract * Multiply / Divide % modulus remainder 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 58 Arithmetic Operators Binary Operator (two operands) + (addition) - (subtraction) * (multiplication) / (division) % (modulus, remainder) (no ** ) Unary Operator (single operands) - (no + ) Example: int i=1, j=2, k=3, x; x=i+2*j-22/k; x=-1+j; x=1+-j; x=+i+j; x=22%k; float f=1.5, g=0.5, y; y=2.5*f+4.0*g; Exercise: Try -5%3-5%-3 5%-3 (x= = -2) (x= 1) (x= -1) (x=3) (x= 1, remainder) (y=5.75) (hint: -5/3=-1-5/-3=1 5/-3=-1 and R=x-y*i) Ans: Mixed data types will be discussed later

30 59 Mixed Type Arithmetic Rule #1 char, short int float double Rule #2 (double long unsigned int) If either operand is double, the other is converted to double, and the result is double Otherwise, if either operand is long, the other is converted to long, and the result is long Otherwise, if either operand is unsigned, the other is converted to unsigned, and the result is unsigned Otherwise, the operand must be int 60 Mixed Type Arithmetic Assign real to int Cut off fractional part of real Assign int value to real Put decimal point at end, converts method of storage to exponential binary form Modify with cast operators Change type of expression Keyword static_cast<type>expression Old form: (type) expression /4 == == (double)3 /4 == static_cast<double>(3) /4 == 1.85

31 61 Integer and Floating Point Divisions x, y of main() are not x, y of intdiv(int, int) void intdiv(int x, int y) Casting int z = x/y; Ask Ask the the compiler to to temporarily cout << "z: " << z << endl; consider x as as a floating point no., no., i.e. i.e in in this this case case void floatdiv(int x, int y) float a = (float)x; // old style float b = static_cast<float>(y); float c = a/b; cout << "c: " << c << endl; int x = 5, y = 3; intdiv(x,y); floatdiv(x,y); Only give integer division result, i.e. i.e. 1 // ANSI style Give floating point division result, i.e. i.e Shorthand of Expressions For some commonly used expressions, there are some shorthands c = c + 1; c += 1; c++; ++c; //increment c = c - 1; c -= 1; c--; --c; //decrement c = c + 2; c += 2; c = c - 3; c -= 3; c = c * 4; c *= 4; // there is no c** or c//, c = c / 5; c /= 5; // since it is meaningless Let c be an integer with value 5. Note that a = c++; a=c; c=c+1; a = ++c; c=c+1; a=c; // a = 5, c = 6 as a = c first and then c++ // a = 6, c = 6 as ++c first and then a = c

32 63 Precedence and Parentheses Mathematical operations are basically performed from left to right It follows the normal mathematical precedence that multiplication / division first and addition / subtraction next Hence x = * 8; // x = 29 since we evaluate 3 * 8 first To change the precedence, we can use parentheses x = (5 + 3) * 8; // x = 64 since we evaluate first Parentheses can be nested as in normal arithmetic x = 5 * ((3 + 2) + 3 * 2); // x = 5 * (5 + 6) = Rules of Operator Precedence Parentheses are applied first. If an expression contains nested parentheses, the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (that is, not nested), they are evaluated left to right. Unary plus (+) and minus (-) are applied next. If an expression contains several unary plus and minus operators, these operators are applied from right to left. Multiplication (*), division (/) and remainder (%) are applied next. If an expression contains several multiplication, division and remainder operations, these operators are applied from left to right. Addition (+) and subtraction (-) are applied next. If an expression contains several addition and subtraction operations, these operators are applied from left to right. Assignment (=) is applied last. This operator has the lowest precedence so far. If an expression contains several assignment operators, these operators are applied from right to left. Figure 3.15 Rules of operator precedence. Precedence is the order in which operators are applied Redundant parentheses make expressions easier to read

33 65 Relational Operators Besides arithmetic operations, we can also perform relational operations with C++ A number of relational operators are defined in C++ Each relational operator returns a bool result (true or false) Operators Meaning == Equals!= Not Equals > Greater than >= Greater than or equals < Less than <= Less than or equals Examples 100 == 50; // return false 100!= 50; // return true 100 > 50; // return true 100 >= 50; // return true 100 < 50; // return false 100 <= 50; // return false 66 Relational Operators Binary Operators ==!= < > <= >= Result is a integer: 1 means true 0 means false Declare logical type variable and constants using bool No space between the operators Example: Meaning equal not equal greater less greater equal less equal C ==!= > < >= <= Expression 5 == 3 5!= 3 5 > 3 5 < 3 5 >= 3 5 <= 3 int i=10, j=10, k=1; i + j <= 3 + k Result

34 67 Applications of Relational Operators Relational operators are often used with if statement The if statement provides branching of the program execution depending on the conditions int bignumber = 10, smallnumber = 5; bool bigger = bignumber > smallnumber; //bigger = true if (bigger) dosomething(); Or Or you can simply write: if if (bignumber > smallnumber) dosomething(); 68 Logical Operators Logical operators do logical operations for bool variables Each logical operation returns a bool result (true or false) Operators && AND OR! NOT Meaning Examples expression1 && expression2 expression1 expression2!expression int bignum = 10, smallnum = 5; if (bignum < 10 && smallnum > 0) dosomething(); Would dosomething() be be called??? NO

35 69 int bignum = 10, smallnum = 5; if ((bignum < 10 && smallnum > 0) bignum > smallnum) dosomething(); Would dosomething() be be called??? YES F T int bignum = 10, smallnum = 5; if (!(bignum > smallnum)) dosomething(); Would dosomething() be be called??? NO 70 Logical (Boolean) Operators Binary Operators && (and) Unary Operator! (not) Operand should be int (OR) Use float, result may be affected by round off error nonzero (true) zero (false) Result is int 1 (true) 0 (false) Example: Expression Result &&3 1 5&&0 0 i&&j (if i=0, j=0) 0 i&&j+1 (if i=5, j=0) 1!5 0!0 1!i (if i=5) 0 Express connected by && or are evaluated from left to right, and evaluation stops as soon as the truth or falsehood of the result is known. i.e. expr1 && expr2 is not equal to expr2 && expr1. This is called short-circuit evaluation. inward == 0 normally be written as!inward Example: 3 < 7 < 5 3 < 7 && 7 < 5 (3 < 7) < 5 1 < && 0 0

36 71 Exercise 3.3 The following program asks the user to enter 3 numbers. If the sum of the first two is equal to the last one, a message is printed to the console a. Build the project and note the result. Does it perform correctly? b. If not, fix the problem and re-build the program int a, b, c; cout << "Enter 3 numbers: \n"; cin >> a; cin >> b; cin >> c; if (c = (a+b)); cout << "c = a+b\n"; 72 Control of Program Flow Normal program execution is performed from top-todown and one-statement by one-statement Often, the program modifies the program flow depending on some conditions set by the programmer or user C++ provides many approaches to control program flow if... else switch... case... break if (cond) // if the cond doa(); // is true, // then do doa() else // else do dob() dob(); switch (expression) case value1: doa(); break; case value2: dob(); break;

37 73 The if / else Selection Structure Compound statement: Set of statements within a pair of braces Example: if ( grade >= 60 ) cout << "Passed.\n"; else cout << "Failed.\n"; cout << "You must take this course again.\n"; Without the braces, if ( grade >= 60 ) cout << "Passed.\n"; else cout << "Failed.\n"; cout << "You must take this course again.\n" ; the statement cout << "You must take this course again.\n" ; would be executed under every condition. 74 #include 3. The <iostream> Nuts and Bolts of C++ int firstnum, secondnum = 10; cout << "Please enter: \n"; cin >> firstnum; cout << "\n\n"; if (firstnum >= secondnum) if ((firstnum% secondnum) == 0) if (firstnum == secondnum) Nested if... else cout << "They are the same!\n"; else cout << "They are evenly divisible!\n"; else cout << "They are not evenly divisible!\n"; else cout << "Hey! The second no. is larger!\n"; can be omitted for single statement

38 75 Using braces with if else What s wrong with this program? How do do you solve the problem? int x; cout << "Enter a number x < 10 or x > 100: "; cin >> x; cout << "\n";? if (x >= 10) if (x > 100)? cout << "More than 100, thanks!\n"; else // not the else intended! cout << "Less than 10, thanks!\n"; 76 Equality (==) vs. Assignment (=) Operators Dangerous error Does not ordinarily cause syntax errors Any expression that produces a value can be used in control structures Nonzero values are true, zero values are false Example: using ==: if ( paycode == 4 ) cout << "You get a bonus!\n"; Checks paycode, if it is 4 then a bonus is awarded Example: replacing == with =: if ( paycode = 4 ) cout << "You get a bonus!\n"; This sets paycode to 4 4 is nonzero, so expression is true, and bonus awarded no matter what the paycode was Logic error, not a syntax error

39 77 Multiple-Selection Structure: switch switch Useful when a variable or expression is tested for all the values it can assume and different actions are taken Format Series of case labels and an optional default case switch ( value ) case 1: Actions; break; case 2: Actions; break; default: actions break; exits from structure case 1 true case 1 action(s) break false case 2 true case 2 break false action(s) true case n case n break action(s) false default action(s) 78 switch if (burger == 1) unit_price = 8.5; else if (burger == 2) unit_price = 12; else if (burger == 3) unit_price = 15.3; else cout<< error \n ; switch(burger) case 1 : unit_price = 8.5; break; case 2 : unit_price = 12; break; case 3: unit_price = 15.3; break; default : cout<< error \n ; // break; optional

40 79 switch case break Only accept number or or expression that that returns a number unsigned short int number; cout << "Enter a number between 1 and 5: "; cin >> number; switch (number) case 0: cout << "Too small, sorry!"; break; case 3: cout << "Excellent!\n"; //falls through case 2: cout << "Masterful!\n"; //falls through case 1: default: cout << "\n\n"; See See the the differences between break and and without break cout << "Incredible!\n"; break; cout << "Too large!\n"; break; Do Do the the default if if all all tests tests fail fail 80 Implement switch with if else switch case statement can be implemented by the if else statement but with more complicated structure However, switch case can only be applied to simple numerical tests if (num == 0) cout << "Too small, sorry!"; else if (num == 3 num == 2 num == 1) cout << "Incredible!\n"; if (num == 3 num == 2) cout << "Masterful!\n"; if (num == 3) cout << "Excellent!\n"; else cout << "Too large!\n";

41 81 Looping Many programming problems are solved by repeatedly acting on the same data The method for achieving repeated execution is by looping C++ provides many approaches to implement looping if goto // old way, strongly NOT recommended while loop // use when the testing parameters are // complicated do-while loop // use when the repeated part is // expected to be executed at least once for loop // use when the testing parameters are // simple 82 while Loop int count ; count = 4; while (count > 0) cout << count << endl ; count -- ; cout << Done << endl ; // initialize loop variable // test expression // repeated action // update loop variable

42 83 while Loops int counter = 0; //initialize counter while (counter<5) counter++; //top of the loop cout << "counter: " << counter << "\n"; cout << "Complete. Counter: " << counter << ".\n"; while loops do the looping until the testing condition fails Test condition (tested variable must change inside the the loop) Repeat this part until counter >= >= More complicated while Loops while loops can be used with a more complicated testing condition unsigned small, large; unsigned short const MAXSMALL = ; cin>>small; cin>>large; while (small < large && large > 0 && small < MAXSMALL) if (small % 5000 == 0) cout << ".\n"; // write a dot every 5000 small++; large -= 2; Testing parameters are updated in in every loop 3 tests for each loop

43 85 Repetition Structure: do/while The do/while repetition structure Similar to the while structure do/while is a post-test condition. The body of the loop is performed at least once. All actions are performed at least once Format: action(s) do statement; while ( condition ); Example: Prints the integers from 1 to 10. (letting counter = 1): do cout << counter <<, ; while (++counter <= 10); condition false true 86 do while while loops do the test first and then the loop Sometimes we would like to have the loop to be done at least once. In this case, do while can be used Hello will be be shown at at least once even if if user enters 0 for counter int counter; cout << "How many hellos? "; cin >> counter; do cout << "Hello\n"; counter--; while (counter > 0); cout << "Counter is: " << counter << endl;

44 87 Repetition Structure: for for loops syntax for ( initialization ; loopcontinuationtest ; increment ) statement Example: Prints the integers from one to ten for ( counter = 1; counter <= 10; counter++ ) cout << counter << endl; For loops can usually be rewritten as while loops: initialization; while ( loopcontinuationtest ) statement; increment; Initialization and increment Can be comma-separated list of statements Example: for ( i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i; No semicolon (;) after last expression 88 for loops In many loops, we initialize a testing parameter, modify the value of the parameter and test the parameter It can be done in a single line by a for loop int counter; Initialize Test Modify for (counter=0; counter<5; counter++) cout << "Looping! "; //counter then increment cout << "\ncounter: " << counter << ".\n"; 5

45 89 Different varieties of for loops Multiple initialization and increments for (int i=0, j=0; i<3; i++, j++) cout << "i: " << i << " j: " << j << endl; Null int counter = 0; initialization and increments for (; counter < 5;) counter++; cout<<"looping! "; cout << "\ncounter: " << counter << ".\n"; 90 Different varieties of for loops Empty for loop int counter = 0; // initialization int max; cout << "How many hellos?"; cin >> max; for (;;) // a for loop that doesn't end if (counter < max) // test cout << "Hello!\n"; counter++; // increment else break; //end for loop

46 91 continue and break Keywords continue and break allow one to change the program flow during looping Should be used with caution since it will make the program hard to understand owing to the sudden change of direction Execution of of continue will will skip skipthe following part part of of the the loop loop but but not not leaving the the loop loop int counter; for (counter=0; counter<5; counter++) cout << "Looping! counter is " << counter <<"\n"; if ((counter%2) == 1) //odd number continue; cout << "Counter is an even number.\n"; 92 The break and continue Statements break Causes immediate exit from a while, for, do/while or switch structure Program execution continues with the first statement after the structure Common uses of the break statement Escape early from a loop Skip the remainder of a switch structure continue Skips the remaining statements in the body of a while, for or do/while structure Proceeds with the next iteration of the loop while and do/while Loop-continuation test is evaluated immediately after the continue statement is executed for Increment expression is executed, then the loop-continuation test is evaluated

47 93 continue Statement while (expr) statement continue; skip statement do statement continue; skip statement while(expr) for (expr1; expr2; expr3) statement continue; statement skip 94 break Statement while (expr) statement; if (expr) break; statements; statement; for (expr1; expr2; expr3) statement if (expr) break; statements; statements; switch (i) case 1: statement_1; case 2: statement_2; case 3: statement_3; break; case 4: statement_4; statements;

48 95 Nested Loop initialize outer loop while ( outer loop condition )... initialize inner loop while ( inner loop condition ) inner loop processing and update // end inner loop... // end outer loop 96 Nested for loops Nested for loop int rows, columns; char thechar; cout << "How many rows? "; cin >> rows; cout << "How many columns? "; cin >> columns; cout << "What characters? "; cin >> thechar; for (int i=0; i<rows; i++) for (int j=0; j<columns; j++) cout << thechar; cout << "\n"; More explanation on next page Will be be executed (rows columns) times

49 97 Assumption: rows = 2 columns = 3 thechar = x Value of of i, i, j for (int i=0; i<rows; i++) for (int j=0; j<columns; j++) cout << thechar; cout << "\n"; i = 0 j =? i = 1 j = 3 i = 0 j = 0 i = 1 j = 0 i = 0 j = 0 i = 1 j = 0 i = 0 j = 1 i = 1 j = 1 x i = 0 j = 1 i = 1 j = 1 i = 0 j = 2 i = 1 j = 2 i = 0 j = 2 i = 1 j = 2 i = 0 j = 3 i = 1 j = 3 i = 0 j = 3 i = 1 j = 3 i = 2 j = 3 Output on on the screen: x x x 98 If a variable is defined in the initialization part of the for loop, the variable will no longer exist on leaving the for loop. It is not an error for old C++ compilers.

50 99 Exercise 3.4 For the program on p. 96 a. Build the project and note the result. b. Try to rewrite the program using nested while loops instead of the nested for loops. Which program is more complicated? 100 Functions - Revisit input A function is, in effect, a subprogram that can act on data and return a value output When the name of the function is encountered in the program, the function is called When the function returns, execution resumes on the next line of the calling function Callingfunc() Statements; funca(); Statements; funcb(); Statements; Return value funca() is void Statements; return; funcb() Statements; return;

51 101 Function Body return type function name type of input parameters unsigned short int // Opening brace Statements; return (return_value); // Closing brace FindArea (int length, int width) name of input parameters return value 102 Why do we need functions? Functions help us shorten our program by re-using the program codes void floatdiv(int x, int y) float a = (float)x; float b = static_cast<float>(y); float c = a/b; cout << "c: " << c << endl; int w = 7, x = 5, y = 3, z = 2; floatdiv(w,x); floatdiv(x,y); floatdiv(y,z); Reason 1 13 lines

52 103 The same program will be much longer without function Can be even longer if the same operation is done in other part of the program int w = 7, x = 5, y = 3, z = 2; float a, b, c; a = (float)w; b = static_cast<float>(x); float c = a/b; cout << "c: " << c << endl; a = (float)x; b = static_cast<float>(y); float c = a/b; cout << "c: " << c << endl; a = (float)y; b = static_cast<float>(z); float c = a/b; cout << "c: " << c << endl; 17 lines 104 Functions make our program much easier to read void floatdiv(int x, int y) float a = (float)x; float b = static_cast<float>(y); float c = a/b; cout << "c: " << c << endl; int w = 7, x = 5, y = 3, z = 2; floatdiv(w,x); floatdiv(x,y); floatdiv(y,z); Reason 2 In this program, it is easily seen that 3 floating-point divisions are to be done Not the case of the previous program without the function.

53 105 Declaring Functions In C++, anything that is not a part of the C++ language needs to be declared Function prototype However, a function need NOT be separately declared if it is placed before the functions that will call it void DemoFunction() cout << "In Demo Function\n"; cout << "In main\n"; DemoFunction(); cout << "Back in main\n"; Since DemoFunction() is is placed before main(), it it need not be be separately declared DemoFunction() can be be used directly 106 However, it is a bad programming practice to require functions to appear in a particular order because It is difficult for code maintenance (too restrictive) Two functions may call each other (typically inside some loop) void FuncA() : FuncB(); : void FuncB() : FuncA(); : Which one should be be placed first?

54 107 Functions are usually declared by either one of the two ways: Write the prototype of the function at the beginning of the file in which the function is used Put the prototype of the function into a header file and include it in the file in which the function is used Function Prototype unsigned short int FindArea(int, int); return type function name type of input parameters 108 using Declaring namespace std; Functions int Area(int length, int width); // function prototype int lengthofyard; Although it it is is not not int widthofyard; necessary, int areaofyard; adding the the name cout << "\nhow wide is your yard? "; of of the the parameters cin >> widthofyard; makes the the prototype cout << "\nhow long is your yard? "; easier to to read read cin >> lengthofyard; areaofyard = Area(lengthOfYard,widthOfYard); cout << "\nyour yard is "; cout << areaofyard; cout << " square feet \n\n"; int Area(int yardlength, int yardwidth) return yardlength * yardwidth; Area() is is placed after after main(). Note Note the the name of of the the parameters are are NOT the the same as as the the prototype

55 109 Assume the file area.h has the following statement and is is at at the same folder as as main() int Area(int length, int width); // function prototype #include "area.h" // function prototype It It is is equivalent to to place the the content : of of area.h to to here here areaofyard = Area(lengthOfYard,widthOfYard); : int Area(int yardlength, int yardwidth) return yardlength * yardwidth; 110 Function Prototypes in Header file Advantage: if a particular set of function prototypes is often used in different programs, we need not declare them every time they are needed E.g. iostream In different.cpp files One line of #include Vs many lines Contains prototypes of many functions that are related to the manipulation of I/O stream Is needed in most programs that need I/O like cout, cin, etc. Should be included at the beginning of most programs; otherwise, we need to type all prototypes in every program.

56 111 Exercise 3.5 1) For the program on p.102, add the function prototype such that we can place the function floatdiv() after main(). 2) Modify the program you've developed in 1) as follows: Remove the function prototype Prepare a file named floatdiv.h that contains just one statement: the function prototype of floatdiv() Store the file floatdiv.h in the same folder as your C++ file Include this header file at the beginning of the program as the example in p.109 Achieve the same result as 1). 112 In C++, there are 3 types of variables that a function may make use of: Where do variables locate in your machine? Passed parameters and return parameter(s) The links between the called function and the calling function Local variable Visible only within a function For temporary local storage Global variable Visible to all functions in the program An old and dangerous way to communicate between functions

57 113 Variable Scope Local variables: variables declared within a function Such variables have local scope; they can be used only within the function in which they are declared Global variables: variables declared outside any function Such variables have global scope; they can be used by all functions that occur after their declaration 114 Variable Scope Global variable The three storage areas created by a C++ Program. Local variable Local variable

58 115 Local Variables float Convert(float); //function prototype float TempFer; float TempCel = 10; TempFer = 100; TempCel = Convert(TempFer); cout << TempCel << endl; float Convert(float Fer) float Cel; Cel = ((Fer - 32) * 5) / 9; return Cel; A function can define local variables for temporary usage Local variables are only visible within the function defining them 116 float Convert(float); same. float TempFer; float Cel = 10; TempFer = 100; Cel = Convert(TempFer); cout << Cel << endl; float Convert(float Fer) float Cel; Cel = ((Fer - 32) * 5) / 9; return Cel; Cel in in main()is different from the Cel in in Convert() although their name is is the same. Actually for each function, a separate piece of of memory is is allocated to to the local variables of of each function disregarding their name.

59 117 float Convert(float); float TempFer; float Cel = 10; TempFer = 100; Cel=Convert(TempFer); cout << Cel << endl; 37.7 main() float Convert(float Fer) float Cel; Cel = ((Fer - 32) * 5) / 9; return Cel; Convert() Variables TempFer Cel For return Fer Cel Memory Parameter Passing Passed by Value It is seen in the previous example that parameters are passed by value Only a copy of the parameter value is passed to the called function What the called function does to the passed parameters have nothing to do with the original one, since they are just two variables (and occupying different memory, even when their names are the same) However, such behavior sometimes is not preferred. In that case, we need the passed by reference parameter, which will be covered in the section of Pointers

60 119 Parameter Passing - by Value Variables a and x use different memory cells. different copies 120 Parameter Passing - by Reference Variables a and x share the same memory cell. same copy

61 121 Global Variables int Convert(float); //function prototype changed float Cel; // Global variable float TempFer; cout << "Please enter the temperature in Fahrenheit: "; cin >> TempFer; Convert(TempFer); //No need to collect the return value cout << "\nhere's the temperature in Celsius: "; cout << Cel << endl; int Convert(float Fer) Cel = ((Fer - 32) * 5) / 9; Global variable are visible to to all all functions Must be be carefully used Make your program difficult to to debug. 122 Scope of Variables It is a rule of thumb that variables defined within a pair of braces are visible only to the statements in that braces after the variable is defined void myfunc() int x = 8; Be careful! x = 8 cout << "\nin myfunc, local x: " << x << endl; x = 8 cout << "\nin block in myfunc, x is: " << x; int x = 9; //This x is not the same as the previous x cout << "\nvery local x: " << x; x = 9 cout << "\nout of block, in myfunc, x: " << x << endl; x = 8 myfunc();

62 123 Default Parameters Calling function should pass parameters of exactly the same types as those defined in the prototype of the called function long myfunction(int); //function prototype It means that any function that calls myfunction() should pass an integer to it The only exception is if the function prototype has a default value long myfunction(int x=50); //default value If the calling function does not provide a parameter, 50 will be automatically used : myfunction( ); myfunction(50); 124 Default Parameters You You may may use use other names int volumecube(int, int width = 25, int height = 1); int length = 100, width = 50, height = 2, volume; volume = volumecube(length, width, height); cout << "First volume equals: " << volume << "\n"; volume = volumecube(length, width); cout << "Second volume equals: " << volume << "\n"; volume = volumecube(length); cout << "Third volume equals: " << volume << "\n"; volume = volume = volume = = = = int volumecube(int length, int width, int height) return (length*width*height); Once Once a default value value is is assigned, the the parameters following must must have have default values.

63 125 Overloading Functions C++ allows overloading of function, i.e. create more than one function with the same name e.g. int myfunction (int, int); 3 different int myfunction (long, long); functions long myfunction (long); Differ by just the return type is NOT allowed When a function calls myfunction(), the compiler checks the number and type of the passed parameters to determine which function should be called Function overloading is also called polymorphism Poly means many, morph means form A polymorphic function is many-formed 126 int intdouble(int); float floatdouble(float); int myint = 6500, doubledint; float myfloat = 0.65, doubledfloat; doubledint = intdouble(myint); doubledfloat = floatdouble(myfloat); cout << "doubledint: " << doubledint << "\n"; cout << " doubledfloat : " << doubledfloat << "\n"; int intdouble(int original) is is to to double the the passed return 2*original; parameter float floatdouble(float original) return 2*original; single function name but but different parameter types The The objective of of both both functions It It looks much better to to have have a different parameter types Overloading allows us us to to do do so so

64 127 int Double(int); float Double(float); int myint = 6500, doubledint; float myfloat = 0.65, doubledfloat; doubledint = Double(myInt); doubledfloat = Double(myFloat); cout << "doubledint: " << doubledint << "\n"; cout << " doubledfloat : " << doubledfloat << "\n"; int Double(int original) return 2*original; float Double(float original) return 2*original; Overloading 128 Parameter Passing Passed by Reference void Double(int& original); void Double(float& original); int myint = 6500; float myfloat = 0.65; Double(myInt); Double(myFloat); cout << "doubledint: " << myint << "\n"; cout << " doubledfloat : " << myfloat << "\n"; void Double(int& original) original = 2*original; void Double(float& original) original = 2*original; Overloading

65 129 Recursive Function Example: factorials: 5! = 5 * 4 * 3 * 2 * 1 5! = 5 * 4! 4! = 4 * 3! 1 n! = n( n 1)! n = 0 n > 0 Can compute factorials recursively Solve base case (1! = 0! = 1) then plug in 2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6; long factorial(int n) if (n == 0) return 1; else return n * factorial(n-1); 130 Exercise 3.6a void myfunc() int x = 8; cout << "\nin myfunc, local x: " << x << endl; cout << "\nin block in myfunc, x is: " << x; int x = 9; cout << "\nvery local x: " << x; cout << "\nout of block, in myfunc, x: " << x << endl; The main() on the right is used to call myfunc() above. Build the program. What is the error message when compiling? Why? Correct the error accordingly. void myfunc(); myfunc();

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

What Is a Function? Illustration of Program Flow

What Is a Function? Illustration of Program Flow What Is a Function? A function is, a subprogram that can act on data and return a value Each function has its own name, and when that name is encountered, the execution of the program branches to the body

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming. Adhi Harmoko S, M.Komp Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information

Programming with C++ as a Second Language

Programming with C++ as a Second Language Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents: Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language Dr. Amal Khalifa Lecture Contents: Introduction to C++ Origins Object-Oriented Programming, Terms Libraries and Namespaces

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 1 C++ Basics Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

This watermark does not appear in the registered version - Slide 1

This watermark does not appear in the registered version -   Slide 1 Slide 1 Chapter 1 C++ Basics Slide 2 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

Chapter 7. Additional Control Structures

Chapter 7. Additional Control Structures Chapter 7 Additional Control Structures 1 Chapter 7 Topics Switch Statement for Multi-Way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements 2 Chapter

More information

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Unit 3. Constants and Expressions

Unit 3. Constants and Expressions 1 Unit 3 Constants and Expressions 2 Review C Integer Data Types Integer Types (signed by default unsigned with optional leading keyword) C Type Bytes Bits Signed Range Unsigned Range [unsigned] char 1

More information

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved. 1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Tutorial-2a: First steps with C++ programming

Tutorial-2a: First steps with C++ programming Programming for Scientists Tutorial 2a 1 / 18 HTTP://WWW.HEP.LU.SE/COURSES/MNXB01 Introduction to Programming and Computing for Scientists Tutorial-2a: First steps with C++ programming Programming for

More information

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are

More information

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator 1 A Closer Look at the / Operator Used for performing numeric calculations C++ has unary, binary, and ternary s: unary (1 operand) - binary ( operands) 13-7 ternary (3 operands) exp1? exp : exp3 / (division)

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING KEY CONCEPTS COMP 10 EXPLORING COMPUTER SCIENCE Lecture 2 Variables, Types, and Programs Problem Definition of task to be performed (by a computer) Algorithm A particular sequence of steps that will solve

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

C++ PROGRAMMING SKILLS Part 2 Programming Structures

C++ PROGRAMMING SKILLS Part 2 Programming Structures C++ PROGRAMMING SKILLS Part 2 Programming Structures If structure While structure Do While structure Comments, Increment & Decrement operators For statement Break & Continue statements Switch structure

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

More information

The following expression causes a divide by zero error:

The following expression causes a divide by zero error: Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++ 10 Stacks of Coins You have 10 stacks with 10 coins each that look and feel

More information

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

Topic 2: C++ Programming fundamentals

Topic 2: C++ Programming fundamentals Topic 2: C++ Programming fundamentals Learning Outcomes Upon successful completion of this topic you will be able to: describe basic elements of C++ programming language compile a program identify and

More information

Programming with C++ Language

Programming with C++ Language Programming with C++ Language Fourth stage Prepared by: Eng. Samir Jasim Ahmed Email: engsamirjasim@yahoo.com Prepared By: Eng. Samir Jasim Page 1 Introduction: Programming languages: A programming language

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Chapter 2: Overview of C++

Chapter 2: Overview of C++ Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman C++ Background Introduced by Bjarne Stroustrup of AT&T s Bell Laboratories in

More information