CHAPTER 4 CONTROL STRUCTURES

Size: px
Start display at page:

Download "CHAPTER 4 CONTROL STRUCTURES"

Transcription

1 CHAPTER 4 CONTROL STRUCTURES 1

2 Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may deviate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. With the introduction of control structures we are going to have to introduce a new concept: the compound statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: : statement1; statement2; statement3; Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement to be a simple statement, we do not need to enclose it in braces ().But in the case that we want the statement to be a compound statement it must be enclosed between braces (), forming a block. Only three control structures needed Three control structures Sequence structure Programs executed sequentially by default Selection structures if, if else, switch Repetition structures while, do while, for 2

3 Selection Structures (or) Conditional Structures (or) Branching Structures 1. if structure If keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: if(condition) statement; where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. Condition YES Statement NO Continue For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100: if(x == 100) cout << "x is 100"; 3

4 If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces : if(x == 100) cout<<"x is "; cout<<x; 2. if else statement We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is: if(condition) statement1; else statement2; Statement2 NO Condition YES Statement1 Continue 4

5 For example: if(x==100) cout<<"x is 100"; else cout< <"x is not 100"; prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not Multi-w ay if else statements (or) if else if ladder When a series of many conditions have to be checked we may use the ladder else if statement which takes the following general form if(condition-1) statement-1; else if(condition-2) statement-2; else if(condition-3) statement-3; else if(condition-n) statement-n; else default statement; statement-x; This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed. 5

6 NO Condition-1 YES Statement-1 Condition-2 YES Statement-2 NO Condition-3 YES Statement-3 NO Condition-n YES Statement-n NO Default Statement Statement-x 6

7 The if + else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero): if(x > 0) cout<<"x is positive"; else if(x<0) cout<<"x is negative"; else cout<<"x is 0"; Example program using if else ladder to grade the student according to the following rules. Marks Grade >=90 A >=80 B >=70 C >=60 D <60 F 7

8 Example: Algorithm steps If student s grade is greater than or equal to 90 Print A else If student s grade is greater than or equal to 80 Print B else If student s grade is greater than or equal to 70 Print C else If student s grade is greater than or equal to 60 Print D else Print F C ++ Program Steps if(studentg rade>= 90) cout<<"a"; else if(studentgrade>= 80) cout<<"b"; else if(studentgrade>=70) cout<<"c"; else if(studentgrade >= 60) cout<<"d"; else cout<<"f"; 8

9 4. Nested if Statements if and if-else statements can be nested, i.e. used inside another if or else statement Every else corresponds to its closest preceding if if(expression) if(e xpression) statement; else statement; else statement; Example: to find the given two numbers are equal, or greater than other if(first == second) cout<<"these two numbers are equal."; else if(first > second) cout<<"the first number is bigger."; else cout<<"the second is bigger."; 9

10 5. The selective structure: switch case In the last Lesson it was shown how a choice could be made from more than two possibilities by using if-else ladder statements. However a less unwieldy method in some cases is to use a switch statement. The general form of a switch case statement is: switch(selector) case label1 : group of statement1 ; break; case label2 : group of statement2 ; break;... case labeln : group of statementn ; break; default : statementd; // optional break; The selector may be an integer or character variable or an expression that evaluates to an integer or a character. The selector is evaluated and the value compared with each of the case labels. The case labels must have the same type as the selector and they must all be different. Switch evaluates selector and checks if it is equivalent to label1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure If the value of the selector cannot be matched with any of the case labels then the statement associated with default is 10

11 executed. The default is optional but it should only be left out if it is certain that the selector will always take the value of one of the case labels. Note that the statement associated with a case label can be a single statement or a sequence of statements (without being enclosed in curly brackets). 11

12 For example The following switch statement will set the variable grade to the character A, B or C depending on whether the variable i has the value 1, 2, or 3. If i has none of the values 1, 2, or 3 then a warning message is output. switch(i) case 1: grade = 'A'; break; case 2: grade = 'B'; break; case 3: grade = 'c'; break; default: cout<<i<<"not in range"; break; The following statement writes out the day of the week depending on the value of an integer variable day. It assumes that day 1 is Sunday. switch(day) case 1: cout<<"sunday"; break; case 2: cout<<"monday"; break; case 3: cout<<"tuesday"; break; 12

13 case 4: cout<<"wednesday"; break; case 5: cout<<"thursday"; break; case 6: cout<<"friday"; break; case 7: cout<<" Saturday"; break; default: cout<<" Not an allowable day number"; break; If it has already been ensured that day takes a value between 1 and 7 then the default case may be missed out. It is allowable to associate several case labels with one statement. For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes unnecessary to include braces surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For exam ple if the above example is amended to write out whether day is a weekday or is part of the weekend: 13

14 switch(day) case 1: case 7: cout<<"this is a weekend day"; break; case 2: case 3: case 4: case 5: case 6: cout<<" This is a weekday"; break; default: cout<<" Not a legal day"; break; Switch statement something similar to what we did at the beginning of this section with if else ladder. Both of the following code fragments have the same behavior: switch example if-else equivalent switch (x) if(x == 1) case 1: cout<<"x is 1"; cout<<"x is 1"; break; else if(x == 2) case 2: cout<<"x is 2"; cout<<"x is 2"; break; default: else cout<<"value of x unknown"; cout<<"value of x unknown"; 14

15 For example the weekday/weekend example above could be written: if(day>=1&&day<=7) if(day==1 day==7) cout<<"this is a weekend day"; else cout<<"this is a weekday"; else cout<< Not a legal day"; However the first example becomes very tedious- there are eight alternatives! Consider the following: if( day==1) cout<<"sunday"; else if(day==2) cout<<"monday"; else if(day==3) cout<<"tuesday";.. else if(day==7) cout<<"saturday"; else cout<<"not a legal day"; Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables s labels (for example case n: where n is a variable) or ranges (case (1..3):) becau se they are not valid C++ constants. If you need to check ranges or values that are not constants, use a concatenation of if and else if statements. 15

16 Common Programming Error Forgetting a break statement when one is needed in a switch statement is a logic error. Omitting the space between the word case and the integral value being tested in a switch statement can cause a logic error. For example, writing case3: instead of writing case 3: simply creates an unused label. Specifying an expression including variables(e.g.,a + b) in a switch statement s case label is a syntax error. Good Programming Pra ctice In a switch statement that lists the default clause last, the default clause does not require a break statement. Some programmers include this break for clarity and for symmetry with other cases. Repetition structures (or) Iteration Structures (or) Looping Structures Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. There are 3 types of loops in C++ 1. while loops 2. do-while loops 3. for loops 1. The while loo p Its format is: while(condition) statement; This while loop executes as long as the given logical expression between parentheses is true. When condition is false, execution continues with the statement following the loop block. 16

17 The condition is tested at the beginning of the loop, so if it is initially false, the loop will not be executed at all, and its functionality is simply to repeat statement while the condition set in expression is true. Two or more number of statements to be repeated then encloses braces. Otherwise no need to enclose brace for single statement repetition. 17

18 For example, we are going to make a program to countdown using a while-loop: Example Program // custom countdown using while #include<iostream> using namespace std; int main() int n; cout<<"enter the starting number"; cin>>n; while(n>0) cout<<n<<","; --n; cout<<"fire!\n"; return(0); Output Enter the starting number 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE! When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true. The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3) 18

19 * condition is false: ignore statement and continue after it (to step 5) 3. Execute statement: cout<<n<<","; --n; (prints the value of n on the screen and decreases n by 1) 4. End of block. Return automatically to step 2 5. Continue the program right after the block: print FIRE! and end program. When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end. Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers. Note: placing semicolon after the while statement, i.e while(); will produce a logical error. 2. The do-while loop Its format is: do statement; while(condition); Its functionality is exactly the same as the while loops, but guarantees at least one execution of the body 19

20 Two or more number of statements to be repeated then encloses braces. Otherwise no need to enclose brace for single statement repetition. For example, the following example program echoes any number you enter until you enter 0. Example Program // number echoer #include<iostream> using namespace std; int main() unsigned long n; do cout<<"enter number (0 to end):"; cin>>n; cout<<"you entered:"<<n<<"\n"; while(n!=0); return(0); 20

21 Output Enter number (0 to end): You entered: Enter number (0 to end): You entered: Enter number (0 to end): 0 You entered: 0 The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever. Note: Forget to place semicolon after the while statement, i.e while() will produce a syntax error. 3. The for loop Its format is: for(initialization;condition;increment) statement; and its main function is to repeat statement while condition remains true, like the while loop. But in addition, for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. It works in the following way: 1. Initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 21

22 2. Condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. Statement is executed. As usual, it can be either a single statement or a block enclosed in braces. 4. Finally, whatever is specified in the increase field is executed and the loop gets back to step 2. Comparison of for and while loops 22

23 Here is an example of countdown using for loop: Example Program // countdown using a for loop #include<iostream> using namespace std; int main() for(int n=10;n>0;n--) cout<<n<<","; cout<<"fire!\n"; return(0); Output 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. For example we could write: 23

24 for(;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the variable was already initialized before). Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop: for(n=0,i=100;n!=i;n++,i-- ) // whatever here... This loop will execute for 50 times if either n or i are modified within the loop: n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to

25 Nested Loops You can nest loops of any kind inside another to any depth. Example Program //Printing a Triangle #include<iostream> using namespace std; int main() for(int i=1;i<=5;i++) for(int j=1;j<=i;j++) cout<<"*"; cout<<"\n"; return(0); Output * ** *** **** ***** Jumping statements 1. The break statement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): E xample Program // break loop example # include<iostream> using namespace std; 25

26 int main() int n; for(n=10; n>0; n--) cout<<n<< ", "; if(n==3) cout<<"countdown aborted!"; break; return(0); Output 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! 2. The con tinue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: Exam ple Program //continue loop example #include<iostream> using namespace std; int main() for(int n=10; n>0; n--) if(n==5) continue; cout<<n<< ", "; cout<<"fire!\n"; 26

27 return(0); Output 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE! 3. The goto sta tement Goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:) Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto: Example Program //goto loop example #include<iostream> using namespace std; int main() int n=10; loop: cout<<n<<","; n--; if(n>0) goto loop; cout<<"fire!\n"; return(0); O utput 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! 27

28 Exercises 1. Write an if statement that prints YES if a variable age is greater than Marks 2. Write an if else statement that displays YES if a variable age is greater than 21, and displays NO otherwise - 2 Marks 3. Write a for loop that displays the number from 100 to 110. Thank You - 2 Marks 4. Write a while loop that displays the number from 500 to Marks 5. At least how many times the loop body is executed in a do while loop? - 1 Mark 6. Write a switch statement that prints YES if a variable ch is y, prints NO if ch is n, and prints UNKNOWN otherwise - 2 Marks 7. Write a program to find the biggest among three given numbers - 2 Marks 8. Write a program to find the given number is odd or even - 2 Marks 9. Write a program to find the factorial of a given number - 2 Marks that displays the following set of by using for loop 10. Write a for loop numbers - 2 Marks Write a program to find sum, difference, multiply and division of given two numbers using switch case selective structure - 3 Marks 12. An electricity board charges the following rates to domestic users to discourage large consumption of energy: For the first 100 units 10 Paisa per unit For next 200 units 20 Paisa per unit Beyond 300 units 30 Paisa per unit If the total cost is more than 10 OMR then an additional surcharge of 15% is added. Write a program to print the consumed unit and total amount for the consumed unit. - 3 Marks 28

29 13. Write a Program to find the GCD of two numbers by using while loop structure - 2 Marks 14. Write a program to calculate and Print the Following table by using for loop structure - 3 Marks 1*2=2 2*2=4 3*2=6 4*2=8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18 10*2=20 29

30 CHAPTER 6 ARRAYS 1

31 An array is a group of elements of the same type that are placed in contiguous memory locations. In general, only the array itself has a symbolic name, not its elements. Each element is identified by an index which denotes the position of the element in the array. Arrays are suitable for representing composite data which consist of many similar, individual items. Examples: a list of names, a table of world cities and their current temperatures, or the monthly transactions for a bank account. The number of elements in an array is called its dimension. The dimension of an array is fixed and predetermined. It cannot be changed during program execution. In this array we will discuss 1. One dimensional Array 2. Two dimensional Array One Dimensional Array Array Declaration C++ Arrays can be declared for all c++ data types (int, float, double, char etc ). All the elements are stored in consecutive memory locations. The elements can be accessed by using the position (or) index. Declaring C++ Arrays of int type: The c++ arrays are declared with the data type name and the number of elements inside the square brackets. int varname[50]; // C++ Array of type int with maximum size=50. The above declaration means, the varname is an array of integer type. The values inside this varname array can be accessed by referring to the position of their elements like varname[0], varname[1] etc., 2

32 All the C++ arrays are based on Zero index values. That means the position reference starts at 0(Zero) and counts till the n-1 th position. So in the above array, 50 elements can be stored starting from 0 to 49. The maximum number of elements that can be stored or the maximum size of the c++ array is 50. Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. Example Program The values can be stored and accessed as given in the following code fragment. #include<iostream> using namespace std; int main() int a[5]; a[0]=10; a[1]=20; cout<<"enter the value for third element"<<endl; cin>>a[2]; a[0]=a[0]*5; cout<<a[0]<<"\t"<<a[1]<<"\t"<<a[2]<<endl; return(0); Output Enter the value for third element Note: Care should be taken while using or referring to the position of the element. The position reference should not exceed the maximum size specified in the declaration. If it exceeds, the program will not generate any compiler errors. But it will raise run time errors and exceptions. 3

33 Declaring C++ arrays of type float: The declaration and use of c++ arrays in float type are the same as int. The declaration is written as follows. float varname[100]; //A c++ array of float type The above declaration means, the c++ float array contains 100 elements starting from position 0 till 99. The elements can be accessed as varname[0], varname[1], varname[2] varname[99]. Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. The values can be stored and accessed as given in the following code fragment. varname[0]=10.05; varname[1]=11.04; varname[2]=13.34; cout<<"enter the value for fourth element"<<endl; cin>>varname[3]; cout<<varname[0]<<endl; Declaring C++ arrays of type char: This is one of the most widely used and problematic type of c++ array. When an array of char is declared, this char array can be used as a string with the maximum size as specified in the array declaration. char varname[50]; //Memory reserved for 50 characters. The above declaration means, the c++ char array contains 50 elements starting from position 0 till 49. The elements can be accessed as varname[0], varname[1], varname[2] varname[49]. 4

34 Accessing Elements Like normal variables, we can use these elements in program statements such as assignment statements, input and output statements. The values can be stored and accessed as given in the following code fragment. varname[0]='a'; cout<<"enter the character for second element"<<endl; cin>>varname[1]; cout<<varname[0]<<endl; cout<<varname[1]<<endl; C++ Array Advantages: Easier to declare and use. Can be used with all data types. C++ Array Disadvantages: Fixed size data. If the number of elements stored are less than the maximum size, then the rest of the memory space goes waste. If the number of elements to be stored are more than the maximum size, the array cannot accommodate those new values. Initialization of Integer, Float and Char types of Array If a programmer wants to initialize an array elements it can be done by specifying the values enclosed within braces. For example, using the array age, if a programmer wants to initialize integer values 55, 35, 30, 40 respectively to each of the array positions it can be written. int age[4]=55,35,30,40; So the above arrays would take values as below 5

35 age [0] [1] [2] [3] values If a programmer wants to initialize float values 34.5, 23.4, and 45.6 in the array temperature then the initialization can be written as float temperature[3]=34.5,23.4,45.6; So the above arrays would take values as below temperature [0] [1] [2] values If a programmer wants to initialize char values e, f, g, y in the array name then the initialization can be written as char name[5]= e, f, g, y, \0 ; When initializing the array of characters, a special character (the null character) is used to signal the end of the string. The null character can be written as '\0' (backslash, zero). So the above arrays would take values as below name [0] [1] [2] [3] [4] values e f g y \0 Note: One interesting fact is that the size of the array element can also be left blank, in which case the array takes the size of the array as the number of elements initialized within. For example if the array takes the form as int age[ ]=55,35,30,40,50; 6

36 Then the size of the array age is 5 which is the number of elements initialized within. float temperature[ ]=34.5,23.4,45.6,28.9; Then the size of the array temperature is 4 which is the number of elements initialized within. char name[ ]= s, a, y, \0 ; Then the size of the array name is 4 which is the number of elements initialized within. In C++ array of characters is called as string. A string or array of characters can be initialized without specifying the single quote inside. But like a string literals it should be given within double quote. Example: char sen[ ]="c++ char array string example"; In this second case, when using double quotes (") for initialization, the null character \0 is appended automatically. Note: When declaring array without initialization, the size should be mentioned in [ ]. Example: int age[ ]; is not the proper declaration. The compiler will generate the error as size should be mentioned. Like the above examples, the c++ arrays can be declared with or without initializing values. 7

37 Accessing Array Elements through For loop In an array, the index values are starts from 0 and it is increasing one by one up to the maximum size of the array. So to get the input values in an array or to display the content of the array, we can use for loop. Without for loop, manipulating the array is difficult. Almost always need to use a for loop to step through the array elements. Example Program /*Program to read the input for an array through for loop and to display the content of the array through for loop*/ #include<iostream> using namespace std; int main() int a[10],i; //To read the input for array for(i=0;i<10;i++) cout<<"enter the Value for a["<<i<<"]"<<endl; cin>>a[i]; //To display the content of the array for(i=0;i<10;i++) cout<<"value of a["<<i<<"] is"<<a[i]<<endl; return(0); Output Enter the Value for a[0] 11 Enter the Value for a[1] 345 Enter the Value for a[2] 15 8

38 Enter the Value for a[3] 3 Enter the Value for a[4] 56 Enter the Value for a[5] 27 Enter the Value for a[6] 90 Enter the Value for a[7] 41 Enter the Value for a[8] 12 Enter the Value for a[9] 77 Value of a[0] is11 Value of a[1] is345 Value of a[2] is15 Value of a[3] is3 Value of a[4] is56 Value of a[5] is27 Value of a[6] is90 Value of a[7] is41 Value of a[8] is12 Value of a[9] is77 Note Without using for loop, array of characters (or) string can be manipulated. This is allowed in c++. But, int and float arrays are always manipulated through for loop. Example Program #include <iostream> using namespace std; int main () char question[ ] = "Please, enter your first name:"; char greeting[ ] = "Hello "; 9

39 char fname[80]; cout<<question; cin>>fname; cout<<greeting<<"your First name is..."<<fname; return(0); Output Please, enter your first name:salim Hello Your First name is...salim In the above example to read the values in fname char array, for loop is not used. Simply the array name, fname is given with cin. Also, to display the content of the fname char array, for loop is not used. Simply the array name, fname is given with cout. Note: When giving input to the char array without for loop, only the characters other than blank space are allowed. If the blank space is given as input from keybord, which means it s the end of array. So after blank space whatever given as the input, it is not stored in the char array. So in this case, only a single word is allowed as the input to the char array. Passing arrays to Functions At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation. In order to pass arrays as parameters to a function, the function declaration is specified as in the following example. void display(int[ ]); 10

40 That is the above function display takes the int type of array as a parameter. In function declaration the array data type is followed by empty [ ]. This is enough to specify in the declaration. No need to specify the array name. Example Program #include<iostream> using namespace std; void print(int[ ],int); int main() int a[20],n,i; cout<<"enter the number of elements in the array"<<endl; cin>>n; for(i=0;i<n;i++) cout<<"enter Value for a["<<i<<"]"<<endl; cin>>a[i]; print(a,n); for(i=0;i<n;i++) cout<<"value of a["<<i<<"] is"<<a[i]<<endl; return(0); void print(int b[ ],int m) int i; for(i=0;i<m;i++) cout<<"value of b["<<i<<"] is"<<b[i]+1<<endl; 11

41 Output Enter the number of elements in the array 3 Enter Value for a[0] 11 Enter Value for a[1] 22 Enter Value for a[2] 33 Value of b[0] is12 Value of b[1] is23 Value of b[2] is34 Value of a[0] is11 Value of a[1] is22 Value of a[2] is33 The print() function is declared before the main(), with the first parameter is an int type of array, and the second parameter is an int type of variable. A int type of array a[20] is declared inside the main() and the input for the array is read out through the for loop. Then this array a is passed as the first parameter to print(). In print() call only the array name a is specified. No need to specify the size. The second parameter is used to get the number of elements in the array, and it is passed to the print() call. In c++ the set of values are passed as a parameter through array concept When receiving the array values in the print() body, another int type of array b[ ] is specified with empty [ ]. The first value a[0] is copied to b[0] and so on up to the last element of the array. So whatever changes in the array b[ ], inside the body of print() will not affect the values of array a[ ] in the main(). So after the print() call, the values in array a[ ] is not changed in main(). 12

42 Exercises 1. Write a C++ program to read 10 integer numbers in an array and find the sum of these numbers. 2. Write a C++ program to read and print your first name, middle name and Family name. 3. Write a C++ program to read 10 floating point numbers in an array and pass this array to a function named sum(), which calculates the sum of these numbers and print the sum. 13

43 Chapter 5 Two-Dimensional Arrays 5 Two-Dimensional Arrays Two-Dimensional Array A two-dimensional array is used to represent items in a table with rows and columns, provided that each item in the table is of the same data type. In the following figure, we have an array with 9 rows which are accessed by an integer ranging from 0 through 8 and 7 columns which are accessed by an integer ranging from 0 through 6. [0] [1] [2] [3] [4] [5] [6] [0] [1] [2] [3] [4] [5] [6] [7] [8] Declaring two-dimensional Array Types Row 7, Column 5 Here is a syntax template describing the simplest form of one-dimensional array declaration: DataType ArrayName [ ConstIntExpression1] [ ConstIntExpression2]; This declaration is explained in the following table: COMP151 Lecture

44 Chapter 5 Two-Dimensional Arrays DataType ArrayName ConstIntExpression1 ConstIntExpression2 Describes the type of each stored component of the array The name of the array An integer expression composed only of literal or named constants. It specifies the first array dimension (the number of rows in the array). An integer expression composed only of literal or named constants. It specifies the second array dimension (the number of colums in the array). ConstIntExpression1 and ConstIntExpression2 must have a value greater than zero. Example of declaring Two-dimensional Array Here an example of declaring two dimensional array : int matrix[6][5]; In this example, we have an array called matrix having 6 rows and 5 columns. This means that the array contains 30 elements (6x5) all of type integer. Accessing Individual Components To access an individual array component, we write the array name, followed by an expression enclosed in square brackets specifying which component to access. Arrayname [ IndexExpression1] [ IndexExpression2] Example Let's consider the following two-dimensional array: A 4 A(3,4) COMP151 Lecture

45 Chapter 5 Two-Dimensional Arrays A is an array with 3 rows and 4 columns. It contains 12 components (3x4). In the following table, we show how to access to any component of the array A. Component How To Component How To Component How To access access access 4 a(0,0) 5 a(1,0) 9 a(2,0) -1 a(0,1) -6 a(1,1) 7 a(2,1) 0 a(0,2) 2 a(1,2) 5 A(2,2) 3 a(0,3) 1 a(1,3) 8 a(2,3) Initializing Two-Dimensional Array in Declaration To initialize the above array A 4 A(3,4) , we can use the following 8 declaration: int A[3][4] = 4, -1, 0, 3, 5, -6, 2, 1, 9, 7, 5, 8; or: int A[3][4] = ; 4, -1, 0, 3, 5, -6, 2, 1, 9, 7, 5, 8 COMP151 Lecture

46 Chapter 5 Two-Dimensional Arrays Example 1 Let's shows how to declare an array of five integers //Declaring two-dimensional array #include <iostream> using namespace std; int main() int matrix[2][3]=-1, 2, 9, -3, 10, 11 ; int i,j; for (i = 0; i<2; i++) for (j = 0; j<3; j++) cout <<"matrix["<< i<<"," <<j<< "] = " << matrix[i][j] << "\n"; return(0); Output: matrix[0,0] = -1 matrix[0,1] = 2 matrix[0,2] = 9 matrix[1,0] = -3 matrix[1,1] = 10 matrix[1,2] = 11 COMP151 Lecture

47 Chapter 5 Two-Dimensional Arrays 5 Two-Dimensional Arrays Two-Dimensional Array A two-dimensional array is used to represent items in a table with rows and columns, provided that each item in the table is of the same data type. In the following figure, we have an array with 9 rows which are accessed by an integer ranging from 0 through 8 and 7 columns which are accessed by an integer ranging from 0 through 6. [0] [1] [2] [3] [4] [5] [6] [0] [1] [2] [3] [4] [5] [6] [7] [8] Declaring two-dimensional Array Types Row 7, Column 5 Here is a syntax template describing the simplest form of one-dimensional array declaration: DataType ArrayName [ ConstIntExpression1] [ ConstIntExpression2]; This declaration is explained in the following table: COMP151 Lecture

48 Chapter 5 Two-Dimensional Arrays DataType ArrayName ConstIntExpression1 ConstIntExpression2 Describes the type of each stored component of the array The name of the array An integer expression composed only of literal or named constants. It specifies the first array dimension (the number of rows in the array). An integer expression composed only of literal or named constants. It specifies the second array dimension (the number of colums in the array). ConstIntExpression1 and ConstIntExpression2 must have a value greater than zero. Example of declaring Two-dimensional Array Here an example of declaring two dimensional array : int matrix[6][5]; In this example, we have an array called matrix having 6 rows and 5 columns. This means that the array contains 30 elements (6x5) all of type integer. Accessing Individual Components To access an individual array component, we write the array name, followed by an expression enclosed in square brackets specifying which component to access. Arrayname [ IndexExpression1] [ IndexExpression2] Example Let's consider the following two-dimensional array: A 4 A(3,4) COMP151 Lecture

49 Chapter 5 Two-Dimensional Arrays A is an array with 3 rows and 4 columns. It contains 12 components (3x4). In the following table, we show how to access to any component of the array A. Component How To Component How To Component How To access access access 4 a(0,0) 5 a(1,0) 9 a(2,0) -1 a(0,1) -6 a(1,1) 7 a(2,1) 0 a(0,2) 2 a(1,2) 5 A(2,2) 3 a(0,3) 1 a(1,3) 8 a(2,3) Initializing Two-Dimensional Array in Declaration To initialize the above array A 4 A(3,4) , we can use the following 8 declaration: int A[3][4] = 4, -1, 0, 3, 5, -6, 2, 1, 9, 7, 5, 8; or: int A[3][4] = ; 4, -1, 0, 3, 5, -6, 2, 1, 9, 7, 5, 8 COMP151 Lecture

50 Chapter 5 Two-Dimensional Arrays Example 1 Let's shows how to declare an array of five integers //Declaring two-dimensional array #include <iostream> using namespace std; int main() int matrix[2][3]=-1, 2, 9, -3, 10, 11 ; int i,j; for (i = 0; i<2; i++) for (j = 0; j<3; j++) cout <<"matrix["<< i<<"," <<j<< "] = " << matrix[i][j] << "\n"; return(0); Output: matrix[0,0] = -1 matrix[0,1] = 2 matrix[0,2] = 9 matrix[1,0] = -3 matrix[1,1] = 10 matrix[1,2] = 11 COMP151 Lecture

51 CHAPTER 5 FUNCTIONS

52 Functions are used to modularize code or sort it into different blocks or sub-tasks. Functions perform a particular job that the programmer assigns it to do. They make code look neater and more elegant and can be "called" or used as many times as you like. Statements in function bodies are written only once and reused from several locations of a program. It enables the divide and conquer technique. It is called as methods or procedure in other language. We are going to discuss two types of Functions 1. User Defined Functions 2. Library Functions (or) Predefined Functions 1. User Defined Functions Example program for Simple Function #include<iostream> using namespace std; void starline(); //Function Declaration (or) Prototype int main() cout<<"program for Function \n"; starline(); //Call to Function starline cout<<"this is the simple Program\n "; starline(); //Call to Function starline cout<<"printing Star line to decorate the output\n"; starline(); //Call to Function starline return(0); void starline() //Function definition int j; for(j=0;j<45;j++) cout<<"*"; cout<<endl; 2

53 Output Program for Function ********************************************* This is the simple Program ********************************************* Printing Star line to decorate the output ********************************************* In C++, Function has 3 parts 1. Function declaration (or) Prototype 2. Function Call 3. Function definition 1. Function Declaration (or) Prototype Just as you can t use a variable without first telling the compiler what it is, you also can t use a function without telling the compiler about it. The most common approach is to declare the function at the beginning of the program. In the above program the function starline() is declared in the line void starline(); The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parenthesis indicate that it takes no arguments (or) parameters. Function declarations are also called prototypes, since they provide a model (or) blueprint for the function. They tell the compiler, a function that looks like this is coming up later in the program. Note: The function declaration is terminated with a semicolon. 3

54 2. Function Call The function is called (or) invoked (or) executed three times from main(). Each of the three calls looks like this: starline(); The syntax of the function call is: The function name followed by the parenthesis. This is very similar to that of the declaration, except that the return type is not used. The call is terminated by a semicolon. Executing the call statement causes the function to execute; that is, control is transferred to the statement in the function definition are executed, and then control returns to the statement following the function call. 3. Function Definition Finally we come to the function itself, which is referred to as the function definition. The definition contains the actual code for the function. Here s the definition for starline(); void starline() //declarator (or) header for(int j=0;j<45;j++) // function body cout<< * ; cout<<endl; The definition consists of a line called the declarator (or) header, followed by the function body. The function body is composed of the statements that make up the function, delimited by braces. The declarator must agree with the declaration: It must use the same function name, have the same argument types in the same order (if there are arguments), and have the same return type. 4

55 Notice that the declarator is not terminated by a semicolon. When the function is called, the control transferred to the first statement in the function body. The other statements in the function body are then executed, and when the closing brace is encountered, the control returns to the calling program. Function Components S.NO Components Purpose Example 1 Declaration Specifies function void func(); (Prototype) name, argument types, and return value. Alerts compiler(and programmer) that function definition is coming up later 2 Call Causes the function func(); to be executed 3 Definition Body of the function. Contains the lines of code that constitute the function 4 Declarator (or) Header First line of definition void func() ;//lines of code ; void func() Common Programming Error A function is invoked (or) called before it is defined (body), and that function does not have a function prototype, a compilation error occurs. 5

56 Note: If a function is defined before it is invoked, then the function s definition also serves as the function s prototype, so a separate prototype is unnecessary. Example Program #include<iostream> using namespace std; /*Function definition before it is called (or) invoked So no need of prototype (or) declaration*/ void starline() int j; for(j=0;j<45;j++) cout<<"*"; cout<<endl; int main() cout<<"program for Function \n"; starline(); //Call to Function starline cout<<"this is the simple Program\n "; starline(); //Call to Function starline cout<<"printing Star line to decorate the output\n"; starline(); //Call to Function starline return(0); Good Program Practice In general for the good program practice do the declaration (or) prototype of the function, then main() function followed by definition of function. 6

57 Passing Parameters (or) Arguments to Functions When a function is called, the program may send values into the function. Values that are passed into a function are called actual arguments (or) actual parameter. The variables that receive these values in function definition are called formal arguments (or) formal parameters. Functions with Empty Parameter List Specified by writing either void or nothing at all in parentheses For example, void print(); (or) void print(void); Specifies that function print does not take arguments and does not return a value Example Program #include<iostream> using namespace std; void function1(); void function2(void); Specify an empty parameter list by putting nothing in the parentheses int main() function1(); function2(); return(0); void function1() cout<< function 1 takes no arguments <<endl; void function2(void) cout<< function 2 also takes no arguments <<endl; Specify an empty parameter list by putting void in the parentheses 7

58 Output function 1 takes no arguments function 2 also takes no arguments Two ways to pass arguments to functions 1. Pass-by-Value 2. Pass-by-Reference 1. Pass-by-Value When an actual argument is passed into a formal argument, only a copy of the actual argument s value is passed. Changes to the formal arguments do not affect the actual arguments. Value given in actual argument is straight value (or) value passed through variable Example 1: actual arguments are straight values #include<iostream> using namespace std; in function prototype void repchar(char,int); only arguments int main() data type is enough repchar( -,45); Actual arguments repchar( *,25); return(0); Formal arguments void repchar(char ch,int n) for(int j=0;j<n;j++) cout<<ch; cout<<endl; Output ************************* 8

59 Example 2: Actual arguments are given through variable #include<iostream> using namespace std; in function prototype void repchar(char,int); only arguments int main() data type is enough char chin; int nin; cout<< Enter a character <<endl cin>>chin; cout<< Enter number of times to repeat it <<endl; cin>>nin; repchar(chin,nin); Actual arguments return(0); void repchar(char ch,int n) Formal arguments for(int j=0;j<n;j++) cout<<ch; cout<<endl; Output Enter a character * Enter number of times to repeat it 5 ***** 2. Pass-by-Reference When the actual arguments passed to the formal arguments, the reference variables (used in function declarator (or) header) allow the function to access the actual argument s original values (not copy). Changes in 9

60 the formal arguments in function body will affect the actual arguments. C++ provides a special type of variable called a reference variable that used as a formal argument allows access to the original values of actual arguments. A reference variable is an alias for another variable. Any changes made to the reference variable are actually performed on the variable for which it is an alias. Reference variables are declared like regular variables, except you have to place an ampersand (&) symbol in front of the name. Example Program #include<iostream> int squarebyvalue(int); void squarebyref(int&); using namespace std; int main() int x=2; int z=3; int y; cout<<"before square by value call x value is"<<x<<endl; y=squarebyvalue(x); cout<<"after square by value call x value is"<<x<<endl; cout<<"after square by value call y value is"<<y<<endl; cout<<"before square by reference call z value is"<<z<<endl; squarebyref(z); cout<<"after square by reference call z value is"<<z<<endl; return(0); int squarebyvalue(int a) a=a*a; return(a); 10

61 void squarebyref(int &b) b=b*b; Output Before square by value call x value is2 After square by value call x value is2 After square by value call y value is4 Before square by reference call z value is3 After square by reference call z value is9 Returning Values From Functions: When function completes its execution it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. When a function returns a value, the data type of this return value must be specified. In the above example squarebyvalue() function returns an integer value to the calling program. So the return type integer is specified before the function name in declaration and in definition. Example Program #include<iostream> using namespace std; float convert(float); int main() float pound,kg; cout<< Enter your weight in pounds <<endl; cin>>pound; kg=convert(pound); cout<< Your weight in Kilograms is <<kg; return(0); 11

62 float convert(float p) float k; k= *p; return(k); Output Enter your weight in pounds 45.7 Your weight in Kilograms is Library Functions (or) Predefined Functions Example: Math Library Functions (or) Math pre-defined Functions Function Description Example ceil( x ) cos( x ) exp( x ) fabs( x ) floor( x ) fmod( x, y ) log( x ) rounds x to the smallest integer not less than x trigonometric cosine of x ( x in radians) e ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0 xponential function e x exp( 1.0 ) is exp( 2.0 ) is absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( ) is 8.76 rounds x to the largest integer not greater than x remainder of x/y as a floating-point num ber natural logarithm of x (base e) floor( 9.2 ) is 9.0 floor( -9.8 ) is fmod( 2.6, 1.2 ) is 0.2 log( ) is 1.0 log( ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( ) is 2.0 pow( x, y ) x raised to power y (x y ) pow( 2, 7 ) is 128 pow( 9,.5 ) is 3 sin( x ) trigonometric sine of x sin( 0.0 ) is 0 (x in radians) sqrt( x ) square root of x (where x is a sqrt( 9.0 ) is 3.0 nonnegative value) tan( x ) trigonometric tangent of x tan( 0.0 ) is 0 (x in radians) 12

63 In the above figure, the variables x and y are of type double. These are the predefined functions for mathematical calculations. These functions are global functions and are placed in header file <cmath> or <math>, so that the global functions can be reused in any program that includes the header file <cmath> or <math>. Example Program #include<iostream> #include<cmath> using namespace std; int main() double x,y; x=12.45; y=1.9; cout<< Output of ceil function <<ceil(x)<<endl; cout<< Output of floor function <<floor(x)<<endl; cout<< Output of exp function <<exp(x)<<endl; cout<< Output of pow function <<pow(x,y)<<endl; cout<< Output of sqrt function <<sqrt(x)<<endl; cout<< Output of fabs function <<fabs(x)<<endl; cout<< Output of fmod function <<fmod(x,y)<<endl; cout<< Output of log function <<log(x)<<endl; cout<< Output of log10 function <<log10(x)<<endl; cout<< Output of sin function <<sin(x)<<endl; cout<< Output of cos function <<cos(x)<<endl; cout<< Output of tan function <<tan(x)<<endl; return(0); Output Output of ceil function13 Output of floor function12 Output of exp function Output of pow function

CHAPTER 4 CONTROL STRUCTURES

CHAPTER 4 CONTROL STRUCTURES CHAPTER 4 CONTROL STRUCTURES 1 Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may deviate, repeat code or take decisions. For that purpose,

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Fifth week Control Structures A program is usually not limited to a linear sequence of instructions. During its process

More information

8. Control statements

8. Control statements 8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

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

Introduction to Programming

Introduction to Programming Introduction to Programming session 9 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

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout

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

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab Sixth week Jump statements The break statement Using break we can leave a loop even if the condition for its end is not fulfilled

More information

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions

More information

INTRODUCTION TO PROGRAMMING

INTRODUCTION TO PROGRAMMING FIRST SEMESTER INTRODUCTION TO PROGRAMMING COMPUTER SIMULATION LAB DEPARTMENT OF ELECTRICAL ENGINEERING Prepared By: Checked By: Approved By Engr. Najeeb Saif Engr. M.Nasim Kha Dr.Noman Jafri Lecturer

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1 Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

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

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

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

Programming Language. Functions. Eng. Anis Nazer First Semester

Programming Language. Functions. Eng. Anis Nazer First Semester Programming Language Functions Eng. Anis Nazer First Semester 2016-2017 Definitions Function : a set of statements that are written once, and can be executed upon request Functions are separate entities

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

CHAPTER 9 FLOW OF CONTROL

CHAPTER 9 FLOW OF CONTROL CHAPTER 9 FLOW OF CONTROL FLOW CONTROL In a program statement may be executed sequentially, selectively or iteratively. Every program language provides constructs to support sequence, selection or iteration.

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

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

CHAPTER : 9 FLOW OF CONTROL

CHAPTER : 9 FLOW OF CONTROL CHAPTER 9 FLOW OF CONTROL Statements-Statements are the instructions given to the Computer to perform any kind of action. Null Statement-A null statement is useful in those case where syntax of the language

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer

More information

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs. 1 3. Functions 1. What are the merits and demerits of modular programming? Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

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

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

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

C++ Programming Lecture 1 Software Engineering Group

C++ Programming Lecture 1 Software Engineering Group C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in

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

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture - 23 Introduction to Arduino- II Hi. Now, we will continue

More information

Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching. Class Incharge: S. Sasirekha Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

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++

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

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

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM

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

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return

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

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE Department of Software The University of Babylon LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE By Collage of Information Technology, University of Babylon, Iraq Samaher_hussein@yahoo.com

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

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

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

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Functions. Lecture 6 COP 3014 Spring February 11, 2018 Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its

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

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

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

CSc Introduction to Computing

CSc Introduction to Computing CSc 10200 Introduction to Computing Lecture 2 Edgardo Molina Fall 2011 - City College of New York Thursday, September 1, 2011 Introduction to C++ Modular program: A program consisting of interrelated segments

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

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 8 Statement-Level Control Structure

Chapter 8 Statement-Level Control Structure Chapter 8 Statement-Level Control Structure To make programs more flexible and powerful: Some means of selecting among alternative control flow paths. Selection statement (conditional statements) Unconditional

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

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

Module3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement

Module3. Program Control Statements CRITICAL SKILLS. 3.1 Know the complete form of the if statement. 3.2 Use the switch statement Module3 Program Control Statements CRITICAL SKILLS 3.1 Know the complete form of the if statement 3.2 Use the switch statement 3.3 Know the complete form of the for loop 3.4 Use the while loop 3.5 Use

More information

Functions. Introduction :

Functions. Introduction : Functions Introduction : To develop a large program effectively, it is divided into smaller pieces or modules called as functions. A function is defined by one or more statements to perform a task. In

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 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 Generation

More information

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

A SHORT COURSE ON C++

A SHORT COURSE ON C++ Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction

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 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

MODULE 2: Branching and Looping

MODULE 2: Branching and Looping MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written

More information

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

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

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

A Freshman C++ Programming Course

A Freshman C++ Programming Course A Freshman C++ Programming Course Dr. Ali H. Al-Saedi Al-Mustansiria University, Baghdad, Iraq January 2, 2018 1 Number Systems and Base Conversions Before studying any programming languages, students

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

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

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as: 11. Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example,

More information

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

Chapter 6 - Notes User-Defined Functions I

Chapter 6 - Notes User-Defined Functions I Chapter 6 - Notes User-Defined Functions I I. Standard (Predefined) Functions A. A sub-program that performs a special or specific task and is made available by pre-written libraries in header files. B.

More information

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review. Modules. CS 151 Review #6. Sample Program 6.1a: Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called

More information

(created by professor Marina Tanasyuk) FUNCTIONS

(created by professor Marina Tanasyuk) FUNCTIONS FUNCTIONS (created by professor Marina Tanasyuk) In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define

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

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

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

Manual. Subject Code: CS593. Computer Science and Engineering

Manual. Subject Code: CS593. Computer Science and Engineering Programming Practices using C++ Laboratory Manual Subject Code: CS593 Computer Science and Engineering B-Tech (5 th Semester) Structure of a program Probably the best way to start learning a programming

More information

In this chapter you will learn:

In this chapter you will learn: 1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

C Syntax Out: 15 September, 1995

C Syntax Out: 15 September, 1995 Burt Rosenberg Math 220/317: Programming II/Data Structures 1 C Syntax Out: 15 September, 1995 Constants. Integer such as 1, 0, 14, 0x0A. Characters such as A, B, \0. Strings such as "Hello World!\n",

More information

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y ); - 50 - Control Structures: 8. Functions (II) Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This

More information

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

Chapter 3. More Flow of Control

Chapter 3. More Flow of Control 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-2 Flow Of Control Flow of control refers to the

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

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

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions Areas for Discussion C++ Functions Joseph Spring School of Computer Science Operating Systems and Computer Networks Lecture Functions 1 Last Week Introduction to Functions Program Structure and Functions

More information

Chapter 2. Outline. Simple C++ Programs

Chapter 2. Outline. Simple C++ Programs Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

More information

Chapter 4 - Notes Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection) Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by

More information

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

More information