Compound-Assignment Operators

  • Java Programming
  • PHP Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • M.A., Advanced Information Systems, University of Glasgow

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.

Compound-Assignment Operators in Java

Java supports 11 compound-assignment operators:

Example Usage

To assign the result of an addition operation to a variable using the standard syntax:

But use a compound-assignment operator to effect the same outcome with the simpler syntax:

  • 10 Math Tricks That Will Blow Your Mind
  • Conditional Operators
  • Java Expressions Introduced
  • Understanding the Concatenation of Strings in Java
  • The 7 Best Programming Languages to Learn for Beginners
  • Popular Math Terms and Definitions
  • The Associative and Commutative Properties
  • The JavaScript Ternary Operator as a Shortcut for If/Else Statements
  • Parentheses, Braces, and Brackets in Math
  • Basic Guide to Creating Arrays in Ruby
  • Dividing Monomials in Basic Algebra
  • C++ Handling Ints and Floats
  • An Abbreviated JavaScript If Statement
  • Using the Switch Statement for Multiple Choices in Java
  • How to Make Deep Copies in Ruby
  • Definition of Variable

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

C Compound Assignment

  • 6 contributors

The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as

expression1 += expression2

can be understood as

expression1 = expression1 + expression2

However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.

The operands of a compound-assignment operator must be of integral or floating type. Each compound-assignment operator performs the conversions that the corresponding binary operator performs and restricts the types of its operands accordingly. The addition-assignment ( += ) and subtraction-assignment ( -= ) operators can also have a left operand of pointer type, in which case the right-hand operand must be of integral type. The result of a compound-assignment operation has the value and type of the left operand.

In this example, a bitwise-inclusive-AND operation is performed on n and MASK , and the result is assigned to n . The manifest constant MASK is defined with a #define preprocessor directive.

C Assignment Operators

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

Using Compound Assignment Operator in a Java Program

CompoundAssignmentOperator.java

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

pep

Find what you need to study

1.4 Compound Assignment Operators

7 min read • december 27, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Compound Assignment Operators

Compound Operators

Sometimes, you will encounter situations where you need to perform the following operation:

This is a bit clunky with the repetition of integerOne in line two. We can condense this with this statement:

The "* = 2" is an example of a compound assignment operator , which multiplies the current value of integerOne by 2 and sets that as the new value of integerOne. Other arithmetic operators also have compound assignment operators as well, with addition, subtraction, division, and modulo having +=, -=, /=, and %=, respectively.

Incrementing and Decrementing

There are special operators for the two following operations in the following snippet well:

These can be replaced with a pre-increment /pre-decrement (++i or - -i) or post-increment /post-decrement (i++ or i- -) operator . You only need to know the post-variant in this course, but it is useful to know the difference between the two. Here is an example demonstrating the difference between them:

By itself, there is no difference between the pre-increment and post-increment operators, but it's evident when you use it in a method such as the println method. For this statement, I will write a debugging output , which happens when we trace the code, which means to follow it line-by-line.

Code Tracing Practice

Now that you’ve learned about code tracing , let’s do some practice! You can use trace tables like the ones shown below to keep track of the values of your variables as they change.

Here are some practice problems that you can use to practice code tracing . Feel free to use whichever method you’re the most comfortable with!

Trace through the following code:

Note: Your answers could look different depending on how you’re tracking your code tracing .

a *= 3: This line multiplies a by 3 and assigns the result back to a. The value of a is now 18.

b -= 2: This line subtracts 2 from b and assigns the result back to b. The value of b is now 2.

c = a % b: This line calculates the remainder of a divided by b and assigns the result to c. The value of c is now 0.

a += c: This line adds c to a and assigns the result back to a. The value of a is now 18.

b = a - b: This line subtracts b from a and assigns the result back to b. The value of b is now 16.

c *= b: This line multiplies c by b and assigns the result back to c. The value of c is now 0.

The final values of the variables are:

double x = 15.0;

double y = 4.0;

double z = 0;

x /= y: This line divides x by y and assigns the result back to x. The value of x is now 3.75.

y *= x: This line multiplies y by x and assigns the result back to y. The value of y is now 15.0.

z = y % x: This line calculates the remainder of y divided by x and assigns the result to z. The value of z is now 3.75.

x += z: This line adds z to x and assigns the result back to x. The value of x is now 7.5.

y = x / z: This line divides x by z and assigns the result back to y. The value of y is now 2.0.

z *= y: This line multiplies z by y and assigns the result back to z. The value of z is now 7.5.

int a = 100;

int b = 50;

int c = 25;

a -= b: This line subtracts b from a and assigns the result back to a. The value of a is now 50.

b *= 2: This line multiplies b by 2 and assigns the result back to b. The value of b is now 100.

c %= 4: This line calculates the remainder of c divided by 4 and assigns the result back to c. The value of c is now 1.

a = b + c: This line adds b and c and assigns the result to a. The value of a is now 101.

b = c - a: This line subtracts a from c and assigns the result to b. The value of b is now -100.

c = a * b: This line multiplies a and b and assigns the result to c. The value of c is now -10201.

a *= 2: This line multiplies a by 2 and assigns the result back to a. The value of a is now 10.

b -= 1: This line subtracts 1 from b and assigns the result back to b. The value of b is now 2.

a += c: This line adds c to a and assigns the result back to a. The value of a is now 10.

b = a - b: This line subtracts b from a and assigns the result back to b. The value of b is now 8.

int y = 10;

int z = 15;

x *= 2: This line multiplies x by 2 and assigns the result back to x. The value of x is now 10.

y /= 3: This line divides y by 3 and assigns the result back to y. The value of y is now 3.3333... (rounded down to 3).

z -= x: This line subtracts x from z and assigns the result back to z. The value of z is now 5.

x = y + z: This line adds y and z and assigns the result to x. The value of x is now 8.

y = z - x: This line subtracts x from z and assigns the result to y. The value of y is now -3.

z = x * y: This line multiplies x and y and assigns the result to z. The value of z is now -24.

double x = 10;

double y = 3;

x /= y: This line divides x by y and assigns the result back to x. The value of x is now 3.3333... (rounded down to 3.33).

y *= x: This line multiplies y by x and assigns the result back to y. The value of y is now 10.

z = y - x: This line subtracts x from y and assigns the result to z. The value of z is now 6.67.

x += z: This line adds z to x and assigns the result back to x. The value of x is now 10.0.

y = x / z: This line divides x by z and assigns the result back to y. The value of y is now 1.5.

z *= y: This line multiplies z by y and assigns the result back to z. The value of z is now 10.0.

Want some additional practice? CSAwesome created this really cool Operators Maze game that you can do with a friend for a little extra practice! 

Key Terms to Review ( 5 )

Code Tracing

Decrementing

Post-increment

Pre-increment

Fiveable

Stay Connected

© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

Operator precedence

Operator overloading

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Compound Assignment Operators in C++

The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −

  • An arithmetic type
  • A pointer, if op is + or –

The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once.

The following are the compound assignment operators in C++ −

Let's have a look at an example using some of these operators −

This will give the output −

Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.

Govinda Sai

Related Articles

  • Compound assignment operators in C#
  • Compound assignment operators in Java\n
  • Assignment Operators in C++
  • What are assignment operators in C#?
  • Perl Assignment Operators
  • Assignment operators in Dart Programming
  • Compound operators in Arduino
  • What is the difference between = and: = assignment operators?
  • Passing the Assignment in C++
  • Airplane Seat Assignment Probability in C++
  • What is an assignment operator in C#?
  • Copy constructor vs assignment operator in C++
  • Ternary Operators in C/C++
  • Unary operators in C/C++
  • Conversion Operators in C++

Kickstart Your Career

Get certified by completing the course

To Continue Learning Please Login

  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise

Now that we've talked about operators. Let's talk about something called the compound assignment operator and I'm going make one little change here in case you're wondering if you ever want to have your console take up the entire window you come up to the top right-hand side here you can undock it into a separate window and you can see that it takes up the entire window.

large

So just a little bit more room now.

Additionally, I have one other thing I'm going to show you in the show notes. I'm going to give you access to this entire set of assignment operators but we'll go through a few examples here. I'm going to use the entire window just to make it a little bit easier to see.

Let's talk about what assignment is. Now we've been using assignment ever since we started writing javascript code. You're probably pretty used to it. Assignment is saying something like var name and then setting up a name

And that is assignment the equals represents assignment.

Now javascript gives us the ability to have the regular assignment but also to have that assignment perform tasks. So for example say that you want to add items up so say that we want to add up a total set of grades to see the total number of scores. I can say var sum and assign it equal to zero.

And now let's create some grades.

I'm going to say var gradeOne = 100.

and then var gradeTwo = 80.

Now with both of these items in place say that we wanted to add these if you wanted to just add both of them together you definitely could do something like sum = (gradeOne + gradeTwo); and that would work.

However, one thing I want to show you is, there are many times where you don't have gradeOne or gradeTwo in a variable. You may have those stored in a database and then you're going to loop through that full set of records. And so you need to be able to add them on the fly. And so that's what a compound assignment operator can do.

Let's use one of the more basic ones which is to have the addition assignment.

Now you can see that sum is equal to 100.

Then if I do

If we had 100 grades we could simply add them just like that.

Essentially what this is equal to is it's a shorthand for saying something like

sum = sum + whatever the next one is say, that we had a gradeThree, it would be the same as doing that. So it's performing assignment, but it also is performing an operation. That's the reason why it's called a compound assignment operator.

Now in addition to having the ability to sum items up, you could also do the same thing with the other operators. In fact literally, every one of the operators that we just went through you can use those in order to do this compound assignment. Say that you wanted to do multiplication you could do sum astrix equals and then gradeTwo and now you can see it equals fourteen thousand four hundred.

This is that was the exact same as doing sum = whatever the value of sum was times gradeTwo. That gives you the exact same type of process so that is how you can use the compound assignment operators. And if you reference the guide that is included in the show notes. You can see that we have them for each one of these from regular equals all the way through using exponents.

Then for right now don't worry about the bottom items. These are getting into much more advanced kinds of fields like bitwise operators and right and left shift assignments. So everything you need to focus on is actually right at the top for how we're going to be doing this. This is something that you will see in a javascript code. I wanted to include it, so when you see it you're not curious about exactly what's happening.

It's a great shorthand syntax for whenever you want to do assignment but also perform an operation at the same time.

  • Documentation for Compound Assignment Operators
  • Source code

devCamp does not support ancient browsers. Install a modern version for best experience.

example of compound assignment statement

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Getting Started
  • 1.1.1 Preface
  • 1.1.2 About the AP CSA Exam
  • 1.1.3 Transitioning from AP CSP to AP CSA
  • 1.1.4 Java Development Environments
  • 1.1.5 Growth Mindset and Pair Programming
  • 1.1.6 Pretest for the AP CSA Exam
  • 1.1.7 Survey
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Values
  • 1.7 Unit 1 Summary
  • 1.8 Mixed Up Code Practice
  • 1.9 Toggle Mixed Up or Write Code Practice
  • 1.10 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Values' data-toggle="tooltip" >

Time estimate: 45 min.

1.5. Compound Assignment Operators ¶

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x . It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .

Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.

Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.

If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.

Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!

Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.

If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.

Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.

In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.

But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.

The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.

exercise

1-5-2: What are the values of x, y, and z after the following code executes?

  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • x = -1, y = 2, z = 2
  • x = 0, y = 1, z = 2
  • x = -1, y = 2, z = 4

1-5-3: What are the values of x, y, and z after the following code executes?

  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • x = 6, y = 2, z = 3
  • x = 4, y = 2.5, z = 3
  • x = 4, y = 2, z = 3

1.5.1. Code Tracing Challenge and Operators Maze ¶

Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.

Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.

Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

../_images/traceTable.png

Trace through the following code:

1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.

After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!

1.5.2. Summary ¶

Compound assignment operators ( += , -= , *= , /= , %= ) can be used in place of the assignment operator.

The increment operator ( ++ ) and decrement operator ( -- ) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.

The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.

example of compound assignment statement

  • Introduction to C
  • Download MinGW GCC C Compiler
  • Configure MinGW GCC C Compiler
  • The First C Program
  • Data Types in C
  • Variables, Keywords, Constants
  • If Statement
  • If Else Statement
  • Else If Statement
  • Nested If Statement
  • Nested If Else Statement
  • Do-While Loop
  • Break Statement
  • Switch Statement
  • Continue Statement
  • Goto Statement
  • Arithmetic Operator in C
  • Increment Operator in C
  • Decrement Operator in C
  • Compound Assignment Operator
  • Relational Operator in C
  • Logical Operator in C
  • Conditional Operator in C
  • 2D array in C
  • Functions with arguments
  • Function Return Types
  • Function Call by Value
  • Function Call by Reference
  • Recursion in C
  • Reading String from console
  • C strchr() function
  • C strlen() function
  • C strupr() function
  • C strlwr() function
  • C strcat() function
  • C strncat() function
  • C strcpy() function
  • C strncpy() function
  • C strcmp() function
  • C strncmp() function
  • Structure with array element
  • Array of structures
  • Formatted Console I/O functions
  • scanf() and printf() function
  • sscanf() and sprintf() function
  • Unformatted Console I/O functions
  • getch(), getche(), getchar(), gets()
  • putch(), putchar(), puts()
  • Reading a File
  • Writing a File
  • Append to a File
  • Modify a File

Advertisement

+= operator

  • Add operation.
  • Assignment of the result of add operation.
  • Statement i+=2 is equal to i=i+2 , hence 2 will be added to the value of i, which gives us 4.
  • Finally, the result of addition, 4 is assigned back to i, updating its original value from 2 to 4.

Example with += operator

-= operator.

  • Subtraction operation.
  • Assignment of the result of subtract operation.
  • Statement i-=2 is equal to i=i-2 , hence 2 will be subtracted from the value of i, which gives us 0.
  • Finally, the result of subtraction i.e. 0 is assigned back to i, updating its value to 0.

Example with -= operator

*= operator.

  • Multiplication operation.
  • Assignment of the result of multiplication operation.
  • Statement i*=2 is equal to i=i*2 , hence 2 will be multiplied with the value of i, which gives us 4.
  • Finally, the result of multiplication, 4 is assigned back to i, updating its value to 4.

Example with *= operator

/= operator.

  • Division operation.
  • Assignment of the result of division operation.
  • Statement i/=2 is equal to i=i/2 , hence 4 will be divided by the value of i, which gives us 2.
  • Finally, the result of division i.e. 2 is assigned back to i, updating its value from 4 to 2.

Example with /= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons

Margin Size

  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Mathematics LibreTexts

1.1: Compound Statements

  • Last updated
  • Save as PDF
  • Page ID 4799

  • Pamini Thangarajah
  • Mount Royal University

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

We can make a new statement from other statements; we call these compound propositions or compound statements .

Example \(\PageIndex{1}\):

  • It is not the case that all birds can fly. (This is the negation of the statement all birds can fly).
  • \(1+1=2\) and "All birds can fly". (Here the connector "and" was used to create a new statement).

Note the following four basic ways to start with one or more propositions and use them to make a more elaborate compound statement. If \(p\) and \(q\) are statements then here are four compound statements made from them:

  • \(\neg p \), Not \(p\) (i.e. the negation of \(p\)),
  • \( p \wedge q,\, p\, \textit{and}\, q\),
  • \(p\vee q, \,p \,\textit{or} \,q\) and
  • \(p \rightarrow q,\: \textit{If} \; p \, \textit{then}\, q.\)

Example \(\PageIndex{2}\):

If \(p =\) "You eat your supper tonight" and \(q = \) "You get desert". Then

  • Not \(p \) is "You don't eat your supper tonight".
  • \(p\, \textit{and}\, q\) is "You eat your supper tonight and you get desert".
  • \( p \,\textit{or} \,q\) is "You eat your supper tonight or you get desert".
  • \(\textit{If} \; p \, \textit{then}\, q\) is "If you eat your supper tonight then you get dessert."

In English, we know these four propositions don't say the same thing. In logic, this is also the case, but we can make that clear by displaying the truth value possibilities. It is common to use a table to capture the possibilities for truth values of compound statements. We call such a table a truth table. Below are the possibilities: the first is the least profound. It says that a statement p is either true or false.

Truth tables are more useful in describing the possible truth values for various compound propositions. Consider the following truth table:

The table above describes the truth value possibilities for the statements \(p\) and \(\neg p\), or "not p". As you can see, if \(p\) is true then \(\neg p\) is false and if \(p\) is false, the negation (i.e. not p) is true. \(\neg\) is the mathematical notation used to mean "not."

Example \(\PageIndex{3}\):

Consider the statement \(p\): \(1 + 1 = 3\).

Statement \(p\) can either be true or false, not both.

\(\neg p\) is "not \(p\)," or the negation of statement \(p\).

\(\neg p\) is \(1 + 1 \ne 3\).

You can see that the negation of a proposition affects only the proposition itself, not any other assumptions.

Conjunction

Conjunction statements use two or more propositions. If two or more simple propositions are involved the truth table gets bigger. Below is the truth table for "and," otherwise known as a conjunction. When is an and statement true? As the truth table indicates, only when both of the component propositions are true is the compound conjunction statement true:

Example \(\PageIndex{4}\):

Consider statements \(p:= \,1 + 1 = 2\) and \(q:=\,2 < 5\).

Note that, \(p \wedge q\) is true only if both \(p\) and \(q\) are both true.

Since statements \(p\) and \(q\) are both true, \(p \wedge q\) is true.

Disjunction

Disjunction statements are compound statements made up of two or more statements and are true when one of the component propositions is true. They are called "Or Statements." In English, "or" is used in two ways:

  • If a person is looking for a house with 4 bedrooms or a short commute, a real estate agent might present houses with either 4 bedrooms or a short commute or both 4 bedrooms and a short commute. This is called an inclusive or .
  • If a person is asked whether they would like a Coke or a Pepsi, they are expected to choose between the two options. This is an exclusive or : "both" is not an acceptable case.

In logic, we use inclusive or statements

The \(p \) or \( q\) proposition is only false if both component propositions \(p \) and \( q\) are false.

Example \(\PageIndex{5}\):

Consider the statement \(2 \leq -3\)

The statement reads "2 is less than or equal to -3", or "\(2 < -3 \vee 2 = -3\)" and can be broken into two component propositions:

  • Proposition \(p\): \(2 < -3\) (False)
  • Proposition \(q\): \(2 = -3\) (False)

Because propositions \(p\) and \(q\) are both false, the statement is false.

Example \(\PageIndex{6}\):

Consider the statement \(2 \leq 5\)

The statement's two component propositions are:

  • Proposition \(p\): \(2 < 5\) (True)
  • Proposition \(q\): \(2 = 5\) (False)

Since proposition \(p\) is true, the statement is true.

Conditional Statements

Consider the "if p then q" proposition. This is a conditional statement . Read the statements below. If these statements are made, in which instance is one lying (i.e. when is the overall statement false)?

Suppose, at suppertime, your mother makes the statement “If you eat your broccoli then you’ll get dessert.” Under what conditions could you say your mother is lying?

  • If you eat your broccoli but don't get dessert, she lied!
  • If you eat your broccoli and get dessert, she told the truth.
  • If you don’t eat your broccoli and you don’t get dessert she told you the truth.
  • If you don’t eat your broccoli but you do get dessert we still think she told the truth. After all, she only outlined one condition that was supposed to get you desert, she didn’t say that was the only way you could earn dessert. Maybe you had cauliflower instead.

Note that the order in which the cases are presented in the truth table is irrelevant. The cases themselves are important information, not their order relative to each other.

It is important to notice that, if the first proposition is false, the conditional statement is true by default. A conditional statement is defined as being true unless a true hypothesis leads to a false conclusion.

Example \(\PageIndex{7}\):

Consider the statement "If a closed figure has four sides, then it is a square." This is a false statement - why?

We can prove it using a counter-example : we draw a four-sided figure that is not a square. So there!

Example \(\PageIndex{8}\):

Consider the statement "If \(2 = 3\), then \(5 = 2\)"

Since \(2 \ne 3\), it does not matter if \(5 = 2\) is true or not, the conditional statement as a whole is true.

The converse of a conditional statement

Let P be a statement if p then q. Then the converse of P is if q then p.

Example \(\PageIndex{9}\):

Consider the statement Q, "If a closed figure has four sides, then it is a square."

Then the converse of Q is "If it is a square then it is a closed figure with four sides".

The contrapositive of a Conditional Statement

Let P be a statement if p then q. Then the contrapositive of P is if \(\neg q\) then \(\neg p.\)

Example \(\PageIndex{10}\):

Then the converse of Q is "If it is not a square then it is not a closed figure with four sides".

Bi-Conditional Statements

Bi-conditional statements are conditional statements which depend on both component propositions. They read "p if and only if q" and are denoted \(p \leftrightarrow q\) or "p iff q", which is logically equivalent to \((p \to q) \wedge (q \to p)\). These compound statements are true if both component propositions are true or both are false:

Example \(\PageIndex{11}\):

Consider the statement: "Two lines are perpendicular if and only if they intersect to form a right angle."

The component propositions are:

  • \(p\): Two lines are perpendicular
  • \(q\): [The lines] intersect to form a right angle

Logically, we can see that if two lines are perpendicular, then they must intersect to form a right angle. Also, we can see that if two lines form a right angle, then they are perpendicular.

If two lines are not perpendicular, then they cannot form a right angle. Conversely, if two lines do not form a right angle, they cannot be perpendicular. This is why, if both propositions in a biconditional statement are false, the statement itself is true!

Logically Equivalent Statements

Once we know the basic statement types and their truth tables, we can derive the truth tables of more elaborate compound statements. Below is the truth table for the proposition, not p or (p and q) . First, we calculate the truth values for not p, then p and q and finally, we use these two columns of truth values to figure out the truth values for not p or (p and q).

So the proposition "not p or (p and q)" is only false if p is true and q is false. Does this seem familiar?

"If p then q" is only false if p is true and q is false as well.

This has some significance in logic because if two propositions have the same truth table they are in a logical sense equal to each other – and we say that they are logically equivalent. So: \(\neg p \vee (p \wedge q) \equiv p \to q\), or "Not p or (p and q) is equivalent to if p then q."

Example \(\PageIndex{12}\):

Prove or disprove: for any mathematical statements \(p,q\) and \(r,\, p\to(q \vee r)\) is logically equivalent to \(\neg r \to ( p \to q).\)

Hence, \(p\to(q \vee r)\) is logically equivalent to \(\neg r \to ( p \to q).\)

Tautologies and Contradictions

There are two cases in which compound statements can be made that result in either always true or always false. These are called tautologies and contradictions , respectively. Let's consider a tautology first, and then a contradiction:

Example \(\PageIndex{13}\):

Consider the statement "\((2 = 3) \vee (2 \ne 3)\)":

There are two component propositions:

  • \(p\): \(2 = 3\)
  • \(\neg p\): \(2 \ne 3\)

Clearly, this statement is a tautology.

Let's make a truth table for general case \(p \vee (\neg p)\):

As you can see, no matter what we do, this statement is always true. It is a tautology . Careful! This is not to say that this statement makes logical sense in English, but rather that, using logical mathematics, this statement is always true.

Example \(\PageIndex{14}\):

Consider the statement "2 is even \(\wedge\) 2 is odd"

  • \(p\): 2 is even
  • \(\neg p\): 2 is odd

Clearly, this statement is a contradiction.

Let's make a truth table for general case \(p \wedge (\neg p)\):

As you can see again, no matter what we do, this statement will always be false. It is a contradiction . These make more sense in English: 2 cannot be both even and odd, after all! Still, what matters is what we decide using logical mathematics.

Notations & Definitions:

  • Negation: \(\neg\) or " not "
  • Conjunction: \(\wedge\) or " and "
  • Disjunction: \(\vee\) or " or "
  • Conditional: \(\to\) or " implies " or " if/then "
  • Bi-Conditional: \(\leftrightarrow\) or " if and only if " or " iff "
  • Counter-example: An example that disproves a mathematical proposition or statement.
  • Logically Equivalent: \(\equiv\) Two propositions that have the same truth table result.
  • Tautology: A statement that is always true, and a truth table yields only true results.
  • Contradiction: A statement which is always false, and a truth table yields only false results.
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Compound Statements in C++

  • std::is_compound Template in C++
  • Conditional Statements in COBOL
  • C++ if Statement
  • Jump statements in C++
  • Switch Statement in C++
  • C++ Program To Find Compound Interest
  • Nested switch statement in C++
  • C++ Nested if-else Statement
  • If Statement in Solidity
  • R - if statement
  • Compound Literals in C
  • C - if Statement
  • C Program For Compound Interest
  • Control Statements in R Programming
  • Combining Conditional Statements in Golang
  • Program to find compound interest
  • Solidity - Decision Making Statements
  • Compound assignment operators in Java
  • PostgreSQL - IF Statement

Compound statements in C++ are blocks used to group multiple statements together into a single unit. These statements are enclosed in curly braces {} and can be used wherever a single statement is expected. The statements put inside curly braces are executed just like a single statement would have been executed. The compound statements help in organizing code and provide a way to execute multiple statements sequentially.

Syntax of Compound Statements

The compound statements look like this in the program:

We just have to put multiple statements in the braces {}.

Examples of Compound Statements

Example 1: using compound statements with functions.

The compound statements are commonly used within the function definitions. All the statements inside a function’s body are enclosed as the compound statement.

Example 2: Compound Statement with if Statement

The compound statements are used in if statements for the instance when multiple statements need to be executed conditionally.

Example 3: Simple Compound Statement Inside a Function

In this program, we will use we’ll use a compound statement in between a function which also controls the scope of the variables.

As we have seen, compound statements are an integral part of the C programming languages. It is used with almost all of the components of the C to group the statements together or provide a separate scope.

Please Login to comment...

Similar reads.

  • Geeks Premier League 2023
  • Geeks Premier League

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Compound assignment statements

This topic describes the syntax and parameters for compound assignment statements.

For information about area assignment, see Area data and attribute .

The operator is applied to the target and source first, and then what results is assigned to the target.

See the following example:

But the following statements are not equivalent:

In a compound assignment, any subscripts or locator expressions specified in the target variable are evaluated only once.

If f is a function and X is an array, the following statements are not equivalent:

The function f is called only once.

IMAGES

  1. Answered: Pick out the compound assignment…

    example of compound assignment statement

  2. Compound Statements

    example of compound assignment statement

  3. SOLUTION: Compound assignment statement in programming languages

    example of compound assignment statement

  4. 025 Compound assignment operators (Welcome to the course C programming)

    example of compound assignment statement

  5. Compound Statements

    example of compound assignment statement

  6. PPT

    example of compound assignment statement

VIDEO

  1. Lecture 5 :Chapter2 Basic Element (Part4)

  2. Java Compound Assignment Operators

  3. Statement, Negations, & Compound Statements Part 1 (Judy Wu)

  4. Power of Compound interest|Einstein statement about CI#compoundinterest

  5. 6 storing values in variable, assignment statement

  6. group assignment math compound interest and annuity

COMMENTS

  1. Compound assignment operators in Java

    Examples : Resolving the statements with Compound assignment operators. ... Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) apart from that we get the result as 20 because In compound assignment operator type-casting is automatically done by ...

  2. Java Compound Operators

    For example, the following two multiplication statements are equivalent, meaning a and b will have the same value: int a = 3, b = 3, c = -2; a = a * c; // Simple assignment operator b *= c; // Compound assignment operator. It's important to note that the variable on the left-hand of a compound assignment operator must be already declared.

  3. Java Compound Assignment Operators (With Examples)

    Use compound assignment operators when you want to perform an operation on a variable and immediately update its value. They are particularly useful for short, straightforward calculations that improve code readability. For more complex expressions, regular operators and separate assignment statements might be more appropriate.

  4. What Is a Compound-Assignment Operator?

    To assign the result of an addition operation to a variable using the standard syntax: But use a compound-assignment operator to effect the same outcome with the simpler syntax: Compound assignment operators provide a shorter syntax to assign the results of the arithmetic and bitwise operators.

  5. C Compound Assignment

    The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as. expression1 += expression2. can be understood as.

  6. PDF Compound assignment operators

    Let d be an int-array and f(int) some function. In the first assignment below, f is called twice. In the second assignment, it is called only once. So the use of the compound operator is more efficient. d[f(5)]= d[f(5)] + 1; d[f(5)] += 1; There is even more of a difference between using += instead of = if one considers side effects. Evaluation of

  7. Compound Assignment Operator in Java

    The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results ...

  8. Compound Assignment Operators

    We can condense this with this statement: integerOne *= 2; The "*= 2" is an example of a compound assignment operator, which multiplies the current value of integerOne by 2 and sets that as the new value of integerOne. Other arithmetic operators also have compound assignment operators as well, with addition, subtraction, division, and modulo ...

  9. 1.5. Compound Assignment Operators

    Compound Assignment Operators — CS Java. 1.5. Compound Assignment Operators ¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen ...

  10. Assignment operators

    For all other compound assignment operators, the type of target-expr must be an arithmetic type. In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

  11. Compound Assignment Operators in C++

    The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −. The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once. The following are the compound assignment operators in C++ −. Multiply the value of the first operand by the ...

  12. Assignment Operators In C++

    Compound Assignment Operators. In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++: Addition Assignment Operator ( += )

  13. Guide to Compound Assignment Operators in JavaScript

    And so that's what a compound assignment operator can do. Let's use one of the more basic ones which is to have the addition assignment. sum += gradeOne; // 100. Now you can see that sum is equal to 100. Then if I do. sum += gradeTwo; // 180. If we had 100 grades we could simply add them just like that.

  14. 1.5. Compound Assignment Operators

    1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...

  15. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  16. IBM Documentation

    IBM Documentation.

  17. C

    In all the compound assignment operators, the expression on the right side of = is always calculated first and then the compound assignment operator will start its functioning. Hence in the last code, statement i+=2*2; is equal to i=i+(2*2), which results in i=i+4, and finally it returns 6 to i. Example with += operator

  18. Compound assignment operators

    The compound assignment operators consist of a binary operator and the simple assignment operator. They perform the operation of the binary operator on both operands and store the result of that operation into the left operand, which must be a modifiable lvalue. The following table shows the operand types of compound assignment expressions:

  19. Compound Statements

    A conjunction statement, otherwise known as an "and" statement, is a compound condition that is true when both separate statements in the condition are true. The conjunction symbol used for statements is "∧.". Example: Let p be the statement "It is sunny" and q be the statement "It is warm.". The conjunction statement p ∧ q ...

  20. Assignment and compound assignment statements

    Assignment and compound assignment statements. The assignment statement evaluates an expression and assigns its value to one or more target variables. These statements are used for internal data movement, as well as for specifying computations. The GET and PUT statements with the STRING option can also be used for internal data movement ...

  21. 1.1: Compound Statements

    Counter-example: An example that disproves a mathematical proposition or statement. Logically Equivalent: \(\equiv\) Two propositions that have the same truth table result. Tautology: A statement that is always true, and a truth table yields only true results.

  22. Compound assignment statement

    Specifies the operator that is applied to the reference and the evaluated expression before the assignment is made. Table 1 lists the compound assignment operators allowed in compound assignments. expression Specifies an expression that is evaluated and possibly converted. Area assignment is described in Area data and attribute.

  23. Compound Statements in C++

    We just have to put multiple statements in the braces {}. Examples of Compound Statements Example 1: Using Compound Statements with Functions. The compound statements are commonly used within the function definitions. All the statements inside a function's body are enclosed as the compound statement.

  24. Compound assignment statements

    In a compound assignment, any subscripts or locator expressions specified in the target variable are evaluated only once. If f is a function and X is an array, the following statements are not equivalent: X (f ()) += 1. is not equivalent to. X (f ()) = X (f ())+1. The function f is called only once.