CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assignment Operators in C

In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression.

The value to be assigned forms the right-hand operand, whereas the variable to be assigned should be the operand to the left of the " = " symbol, which is defined as a simple assignment operator in C.

In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Simple Assignment Operator (=)

The = operator is one of the most frequently used operators in C. As per the ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed.

You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable, or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented Assignment Operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression "a += b" has the same effect of performing "a + b" first and then assigning the result back to the variable "a".

Run the code and check its output −

Similarly, the expression "a <<= b" has the same effect of performing "a << b" first and then assigning the result back to the variable "a".

Here is a C program that demonstrates the use of assignment operators in C −

When you compile and execute the above program, it will produce the following result −

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Mostly Asked C Interview Questions and Answers

02 Beginner

  • Understanding do...while loop in C
  • If...else statement in C Programming
  • If Statement in C
  • Understanding realloc() function in C
  • Understanding While loop in C
  • Why C is called middle level language?
  • Arithmetic Operators in C Programming
  • Relational Operators in C Programming

C Programming Assignment Operators

  • Logical Operators in C Programming
  • Understanding for loop in C
  • if else if statements in C Programming
  • Beginner's Guide to C Programming
  • First C program and Its Syntax
  • Escape Sequences and Comments in C
  • Keywords in C: List of Keywords
  • Identifiers in C: Types of Identifiers
  • Data Types in C Programming - A Beginner Guide with examples
  • Variables in C Programming - Types of Variables in C ( With Examples )
  • 10 Reasons Why You Should Learn C
  • Boolean and Static in C Programming With Examples ( Full Guide )
  • Operators in C: Types of Operators
  • Bitwise Operators in C: AND, OR, XOR, Shift & Complement
  • Expressions in C Programming - Types of Expressions in C ( With Examples )
  • Conditional Statements in C: if, if..else, Nested if
  • Switch Statement in C: Syntax and Examples
  • Ternary Operator in C: Ternary Operator vs. if...else Statement
  • Loop in C with Examples: For, While, Do..While Loops
  • Nested Loops in C - Types of Expressions in C ( With Examples )
  • Infinite Loops in C: Types of Infinite Loops
  • Jump Statements in C: break, continue, goto, return
  • Continue Statement in C: What is Break & Continue Statement in C with Example

03 Intermediate

  • Getting Started with Data Structures in C
  • Constants in C language
  • Functions in C Programming
  • Call by Value and Call by Reference in C
  • Recursion in C: Types, its Working and Examples
  • Storage Classes in C: Auto, Extern, Static, Register
  • Arrays in C Programming: Operations on Arrays
  • Strings in C with Examples: String Functions

04 Advanced

  • How to Dynamically Allocate Memory using calloc() in C?
  • How to Dynamically Allocate Memory using malloc() in C?
  • Pointers in C: Types of Pointers
  • Multidimensional Arrays in C: 2D and 3D Arrays
  • Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

05 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • C Programming Course
  • Data Structures and Algorithms Training
  • C Programming Assignment ..

C Programming Assignment Operators

C Programming For Beginners Free Course

What is an assignment operator in c.

Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". The value on the right side must be of the same data type as the variable on the left side. Hence, the associativity is from right to left.

In this C tutorial , we'll understand the types of C programming assignment operators with examples. To delve deeper you can enroll in our C Programming Course .

Before going in-depth about assignment operators you must know about operators in C. If you haven't visited the Operators in C tutorial, refer to Operators in C: Types of Operators .

Types of Assignment Operators in C

There are two types of assignment operators in C:

Types of Assignment Operators in C
+=addition assignmentIt adds the right operand to the left operand and assigns the result to the left operand.
-=subtraction assignmentIt subtracts the right operand from the left operand and assigns the result to the left operand.
*=multiplication assignmentIt multiplies the right operand with the left operand and assigns the result to the left operand
/=division assignmentIt divides the left operand with the right operand and assigns the result to the left operand.
%=modulo assignmentIt takes modulus using two operands and assigns the result to the left operand.

Example of Augmented Arithmetic and Assignment Operators

There can be five combinations of bitwise operators with the assignment operator, "=". Let's look at them one by one.

&=bitwise AND assignmentIt performs the bitwise AND operation on the variable with the value on the right
|=bitwise OR assignmentIt performs the bitwise OR operation on the variable with the value on the right
^=bitwise XOR assignmentIt performs the bitwise XOR operation on the variable with the value on the right
<<=bitwise left shift assignmentShifts the bits of the variable to the left by the value on the right
>>=bitwise right shift assignmentShifts the bits of the variable to the right by the value on the right

Example of Augmented Bitwise and Assignment Operators

Practice problems on assignment operators in c, 1. what will the value of "x" be after the execution of the following code.

The correct answer is 52. x starts at 50, increases by 5 to 55, then decreases by 3 to 52.

2. After executing the following code, what is the value of the number variable?

The correct answer is 144. After right-shifting 73 (binary 1001001) by one and then left-shifting the result by two, the value becomes 144 (binary 10010000).

Benefits of Using Assignment Operators

  • Simplifies Code: For example, x += 1 is shorter and clearer than x = x + 1.
  • Reduces Errors: They break complex expressions into simpler, more manageable parts thus reducing errors.
  • Improves Readability: They make the code easier to read and understand by succinctly expressing common operations.
  • Enhances Performance: They often operate in place, potentially reducing the need for additional memory or temporary variables.

Best Practices and Tips for Using the Assignment Operator

While performing arithmetic operations with the same variable, use compound assignment operators

  • Initialize Variables When Declaring int count = 0 ; // Initialization
  • Avoid Complex Expressions in Assignments a = (b + c) * (d - e); // Consider breaking it down: int temp = b + c; a = temp * (d - e);
  • Avoid Multiple Assignments in a Single Statement // Instead of this a = b = c = 0 ; // Do this a = 0 ; b = 0 ; c = 0 ;
  • Consistent Formatting int result = 0 ; result += 10 ;

When mixing assignments with other operations, use parentheses to ensure the correct order of evaluation.

Live Classes Schedule

Generative AI For Software Developers Jul 14 SAT, SUN Filling Fast
Angular Certification Course Jul 14 SAT, SUN Filling Fast
ASP.NET Core Certification Training Jul 15 MON, WED, FRI Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jul 15 MON, WED, FRI Filling Fast
Azure Master Class Jul 20 SAT, SUN Filling Fast
Azure Developer Certification Training Jul 21 SAT, SUN Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN Filling Fast
ASP.NET Core Certification Training Jul 28 SAT, SUN Filling Fast
Software Architecture and Design Training Jul 28 SAT, SUN Filling Fast
.NET Solution Architect Certification Training Jul 28 SAT, SUN Filling Fast

Can't find convenient schedule? Let us know

About Author

Author image

  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

Assignment Operators in C

C Assignment OperatorsExampleExplanation
=x = 25Value 25 is assigned to x
+=x += 25This is the same as x = x + 25
-=x -= 25This is the same as x = x – 25
*=y *= 25This is the same as y = y * 25
/=y /= 25This is the same as y = y / 25
%=y%= 25This is the same as y = y % 25

Assignment Operators in C Example

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

C array declaration and assignment?

I've asked a similar question on structs here but I'm trying to figure out how C handles things like assigning variables and why it isn't allowed to assign them to eachother if they are functionally the same.

Lets say I have two arrays:

Why won't x = y compile? If they are both the same "signature" like that, then shouldn't you be able to assign them back and forth?

Can I declare these in a way that would allow me to do that in C? It makes sense to me that you would be able to, but maybe there is a way that this can be done? Typedefs for structs seemed to be the solution, would it be the same for array declaration and assignment?

I appreciate your guys help, I'm new to Stackoverflow but it has been a really good resource for me so far!

  • variable-assignment

Community's user avatar

7 Answers 7

Simply put, arrays are not assignable. They are a "non-modifiable lvalue". This of course begs the question: why? Please refer to this question for more information:

Why does C++ support memberwise assignment of arrays within structs, but not generally?

Arrays are not pointers. x here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y too is the name of an array, not a pointer.

You can do array assignment within structs:

But you can't do it directly with arrays. Use memcpy .

Jakob's user avatar

  • That code still doesn't do what he was wanting it to do though, does it? Perhaps I'm wrong, but I got the impression he was hoping to copy the contents of the y array into x. –  T.E.D. Commented Apr 13, 2009 at 18:18
  • True. Fortunately, lots of other replies have indicated memcpy() is the correct choice. I'll add it in... –  user82238 Commented Apr 13, 2009 at 18:21
  • 6 "The name of an array is actually the address of the first element of that array. \ The example code you provide here is attempting to assign to something which is not an l-value.": for the sake of posterity I thought I'd note that both of these sentences from the most highly voted answer are wrong. First, the name of an array most definitely is not a pointer (e.g. think sizeof()), it simply decays to a pointer in many cases. Second, the array name is an lvalue, just not a modifiable lvalue. –  Alexandros Gezerlis Commented Oct 31, 2011 at 23:32
  • 3 I'm high-jacking this answer. It's top-voted and accepted, yet contained incorrect information and the user is long-gone. Hopefully this clears things up. –  GManNickG Commented Oct 5, 2016 at 6:16

This compiles and y will be the same as x .

Stephan's user avatar

  • 4 y will be a pointer equivalent to &x[0] , due to array-to-pointer conversion, but it won't be "the same" as x is an array, not a pointer. –  GManNickG Commented Oct 5, 2016 at 6:05

Some messages here say that the name of an array yields the address of its first element. It's not always true:

Bastien Léonard's user avatar

In order to assign arrays you will have to assign the values inside the array.

ie. x=y is equivalent to

aJ.'s user avatar

  • thats why I am giving the equivalent! –  aJ. Commented Apr 13, 2009 at 16:55
  • it gives the impression that x=y is a valid statement –  Naveen Commented Apr 13, 2009 at 16:57
  • Actually in the OP its already mentioned that x=y doesn't compile. –  aJ. Commented Apr 13, 2009 at 16:58
  • x=y being impossible for arrays is the entire context for this question, Naveen. –  Chuck Commented Apr 13, 2009 at 17:02

In an attempt to complement Blank's answer, I devised the following program:

When executed, the following is output:

The point is to illustrate how the copy of structures' values occurs.

David's user avatar

When saying "int x[10]" is saying, "reserve some room for 10 integers and pass me a pointer to the location". So for the copy to make sense you'd need to operate on the memory pointed by, rather than 'the name of the memory location'.

So for copying here you'd use a for loop or memcpy().

amo-ej1's user avatar

I've used C compilers where that would compile just fine...and when run the code would make x point to y's array.

You see, in C the name of an array is a pointer that points to the start of the array. In fact, arrays and pointers are essentially interchangable. You can take any pointer and index it like an array.

Back when C was being developed in the early 70's, it was meant for relatively small programs that were barely above assembly language in abstraction. In that environment, it was damn handy to be able to easily go back and forth between array indexing and pointer math. Copying whole arrays of data, on the other hand, was a very expensive thing do do, and hardly something to be encouraged or abstracted away from the user.

Yes, in these modern times it would make way more sense to have the name of the array be shorthand for "the whole array", rather than for "a ponter to the front of the array". However, C wasn't designed in these modern times. If you want a language that was, try Ada. x := y there does exactly what you would expect; it copies one array's contents to the other.

T.E.D.'s user avatar

  • Friendly random ping. :) As you undoubtedly (now) know, the name of an array is not a pointer. –  GManNickG Commented Oct 5, 2016 at 6:05

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 arrays variable-assignment or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Why bother with planetary battlefields?
  • These two Qatar flights with slightly different times and different flight number must actually be the same flight, right?
  • Multiple citations of the same reference, each time with a different page number
  • Is this a Hadamard matrix?
  • Definability of acyclic graphs
  • Real-life problems involving solving triangles
  • Can I prettify a XML string using Apex?
  • How can I watch a timelapse movie on the Nikon D7100?
  • What enforcement exists for medical informed consent?
  • Is ElGamal homomorphic encryption using additive groups works only for Discrete Log ElGamal? What about EC ElGamal?
  • How can one count how many pixels a GIF image has via command line?
  • Can computer components be damaged if they stay off for a long time?
  • Big zeros in block diagonal matrix
  • Was I wrongfully denied boarding for a flight where the airliner lands to a gate that doesn't directly connect to the international part the airport?
  • Why can't CVP be trivially reduced to SVP by shifting?
  • TTL to RS485 converter problems
  • MOSFET Datasheet Confusion
  • Why do jet aircraft need chocks when they have parking brakes?
  • Can a big mass defect make the mass negative?
  • Why there is two different answers for the volume of a frustum?
  • Fill the grid subject to product, sum and knight move constraints
  • How do contradictions within Halacha impact the credibility of Judaism?
  • DHCP assigned addresses following devices/users and routing
  • Is it possible to understand in simple terms what a Symplectic Structure is?

c program to find assignment

Assignment Operators in C

C++ Course: Learn the Essentials

Operators are a fundamental part of all the computations that computers perform. Today we will learn about one of them known as Assignment Operators in C. Assignment Operators are used to assign values to variables. The most common assignment operator is = . Assignment Operators are Binary Operators.

Types of Assignment Operators in C

LHS and RHS Operands

Here is a list of the assignment operators that you can find in the C language:

  • basic assignment ( = )
  • subtraction assignment ( -= )
  • addition assignment ( += )
  • division assignment ( /= )
  • multiplication assignment ( *= )
  • modulo assignment ( %= )
  • bitwise XOR assignment ( ^= )
  • bitwise OR assignment ( |= )
  • bitwise AND assignment ( &= )
  • bitwise right shift assignment ( >>= )
  • bitwise left shift assignment ( <<= )

Working of Assignment Operators in C

This is the complete list of all assignment operators in C. To read the meaning of operator please keep in mind the above example.

OperatorMeaning Of OperatorExampleSame as
=Simple assignment operatorx=yx=y
+=Add left operand to right operand then assign result to left operandx+=yx=x+y
-=subtract right operand from left operand then assign result to left operandx-=yx=x-y
*=multiply left operand with right operand then assign result to left operandx*=yx=x*y
/=divide left operand with right operand then assign result to left operandx/=yx=x/y
%=take modulus left operand with right operand then assigned result in left operandx%=yx=x%y
<<=Left Shift Assignment Operator means the left operand is left shifted by right operand value and assigned value to left operandx<<=yx=x<<y
>>=Right shift Assignment Operator means the left operand is right shifted by right operand value and assigned value to left operandx>>=yx=x>>y
&=Bitwise AND Assignment Operator means does AND on every bit of left operand and right operand and assigned value to left operandx&=yx=x&y
|=Bitwise inclusive OR Assignment Operator means does OR on every bit of left operand and right operand and assigned value to left operandx|=yx=x|y
^=Bitwise exclusive OR Assignment Operator means does XOR on every bit of left operand and right operand and assigned value to left operandx^=yx=x^y

Example for Assignment Operators in C

Basic assignment ( = ) :

Subtraction assignment ( -= ) :

Addition assignment ( += ) :

Division assignment ( /= ) :

Multiplication assignment ( *= ) :

Modulo assignment ( %= ) :

Bitwise XOR assignment ( ^= ) :

Bitwise OR assignment ( |= ) :

Bitwise AND assignment ( &= ) :

Bitwise right shift assignment ( >>= ) :

Bitwise left shift assignment ( <<= ) :

This is the detailed explanation of all the assignment operators in C that we have. Hopefully, This is clear to you.

Practice Problems on Assignment Operators in C

1. what will be the value of a after the following code is executed.

A) 10 B) 11 C) 12 D) 15

Answer – C. 12 Explanation: a starts at 10, increases by 5 to 15, then decreases by 3 to 12. So, a is 12.

2. After executing the following code, what is the value of num ?

A) 4 B) 8 C) 16 D) 32

Answer: C) 16 Explanation: After right-shifting 8 (binary 1000) by one and then left-shifting the result by two, the value becomes 16 (binary 10000).

Q. How does the /= operator function? Is it a combination of two other operators?

A. The /= operator is a compound assignment operator in C++. It divides the left operand by the right operand and assigns the result to the left operand. It is equivalent to using the / operator and then the = operator separately.

Q. What is the most basic operator among all the assignment operators available in the C language?

A. The most basic assignment operator in the C language is the simple = operator, which is used for assigning a value to a variable.

  • Assignment operators are used to assign the result of an expression to a variable.
  • There are two types of assignment operators in C. Simple assignment operator and compound assignment operator.
  • Compound Assignment operators are easy to use and the left operand of expression needs not to write again and again.
  • They work the same way in C++ as in C.

Assignment Operators in C

January 17, 2023

Assignment Operator in C

Simple assignment operator is used to assign a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables.

Assignment Operators in C

Assignment Operators

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

a will be assigned value of 5, and b will be assigned value of 10.

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

eg; ( a+=b ) can written as( a=a+b )

  •   ” -=” This operator is combination ‘-‘ and ‘=’ operator. This operator subtracts the value on right from the current value of the variable on left and then assigns the result to the variable on the left.

eg; ( a-=b ) can written as( a=a-b )

Assignment Operators in C img

Tokens in C

Size of Operators

Conditional statement Program in C

fseek() in C

pointer v/s array in C

Implementation of Assignment Operator

  • First of all in this program we will initialize the value in the variable, the we will assign the value of the right to the variable.
  • like a=20 means 20 will assign to the a variable.
  • b+=10 means b=b+10 and b=10 initialize so b=10+10 it means b=20 so 20 will assign to b.
  • c*=2 means c=c*2 that means multiply of 2*5 because the value of 5 is c so c=10 ,then 10 will assign to the C.

Code for Assignment operator in C

Prime course trailer, related banners.

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

While loop in C

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Login/Signup to comment

c program to find assignment

30+ Companies are Hiring

Get Hiring Updates right in your inbox from PrepInsta

Tutorials Class - Logo

  • C All Exercises & Assignments

Write a C program to check whether a number is even or odd

Description:

Write a C program to check whether a number is even or odd.

Note: Even number is divided by 2 and give the remainder 0 but odd number is not divisible by 2 for eg. 4 is divisible by 2 and 9 is not divisible by 2.

Conditions:

  • Create a variable with name of number.
  • Take value from user for number variable.

Enter the Number=9 Number is Odd.

Write a C program to swap value of two variables using the third variable.

You need to create a C program to swap values of two variables using the third variable.

You can use a temp variable as a blank variable to swap the value of x and y.

  • Take three variables for eg. x, y and temp.
  • Swap the value of x and y variable.

Write a C program to check whether a user is eligible to vote or not.

You need to create a C program to check whether a user is eligible to vote or not.

  • Minimum age required for voting is 18.
  • You can use decision making statement.

Enter your age=28 User is eligible to vote

Write a C program to check whether an alphabet is Vowel or Consonant

You need to create a C program to check whether an alphabet is Vowel or Consonant.

  • Create a character type variable with name of alphabet and take the value from the user.
  • You can use conditional statements.

Enter an alphabet: O O is a vowel.

Write a C program to find the maximum number between three numbers

You need to write a C program to find the maximum number between three numbers.

  • Create three variables in c with name of number1, number2 and number3
  • Find out the maximum number using the nested if-else statement

Enter three numbers: 10 20 30 Number3 is max with value of 30

Write a C program to check whether number is positive, negative or zero

You need to write a C program to check whether number is positive, negative or zero

  • Create variable with name of number and the value will taken by user or console
  • Create this c program code using else if ladder statement

Enter a number : 10 10 is positive

Write a C program to calculate Electricity bill.

You need to write a C program to calculate electricity bill using if-else statements.

  • For first 50 units – Rs. 3.50/unit
  • For next 100 units – Rs. 4.00/unit
  • For next 100 units – Rs. 5.20/unit
  • For units above 250 – Rs. 6.50/unit
  • You can use conditional statements.

Enter the units consumed=278.90 Electricity Bill=1282.84 Rupees

Write a C program to print 1 to 10 numbers using the while loop

You need to create a C program to print 1 to 10 numbers using the while loop

  • Create a variable for the loop iteration
  • Use increment operator in while loop

1 2 3 4 5 6 7 8 9 10

  • C Exercises Categories
  • C Top Exercises
  • C Decision Making

Javatpoint Logo

  • Design Pattern
  • Interview Q

C Control Statements

C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.

JavaTpoint

There are different kinds of the operators, such as arithmetic, relational, bitwise, assignment, etc., in the C programming language. The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=.


It is the operator used to assign the right side operand or variable to the left side variable.

Let's create a program to use the simple assignment operator in C.

The operator is used to add the left side operand to the left operand and then assign results to the left operand.

Let's create a program to use the Plus and assign operator in C.

The operator is used to subtract the left operand with the right operand and then assigns the result to the left operand.

Let's create a program to use the Subtract and Assign (-=) operator in C.

The operator is used to multiply the left operand with the right operand and then assign result to the left operand.

Let's create a program to use the multiply and assign operator (*=) in C.

An operator is used between the left and right operands, which divides the first number by the second number to return the result in the left operand.

Let's create a program to use the divide and assign operator (/=) in C.

An operator used between the left operand and the right operand divides the first number (n1) by the second number (n2) and returns the remainder in the left operand.

Let's create a program to use the divide and assign operator (%=) in C.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

C Programming Examples

  • C Program to find the student's grade

Last updated on September 24, 2020

The following is a C program to find the grade of the student based on the marks entered by the user.

/**************************************** * C Program to find the student's grade *****************************************/ #include<stdio.h> // include stdio.h int main() { float marks; char grade; printf("Enter marks: "); scanf("%f", &marks); if(marks >= 90) { grade = 'A'; } else if(marks >= 80 && marks < 90) { grade = 'B'; } else if(marks >= 70 && marks < 80) { grade = 'C'; } else if(marks >= 60 && marks < 70) { grade = 'D'; } else if(marks >= 50 && marks < 60) { grade = 'E'; } else { grade = 'F'; } printf("Your grade is %c", grade); return 0; }

Expected Output:

Enter marks: 92 Your grade is A
Enter marks: 75 Your grade is C

Load Comments

  • C Program to find the sum of digits of a number
  • C Program to find the factorial of a number
  • C Program to find Armstrong numbers
  • C Program to find Prime Numbers
  • C Program to generate Fibonacci sequence
  • C Program to find the sum of the digits of a number untill the sum is reduced to a single digit
  • C Program to count number of digits in a number
  • C Program to reverse the digits of a number
  • C Program to find the sum of natural numbers upto N terms
  • C Program to check whether the number is even or odd.
  • C Program to find the roots of a Quadratic equation
  • C Program to print Triad Numbers
  • C Program to multiply two numbers using Russian peasant method
  • C Program to find the number of denominations for a given amount
  • C Program to check whether the number is a Palindrome
  • C Program to determine the type and Area of a Triangle
  • C Program to print Twin prime numbers between two ranges
  • C Program to print the two digit number in words
  • C Program to calculate the power of a number
  • C Program to find the largest of three numbers
  • C Program to find the product of digits of a number
  • C Program to calculate Permutation and Combination
  • C Program to find LCM and HCF of two numbers
  • C Program to find the maximum and minimum element in the array
  • C Program to reverse the elements of an array
  • C Program to sum the elements of an array
  • C Program to find the count of even and odd elements in the array
  • C Program to add two Matrices
  • C Program to multiply two matrices
  • C Program to find the transpose of a matrix
  • C Program to search for an item using Linear Search
  • C Program to search for an item using Binary Search
  • C Program to sort an array in ascending order using Bubble Sort
  • C Program to check whether a string is palindrome or not
  • C Program to calculate Factorial using recursion
  • C Program to calculate the power using recursion
  • C Program to reverse the digits of a number using recursion
  • C Program to convert a decimal number to binary, octal and hexadecimal using recursion
  • C Program to convert a decimal number to a binary number
  • C Program to convert a decimal number to a hexadecimal number
  • C Program to convert a decimal number to an octal number
  • C Program to Convert a Binary Number to a Decimal Number
  • C Program to convert the temperature in Fahrenheit to Celsius
  • C Program to convert a decimal number to Roman numerals
  • C Program to print Fibonacci Sequence using recursion
  • C Program to check whether a year is a leap year
  • C Program to print the earlier of the two dates
  • C Program to check whether a date is valid or not
  • C Program to calculate the difference of two dates in years, months and days
  • C Program to calculate the day of year from the date
  • C Program to print the date in legal form
  • C Program to print various triangular patterns
  • C Program to print Pascal Triangle
  • C Program to print Floyd’s Triangle
  • C Program to simulate a simple calculator using switch statement

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

c program to find assignment

  • C Programming Home
  • ▼C Programming Exercises
  • Basic Declarations and Expressions
  • Basic Part-II
  • Basic Algorithm
  • Variable Type
  • Input - Output
  • Conditional Statements
  • Do-While Loop
  • Linked List
  • Callback function
  • Variadic function
  • Inline Function
  • File Handling
  • Searching and Sorting
  • C Programming Exercises, Practice, Solution

What is C Programming Language?

C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs. It has since become one of the most widely used programming languages of all time, with C compilers from various vendors available for the majority of existing computer architectures and operating systems.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with C programming.

Hope, these exercises help you to improve your C programming coding skills. Currently, following sections are available, we are working hard to add more exercises. Please refer to this page for important C snippets, code, and examples before starting the exercises. Happy Coding!

List of C Programming Exercises :

  • Basic Declarations and Expressions [ 150 Exercises with Solution ]
  • Basic Part-II [ 7 Exercises with Solution ]
  • Basic Algorithm [ 75 Exercises with Solution ]
  • Variable Type [ 18 Exercises with Solution ]
  • Input, Output [ 10 Exercises with Solution ]
  • Conditional Statement [ 26 Exercises with Solution ]
  • While Loop [ 11 Exercises with Solution ]
  • Do-While Loop [ 12 Exercises with Solution ]
  • For Loop [ 61 Exercises with Solution ]
  • Array [ 107 Exercises with Solution ]
  • Structure [ 9 Exercises with Solution ]
  • Pointer [ 22 Exercises with Solution ]
  • Linked List [ 64 Exercises with Solution ]
  • Stack [ 17 Exercises with Solution ]
  • Binary Heap (Tree-Based Structure) [ 9 Exercises with Solution ]
  • Queue [ 13 Exercises with Solution ]
  • Hash [ 10 Exercises with Solution ]
  • Tree [ 10 Exercises with Solution ]
  • Graph [ 10 Exercises with Solution ]
  • Numbers [ 38 Exercises with Solution ]
  • Math [ 38 Exercises with Solution ]
  • String [ 41 Exercises with Solution ]
  • Date Time [ 10 Exercises with Solution ]
  • Function [ 12 Exercises with Solution ]
  • Callback Function [ 11 Exercises with Solution ]
  • Variadic Function [ 8 Exercises with Solution ]
  • Inline Function [ 11 Exercises with Solution ]
  • Recursion [ 21 Exercises with Solution ]
  • File Handling [ 19 Exercises with Solution ]
  • Search and Sorting [ 31 Exercises with Solution ]
  • Challenges [ 35 exercises with solution ]
  • C Snippets [29]
  • More to Come !

[ Want to contribute to C exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Popularity of Programming Language Worldwide, Nov 2023 compared to a year ago:

`
Rank Change Language Share Trend
1 Python 27.99 % +0.0 %
2 Java 15.91 % -0.8%
3 Javascript 9.18 % -0.3%
4 C/C++ 6.76 % +0.2%
5 C# 6.67 % -0.3 %
6 PHP 4.86 % -0.3 %
7 R 4.45% +0.4%
8 TypeScript 2.95 % +0.1%
9 Swift 2.7 % +0.6%
10 Objective-C 2.32% +0.2%
11 Rust1.98% +0.3%
12 Go 1.98% -0.0%
13 Kotlin 1.76 % -0.1%
14 Matlab 1.6 % +0.0%
15 Ada 1.02% +0.2%
16 Ruby 1.0 % -0.1 %
17 Dart 0.99 % +0.1 %
18 Powershell 0.93 % +0.0 %
19 VBA 0.93 % -0.1 %
20 Scala 0.62 % -0.1 %
21 Lua 0.62 % 0.0 %
22 Abap 0.58 % +0.1 %
23 Visual Basic 0.55 % -0.1 %
24 Julia 0.35 % -0.0 %
25 Groovy 0.31 % -0.1 %
26 Perl 0.31 % -0.1 %
27 Haskell 0.27 % -0.0 %
28 Cobol 0.25 % -0.1 %
29 Delphi/Pascal 0.18 % +0.2 %

Source : https://pypl.github.io/PYPL.html

TIOBE Index for November 2023

Nov 2023 Nov 2022 Change Programming Language Ratings Change
1 1 Python 14.16% -3.02%
2 2 C 11.77% -3.31%
3 4 C++ 10.36% -0.39%
4 3 Java 8.35% -3.63%
5 5 C# 7.65% +3.40%
6 7 JavaScript 3.21% +0.47%
7 10 PHP 2.30% +0.61%
8 6 Visual Basic 2.10% -2.01%
9 9 SQL 1.88% +0.07%
10 8 Assembly language 1.35% -0.83%
11 17 Scratch 1.31% +0.43%
12 24 Fortran 1.30% +0.74%
13 11 Go 1.19% +0.05%
14 15 MATLAB 1.15% +0.14%
15 28 Kotlin 1.15% +0.68%
16 14 Delphi/Object Pascal 1.14% +0.07%
17 18 Swift 1.04% +0.17%
18 19 Ruby 0.99% +0.14%
19 12 R 0.93% -0.20%
20 20 Rust 0.91% +0.16%

Source : https://www.tiobe.com/tiobe-index/

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • Python Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Browse Course Material

Course info, instructors.

  • Daniel Weller
  • Sharat Chikkerur

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages
  • Software Design and Engineering

Learning Resource Types

Practical programming in c, assignments.

ASSN # TOPICS ASSIGNMENTS SOLUTIONS
1 Writing, compiling, and debugging programs; preprocessor macros; C file structure; variables; functions and problem statements; returning from functions ( ) ( )
2 Types, operators, expressions ( ) ( )
3 Control flow, functions, variable scope, static and global variables, I/O: printf and scanf, file I/O, character arrays, error handling, labels and goto

( )

( ) (This ZIP file contains: 1 .txt file and 2 .c files.)

( )
4 Pointers, arrays, strings, searching and sorting algorithms ( ) ( )
5 Linked lists, trees ( ) ( )
6a Pointers to pointers, multidimensional arrays, stacks and queues

( )

( ) (This ZIP file contains: 1 .txt file and 2 .c files.)

( )
6b Function pointers, hash table

( )

( ) (This ZIP file contains: 1 .txt file and 2 .c files.)

( )
7 Using and creating libraries, B-trees and priority queues

( )

( ) (This ZIP file contains: 2 .c files and 1 .db file.)

( ) (This ZIP file contains: 5 .txt files and 5 .c files.)

facebook

You are leaving MIT OpenCourseWare

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively.

Print Pyramids and Patterns

  • Make a Simple Calculator Using switch...case
  • Display Factors of a Number
  • Display Armstrong Number Between Two Intervals
  • Check Armstrong Number
  • Display Prime Numbers Between Two Intervals
  • Check Whether a Number is Prime or Not
  • Check Whether a Number is Palindrome or Not

C Tutorials

Print an Integer (Entered by the User)

Calculate the Sum of Natural Numbers

  • Find GCD of two Numbers
  • C "Hello, World!" Program
  • Generate Multiplication Table

C Program to Display Fibonacci Sequence

To understand this example, you should have the knowledge of the following C programming topics:

  • C Programming Operators
  • C while and do...while Loop
  • C break and continue

The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.

Visit this page to learn about the Fibonacci sequence .

Fibonacci Series up to n terms

Let us suppose n = 10 . First, we have printed the first two terms of the Fibonacci sequence before using a for loop to print the next  n terms.

Let us see how the for loop works:

i t1 t2 nextTerm
3 0 1 1
4 1 1 2
5 1 2 3
6 2 3 5
7 3 5 8
8 5 8 13
9 8 13 21
10 13 21 34

Fibonacci Sequence Up to a Certain Number

In this program, we have used a while loop to print all the Fibonacci numbers up to n .

If n is not part of the Fibonacci sequence, we print the sequence up to the number that is closest to (and lesser than) n .

Suppose n = 100 . First, we print the first two terms t1 = 0 and t2 = 1 .

Then the while loop prints the rest of the sequence using the nextTerm variable:

t1 t2 nextTerm nextTerm <= n
0 1 1 . Print .
1 1 2 . Print .
1 2 3 . Print .
... ... ... ...
34 55 89 . Print .
55 89 144 . Terminate Loop.

Sorry about that.

Related Examples

Check Whether a Number is Positive or Negative

Codeforwin

C programming examples, exercises and solutions for beginners

Fundamentals.

  • Hello world program in C
  • Basic input/output
  • Basic IO on all data types
  • Perform arithmetic operations
  • Find area and perimeter of rectangle
  • Find diameter and area of circle
  • Find area of triangle
  • Find angles of triangle
  • Temperature conversion
  • Length conversion
  • Days conversion
  • Find power of a number
  • Find square root
  • Calculate simple interest
  • Calculate compound interest
  • Find range of data types

Bitwise Operator

  • Check Least Significant Bit (LSB)
  • Check Most Significant Bit (MSB)
  • Get nth bit of a number
  • Set nth bit of a number
  • Clear nth bit of a number
  • Toggle nth bit of a number
  • Highest set bit of a number
  • Lowest set bit of a number
  • Count trailing zeros of binary number
  • Count leading zeros of binary number
  • Flip bits of a number
  • Rotate bits of a number
  • Decimal to binary
  • Swap two numbers
  • Check even or odd
  • View all Bitwise operator examples →

Ternary Operator

  • Maximum of two numbers
  • Maximum of three numbers
  • Check leap year
  • Check alphabet
  • View all ternary operator examples →
  • Find maximum of two numbers
  • Find maximum of three numbers
  • Check negative, positive or zero
  • Check divisibility
  • Check alphabet character
  • Check vowel or consonant
  • Check alphabet, digit or special character
  • Check uppercase or lowercase
  • Print day of week
  • Find number of days in month
  • Find roots of quadratic equation
  • Calculate profile/loss
  • View all if else examples →

Switch case

  • Find total days in month
  • Check positive, negative or zero
  • Simple calculator application
  • View all switch case examples →

Loop/Iteration

  • Print natural numbers from 1 to n
  • Print alphabets from a to z
  • Print even numbers from 1 to n
  • Print sum of all numbers from 1 to n
  • Print sum of all odd numbers from 1 to n
  • Print multiplication table of n
  • Find number of digits in a number
  • Find first and last digit
  • Find sum of first and last digit
  • Swap first and last digit
  • Find sum of digits of a number
  • Find reverse of a number
  • Find frequency of digits in a number
  • Find power of a number using loop
  • Find factorial of a number
  • Find HCF of two numbers
  • Find LCM of two numbers
  • View all loop examples →

Number system and conversion

  • Find one's complement
  • Find two's complement
  • Binary to octal conversion
  • Binary to decimal conversion
  • Binary to hexadecimal conversion
  • Octal to binary conversion
  • Octal to decimal conversion
  • Octal to hexadecimal conversion
  • Decimal to binary conversion
  • Decimal to octal conversion
  • Decimal to hexadecimal conversion
  • Hexadecimal to binary conversion
  • Hexadecimal to octal conversion
  • Hexadecimal to decimal conversion
  • View all conversion examples →

Star patterns

  • Pascal triangle generation
  • Square star pattern
  • Hollow square star pattern
  • Hollow square star pattern with diagonal
  • Rhombus star pattern
  • Hollow rhombus star pattern
  • Right triangle star pattern
  • Hollow right triangle star pattern
  • Inverted right triangle star pattern
  • Mirrored inverted right triangle star pattern
  • Pyramid star pattern
  • Inverted pyramid star pattern
  • Diamond star pattern
  • Plus starpattern
  • X star pattern
  • 8 star pattern
  • Heart star with name pattern
  • View all star pattern examples →

Number patterns

  • Square number pattern
  • Right triangle number pattern
  • Inverted right triangle
  • Triangle with zero filled
  • Half diamond pattern
  • Half diamond star bordered pattern
  • X number pattern
  • View all number pattern examples →
  • Find cube using functions
  • Diameter & area of circle using functions
  • Maximum and minimum using functions
  • Check even odd using functions
  • Check Prime number using functions
  • Find all prime numbers using functions
  • Find all strong numbers using functions
  • Find all armstrong numbers using functions
  • Find all perfect numbers using functions
  • View all function examples →
  • Find power using recursion
  • Print natural numbers using recursion
  • Print even numbers using recursion
  • Sum of natural numbers using recursion
  • Sum of even/odd numbers using recursion
  • Find reverse using recursion
  • Check palindrome using recursion
  • Find sum of digits using recursion
  • Find factorial using recursion
  • Generate nth Fibonacci term using recursion
  • Find HCF (GCD) using recursion
  • Find LCM using recursion
  • Sum of array elements using recursion
  • View all recursion examples →
  • Input and display array elements
  • Sum of all array elements
  • Find second largest element in array
  • Copy one array to another
  • Insert new element in array
  • Delete an element from array
  • Find frequency of array elements
  • Merge two array to third array
  • Delete duplicate elements from array
  • Reverse an array
  • Search an element in array
  • Sort an array
  • Left rotate an array
  • Right rotate an array
  • View all array examples →

Matrix (2D array)

  • Add two matrices
  • Scalar matrix multiplication
  • Multiply two matrices
  • Check if two matrices are equal
  • Sum of diagonal elements of matrix
  • Interchange diagonal of matrix
  • Find upper triangular matrix
  • Find sum of lower triangular matrix
  • Find transpose of triangular matrix
  • Find determinant of a matrix
  • Check identity matrix
  • Check sparse matrix
  • Check symmetric matrix
  • View all matrix examples →
  • Find length of string
  • Copy string to another string
  • Concatenate two strings
  • Compare two strings
  • Convert lowercase to uppercase
  • Find reverse of a string
  • Check palindrome
  • Reverse order of words
  • Search a character in string
  • Search a word in string
  • Find highest occurring character
  • Remove all duplicate characters
  • Replace a character in string
  • Trim whitespace from string
  • View all string examples →
  • Create, initialize and use pointer
  • Add two numbers using pointers
  • Swap two numbers using pointers
  • Access array using pointers
  • Copy array using pointers
  • Reverse array using pointers
  • Access 2D array using pointers
  • Multiply matrices using pointers
  • Copy strings using pointers
  • Concatenate strings using pointers
  • Compare strings using pointers
  • Reverse strings using pointers
  • Sort array strings using pointers
  • Return multiple values from function using pointers
  • View all pointers examples →
  • Create file and write contents
  • Read file contents and display
  • Append contents to file
  • Compare two files
  • Copy one file to another
  • Merge two files
  • Remove a word from file
  • Remove a line from file
  • Replace a word in file
  • Replace a line in file
  • Print source code
  • Convert uppercase to lowercase in file
  • Find properties of file
  • Check if file or directory exists
  • Rename a file or directory
  • List of files recursively
  • View all files handling examples →

Macros/Pre-processor directives

  • Create custom header file
  • Define, undefine and redefine a macro
  • Find sum using macro
  • Find square and cube using macro
  • Check even/odd using macro
  • Find maximum or minimum using macro
  • Check lowercase/uppercase using macro
  • Swap two numbers using macro
  • Multiline macros
  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Left Shift and Right Shift Operators in C/C++

In C/C++, left shift (<<) and right shift (>>) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators.

Left Shift (<<) Operators

The left shift(<<) is a binary operator that takes two numbers, left shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, left-shifting an integer “ a ” with an integer “ b ” denoted as ‘ (a<<b)’ is equivalent to multiplying a with 2^b (2 raised to power b).  

  • a is the integer value to be shifted.
  • b specifies how many positions to shift the bits.

Example: Let’s take a=5 ; which is 101 in Binary Form. Now, if “ a is left-shifted by 2 ” i.e a=a<<2 then a will become a=a*(2^2) . Thus, a=5*(2^2)=20 which can be written as 10100.

Left-Shift-in-c-cpp

Example of Left Shift Operator

Applications of left shift operator.

  • Multiplication by Powers of Two : Left shifting a number by n positions is equivalent to multiplying it by 2^n and is much faster than normal multiplication
  • Efficient Calculations : Used in performance-critical applications where arithmetic operations need to be fast.
  • Bit Manipulation : Common in low-level programming, such as embedded systems and hardware interfacing.

Right Shift(>>) Operators

Right Shift(>>) is a binary operator that takes two numbers, right shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, right-shifting an integer “ a ” with an integer “ b ” denoted as ‘ (a>>b) ‘ is equivalent to dividing a with 2^b. 

Example: let’s take a=5 ; which is 101 in Binary Form. Now, if “ a is right-shifted by 2 ” i.e a=a>>2 then a will become a=a/(2^2) . Thus, a=a/(2^2)=1 which can be written as 01 .

right-Shift-in-c-cpp

Example of Right Shift Operator

Applications of right shift operators.

  • Division by Powers of Two : Right shifting a number by n positions is equivalent to dividing it by 2^n and it is very fast.
  • Efficient Calculations : Used in performance-critical applications for fast division operations.
  • Bit Manipulation : Useful in extracting specific bits from data, common in data compression and cryptography.

Important Points of Shift Operators

1. The left-shift and right-shift operators should not be used for negative numbers. The result of is undefined behavior if any of the operands is a negative number. For example, results of both 1 >> -1 and 1 << -1 is undefined.

2. If the number is shifted more than the size of the integer, the behavior is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. For bit shift of larger values 1ULL<<62   ULL is used for Unsigned Long Long which is defined using 64 bits that can store large values.

3. The left-shift by 1 and right-shift by 1 are equivalent to the product of the first term and 2 to the power given element(1<<3 = 1*pow(2,3)) and division of the first term and second term raised to power 2 (1>>3 = 1/pow(2,3)) respectively. 

Must Read: Bitwise Operators in C/C++

author

Please Login to comment...

Similar reads.

  • C++ Bit Manipulation
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment Operators in C Example

    c program to find assignment

  2. C programming +=

    c program to find assignment

  3. Assignment Operators in C

    c program to find assignment

  4. Assignment Operators in C++

    c program to find assignment

  5. C Programming Tutorial

    c program to find assignment

  6. C++ Program to Find Student Grade

    c program to find assignment

VIDEO

  1. Augmented assignment operators in C

  2. Assignment Operator in C Programming

  3. Assignment Operator in C Programming

  4. C Program to Find the Sum or Addition of Linear or 1D Array Elements or Values || By Gmone Lab

  5. c Program for Beginners: Ascending order in c

  6. C Program to compute sum and average using Array

COMMENTS

  1. Assignment Operators in C

    Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=.

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

  3. C Programming Assignment Operators

    Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=".

  4. c

    An assignment expression has the value of the left operand after the assignment. It's to allow things like this: a = b = c; (although there's some debate as to whether code like that is a good thing or not.) Incidentally, this behaviour is replicated in Java (and I would bet that it's the same in C# too). edited Feb 20, 2017 at 8:59.

  5. Assignment and shorthand assignment operator in C

    Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator. For example, consider following C statements. int a = 5; a = a + 2; The above expression a = a + 2 is equivalent to a += 2. Similarly, there are many shorthand assignment operators. Below is a list of shorthand assignment operators in C.

  6. Assignment Operators in C Example

    The Assignment operators in C are some of the Programming operators that are useful for assigning the values to the declared variables. Equals (=) operator is the most commonly used assignment operator. For example: int i = 10; The below table displays all the assignment operators present in C Programming with an example. C Assignment Operators.

  7. C array declaration and assignment?

    Why does C++ support memberwise assignment of arrays within structs, but not generally? Arrays are not pointers. x here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y too is the name of an array, not a pointer. You can do array assignment within structs:

  8. Assignment Operators in C with Examples

    Assignment operators are used to assign value to a variable. The left side of an assignment operator is a variable and on the right side, there is a value, variable, or an expression. It computes the outcome of the right side and assign the output to the variable present on the left side. C supports following Assignment operators: 1.

  9. Assignment Operators in C

    A) 4 B) 8 C) 16 D) 32. Answer: C) 16 Explanation: After right-shifting 8 (binary 1000) by one and then left-shifting the result by two, the value becomes 16 (binary 10000). FAQs. Q. How does the /= operator function? Is it a combination of two other operators? A. The /= operator is a compound assignment operator in C++. It divides the left operand by the right operand and assigns the result to ...

  10. Assignment Operator in C Programming

    Assignment Operators. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. a will be assigned value of 5, and b will be assigned value of 10. "+=":This operator is combination of '+' and '=' operators. This operator first adds the current value of the ...

  11. C All Exercises & Assignments

    Write a C program to find the maximum number between three numbers . Description: You need to write a C program to find the maximum number between three numbers. Conditions: Create three variables in c with name of number1, number2 and number3; Find out the maximum number using the nested if-else statement

  12. Assignment Operator in C

    Assignment Operator in C is a tutorial that explains how to use the operator that assigns a value to a variable in C programming language. It covers the syntax, types, and examples of assignment operator in C. It also provides a quiz and interview questions to test your knowledge. Learn assignment operator in C from javatpoint, a leading online platform for learning various technologies.

  13. C Program to find the student's grade

    The following is a C program to find the grade of the student based on the marks entered by the user. ... Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts; Top 9 Machine Learning Algorithms for Data Scientists;

  14. C programming Exercises, Practice, Solution

    C is a general-purpose, imperative computer programming language, supporting structured programming, lexical variable scope and recursion, while a static type system prevents many unintended operations. C was originally developed by Dennis Ritchie between 1969 and 1973 at Bell Labs.

  15. Job Assignment Problem using Branch And Bound

    Solution 1: Brute Force. We generate n! possible job assignments and for each such assignment, we compute its total cost and return the less expensive assignment. Since the solution is a permutation of the n jobs, its complexity is O (n!). Solution 2: Hungarian Algorithm. The optimal assignment can be found using the Hungarian algorithm.

  16. Assignments

    (This ZIP file contains: 1 .txt file and 2 .c files.) 4 Pointers, arrays, strings, searching and sorting algorithms 5 Linked lists, trees 6a Pointers to pointers, multidimensional arrays, stacks and queues (This ZIP file contains: 1 .txt file and 2 .c files.) 6b Function pointers, hash table

  17. Hungarian Algorithm for Assignment Problem

    The Quadratic Assignment Problem (QAP) is an optimization problem that deals with assigning a set of facilities to a set of locations, considering the pairwise distances and flows between them. The problem is to find the assignment that minimizes the total cost or distance, taking into account both the distances and the flows. The distance matrix a

  18. C Arrays (With Examples)

    Access Array Elements. You can access elements of an array by indices. Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on.. Declare an Array Few keynotes:

  19. C Program to Display Fibonacci Sequence

    nextTerm = t1 + t2; return 0; Output. In this program, we have used a while loop to print all the Fibonacci numbers up to n. If n is not part of the Fibonacci sequence, we print the sequence up to the number that is closest to (and lesser than) n. Suppose n = 100. First, we print the first two terms t1 = 0 and t2 = 1.

  20. C programming examples, exercises and solutions for beginners

    Matrix (2D array) Add two matrices. Scalar matrix multiplication. Multiply two matrices. Check if two matrices are equal. Sum of diagonal elements of matrix. Interchange diagonal of matrix. Find upper triangular matrix. Find sum of lower triangular matrix.

  21. C Exercises

    Q2: Write a Program to find the Sum of two numbers entered by the user. In this problem, you have to write a program that adds two numbers and prints their sum on the console screen. For Example, Input: Enter two numbers A and B : 5 2. Output: Sum of A and B is: 7.

  22. Advanced C Programming

    C Assignments. A1: Write a program to check whether a given number is perfect or not. A2: Write a program to generate Fibonacci numbers less than equals to 'n'. A3: Write a program to print "Hello" in X format. A4: Write a program to read 3 numbers a, r, n, Generate AP, GP, HP. A5: Given the number from 1 to 365 , WAP to find which day of the year.

  23. 7 Best Java Homework Help Websites: How to Choose Your Perfect Match?

    AssignCode is one of the best Java assignment help services that you can entrust with programming, mathematics, biology, engineering, physics, and chemistry. A large professional staff makes this ...

  24. Left Shift and Right Shift Operators in C/C++

    The left shift (<<) is a binary operator that takes two numbers, left shifts the bits of the first operand, and the second operand decides the number of places to shift. In other words, left-shifting an integer "a" with an integer "b" denoted as '(a<<b)' is equivalent to multiplying a with 2^b (2 raised to power b). Syntax.