Presentation is loading. Please wait.

Presentation is loading. Please wait.

Increment/Decrement Unary operators require only one operand

Similar presentations


Presentation on theme: "Increment/Decrement Unary operators require only one operand"— Presentation transcript:

1 Increment/Decrement Unary operators require only one operand
++ increment operator Adds 1 to the value of a variable x ++; is equivalent to x = x + 1; decrement operator Subtracts 1 from the value of a variable x --; is equivalent to x = x – 1; Are the following ok? (x+y)++ 5++

2 V++ vs ++V int number=2; int value_produced=2*(number++); cout<<value_produced<<endl; cout<<number<<endl; int value_produced=2*(++number);

3 For Loops The next major loop we use is the For Loop
Consider the code below, which is very common A variable (count) controls the loop – we call it the iteration variable We initialize it before the loop, we check it to see if we should exit each iteration, and we update its value each iteration This situation is so common, C++ has a special case of the while loop called the for loop count = 0; while (count < 50) { doSomeStuff(); count++; }

4 For Loops For loops Format: for (initialization; condition; update) statements Does same functionality as while, but more succinctly Like if and while, for-loops almost always use { } for statement Frequently used when you know the # of iterations Example below would normally use a for-loop count = 0; while (count < 50) { doSomeStuff(); count++; } initialization; while (condition) { doSomeStuff(); update; } for (count=0; count<50; count++ ) { doSomeStuff(); }

5 Initialization Action
For Loop Dissection The for loop uses the same components as the while loop in a more compact form for (n = 1; n <= 10; n++) Initialization Action Boolean Expression Update Action

6 Which One to Use? Use "for" loop when number of iterations is known at outset Use "while" loop if number is unknown or depends on a non-numeric condition

7 Exercises 1.How to calculate 1+2+3+…+100

8 Nested Loop Example:  The for-j loop is nested (or enclosed within) the control of the for-i loop, so that it is executed ten times.                for (int i = 0, k = 1; i < 10; i++) {                                 for (int j = 0; j < 10; j++) k++;                         } Final value of k? Example1: what does the following code do? for (int i=1; i<=10;i++) { for (int j=1; j<=i; j++) cout<<'*'; cout<<endl; }

9 More examples for (int n=1; n<=10; n+=2) do something; for (double size=0.75; size<=5; size=size+0.05) for (double x=pow(y,30); x>2.0; x=sqrt(x)) do something


Download ppt "Increment/Decrement Unary operators require only one operand"

Similar presentations


Ads by Google