C Programming
In this tutorial we will learn about assignment operators in C programming language.
We use the assignment operators to assign the result of an expression to a variable.
In the following example we are assigning integer value 10 to a variable score of data type integer.
int score = 10;
Lets say we have an integer variable and we have initially assigned 10 to it. Then lets say we increase the value by 5 and assign the new value to it.
//declare and set value int x = 10; //increase the value by 5 and re-assign x = x + 5;
Another way to write the code x = x + 5 is by using the shorthand assignment += as shown below.
x = x + 5
+=
//declare and set value int x = 10; //increase the value by 5 and re-assign x += 5;
Following is a list of shorthand assignment operators.
In the following example we are taking a value x from user then we are taking a new value y from user. Then we are adding y to x and assigning the result to x. Finally we are printing the new value stored in variable x.
#include <stdio.h> int main(void) { int x, y; printf("Enter the value of x: "); scanf("%d", &x); printf("Enter the value of y: "); scanf("%d", &y); // add y to x and re-assign x = x + y; printf("New value of x: %d\n", x); return 0; }
Output
Enter the value of x: 10 Enter the value of y: 20 New value of x: 30
Another way of adding y to x and re-assigning the new value to x is by using the shorthand assignment operator +=.
#include <stdio.h> int main(void) { int x, y; printf("Enter the value of x: "); scanf("%d", &x); printf("Enter the value of y: "); scanf("%d", &y); // add y to x and re-assign x += y; printf("New value of x: %d\n", x); return 0; }