Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Is there a greedy algorithm to solve the assignment problem?

The assignment problem is defined as:

There are n people who need to be assigned to n jobs, one person per job. The cost that would accrue if the ith person is assigned to the jth job is a known quantity C[i,j] for each pair i, j = 1, 2, ..., n. The problem is to find an assignment with the minimum total cost.

There is a question asking to design a greedy algorithm to solve the problem. It also asks if the greedy algorithm always yields an optimal solution and for the performance class of the algorithm. Here is my attempt at designing an algorithm:

Algorithm Design

Am I correct in saying that my algorithm is of O(n^2)? Am I also correct in saying that a greedy algorithm does not always yield an optimal solution? I used my algorithm on the following cost matrix and it is clearly not the optimal solution. Did I Do something wrong?

Applying greedy algorithm to cost matrix

  • greedy-algorithms
  • assignment-problem

Frank's user avatar

  • $\begingroup$ Algorithms for maximum weight bipartite maximum matching are unfortunately more complicated than that. They don't really follow the greedy paradigm. $\endgroup$ –  Yuval Filmus Commented Apr 7, 2017 at 6:05

The answer of your post question (already given in Yuval comment) is that there is no greedy techniques providing you the optimal answer to an assignment problem.

The commonly used solution is the Hungarian algorithm, see

Harold W. Kuhn, "The Hungarian Method for the assignment problem", Naval Research Logistics Quarterly, 2: 83–97, 1955

for the original paper.

Otherwise your solution seems correct to me, and as usually with greedy algorithms, it will provide you a feasible solution which you may hope to not be "too far" from the global optimal solution.

Seb Destercke's user avatar

Your Answer

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 algorithms greedy-algorithms assignment-problem or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • We spent a sprint addressing your requests — here’s how it went

Hot Network Questions

  • Does the damage from Thunderwave occur before or after the target is moved
  • How to POSIX-ly ignore "warning: command substitution: ignored null byte in input"?
  • Why does Google Maps only rotate 90º but not 180º when I rotate my iPhone?
  • Can compositions "da + preposition" be used as a relative pronoun?
  • Looking for the title of a short story for my students to read about a woman searching for the last man alive
  • LCR Meter U1733C "rn" Symbol Meaning
  • Is "sinnate" a word? What does it mean?
  • Substitute HS Experiment for Synthesis/Decomposition of HgO
  • Positive market impact
  • Recommend an essay, article, entry, author, or branch of philosophy that addresses the futility of arguing for or against free will
  • Identify the story about an author whose work-in-progress is completed by a computer
  • Coping with consequences of a dog bite before buying a puppy
  • Is a "single" cpu safer than multiple cores?
  • Did Joe Biden refer to himself as a black woman?
  • Finding the Zeckendorf Representation of a Positive Integer (BIO 2023 Q1)
  • What methods can quickly determine the coefficient of determination of the data?
  • Where can I find a complete archive of audio recordings of Hitler speeches?
  • Has the Journal of Fluid Mechanics really published more than 800 volumes?
  • What caused the builder to change plans midstream on this 1905 library in New England?
  • Is the variance of the mean of a set of possibly dependent random variables less than the average of their respective variances?
  • Signature of Rav Ovadia Hedaya
  • Understanding top memory bar
  • Real-life problems involving solving triangles
  • DHCP assigned addresses following devices/users and routing

assignment problem in c

Branch and Bound Algorithm

Last updated: March 18, 2024

assignment problem in c

1. Overview

In computer science, there is a large number of optimization problems which has a finite but extensive number of feasible solutions. Among these, some problems like finding the shortest path in a graph  or  Minimum Spanning Tree  can be solved in polynomial time .

A significant number of optimization problems like production planning , crew scheduling can’t be solved in polynomial time, and they belong to the NP-Hard class . These problems are the example of NP-Hard combinatorial optimization problem .

Branch and bound (B&B) is an algorithm paradigm widely used for solving such problems.

In this tutorial, we’ll discuss the branch and bound method in detail.

2. Basic Idea

Branch and bound algorithms are used to find the optimal solution for combinatory, discrete, and general mathematical optimization problems. In general, given an NP-Hard problem, a branch and bound algorithm explores the entire search space of possible solutions and provides an optimal solution.

A branch and bound algorithm consist of stepwise enumeration of possible candidate solutions by exploring the entire search space. With all the possible solutions, we first build a rooted decision tree. The root node represents the entire search space:

example 1-1

Here, each child node is a partial solution and part of the solution set. Before constructing the rooted decision tree, we set an upper and lower bound for a given problem based on the optimal solution. At each level, we need to make a decision about which node to include in the solution set. At each level, we explore the node with the best bound. In this way, we can find the best and optimal solution fast.

Now it is crucial to find a good upper and lower bound in such cases. We can find an upper bound by using any local optimization method or by picking any point in the search space. On the other hand, we can obtain a lower bound from convex relaxation  or  duality .

In general, we want to partition the solution set into smaller subsets of solution. Then we construct a rooted decision tree, and finally, we choose the best possible subset (node) at each level to find the best possible solution set.

3. When Branch and Bound Is a Good Choice?

We already mentioned some problems where a branch and bound can be an efficient choice over the other algorithms. In this section, we’ll list all such cases where a branch and bound algorithm is a good choice.

If the given problem is a discrete optimization problem, a branch and bound is a good choice. Discrete optimization is a subsection of optimization where the variables in the problem should belong to the discrete set. Examples of such problems are 0-1 Integer Programming  or  Network Flow problem .

Branch and bound work efficiently on the combinatory optimization problems. Given an objective function for an optimization problem, combinatory optimization is a process to find the maxima or minima for the objective function. The domain of the objective function should be discrete and large. Boolean Satisfiability , Integer Linear Programming are examples of the combinatory optimization problems.

4. Branch and Bound Algorithm Example

In this section, we’ll discuss how the job assignment problem can be solved using a branch and bound algorithm.

4.1. Problem Statement

Job 1 Job 2 Job 3
A 9 3 4
B 7 8 4
C 10 5 2

We can assign any of the available jobs to any worker with the condition that if a job is assigned to a worker, the other workers can’t take that particular job. We should also notice that each job has some cost associated with it, and it differs from one worker to another.

Here the main aim is to complete all the jobs by assigning one job to each worker in such a way that the sum of the cost of all the jobs should be minimized.

4.2. Branch and Bound Algorithm Pseudocode

Now let’s discuss how to solve the job assignment problem using a branch and bound algorithm.

Let’s see the pseudocode first:

In the search space tree, each node contains some information, such as cost, a total number of jobs, as well as a total number of workers.

Now let’s run the algorithm on the sample example we’ve created:

flowchart 1

4. Advantages

In a branch and bound algorithm, we don’t explore all the nodes in the tree. That’s why the time complexity of the branch and bound algorithm is less when compared with other algorithms.

If the problem is not large and if we can do the branching in a reasonable amount of time, it finds an optimal solution for a given problem.

The branch and bound algorithm find a minimal path to reach the optimal solution for a given problem. It doesn’t repeat nodes while exploring the tree.

5. Disadvantages

The branch and bound algorithm are time-consuming. Depending on the size of the given problem, the number of nodes in the tree can be too large in the worst case.

Also, parallelization is extremely difficult in the branch and bound algorithm.

6. Conclusion

One of the most popular algorithms used in the optimization problem is the branch and bound algorithm. We’ve discussed it thoroughly in this tutorial.

We’ve explained when a branch and bound algorithm would be the right choice for a user to use. Furthermore, we’ve presented a branch and bound based algorithm for solving the job assignment problem.

Finally, we mentioned some advantages and disadvantages of the branch and bound algorithm.

Press ESC to close

Or check our popular categories..., branch and bound | set 4 (job assignment problem).

Let there be N workers and N jobs. Any worker can be assigned to perform any job, incurring some cost that may vary depending on the work-job assignment. It is required to perform all jobs by assigning exactly one worker to each job and exactly one job to each agent in such a way that the total cost of the assignment is minimized.

Branch And Bound | Set 4 (Job Assignment Problem)

Let us explore all approaches for this problem.

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. The Hungarian algorithm has worst case run-time complexity of O(n^3).

Solution 3: DFS/BFS on state space tree A state space tree is a N-ary tree with property that any path from root to leaf node holds one of many solutions to given problem. We can perform depth-first search on state space tree and but successive moves can take us away from the goal rather than bringing closer. The search of state space tree follows leftmost path from the root regardless of initial state. An answer node may never be found in this approach. We can also perform a Breadth-first search on state space tree. But no matter what the initial state is, the algorithm attempts the same sequence of moves like DFS.

Solution 4: Finding Optimal Solution using Branch and Bound The selection rule for the next node in BFS and DFS is “blind”. i.e. the selection rule does not give any preference to a node that has a very good chance of getting the search to an answer node quickly. The search for an optimal solution can often be speeded by using an “intelligent” ranking function, also called an approximate cost function to avoid searching in sub-trees that do not contain an optimal solution. It is similar to BFS-like search but with one major optimization. Instead of following FIFO order, we choose a live node with least cost. We may not get optimal solution by following node with least promising cost, but it will provide very good chance of getting the search to an answer node quickly.

There are two approaches to calculate the cost function:

  • For each worker, we choose job with minimum cost from list of unassigned jobs (take minimum entry from each row).
  • For each job, we choose a worker with lowest cost for that job from list of unassigned workers (take minimum entry from each column).

In this article, the first approach is followed.

Let’s take below example and try to calculate promising cost when Job 2 is assigned to worker A.

Branch And Bound | Set 4 (Job Assignment Problem)

Since Job 2 is assigned to worker A (marked in green), cost becomes 2 and Job 2 and worker A becomes unavailable (marked in red).

Branch And Bound | Set 4 (Job Assignment Problem)

Now we assign job 3 to worker B as it has minimum cost from list of unassigned jobs. Cost becomes 2 + 3 = 5 and Job 3 and worker B also becomes unavailable.

Branch And Bound | Set 4 (Job Assignment Problem)

Finally, job 1 gets assigned to worker C as it has minimum cost among unassigned jobs and job 4 gets assigned to worker C as it is only Job left. Total cost becomes 2 + 3 + 5 + 4 = 14.

Branch And Bound | Set 4 (Job Assignment Problem)

Below diagram shows complete search space diagram showing optimal solution path in green.

Branch And Bound | Set 4 (Job Assignment Problem)

Complete Algorithm:

Below is its C++ implementation.

Categorized in:

Share Article:

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Leave a Reply

Save my name, email, and website in this browser for the next time I comment.

Related Articles

10 steps to quickly learn programming in c#, c program print bst keys in the given range, java program print bst keys in the given range, cpp algorithm – length of the longest valid substring, other stories, c programming – inserting a node in linked list | set 2, c++ program check if a number is multiple of 9 using bitwise operators, summer offline internship.

  • Internship for cse students
  • Internship for it students
  • Internship for ece students
  • Internship for eee students
  • Internship for mechanical engineering students
  • Internship for aeronautical engineering students
  • Internship for civil engineering students
  • Internship for bcom students
  • Internship for mcom students
  • Internship for bca students
  • Internship for mca students
  • Internship for biotechnology students
  • Internship for biomedical engineering students
  • Internship for bsc students
  • Internship for msc students
  • Internship for bba students
  • Internship for mba students

Summer Online Internship

  • Online internship for cse students
  • Online internship for ece students
  • Online internship for eee students
  • Online internship for it students
  • Online internship for mechanical engineering students
  • Online internship for aeronautical engineering students
  • Online internship for civil engineering students
  • Online internship for bcom students
  • Online internship for mcom students
  • Online internship for bca students
  • Online internship for mca students
  • Online internship for biotechnology students
  • Online internship for biomedical engineering students
  • Online internship for bsc students
  • Online internship for msc students
  • Online internship for bba students
  • Online internship for mba students

Internship in Chennai

  • Intenship in Chennai
  • Intenship in Chennai for CSE Students
  • Internship in Chennai for IT Students
  • Internship in Chennai for ECE Students
  • Internship in Chennai for EEE Students
  • Internship in Chennai for EIE Students
  • Internship in Chennai for MECH Students
  • Internship in Chennai for CIVIL Students
  • Internship in Chennai for BIOTECH Students
  • Internship in Chennai for AERO Students
  • Internship in Chennai for BBA Students
  • Internship in Chennai for MBA Students
  • Internship in Chennai for MBA HR Students
  • Internship in Chennai for B.Sc Students
  • Internship in Chennai for M.Sc Students
  • Internship in Chennai for BCA Students
  • Internship in Chennai for MCA Students
  • Internship in Chennai for B.Com Students
  • Internship in Chennai for M.Com Students

Programming / Technology Internship in Chennai

  • Data Science Internship in Chennai
  • Artificial Intelligence Internship in Chennai
  • Web Development Internship in Chennai
  • Android Internship in Chennai
  • Cloud Computing Internship in Chennai
  • .Net Internship in Chennai
  • JAVA Internship in Chennai
  • Ethical Hacking Internship in Chennai
  • IOT Internship in Chennai
  • Machine Learning Internship in Chennai
  • Networking Internship in Chennai
  • Robotics Internship in Chennai
  • Matlab Internship in Chennai

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

assignment-problem

Here are 97 public repositories matching this topic..., root-11 / graph-theory.

A simple graph library

  • Updated Apr 29, 2024

mayorx / hungarian-algorithm

(Kuhn-Munkres) numpy implementation, rectangular matrix is supported (|X| <= |Y|). 100x100000 in 0.153 s.

  • Updated Dec 8, 2022

HalemoGPA / Learn-Js

Elzero Web School Js Course Assignments Solutions

  • Updated May 26, 2024

Gnimuc / Hungarian.jl

The Hungarian(Kuhn-Munkres) algorithm for Julia

  • Updated Jan 29, 2023

aalmi / HungarianAlgorithm

A Java implementation of the Kuhn–Munkres assignment algorithm (Hungarian Algorithm)

  • Updated Aug 10, 2019

HalemoGPA / Learn-CSS

Elzero Web School CSS Course Assignments Solutions

  • Updated Aug 5, 2022

sharathadavanne / hungarian-net

Deep-learning-based implementation of the popular Hungarian algorithm that helps solve the assignment problem.

  • Updated Aug 31, 2023

alieldeba / Elzero-Cpp-Assignments

All C++ Solutions Of Elzero Web School Channel Assignments and elzero.org Website Assignments

  • Updated Sep 6, 2023

jbytecode / OperationsResearchModels.jl

A Julia package for operations research subjects

  • Updated May 22, 2024

jundsp / Fast-Partial-Tracking

Fast partial tracking of audio with real-time capability through linear programming. Hungarian algorithm provides optimal spectral peak-to-peak matching in polynomial time.

  • Updated Mar 6, 2021

YaleDHLab / pointgrid

Transform a 2D point distribution to a hex grid to avoid overplotting in data visualizations

  • Updated Jun 30, 2021

Gluttton / munkres-cpp

Generic implementation of Kuhn-Munkres (Hungarian) Algorithm in C++

  • Updated Oct 14, 2023

phoemur / hungarian_algorithm

An implementation of the Hungarian Algorithm in C++

  • Updated Dec 11, 2018

oddg / hungarian-algorithm

A Go implementation of the Hungarian algorithm

  • Updated Aug 9, 2017

HalemoGPA / Learn-HTML

Elzero Web School HTML Course

  • Updated Sep 24, 2023

dutta-alankar / PH-354-2019-IISc-Assignment-Problems

Solutions to the complete set of assignment problems which I did while crediting Computational Physics course by Prof. Manish Jain at IISc, Physical Sciences department on 2019

  • Updated May 30, 2021

Ibrahim5aad / kuhn-munkres-algorithm

A python program to solve assignment problem by the Kuhn–Munkres algorithm (The Hungarian Method).

  • Updated Oct 22, 2021

EvanOman / AuctionAlgorithmScala

Scala Implementation of Bertsekas' Auction Algorithm

  • Updated Jun 24, 2016

i10416 / munkres

Munkres(Hangarian) Algorithm Implimentation for Scala

  • Updated Jun 4, 2023

Improve this page

Add a description, image, and links to the assignment-problem topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the assignment-problem topic, visit your repo's landing page and select "manage topics."

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

1. Simple Assignment Operator (=)

This assigns the value on the right-hand side (RHS) to the variable on the left-hand side (LHS). You can use a literal, another variable, or an expression in the assignment statement.

Example of Simple Assignment Operator

In this example, we have assigned the value 30 to the variable x using the assignment operator (=).

2. Compound Assignment Operators

In addition to the = operator, you can combine arithmetic and bitwise operators with the = symbol to form an augmented or compound assignment operator.

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

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

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

One line assignment according condition in c/c++

i would like to know which one of these assignments is faster, safer, better etc. and possibly why:

  • conditional-statements
  • variable-assignment

Neko's user avatar

  • 5 Reading in the character from the file is going to eclipse the time it takes to execute either line. –  Cameron Commented Apr 28, 2012 at 18:41
  • 2 Surely 1 is more readable. Whatever the compiler produces in this situation is unlikely to have a noticeable impact on performance. –  user1233508 Commented Apr 28, 2012 at 18:41
  • @DCoder: +1 - readability is far more important in this case then minor hypothetical (and premature) micro-optimisations –  Paul R Commented Apr 28, 2012 at 19:01

2 Answers 2

Regarding speed, this would be at least as fast as choice 2:

Whether that would be faster than choice 1 is not immediately obvious to me. However, for tuned performance on an unknown platform, I think that I like the suggested variant on choice 2. The reason is that, at the hardware level, choice 2 (original or variant) does not involve reloading the program counter, but invokes a relatively straightforward shift-register operation, involving relatively few transistors. (Actually, if you want to get really technical about it, I am given to understand that the shift is probably accomplished by multiplexing. To detail that would be too much for the present format, but the point is that the output of (choice == 'y' || choice == 'Y') is effectively piped straight to one of the multiplexer's control lines. Anyway, it's really fast.)

Regarding whether one can safely use the evaluated condition in the manner suggested, ISO/IEC 9899:1999 (E), sect. 6.5.14.3, guarantees that one can safely do this. It reads, "The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int."

(@PaulR rightly observes that electronic-theoretical considerations like the ones this answer offers are not decisive. One must profile actual code on an actual platform to tell for sure which is faster. Nor is this a mere quibble on @PaulR's part. It is all well to argue that choice 2 would be faster, but this does not mean that is is faster. Depending on the CPU in use, branch-predicting or other hardware could promote choice 1, nor would I be extremely surprised if it did.)

thb's user avatar

  • Yeah, i guess like this it would be even faster than choice 2, still is it 100% safe to use evaluated condition as variable ? –  Neko Commented Apr 28, 2012 at 18:47
  • -1: you really can't make any general predictions about the efficiency of the above examples, particularly without knowing anything about the specific compiler or platform –  Paul R Commented Apr 28, 2012 at 18:57
  • @Neko: It's safe. I have modified the answer above to explain why. –  thb Commented Apr 28, 2012 at 18:57
  • 1 @PaulR: Wow, you're a tough audience. Of course you are right, but general electronic principles do come to bear, whether the C standard guarantees their preformance or not. I suspect that multiplexing a bit-shift is cheaper than invoking the CPU's branch-prediction hardware, especially if the brand-predictor guesses wrong and has to flush a pipeline. But what do I know? Nevertheless, your point is well taken (though I'm admittedly a little grumpy about the downvote). –  thb Commented Apr 28, 2012 at 19:04
  • @thb: sorry, but it's a pet peeve of mine - making blind assumptions/predictions about performance, particularly without taking compiler and CPU into consideration, is the worst kind of premature optimisation. If performance actually matters in a given case, then profile the different options - evidence in the form of measured performance is infinitely more useful than guesswork. –  Paul R Commented Apr 28, 2012 at 19:08

In my opinion 'Choice 1' is 'faster' because there's only one assignment operation done after the comparison. In 'Choice 2' it does '+' and '<<' along with the comparison part. 'Choice 1' is 'safer' because it is more readable than the other choice so programmer will have less chance to do error in writing it. Choice 1 is 'better' because of the previous two reasons.

Ayub's user avatar

  • The only problem is that choice 1 is using branching (some compare and jump instruction), where choice 2 is not. –  Neko Commented Apr 28, 2012 at 18:56
  • 1 @Neko: You can't know whether the compiler will use branches or not, or what the penalty for branches might be without knowing details of the platform etc –  Paul R Commented Apr 28, 2012 at 18:58
  • -1: all predictions are meaningless without taking compiler and platform into consideration –  Paul R Commented Apr 28, 2012 at 19:00
  • [sorry,comments don't allow newlines]Dear Neko, I understand what you thought. But look at the code generated by 'gcc' with '-S' option: Choice 1: movl %eax, -4(%rbp) cmpl $121, -4(%rbp) je .L2 cmpl $89, -4(%rbp) jne .L3 .L2: movl $256, %eax jmp .L4 .L3: movl $128, %eax .L4: movl %eax, -8(%rbp) movl $0, %eax leave Choice 2: movl %eax, -4(%rbp) cmpl $121, -4(%rbp) je .L2 cmpl $89, -4(%rbp) jne .L3 .L2: movl $1, %eax jmp .L4 .L3: movl $0, %eax .L4: sall $7, %eax subl $-128, %eax movl %eax, -8(%rbp) movl $0, %eax leave See, the L4 section in both cases. Choice is yours. –  Ayub Commented Apr 28, 2012 at 19:06
  • Yes, I agree with Paul R, it is Platform and/or Compiler specific. –  Ayub Commented Apr 28, 2012 at 19:17

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 conditional-statements 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

  • DHCP assigned addresses following devices/users and routing
  • How do I know that my saddle fits me
  • Why does black have a higher win rate in Exchange French?
  • Infinity is not a number
  • Animate multiple material transitions smoothly
  • TTL to RS485 converter problems
  • Fill the grid subject to product, sum and knight move constraints
  • Is the variance of the mean of a set of possibly dependent random variables less than the average of their respective variances?
  • Why does King Aegon speak to his dragon in the Common Tongue (English)?
  • Coincidence between coefficients of tanh(tan(x/2)) and Chow ring computations?
  • 为什么「五二〇运动」没有别称「五廿运动」?
  • Positive market impact
  • Would moving the equator to the Tropic of Cancer increase Earth's arable land?
  • Does there exist a Dehn filling of an irreducible 3-manifold with toroidal boundaries which is still irreducible?
  • Can computer components be damaged if they stay off for a long time?
  • Why can't CVP be trivially reduced to SVP by shifting?
  • Are there countries where only voters affected by a given policy get to vote on it?
  • How is 11:22 four minutes slow if it's actually 11:29?
  • Can Black Lotus alone enable the Turn 1 Channel-Fireball combo?
  • Why do jet aircraft need chocks when they have parking brakes?
  • If someone clearly believes that he has witnessed something extraordinary very clearly, why is it more reasonable to believe that they hallucinated?
  • Understanding top memory bar
  • Is ElGamal homomorphic encryption using additive groups works only for Discrete Log ElGamal? What about EC ElGamal?
  • Where can I find a complete archive of audio recordings of Hitler speeches?

assignment problem in c

C Data Types

C operators.

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

C File Handling

  • C Cheatsheet

C Interview Questions

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

C Variables and Constants

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

C Input/Output

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

Assignment Operators in C

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

C Control Statements Decision-Making

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

C Arrays & Strings

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

C User-Defined Data Types

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

C Storage Classes

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

C Memory Management

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

C Preprocessor

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

Miscellaneous

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

assignment problem in c

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

Different types of assignment operators are shown below:

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

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

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

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

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

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

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

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

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

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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 −

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

swayam-logo

Problem Solving Through Programming In C

  • Formulate simple algorithms for arithmetic and logical problems
  • Translate the algorithms to programs (in C language)
  • Test and execute the programs and  correct syntax and logical errors
  • Implement conditional branching, iteration and recursion
  • Decompose a problem into functions and synthesize a complete program using divide and conquer approach
  • Use arrays, pointers and structures to formulate algorithms and programs
  • Apply programming to solve matrix addition and multiplication problems and searching and sorting problems 
  • Apply programming to solve simple numerical method problems, namely rot finding of function, differentiation of function and simple integration
--> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> --> -->

Note: This exam date is subjected to change based on seat availability. You can check final exam date on your hall ticket.

Page Visits

Course layout, books and references, instructor bio.

assignment problem in c

Prof. Anupam Basu

Course certificate.

  • Assignment score = 25% of average of best 8 assignments out of the total 12 assignments given in the course. 
  • ( All assignments in a particular week will be counted towards final scoring - quizzes and programming assignments). 
  • Unproctored programming exam score = 25% of the average scores obtained as part of Unproctored programming exam - out of 100
  • Proctored Exam score =50% of the proctored certification exam score out of 100

assignment problem in c

DOWNLOAD APP

assignment problem in c

SWAYAM SUPPORT

Please choose the SWAYAM National Coordinator for support. * :

Course Status : Completed
Course Type : Elective
Duration : 12 weeks
Category :
Credit Points : 3
Undergraduate/Postgraduate
Start Date : 25 Jul 2022
End Date : 14 Oct 2022
Enrollment Ends : 08 Aug 2022
Exam Date : 29 Oct 2022 IST

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

IMAGES

  1. Solved Assignment Problems in C (with Algorithm and Flowchart

    assignment problem in c

  2. [Week 10] NPTEL Problem Solving Through Programming In C Assignment

    assignment problem in c

  3. PPT

    assignment problem in c

  4. Solved Assignment Problems in C++

    assignment problem in c

  5. Problem solving through Programming In C||WEEK-6 Assignment Answers

    assignment problem in c

  6. Assignment Operators in C with Examples

    assignment problem in c

VIDEO

  1. Alternative Solution in Assignment Problem

  2. Assignment Operator in C Programming

  3. NPTEL Problem Solving Through Programming In C Week 0 Quiz Assignment Solution

  4. Exercise 1: How to solve coding problems

  5. Assignment Operator in C Programming

  6. NPTEL Problem Solving through Programming in C ASSIGNMENT 6 ANSWERS 2024

COMMENTS

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

  2. Hungarian Algorithm for Assignment Problem

    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. 11 min read. Job Assignment Problem using Branch And Bound. Let there be N workers and N jobs. Any worker can be assigned to perform any job, incurring some cost that may vary depending on ...

  3. Assignment problem

    The assignment problem is a fundamental combinatorial optimization problem. In its most general form, the problem is as follows: The problem instance has a number of agents and a number of tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment.

  4. Assignment Problem and Hungarian Algorithm

    The assignment problem is a special case of the transportation problem, which in turn is a special case of the min-cost flow problem, so it can be solved using algorithms that solve the more general cases. Also, our problem is a special case of binary integer linear programming problem (which is NP-hard). But, due to the specifics of the ...

  5. PDF 7.13 Assignment Problem

    Equivalent Assignment Problem c(x, y) 00312 01015 43330 00110 12204 cp(x, y) 3891510 41071614 913111910 813122013 175119 8 13 11 19 13 5 4 3 0 8 9 + 8 - 13 10 Reduced costs. For x # X, y # Y, define cp(x, y) = p(x) + c(x, y) - p(y). Observation 1. Finding a min cost perfect matching with reduced costs

  6. Is there a greedy algorithm to solve the assignment problem?

    The assignment problem is defined as: There are n people who need to be assigned to n jobs, one person per job. The cost that would accrue if the ith person is assigned to the jth job is a known quantity C[i,j] for each pair i, j = 1, 2, ..., n. The problem is to find an assignment with the minimum total cost.

  7. Branch and Bound Algorithm

    Now let's discuss how to solve the job assignment problem using a branch and bound algorithm. Let's see the pseudocode first: algorithm MinCost(M): // INPUT // M = The cost matrix // OUTPUT // The optimal job assignment minimizing the total cost while true: E <- LeastCost() if E is a leaf node: print(E) return for each child S of E: Add(S) S.parent <- E

  8. PDF Section 7.5: The Assignment Problem

    Section 7.5: The Assignment ProblemIn this section, we investigate the assignment problem- That is, given n jobs and n people, ssign every job to a unique person. Typically, there are either costs or time involved, and we would want to make the assignments in such. a way as to minimize this quantity.Let's be more speci c with the example from ...

  9. Solved Assignment Problems in C (with Algorithm and Flowchart)

    Solved Assignment Problems in C (with Algorithm and Flowchart) Q1. Create a program to compute the volume of a sphere. Use the formula: V = (4/3) *pi*r 3 where pi is equal to 3.1416 approximately. The r is the radius of sphere. Display the result. Q2.

  10. PDF 17 The Assignment Problem

    Then X∗ solves the assignment problem specified by C since z(X∗)=0and z(X) ≥ 0 for any other solution X.ByExample5,X∗ is also an optimal solution to the assignment problem specified by C.NotethatX∗ corresponds to the permutation 132. The method used to obtain an optimal solution to the assignment problem specified by C

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

  12. PDF On Approximation Methods for the Assignment Problem*

    Definition of Assignment Problem. The statement of the assignment problem is as follows: There are n men and n jobs, with a cost c, for assigning man i to job j. It is required to assign all men to jobs such that one and only one man is assigned to each job and the total cost of the assignments is minimal.

  13. C Exercises

    This C Exercise page contains the top 30 C exercise questions with solutions that are designed for both beginners and advanced programmers. It covers all major concepts like arrays, pointers, for-loop, and many more. So, Keep it Up! Solve topic-wise C exercise questions to strengthen your weak topics.

  14. Solved Assignment Problems in C

    Solved Assignment Problems in C - Part1. October 3, 2020 Gopal Krishna 3306 Views 0 Comments assignment problems in C, C programming. Q1. Create a program to compute the volume of a sphere. Use the formula: V = (4/3) *pi*r 3 where pi is equal to 3.1416 approximately. The r is the radius of sphere. Display the result.

  15. assignment-problem · GitHub Topics · GitHub

    Add this topic to your repo. To associate your repository with the assignment-problem topic, visit your repo's landing page and select "manage topics." GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 420 million projects.

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

  17. One line assignment according condition in c/c++

    1. Regarding speed, this would be at least as fast as choice 2: bSize = 128 << (choice == 'y' || choice == 'Y'); Whether that would be faster than choice 1 is not immediately obvious to me. However, for tuned performance on an unknown platform, I think that I like the suggested variant on choice 2. The reason is that, at the hardware level ...

  18. PDF Solved Assignment Problems in C (with Algorithm and Flowchart)

    Solved Assignment Problems in C (with Algorithm and Flowchart) Q1. Create a program to compute the volume of a sphere. Use the formula: V = (4/3) *pi*r3where pi is equal to 3.1416 approximately. The r is the radius of sphere. Display the result. Algorithm Flowchart Program. 1.

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

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

  21. Assignments

    Writing, compiling, and debugging programs; preprocessor macros; C file structure; variables; functions and problem statements; returning from functions 2 Types, operators, expressions 3 ... assignment_turned_in Programming Assignments with Examples. Download Course.

  22. Problem Solving Through Programming In C

    Learners enrolled: 29073. ABOUT THE COURSE : This course is aimed at enabling the students to. Formulate simple algorithms for arithmetic and logical problems. Translate the algorithms to programs (in C language) Test and execute the programs and correct syntax and logical errors. Implement conditional branching, iteration and recursion.

  23. Assignment Operator in C

    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 %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A. B = A; // Assign operand A to the B.