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

choose correct syntax for c arithmetic compound assignment operators

  • 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

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:

  • Java Expressions Introduced
  • Understanding the Concatenation of Strings in Java
  • Conditional Operators
  • Conditional Statements in Java
  • Working With Arrays in Java
  • Declaring Variables in Java
  • If-Then and If-Then-Else Conditional Statements in Java
  • How to Use a Constant in Java
  • Common Java Runtime Errors
  • What Is Java?
  • What Is Java Overloading?
  • Definition of a Java Method Signature
  • What a Java Package Is In Programming
  • Java: Inheritance, Superclass, and Subclass
  • Understanding Java's Cannot Find Symbol Error Message
  • Using Java Naming Conventions

Using Compound Assignment Operators in C: A Beginner's Guide

An assignment operator is used for assigning a value to a variable. The most common assignment operator is = (equal). 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.

Compound OperatorSample ExpressionExpanded Form
+= a+=5 a=a+5
-= a-=6 a=a-6
*= a*=7 a=a*7
/= a/=4 a=a/4
%= a%=9 a=a%9

The code is a C program that demonstrates the use of compound assignment operators in C. Here is an explanation of each line of the code:

  • int a=10,b=5; declares two variables a and b of type int and assigns them the values 10 and 5 respectively.
  • a+=b; is the compound assignment operator +=, it performs a+b and assigns the value to a. It is equivalent to a=a+b.
  • printf("A : %d",a); prints the value of a which is 15, this is the result after using += operator.
  • a-=10; is the compound assignment operator -=, it performs a-10 and assigns the value to a. It is equivalent to a=a-10.
  • printf("\nA : %d",a); prints the value of a which is 5, this is the result after using -= operator.
  • return 0; The return 0; statement is used to indicate that the main function has completed successfully. The value 0 is returned as the exit status of the program, which indicates a successful execution.

When you run this code, it will perform the compound assignment operation on variables and print the results in the console.

Source Code

List of programs.

  • C Introduction
  • Hello World
  • Basic Addition
  • Data Types in C
  • Variables and Literals in C
  • Arithmetic Operator in C
  • Example for Arithmetic Operator in C
  • Assignment Operators in C Program
  • Relational Operators in C Program
  • Logical Operators in C Program
  • Increment and Decrement Operators in C Program
  • Bitwise Operators in C Program
  • if Statement in C Program
  • if else Statement in C Program
  • else if Statement in C Program
  • Nested if Statement in C Program
  • Switch Statement in C Program
  • Conditional Operator Statement in C Program
  • School Management in C Program
  • Library Management in C Program
  • Find the given number is odd or even in C Program
  • Check the given number is vowels or not in C Program
  • Check the given number is Armstrong or not in C Program
  • Hotel Management in C Program
  • Goto Statement in C Program
  • Hotel Management using goto in C Program
  • While Loop in C Program
  • Do while Loop in C Program
  • For Loop in C Program
  • Nested For Loop in C Program
  • Break and Continue Statement in C Program
  • ASCII Values in C Program
  • Single Dimensional Array in C Program
  • 2D Array in C Program
  • String Function in C Program
  • Math Function in C Program
  • Function in C Program
  • No Return Without Argument Function in C Program
  • No Return With Argument Function in C Program
  • Return Without Argument Function in C Program
  • Return With Argument Function in C Program
  • Recursion Function in C Program
  • Call by Reference Function in C Program
  • Local Variable in C Program
  • Global Variable in C Program
  • Static Variable in C Program
  • Enumeration or enum in C Program
  • Single pointer in C Program
  • Double & Triple pointer in C Program
  • Pointer Arithmetic in C Program
  • Pointer Handle Array Values in C Program
  • Void * Pointer in C Program
  • Malloc Function in C Program
  • Calloc Function in C Program
  • Realloc Function in C Program
  • Free Function in C Program
  • Dangling Pointer in C Program
  • Using Const in Pointer in C Program
  • Structure in C Program
  • Local and Global Structure in C Program
  • Typedef in C Program
  • Initializing & Accessing the Structure Members in C Program
  • Access members of structure using pointer in C Program
  • Structure as function arguments in C Program
  • Array of Objects Structure in C Program
  • Union in C Program
  • Shop Management using Structure and Union in C Program
  • Input and output functions in C Program
  • Preprocessor Directives in C Program
  • Read File in C Program
  • Write File in C Program
  • Multiplication tables in C Program
  • Total no of even and odd numbers in an array in C Program
  • Count Alphabets Digits and Special Characters in a String in C Program
  • Convert string to uppercase in C Program
  • Convert string to lowercase in C Program
  • Display Fibonacci Sequence in C Program
  • Greatest of n numbers in an array in C Program

Sample Programs

Switch case in c.

  • Present Elevator Position
  • Check Vowel or Consonent
  • Hotel Management using Swtich Case

Conditional Operators in C

  • Find Greatest Number
  • Check Find Smallest Number
  • Check Number Equal or Not
  • Check Char. Vowel or Consonent
  • Check Character Capital or Small

Goto Statement in C

  • Consecutive Numbers
  • Print Text Using Goto
  • Print Odd Numbers
  • Printing Tables
  • Printing Sum of Values
  • Printing Reverse Table
  • Print Factorial in C

While Loop Example Programs

  • Print numbers using While Loop
  • Armstrong Number using While Loop
  • Print Odd and Even numbers
  • Print Positive and Negative numbers
  • Print Prime or Composite Number Upto Limit
  • Print Prime or Composite Number
  • Reverse table using While Loop
  • Print table using While Loop
  • Covert Decimal to Binary using While Loop

Looping Statements in C

For loop example programs.

  • Print Value upto limit
  • Print Number upto limit
  • Armstrong Number using For Loop
  • Square Pattern using For Loop
  • Flag Pattern using For Loop
  • Diamond Pattern using For Loop
  • Triangle Facing Downward using For Loop
  • Triangle Facing upside using For Loop
  • Right Angle Triangle facing left
  • Right Angle Triangle facing right
  • Reverse Number using For Loop
  • Prime Number using For Loop
  • Print Number divisible by 7
  • Print tables using For Loop
  • Reverse tables using For Loop
  • Separate odd and even numbers
  • Check prime or composite number
  • Separate positive and negative number
  • For Loop Patterns
  • Square Pattern Outline using For Loop
  • Triangle Outline Pattern
  • Diamond Pattern Outline

Array Examples in C

One dimensional array.

  • Add Elements to the Array
  • Arrange array elements in Ascending
  • Arrange array elements in Descending
  • Insert an element using Array
  • Update an element using Array
  • Delete an element using Array
  • Interchange an element using Array
  • Reverse an element using Array
  • Odd or Even Number using Array
  • Positive and Negative Numbers using Array
  • Armstrong Number 100 to 999
  • Greatest Number using Array
  • Smallest Number using Array
  • Print values divisible by 7 using Array
  • Convert binary to decimal using Array
  • Convert decimal to binary using Array
  • Convert decimal to octal using Array

Two Dimensional Array in C

  • Print Two Dimensional Array
  • Array Addition in Two-Dimenional Array
  • Array Subtraction in Two-Dimensional Array
  • Array Multiplication using Array
  • Lower Triangular Matrix using Array
  • Upper Triangluar Matrix using Array
  • Print Unit Matrix using Array
  • Check and Print Unit Matrix

String Example Programs in C

  • Print text using String
  • String Example
  • String Comparison in C
  • String Concatenation in C
  • String Copy Example in C
  • Convert Uppercase to Lowercase
  • Remove Duplicate String
  • Reverse text using String
  • Toggle Case using String
  • Conver text into Capital or Small
  • Convert Lowercase to Uppercase
  • Convert text into Ascending Order using
  • Capitalising the first letter
  • Check given strings Equal or Not
  • Copy String using Predefined Function
  • String Length using Predefined Function
  • String Length without Predefined Function
  • Uppercase to Lowercase using Predefined Function
  • Check Palindrome or Not

Functions Example Programs in C

  • Addition using return type and arguments
  • Print marks using return type & arguments
  • Function with no return and with arguments in c
  • Print tables without arguments

Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions

C Programming Tutorial

  • Assignment Operator in C

Last updated on July 27, 2020

We have already used the assignment operator ( = ) several times before. Let's discuss it here in detail. The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows:

The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression. Here are some examples:

x = 18 // right operand is a constant y = x // right operand is a variable z = 1 * 12 + x // right operand is an expression

The precedence of the assignment operator is lower than all the operators we have discussed so far and it associates from right to left.

We can also assign the same value to multiple variables at once.

here x , y and z are initialized to 100 .

Since the associativity of the assignment operator ( = ) is from right to left. The above expression is equivalent to the following:

Note that expressions like:

x = 18 y = x z = 1 * 12 + x

are called assignment expression. If we put a semicolon( ; ) at the end of the expression like this:

x = 18; y = x; z = 1 * 12 + x;

then the assignment expression becomes assignment statement.

Compound Assignment Operator #

Assignment operations that use the old value of a variable to compute its new value are called Compound Assignment.

Consider the following two statements:

x = 100; x = x + 5;

Here the second statement adds 5 to the existing value of x . This value is then assigned back to x . Now, the new value of x is 105 .

To handle such operations more succinctly, C provides a special operator called Compound Assignment operator.

The general format of compound assignment operator is as follows:

where op can be any of the arithmetic operators ( + , - , * , / , % ). The above statement is functionally equivalent to the following:

Note : In addition to arithmetic operators, op can also be >> (right shift), << (left shift), | (Bitwise OR), & (Bitwise AND), ^ (Bitwise XOR). We haven't discussed these operators yet.

After evaluating the expression, the op operator is then applied to the result of the expression and the current value of the variable (on the RHS). The result of this operation is then assigned back to the variable (on the LHS). Let's take some examples: The statement:

is equivalent to x = x + 5; or x = x + (5); .

Similarly, the statement:

is equivalent to x = x * 2; or x = x * (2); .

Since, expression on the right side of op operator is evaluated first, the statement:

is equivalent to x = x * (y + 1) .

The precedence of compound assignment operators are same and they associate from right to left (see the precedence table ).

The following table lists some Compound assignment operators:

Operator Description
equivalent to
equivalent to
equivalent to
equivalent to

The following program demonstrates Compound assignment operators in action:

#include<stdio.h> int main(void) { int i = 10; char a = 'd'; printf("ASCII value of %c is %d\n", a, a); // print ASCII value of d a += 10; // increment a by 10; printf("ASCII value of %c is %d\n", a, a); // print ASCII value of n a *= 5; // multiple a by 5; printf("a = %d\n", a); a /= 4; // divide a by 4; printf("a = %d\n", a); a %= 2; // remainder of a % 2; printf("a = %d\n", a); a *= a + i; // is equivalent to a = a * (a + i) printf("a = %d\n", a); return 0; // return 0 to operating system }

Expected Output:

ASCII value of d is 100 ASCII value of n is 110 a = 38 a = 9 a = 1 a = 11

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

DataFlair

  • C Tutorials

Arithmetical Assignment Operators in C

In the realm of programming, effectiveness and clarity play pivotal roles. To streamline code and make it more concise, programmers often utilize assignment operators. Among these, arithmetical assignment operators hold a special place. They combine arithmetic operations with assignments, allowing for efficient and cleaner code. In this piece, we will delve into the realm of arithmetical assignment operators within the context of C programming. We will uncover their purpose, how to use them effectively, and the advantages they bring, all while offering simplified examples catered to beginners, ensuring a seamless learning experience.

Understanding Arithmetical Assignment Operators

Arithmetical assignment operators are shorthand notations that perform arithmetic operations and assignments in a single step.

These operators include:

  • += (Add and Assign)
  • -= (Subtract and Assign)
  • *= (Multiply and Assign)
  • /= (Divide and Assign)
  • %= (Modulus and Assign)

arithmetic operators in c

For instance, using +=, you can add a value to a variable without needing a separate assignment statement. Similarly, the other operators work by performing the respective operation and updating the variable’s value directly.

left right operand

OperatorOperationExample
+AdditionX + Y = 42
SubtractionX – Y = -18
*MultiplicationX * Y = 315
/DivisionY / X = 7
%Modulus (Remainder)Y % X = 0
++Increment (Increase by One)X++ = 8
Decrement (Decrease by One)X– = 6
Operator nameOperatorDescriptionEquivalentExample
Basic assignment=Assign the value of n to mN/Am = n
Addition assignment+=Adds the value of n to m and assigns the result to mm = m + nm += n
Subtraction assignment-=Subtracts the value of n from m and assigns the result to mm = m – nm -= n
Multiplication assignment*=Multiplies the value of m by n and assigns the result to mm = m * nm *= n
Division assignment/=Divide the value of m by n and assign the result to mm = m / nm /= n
Modulo assignment%=Calculates the remainder of m divided by n and assigns it to mm = m % nm %= n

Usage of Arithmetical Assignment Operators

The primary advantage of using arithmetical assignment operators is code simplicity. They reduce the need for separate lines of code for arithmetic operations and assignments. This improves code readability while lowering the likelihood of mistakes brought on by forgotten assignments.

Consider this example:

Technology is evolving rapidly! Stay updated with DataFlair on WhatsApp!!

// Without arithmetical assignment operator x = x + 5;

// With arithmetical assignment operator x += 5;

The second approach is not only shorter but also more intuitive, as it directly communicates the intent.

Let’s explore arithmetical assignment operators through some examples:

Output: The number of apples left after eating is 13.

Subtraction:

Output: Total is now 80.

Multiplication:

Output: quantity is now 12.

Output: value is now 25.0.

Output: dividend is now 2.

Original total amount: 100 After adding incremental: 125 After subtracting incrementValue: 100 After multiplying by incrementValue: 2500 After dividing by incrementValue: 100 After getting remainder by incrementValue: 0

These examples show how, depending on the operation, the arithmetical assignment operators change the value of the variable they are applied to.

Common Mistakes and Pitfalls

While arithmetical assignment operators can simplify code, beginners should be cautious about data types. Mixing incompatible data types can lead to unexpected results. Also, remember that the order of operations still matters.

Performance Considerations

In addition to improving code readability, using arithmetical assignment operators can improve efficiency.These operators can be efficiently optimised by contemporary compilers, which lowers memory and computation overhead.

Arithmetical assignment operators are a powerful tool in a programmer’s arsenal. By combining arithmetic operations and assignments, they make code more elegant and efficient. From novice programmers to seasoned developers, anyone can benefit from incorporating these operators into their coding practices. So go ahead, simplify your code and make your programming journey smoother with arithmetical assignment operators in C.

We work very hard to provide you quality material Could you take 15 seconds and share your happy experience on Google

courses

Tags: arithmetic assignment operator in c arithmetic operator in c assignment operator in c operator in c

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • C – Introduction
  • C – Features
  • C – Pros & Cons
  • C – Applications
  • C – Installation
  • Why C is Popular
  • C – Preprocessors
  • C/C++ Header Files
  • C – Structure of Program
  • C – Escape Sequence
  • C – Structures
  • C – Bit Fields
  • C – Binary Tree
  • C/C++ Operators
  • C/C++ Strings
  • C/C++ Arrays
  • C/C++ Multi-dimensional Arrays
  • C/C++ Variables
  • C/C++ Constants & Literals
  • C/C++ Data Types
  • C/C++ Loops
  • C/C++ Functions
  • C/C++ Pointer
  • C/C++ Recursion
  • C/C++ typedef
  • C/C++ Typecasting
  • C/C++ Linked List
  • C/C++ Stacks
  • C/C++ Queue
  • C – File Handling
  • C – Standard Library Functions
  • C – Command Line Arguments
  • C – Error Handling
  • C – Popular Programs
  • C/C++ Career Opportunities
  • C – Best Practices
  • C Interview Que. for Freshers
  • C Interview Que. for Experienced
  • C Quiz Part – 1
  • C Quiz Part – 2
  • C Quiz Part – 3
  • C++ Introduction
  • C++ Features
  • C++ Pros & Cons
  • C++ Application
  • C++ Installation
  • C++ Namespace
  • C++ Class & Object
  • C++ Polymorphism
  • C++ Data Abstraction
  • C++ Encapsulation
  • C++ Inheritance
  • C++ Virtual Function
  • C++ Inline Function
  • C++ Friend Function
  • C++ Interfaces
  • C++ Data Strcutures
  • C++ Exception Handling
  • C++ Template
  • C++ Overloading
  • C++ Constructors & Destructor
  • C++ Dynamic Memory Allocation
  • C++ Interview Que. for Freshers
  • C++ Interview Que. for Experienced

job-ready courses

Home » Learn C Programming from Scratch » C Arithmetic operators

C Arithmetic operators

Summary : in this tutorial, you’ll learn about the arithmetic operators in C for performing arithmetic calculations.

Introduction to the C arithmetic operators

C supports common arithmetic operators such as addition, subtraction, multiplication, and division. The folllowing table illustrates some arithmetic operators in C:

+Addition5 + 3 = 8
Subtraction5 – 3 = 2
*Multiplication5 * 3 = 15
/Division5 / 3 = 1 (for integer)
%Modulo (return the remainder of a division of two integers)5 % 3 = 2

All arithmetic operators above accepts two operand and return the result.

The following example uses the above arithmetic operators on integers:

It’s important to note that the % operator is relevant to the floating-point numbers only suchas float, double, and long double.

The followning example applies the arithmetic operators to floats:

Increment operators in C

The increment operator adds one to an operand. Unlike the +, -, *, /, and % operators, the increment operator accepts one operand.

The increment operator has two forms: prefix and postfix:

In the prefix form, you place the ++ in front of an operand like this:

And in the postfix form, you place the ++ after the operator as follows:

Both forms add one to the variable_name . And they’re equivalent to the following:

The ++variable_name is called a pre-increment and variable_name++ is called post-increment.

The following program illustrates how to use the increment opertors:

The difference between ++x and x++

The different between the postfix and prefix is the order of using the value and increment it. It’s more obvious if you use the preincrement and post-increment in an expression.

In this example, the increment operator adds one to x and assign the result to y.

In this example, the increment operator assign x to y and add one to x.

The following program illustrates the difference between preincrement and postincrement operators:

Decrement operators in C

Like the increment operators, C also has decrement operators in both prefix and postfix forms:

The predecrement operator subtract one from the variable and returns the result while the postdecrement operator returns the value of the variable before subtracting one from it.

The following program illustrates the decrement operators and the difference between the predecrement and postdecrement operators:

C Arithmetic operator’s precedence and associativity

Let’s discuss the arithmetic operators’ precedence and associativity.

Arithmetic operator precedence

When you use multiple arithmetic operators in an expression, C evaluates the expression based on the order of precedence of the operators. It works like Math. For example:

C will evaluate the multiplication operator before the addition operator. The result will be 11.

To change the order of evaluation, you use parentheses like this:

Now, C evaluates the addition operator first due to the parentheses and the multiplication operator after that. The result will be 30.

The precedences of the arithmetic operators from high to low:

OperatorPrecedence
++, — ( both prefix, suffix forms)3
*, /, %2
+,-1

Arithmetic operator associativity

The associativity of an operator determines how C groups the operators of the same precedence when the expression doesn’t have parentheses.

The arithmetic operators such as addition, subtraction, multiplication, and division are left-associative. It means that C group operations from the left.

  • The arithmetic operators such as +, -, *, /, and % take two operands and return the result.
  • The modulo operator (%) only relevant to integers.
  • The increment / decrement operators add one to / subtract one from an operand. They support both prefix and postfix forms.
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Compound Assignment Operators in C

What is the output of the following program, and why?

Nick is tired's user avatar

  • 2 undefined behavior i think because there are multiple assignment and reads of the same value in the same line –  Tyker Commented May 30, 2018 at 10:55
  • 2 Not a duplicate but please read Why are these constructs (using ++) undefined behavior in C? . –  Lundin Commented May 30, 2018 at 11:22
  • 3 Everyone: can't close this as "unclear". It is perfectly clear and contains a MCVE. I was trigger-happy myself and closed as dupe to i++ questions but it is not a good dupe so I re-opened it. "I find this newbie FAQ uninteresting" is not a valid close reason. Either find a good duplicate or stay clear of the question. Voting to re-open. –  Lundin Commented May 30, 2018 at 11:32
  • 2 @EricPostpischil I disagree. Especially since one of the reasons to vote down is "does not show any research effort" which this question clearly does not. –  klutt Commented May 30, 2018 at 13:59
  • 2 @klutt: Asking somebody to do something productive might be reasonable. Asking somebody to do an unproductive task is not. It serves no purpose, wastes time and effort, and misleads people about what methods are useful for finding information. If you had asked not what output they get but rather what documents did they search for information, you might have established a lack of effort. But asking for somebody to do something useless is nothing more than ask them to perform for your entertainment. –  Eric Postpischil Commented May 30, 2018 at 15:16

3 Answers 3

The behaviour of your program is undefined as you are reading from and writing to a in an unsequenced step.

What your ancient compiler is doing is correctly following the C grammar rules and is grouping the expression as

But grouping is not the same as sequencing . From this point the behaviour is undefined. Your compiler appears to evaluate the above to

followed by

to yield 28 .

Bathsheba's user avatar

  • What is now undefined? Can you give an example of another outcome? –  Paul Ogilvie Commented May 30, 2018 at 11:01
  • @PaulOgilvie: I've clarified that. Another outcome is that the compiler eats my cat. –  Bathsheba Commented May 30, 2018 at 11:02
  • 1 The value of a is only required to be written once in the whole statement. Since the grouping implies writing a value to it more than once, those writes are unsequenced, and the behaviour is undefined. –  Peter Commented May 30, 2018 at 11:04
  • 2 This answer would be better if you'd just leave the first paragraph, and remove any attempt to reason with undefined behaviour. In it's current state your answer implies that 28 is predictable outcome, when predictable outcome is impossible. –  user694733 Commented May 30, 2018 at 11:12
  • 1 @user694733: I know, rationalising UB is an automatic -1. I feel you can sort of get away with it if you stick to a particular toolchain (here conio.h is the clue). Tell you what, I'll put a line in the answer. –  Bathsheba Commented May 30, 2018 at 11:17

This is a tough question without an easy, obvious answer.

The expression is probably undefined, in which case it's meaningless to ask "what could be the possible output?", because it could be anything .

If it's undefined, it's because there are multiple writes (stores) to a without any intervening sequence points. The rightmost a += 2 computes 7 and prepares to store it into a . Next we have the middle a += , which tries to take the 7 and add it to... what? The old or the new value of a ? If it's the old we compute 5+7= 12 and if it's the new we compute 7+7=14, and whichever value we compute, we prepare to store it into a , but does it "win" and overwrite the value that the rightmost a += 2 tried to store, or not? And then the arguments (and the multiplicity of different interpretations and possible answers) proliferate for the leftmost a += .

Not all assignment expressions are undefined, of course. For example, the old standby

is well-defined. It both fetches from a and assigns to a , but in this case we don't have to ask, "what if it assigns to a before it fetches from it?", because obviously, it has to fetch from a first, in the process of computing the new value to be assigned. But this argument doesn't rescue a += a += 2 , I don't think.

There are newer rules about "sequencing" which do away with the old concept of "sequence points", and the new rules might render this expression well-defined, but I'm not sure.

Unless you're interested in frustrating, head-banging puzzles, it's best to steer clear of expressions like this one. You obviously wouldn't have any use for an expression like this in a real program. It's nearly impossible to figure out (a) if the expression is well-defined and (b) if so, what it's supposed to do, so a program containing an expression like this is unmaintainable; you have to be a hard-core language lawyer to properly understand it.

Naturally it's important to understand how simpler, saner expressions like a += 2 or x += y[i++] work. But for something insane like a += a += a += 2 , don't fall into the trap of asking "Wouldn't it help me understand C better if I understand what it means?", because the only thing to understand is that it's borderline, if not absolutely, meaningless.

See also SO's canonical entry on undefined expressions, Why are these constructs (using ++) undefined behavior in C? (although none of the answers there cover this particular case).

Steve Summit's user avatar

It depends on the compiler ! But theoretically 28 is the answer ! The assignment will be from right to left so a +=a += a += 2; can be break down as

Bharadwaj's user avatar

  • Where is left for you? –  Gerard H. Pille Commented May 30, 2018 at 10:58

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c operators or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • What is the source for the teaching, ‘Shame is intelligence, intelligence shame’?
  • Sharing course material from a previous lecturer with a new lecturer
  • Applying for ESTA after rejection but subsequent B visa grant
  • Why did Borland ignore the Macintosh market?
  • Sci-fi movie about a woman alone on a spaceship with an AI
  • Will I have to disclose traffic tickets to immigration (general)
  • Birthday of combinatorial game product
  • Indian passport holder - Schengen visa extension
  • Can a Promethean's transmutation dramatic failure be used to benefit the Promethean?
  • What was I thinking when I drew this diagram?
  • A post-apocalyptic short story where very sick people from our future save people in our timeline that would be killed in plane crashes
  • Ripple counter from as few transistors as possible
  • Reference Request: Suttas that address avijja (ignorance) with respect to anatta (non-self)
  • Can you continue a database log restore after putting an interim restore online?
  • Why didn't Walter White choose to work at Gray Matter instead of becoming a drug lord in Breaking Bad?
  • How to define a function in Verilog?
  • Why is Excel not counting time with COUNTIF?
  • Embedding rank of finite groups and quotients
  • Could a 3D sphere of fifths reveal more insights than the 2D circle of fifths?
  • Is there a limit to how much power could be transmitted wirelessly?
  • Using elastic-net only for feature selection
  • Concise zsh regular expression parameter expansion to replace the last match of a pattern
  • Did Newton predict the deflection of light by gravity?
  • Does full erase create all 0s or all 1s on the CD-RW?

choose correct syntax for c arithmetic compound assignment operators

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

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 becomes equal to
+= addition assignment a += b becomes equal to the addition of and a = a + b
-= subtraction assignment a -= b becomes equal to the subtraction of from a = a - b
*= multiplication assignment a *= b becomes equal to the product of and a = a * b
/= division assignment a /= b becomes equal to the division of by a = a / b
%= modulo assignment a %= b becomes equal to the remainder of divided by a = a % b
&= bitwise AND assignment a &= b becomes equal to the bitwise AND of and a = a & b
|= bitwise OR assignment a |= b becomes equal to the bitwise OR of and a = a | b
^= bitwise XOR assignment a ^= b becomes equal to the bitwise XOR of and a = a ^ b
<<= bitwise left shift assignment a <<= b becomes equal to left shifted by a = a << b
>>= bitwise right shift assignment a >>= b becomes equal to right shifted by a = a >> b
Simple assignment Notes Compound assignment References See Also See also

[ edit ] Simple assignment

The simple assignment operator expressions have the form

lhs rhs
lhs - expression of any complete object type
rhs - expression of any type to lhs or with lhs

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)
has type (possibly qualified or atomic(since C11)) _Bool and rhs is a pointer or a value(since C23) (since C99)
has type (possibly qualified or atomic) and rhs has type (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

lhs op rhs
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
lhs, rhs - expressions with (where lhs may be qualified or atomic), except when op is += or -=, which also accept pointer types with the same restrictions as + and -

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

If lhs has type, the operation behaves as a single atomic read-modify-write operation with memory order .

For integer atomic types, the compound assignment @= is equivalent to:

addr = &lhs; T2 val = rhs; T1 old = *addr; T1 new; do { new = old @ val } while (! (addr, &old, new);
(since C11)

[ 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

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b

a[b]
*a
&a
a->b
a.b

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

[ edit ] See also

for Assignment operators
  • 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.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

choose correct syntax for c arithmetic compound assignment operators

  • 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.12 Method Signatures (preview 2026 curriculum)
  • 1.13 Calling Class Methods (preview 2026 curriculum)
  • 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!

Operator

Written out

= x + 1

= x - 1

= x * 2

= x / 2

= x % 2

Compound

+= 1

-= 1

*= 2

/= 2

%= 2

Extra concise

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.

logo

Have an account?

Suggestions for you See more

Quiz image

Principles of Programming Languages

University  , java arrays, java programming, java operators, c programming, professional development  , pointers in c, python basics, 12.3k plays, iterative statements in python.

pencil-icon

52 questions

Player avatar

Introducing new   Paper mode

No student devices needed.   Know more

Choose a right C Statement.

Loops or Repetition block executes a group of statements repeatedly.

Loop is usually executed as long as a condition is met.

Loops usually take advantage of Loop Counter

All the above.

What is the output of C Program.?

while(a >= 3);

printf("RABBIT\n");

printf("GREEN");

RABBIT GREEN

RABBIT is printed infinite times

None of the above

while(a <= 27)

printf("%d ", a);

Compiler error

while(a <= 30);

if(a > 35)

32 33 34 35

Choose a correct C Statement.

a++ is (a=a+1) POST INCREMENT Operator

a-- is (a=a-1) POST DECREMENT Operator

--a is (a=a-1) PRE DECREMENT Operator

++a is (a=a+1) PRE INCREMENT Operator

Choose correct Syntax for C Arithmetic Compound Assignment Operators.

a+=b is (a= a+ b)

a-=b is (a= a-b)

a*=b is (a=a*b)

a/=b is (a = a/b)

a%=b is (a=a%b)

for(k=1, j=10; k <= 5; k++)

printf("%d ", (k+j));

compiler error

10 10 10 10 10

10 11 12 13 14 15

for(k=1; k <= 5; k++);

printf("%d ", k);

printf("TESTING\n");

for(printf("FLOWER "); printf("YELLOW "); printf("FRUITS "))

} return 0;

FLOWER FRUITS

FLOWER YELLOW

FLOWER YELLOW FRUITS

Loops in C Language are implemented using.?

While Block

Do While Block

All the above

What is the way to suddenly come out of or Quit any Loop in C Language.?

continue; statement

break; statement

leave; statement

quit; statement

Which loop is faster in C Language, for, while or Do While.?

all of the above

Choose correct C while loop syntax.

while(condition) { //statements }

{ //statements }while(condition)

while(condition); { //statements }

while() { if(condition) { //statements } }

Choose a correct C for loop syntax.

for(initalization; condition; incrementoperation) { //statements }

for(declaration; condition; incrementoperation) { //statements }

for(declaration; incrementoperation; condition) { //statements }

for(initalization; condition; incrementoperation;) { //statements }

Choose a correct C do while syntax.

dowhile(condition) { //statements }

do while(condition) { //statements }

do { //statements }while(condition)

do { //statements }while(condition);

while(true)

printf("RABBIT");

RABBIT is printed unlimited number of times.

Compiler error.

while(a==5)

RABBIT is printed unlimited number of times

None of the above.

while(a=123)

int a = 10, b = 25;

a = b++ + a++;

b = ++b + ++a;

printf("%d %d n", a, b);

#include<stdio.h>

float a=0.7;

if(a<0.7)

printf("C");

printf("C++");

Compilation Error

None of the these

int main ()

int x = 24, y = 39, z = 45;

printf ("n%d %d %d", x, y, z);

int main() {

int m = -10, n = 20;

n = (m < 0) ? 0 : 1;

printf("%d %d", m, n);

int x = 0, y = 0;

if(x > 0)

if(y > 0)

printf("True");

printf("False");

Error because of dangling else problem

int a = 1, b=2, c=3;

char d = 0;

if(a,b,c,d)

printf("EXAM");

No Output and No Error

Run time error

Compile time error

int a=2,b=7,c=10;

printf("%d",c);

Compilation error

What will be output of the following c program?

int max-val=100;

int min-val=10;

int avg-val;

avg-val = max-val + min-val / 2;

printf("%d",avg-val);

An external variable is one

Which resides in the memory till the end of the program

Which is globally accessible by all functions

Which is declared outside the body of any function

All of the above

When applied to a variable, what does the unary "&" operator yield?

The variable's address

The variable's right value

The variable's binary form

The variable's value

Which are built-in data structures in C programming?

The size of a character variable in C is

An expression contains relational, assignment and arithmetic operators. If parenthesis are not specified, the order of evaluation of the operators would be:

assignment, arithmetic, relational

relational, assignment, arithmetic

assignment, relational, arithmetic

arithmetic, relational, assignment

Given two literals 0x001B and 033. What are these equal to?

What is the outpur of the following code segment (assuming sizeof(int) returns 4)?

int i=0x1 << sizeof(int) * 8-1;

printf("\n%x", i);

i = i >> sizeof(int) * 8-1;

printf("%d", i);

0x8000000-1

-1 0x0000000

Which is the correct sequence statements that swaps values of two statements?

a=a+b; a=a-b; b=a-b;

a=a+b, b=a-b; a=a-b;

a=a-b; a=a+b; b=b-a;

None of these

Choose the option that contains only Unary operators of C:

sizeof, (type conversion)

short hand operator, &

increment(++), >=, !

What is the value of this expression using integer arithmetic:

What is the value of a in this code fragment

int a=3, b;

Determine the value of this expression using integer arithmetic:

Determine the value of b in this code fragment:

Determine the value of the expression using integer arithmetic:

6 * 9 % 3 / 2

Determine the value of a in the second line of the code fragment:

int a=1, b=2;

Determine the value of b in the second line of the code fragment:

Which line of code is correct for the statement:

Add 1 variable to x.

Which line of code is incorrect for the statement:

Subtract 4 from the variable y.

Read in a value for the integer variable num .

printf("%d", &num);

scanf("%d", num);

scanf("%d", &num);

What is the EXACT output from this code fragment:

float num=3.238;

printf("num=%.2f", num);

int num=10;

if(num> 7 % 3 / 2 * 3)

printf("This is True");

printf("This is False");

This is True

This is False

What symbol is used in conditional operators for AND:

What will be printed on the screen from this fragment:

printf("%d", ++num)

What is the abbreviated way to write this assignment statement:

total=total+num;

total=(total+num)

Explore all questions with a free account

Google Logo

Continue with email

Continue with phone

a+=bis (a= a+ b) a-=b is (a= a-b)

a*=b is (a=a*b) a/=b is (a = a/b)

a%=b is (a=a%b)

All of the above

Posted under Control Flow Statements in C C Programming

Engage with the Community - Add Your Comment

Confused About the Answer? Ask for Details Here.

Know the Explanation? Add it Here.

Q. Choose correct Syntax for C Arithmetic Compound Assignment Operators.

Similar questions, discover related mcqs.

Q. Choose a correct C do while syntax.

View solution

Q. Choose a correct C for loop syntax.

Q. Choose correct C while loop syntax.

Q. Which loop is faster in C Language, for, while or Do While?

Q. Loops in C Language are implemented using?

Q. Choose a right C Statement.

Q. Choose a correct C Statement.

Q. Choose a correct C Operator Priority? Items in one group ( ) has same priority.

Q. What is the Priority of C Logical Operators? NOT (!), AND (&&) and OR (||)

Q. In _______, the bodies of the two loops are merged together to form a single loop provided that they do not make any references to each other.

Q. In the context of "break" and "continue" statements in C, pick the best statement.

Q. Which of the following statement about for loop is true ?

Q. For loop in a C program, if the condition is missing?

Q. c = (n) ? a : b; can be rewritten as exp1 ? exp2 : exp3;

Q. do-while loop terminates when conditional expression returns?

Q. A labeled statement consist of an identifier followed by

Q. Which loop is guaranteed to execute at least one time.

Q. goto can be used to jump from main to within a function?

Q. The continue statment cannot be used with

Q. In the following loop construct, which one is executed only once always. for(exp1; exp2; exp3)

Suggested Topics

Are you eager to expand your knowledge beyond C Programming? We've curated a selection of related categories that you might find intriguing.

Click on the categories below to discover a wealth of MCQs and enrich your understanding of Computer Science. Happy exploring!

choose correct syntax for c arithmetic compound assignment operators

IT Fundamentals

Navigate the basics of information technology with our IT Fundamentals MCQs. Get a...

choose correct syntax for c arithmetic compound assignment operators

Hone your computational mathematics skills with our MATLAB MCQs. Understand...

choose correct syntax for c arithmetic compound assignment operators

Data Science

Discover the fascinating world of extracting insights from data with our Data Science...

choose correct syntax for c arithmetic compound assignment operators

Learn the leading NoSQL database with our MongoDB MCQs. Understand everything from...

choose correct syntax for c arithmetic compound assignment operators

Become proficient with the Unix operating system using our UNIX MCQs. Learn about...

choose correct syntax for c arithmetic compound assignment operators

Dive into the world of big data with our Hadoop MCQs. Cover key concepts including...

choose correct syntax for c arithmetic compound assignment operators

Visual Basic

Enhance your knowledge of Microsoft's event-driven programming language with our...

choose correct syntax for c arithmetic compound assignment operators

Management Information Systems

Discover how businesses leverage technology with our Management Information Systems...

choose correct syntax for c arithmetic compound assignment operators

Wireless and Mobile Communications

Get to grips with modern communication technologies with our Wireless and Mobile...

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

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. The following are all possible assignment operator in java:

Implementation of all compound assignment operator

Rules for resolving the Compound assignment operators

At run time, the expression is evaluated in one of two ways.Depending upon the programming conditions:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set, and the result of the conversion is stored into the variable.
  • First, the array reference sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index sub-expression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, if the value of the array reference sub-expression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference sub-expression indeed refers to an array. If the value of the index sub-expression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an ArrayIndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index sub-expression is used to select a component of the array referred to by the value of the array reference sub-expression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Examples : Resolving the statements with Compound assignment operators

We all know that whenever we are assigning a bigger value to a smaller data type variable then we have to perform explicit type casting to get the result without any compile-time error. If we did not perform explicit type-casting then we will get compile time error. But in the case of compound assignment operators internally type-casting will be performed automatically, even we are assigning a bigger value to a smaller data-type variable but there may be a chance of loss of data information. The programmer will not responsible to perform explicit type-casting. Let’s see the below example to find the difference between normal assignment operator and compound assignment operator. A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

For example, the following code is correct:

and results in x having the value 7 because it is equivalent to:

Because here 6.6 which is double is automatically converted to short type without explicit type-casting.

Refer: When is the Type-conversion required?

Explanation: In the above example, we are using normal assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) that’s results in compile time error. Here we have to do type-casting to get the result.

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 compile. Here we don’t have to do type-casting to get the result.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

Please Login to comment...

Similar reads.

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. Solved Choose correct Syntax for C Arithmetic Compound

    Your solution's ready to go! Enhanced with AI, our expert help has broken down your problem into an easy-to-learn solution you can count on. See Answer See Answer See Answer done loading

  2. C Compound Assignment

    The result of a compound-assignment operation has the value and type of the left operand. #define MASK 0xff00 n &= MASK; 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. See also. C Assignment Operators

  3. Operators in C (Examples and Practice)

    Learn about all the different types of operators available in C like Arithmetic, Assignment, Relational and Logical operators. Practice Problems to solidify your knowledge. ... In the division example (a / b), you might notice that the result is 3, not 3.33. This is because when you divide two integers in C, the result is also an integer ...

  4. Assignment Operators in C

    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 value of the variable on left to the value on the right and then assigns the result to the variable on the left.

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

  6. C Assignment Operators

    Code language:C++(cpp) The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand. Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the ...

  7. C

    A special case scenario for all the compound assigned operators. int i= 2 ; i+= 2 * 2 ; //equals to, i = i+(2*2); 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 ...

  8. What Is a Compound-Assignment Operator?

    Compound-Assignment Operators in Java. Java supports 11 compound-assignment operators: += assigns the result of the addition. -= assigns the result of the subtraction. *= assigns the result of the multiplication. /= assigns the result of the division. %= assigns the remainder of the division. &= assigns the result of the logical AND.

  9. 4.4: Arithmetic Assignment Operators

    The five arithmetic assignment operators are a form of short hand. Various textbooks call them "compound assignment operators" or "combined assignment operators". Their usage can be explaned in terms of the assignment operator and the arithmetic operators. In the table we will use the variable age and you can assume that it is of integer data type.

  10. Using Compound Assignment Operators in C: A Beginner's Guide

    The code is a C program that demonstrates the use of compound assignment operators in C. Here is an explanation of each line of the code: int a=10,b=5; declares two variables a and b of type int and assigns them the values 10 and 5 respectively. a+=b; is the compound assignment operator +=, it performs a+b and assigns the value to a. It is equivalent to a=a+b.

  11. Assignment Operator in C

    The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows: variable = right_side. The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression. Here are some examples:

  12. Arithmetical Assignment Operators in C

    Arithmetical assignment operators are shorthand notations that perform arithmetic operations and assignments in a single step. These operators include: For instance, using +=, you can add a value to a variable without needing a separate assignment statement. Similarly, the other operators work by performing the respective operation and updating ...

  13. C Arithmetic Operators

    Code language: C++ (cpp) C Arithmetic operator's precedence and associativity. Let's discuss the arithmetic operators' precedence and associativity. Arithmetic operator precedence. When you use multiple arithmetic operators in an expression, C evaluates the expression based on the order of precedence of the operators. It works like Math ...

  14. Compound Assignment Operators in C

    What your ancient compiler is doing is correctly following the C grammar rules and is grouping the expression as. a += (a += (a += 2)) But grouping is not the same as sequencing. From this point the behaviour is undefined. Your compiler appears to evaluate the above to. a += (a += 7) followed by. a += 14.

  15. Compound Assignment Operator in C with Example

    In this video we are going to study about.. Assignment Operator in C Assignment Operator Example Use of Assignment Operator in CCompound Assignment Operato...

  16. #21

    Study with Quizlet and memorize flashcards containing terms like What do compound assignment operators do?, What are the compound assignment operators for the following: Addition Subtraction Multiplication Division Modulo, SECTION REVIEW1A: #1) You are also in charge of keeping track of how many cookies there are at the bake sale. This value is represented by the number of numCookies.

  17. Assignment operators

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

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

  19. c

    Choose correct Syntax for C Arithmetic Compound Assignment Operators. a+=b is (a= a+ b) a-=b is (a= a-b) ... assignment and arithmetic operators. If parenthesis are not specified, the order of evaluation of the operators would be: ... What is the abbreviated way to write this assignment statement: total=total+num; t=t+n; total+=num. total ...

  20. Choose correct Syntax for C Arithmetic Compound Assignment Operators

    Dive into the world of Artificial Intelligence with our Neural Networks MCQs. Uncover... Choose correct Syntax for C Arithmetic Compound Assignment Operators. a+=bis (a= a+ b) a-=b is (a= a-b) a*=b is (a=a*b) a/=b is (a = a/b) a%=b is (a=a%b) All of the above. C Programming Objective type Questions and Answers.

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

  22. 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. ... For example, the following code is correct: short x = 4; x += 6.6;

  23. Choose correct Syntax for C Arithmetic Compound Assignment Operators.A

    Compound Assignment Operator: These operators combine the simple-assignment operator with another binary operator. Compound assignment operators execute the action provided by the extra operator before assigning the result to the left operand. for eg. exp1 += exp2. All the options are following the above format so D is correct