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:

  • Popular Math Terms and Definitions
  • 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
  • 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

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

About Fiveable

Code of Conduct

Terms of Use

Privacy Policy

CCPA Privacy Policy

AP Score Calculators

Study Guides

Practice Quizzes

Cram Events

Crisis Text Line

Help Center

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.

example of compound assignment

  • 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.

cppreference.com

Assignment operators.

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

[ edit ] Simple assignment

The simple assignment operator expressions have the form

Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs .

Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic (since C11)
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict (since C99) -qualified or atomic (since C11) .
  • lhs is a (possibly qualified or atomic (since C11) ) pointer and rhs is a null pointer constant such as NULL or a nullptr_t value (since C23)

[ edit ] Notes

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C.

[ edit ] Compound assignment

The compound assignment operator expressions have the form

The expression lhs @= rhs is exactly the same as lhs = lhs @ ( rhs ) , except that lhs is evaluated only once.

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.16 Assignment operators (p: 72-73)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

[ edit ] See Also

Operator precedence

[ edit ] See also

  • 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 19 August 2022, at 09:36.
  • This page has been accessed 58,085 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

example of compound assignment

  • 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

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

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 operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators

Assignment Operators in C

  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

example of compound assignment

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example:

2. “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. PPT

    example of compound assignment

  2. PPT

    example of compound assignment

  3. Day 06, Part 01: Compound Assignment

    example of compound assignment

  4. 13 Compound Assignment

    example of compound assignment

  5. Java Lesson 12

    example of compound assignment

  6. Lecture 12: Control Flow

    example of compound assignment

VIDEO

  1. Lecture 5 :Chapter2 Basic Element (Part4)

  2. Preposition

  3. COMPOUND INTEREST & ANNUITY GROUP ASSIGNMENT MAT112

  4. Compound Angles Assignment Discussion

  5. Group 4(assignment) compound interest and annuity

  6. MAT112 Annuity and Compound Interest A4AC1101A (Group 8)

COMMENTS

  1. Compound assignment operators in Java

    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. ... Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to ...

  2. What Is a Compound-Assignment Operator?

    Compound-Assignment Operators. 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.

  3. 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.

  4. 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:

  5. Compound Assignment Operators in Java (With Examples)

    In this article, let's know about the Java's compound assignment operators with examples and programs. What are Compound Assignment Operators in Java? Compound assignment operators in Java are shorthand notations that combine an arithmetic or bitwise operation with an assignment. They allow you to perform an operation on a variable's value ...

  6. 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.

  7. Compound Assignment Operators

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

  8. 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 ...

  9. PDF Compound assignment operators

    The Java language specification says that: The compound assignment E1 op= E2 is equivalent to [i.e. is syntactic sugar for] E1 = (T) ((E1) op (E2)) where T is the type of E1, except that E1 is evaluated only once. We note two important points: The expression is cast to the type of E1 before the assignment is made (the cast is in red above) E1 ...

  10. 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 ...

  11. 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 ( += )

  12. 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 ...

  13. Assignment operators

    Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right. Operator Operator name Example Description Equivalent of = basic assignment a = b: a becomes equal to b: N/A + = addition assignment a + = b: a becomes equal to the addition of a and b: a = a + b-= subtraction ...

  14. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  15. 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

  16. 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 ...

  17. 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:

  18. Assignment Statements

    This is implemented with one of a series of compound assignment operators. Using the same example, if we wanted to add 5 to the variable x, we could write it as x += 5. Similar operations may be carried out using one of the many compound operators shown in Table 2. Example

  19. Compound assignment in C++

    6. The compound assignment operators are in the second lowest precedence group of all in C++ (taking priority over only the comma operator). Thus, your a += b % c case would be equivalent to a += ( b % c ), or a = a + ( b % c ). This explains why your two code snippets are different. The second:

  20. 1.1: Compound Statements

    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: ¬p, Not p (i.e. the negation of p), p ∧ q, pandq, p ∨ q, porq and. p → q, Ifpthenq.

  21. c

    According to Microsoft, "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". Here is what I am expecting some kind of ...

  22. Assignment Operators in C

    Different types of assignment operators are shown below: 1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current ...

  23. IBM Documentation

    IBM Documentation.

  24. PDF Investigation 5: Preparation and Analysis of a Compound

    one hour. Cool the weighing bottle containing the dehydrated sample in a desiccator, then record the final precise mass of the sample and bottle. Preparation of 0.05000 M Ce4+ solution. To a 10 mL volumetric flask, add the appropriate amount (calculated in the prelab assignment or class) of ceric ammonium nitrate (CAN).