1 / 47

Fundamentals of C and C++ Programming Control Structures and Functions

Fundamentals of C and C++ Programming Control Structures and Functions. The Assignment Operators. The assignment operator : “=“ assigns a value to a variable.

dryerj
Download Presentation

Fundamentals of C and C++ Programming Control Structures and Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Fundamentals of C and C++ ProgrammingControl Structures and Functions

  2. The Assignment Operators • The assignment operator: “=“ assigns a value to a variable. • The addition assignment operator: “+=“ adds the value of the expression on its right to the value of the variable on its left, and saves the result to the variable on the left. • Can also be done with the other arithmetic operators: -= *= /= %=

  3. The Inc/Decrement Operators • Unary increment and decrement operators increment and decrement the value of an integer variable by 1. • ++ and -- are the operators. • Placed before the variable, they are pre-increment and pre-decrement: the value is incremented or decremented before it is used in the expression in which it appears.

  4. The Inc/Decrement Operators • Placed after, they are known as the post-increment and post-decrement operators. • The value of the variable is incremented or decremented after it is used in the expression in which it appears. • In general, the use of pre-increment and decrement operators it is a programming artifact, which is strongly discouraged in modern programming.

  5. The Inc/Decrement Operators Example: main() { int c=5; printf(“%d ”, c); printf(“%d ”, c++); printf(“%d ”, c); return 0; } Output ==> 5 5 6

  6. The Inc/Decrement Operators Example: main() { int c=5; printf(“%d ”, c); printf(“%d ”, ++c); printf(“%d ”, c); return 0; } Output ==> 5 6 6

  7. Logical Operators • && this is the logical conjunction (AND) • || this is the logical disjunction (OR) • ! This is the logical negation (NOT) • == This is the equality operator. (Do not confuse with the assignment operator =). • < <= > >= These are self explanatory. • != This is the inequality operator.

  8. Functions • C allows, nay encourages, the development of many functions. • The C Standard Library has several functions already available for use by the programmer. • These libraries are included using the #include preprocessor directive.

  9. Functions • The most common ones are stdio.h and math.h for C. • Functions can be called from within other functions at an arbitrary level of nesting. • Functions cannot be defined within other functions. • Functions must be prototyped as discussed previously.

  10. Functions • Definition of a function requires the following: • the type of value returned (if any) • the name of the function • the type of arguments passed to it • declaration of local (automatic) variables • the body of the function • return a value of the correct type (if any)

  11. Functions Example: float square(float x) { float y; y = x * x; return y; }

  12. Functions • A function that does not return any value is designated as void for its return value. • A function that does not accept any arguments also has void in its paramenter definition.

  13. Passing Arguments • Two ways: • Call by value: Only the value of the variable being referenced is passed, not its address. The called function cannot make any changes to the original variable. • Call by Reference: The address of the variable is passed. The called function can make changes to the original variable. • C is naturally Call by Value

  14. Passing Arguments • In order to do Call by reference, a pointer to the variable must be passed. • We’ll see this when we get to pointers.

  15. Basic Program Control Structure • Most programming languages implement sequential execution - one statement after the other. • Certain instructions permit control of the next statement (instruction) to be executed. • The basic one is the GOTO instruction. • GOTO’s are the basic machine instruction, but aren’t desirable in high level languages.

  16. Basic Program Control Structure • Bohm and Jacopini found that programs could in fact be written without GOTO’s • Instead of the the GOTO in HLL’s: • The Sequential Structure • The Selection Structure • The Repetition Structure • Called Structured Programming

  17. The Sequential Structure • The sequential structure is the most basic structure in computer programming, and the basis of instruction sequences • Unless told otherwise, the processor executes the next instruction in the instruction sequence. • Self-explanatory

  18. The Selection Structure • Three types of selection structures; • The if structure: performs an action if the condition is true, or skips that action and continues. Called the single selection structure. • The if/else structure: performs an action if the condition is true; performs a different action if false. Called the double selection structure. • The switch structure: selects among several different actions. Called multiple select. struct.

  19. The IF Structure Has the following syntax: if (test) <action> If the action is more than one statement, then: if (test){ <action1> <action2> } -this notation is encouraged

  20. The IF Structure - Example The following is an example of the if structure: if (grade >= 60){ printf(“Passed\n”); } <next statement>; Note that nothing is printed if the grade < 60, as it goes to the <next statement>.

  21. The IF-ELSE Structure • Allows the programmer to specify alternative action if the test is not true. The syntax is: if (test) <action>; else <alternative action>;

  22. The IF-ELSE Structure If more than one statement comprises the action or alternative actions, then we can use a brace to group several statements. if (test) { <statement 1>; <statement 2>; } else { <alt. statement1>; <alt. Statement2>; }

  23. The IF-ELSE Structure An example of the IF-ELSE structure is as follows: if (grade >= 60) { printf(“Passed\n”); } else { printf(“Failed\n”); }

  24. The IF-ELSE Structure • IF-ELSE structures can be nested so as to perform other tests before another action is executed. The syntax is: if (grade >= 90) printf(“A\n”); else if (grade >= 80) printf(“B\n”); else printf(“Failed\n”);

  25. The IF-ELSE Structure • Has a shortcut. Its syntax is: <control expression> ? <then expression> : <else expression> Example: m>0 ? M+5 : m*2;

  26. The switch Structure • Is the multiple selection structure. • Consists of a series of case labels and an optional default case. • The labels are like in assembly programming, a name and a colon: • The value of the label must agree with the value of the test.

  27. The break Statement • The break statement is important in the definition of some control structures. • When executed in a repetition control structure or in the switch selection structure, causes an immediate exit from that structure, to the first statement after the structure. • It is transparent to other selection structures.

  28. The switch Structure • Each statement or group of statements corresponding to a label must be followed by the break statement. • break will cause the processor to break out of the switch structure and not evaluate the other statements in the sequence. Goes to the first statement after the switch. Usually very important.

  29. The switch Structure • If no match is found between the test and the labels, then the statements corresponding to the default label are executed. • No braces are needed to group together the statements corresponding to each label. This is counter to all else in C. • default not required.

  30. The switch Structure • The default typically goes last. However, this is not a requirement. • The default statement block does not need a break statement, but it is typically supplied in order to clarify the issue. • Test can only be an expression that evaluates to a constant integer value. • Characters enclosed in single quotes.

  31. The switch Struct. - Example Switch (grade) { case ‘A’: ++acount; break; case ‘B’: ++bcount; break; case ‘C’: ++ccount; break; default: printf(“This is an error.\n”); break: }

  32. The Repetition Structure • Permits an action to be repeated several times, as in a loop, either • as long as a condition is true (sentinel control) • for a fixed number of times (counter control) • There are 3 of them: • The while loop: sentinel control (entry cond.) • The for loop: counter control (entry condition) • The do/while loop: sentinel ctrl (exit cond.)

  33. The continue Statement • Like the break, the continue statement affects the execution of repetition structures. • Causes the processor to skip the remaining statements in the loop body, but goes back to the next iteration. • Typically associated with a selection structure.

  34. The continue Statement • In the for loop, the increment expression is executed and the loop continuation test is evaluated thereafter. • In the while loop, the loop continuation test is evaluated immediately after the continue statement. • In the do/while loop, the loop continuation test is evaluated immediately after the continue statement.

  35. The for Structure • Counter controlled. • Requires control variable to be defined. • Handles details of running the loop automatically. • Carries out the loop continuation test immediately after the counter is incremented (at top of loop).

  36. The for Structure • Requires the following information: • Name of the control variable • Initial value of counter • Increment or decrement of the counter • Final value of the counter. Defines exit conditions. Continues as long as test is true. • Programmer must ensure that the control variable will converge to the final value.

  37. The for Structure The syntax for the for loop is as follows: for (<ctrl var> = <init val>; <ctrl var> = <final value> <incrementation def>) { <body of loop> }

  38. The for Structure • Final value and increment can be mathematical functions. • The increment can be negative - decrement. • If loop continuation condition is initially false, body will never be executed. • Control variable does not need to be used in body of loop, but can be, such as for arrays.

  39. The for Structure Example: main() { int sum = 0, n; for (n=2;n<=100;n+=2) sum += n; printf(“Sum = %d”, n); return 0; }

  40. The while Structure • Specifies action to be repeated as long as condition remains true. • The loop continuation condition is “implicit”, but variable initialization and updating has to be programmed explicitly. • Checks for loop continuation at the beginning of the loop body.

  41. The while Structure • Basically a sentinel controlled loop, but can also be used as counter controlled. • Can be used in place of the for loop in most cases. • One exception is when a continue is used and the increment/decrement expression is placed after the continue statement.

  42. The while Structure The syntax is as follows: cont_var=<initial val>; while (loop cont test on cont_var){ <statement1>; <statement 2>; <statement 3>; }

  43. The while Structure Example: product = 2; while (product <= 1000) product = 2*product;

  44. The do/while Structure • Same as the while loop, with the exception that the loop continuation test is done after the body of the loop has been executed. • Thus, the body of the do/while loop is guaranteed to be executed at least once. • Braces not required if only one statement, but typically used anyway for clarity.

  45. The do/while Structure The syntax is as follows: cont_var=<initial val>; do { <statement1>; <statement 2>; <statement 3>; } while (loop cont test on cont_var);

  46. Interesting Note • C++ allows the declaration of the control variables directly within the specification of the repetition structure. • C does not. • Example: for (int n=0; n>=10;n++) • Same for the while and do/while.

  47. Control Structures - Summary • C/C++ only has 7 control structures. • Structures are single-entry/single-exit, which facilitate programming. • Repetition structures can be nested within one another at an arbitrary level of nesting. • This nesting is what can cause combinatorial explosion.

More Related