Programming by Doing
“the best way to learn is to do.” - p.r. halmos.
If you've ever tried to teach yourself programming and couldn't quite get going, then these assignments are for you. Refined over fifteen years, these are the assignments I have used to teach the basics of Java to nearly 2,000 ordinary public school students over my career.
Buy My Books!
If you are having trouble figuring out how to do these assignments without help, then my book with videos “ Learn Java the Hard Way ” will explain things a lot better. (Especially if you have never coded before!)
Or if you have finished most of these assignments and are ready for the object-oriented side of Java, “ Learn Object-Oriented Java the Hard Way ” is the book for you!
If you have any questions about these assignments, please read the Frequently-Asked Questions at the bottom of this page.
Happy coding! - Graham Mitchell
Last updated: Saturday, 2015-11-28
Frequently-Asked Questions
No, I didn't forget. Back in 2005, I didn't have any assignments to explain new concepts. I taught my students everything through lectures.
Then in 2010 I stopped lecturing and started creating "assignments" to replace my lectures. I got some of these completed, and you see them here. Students worked through the material at their own pace and asked me questions in person about anything that I hadn't gotten around to.
Finally, in 2013 I wrote “ Learn Java the Hard Way ”. Now students now use my book to learn each concept and then they use the rest of the assignments listed here to practice.
So the explanations for some of the later assignments (like File Input & Output) aren't "missing"; they never existed. Sorry for the inconvenience!
Browse Course Material
Course info, instructors.
- Prof. Eric Grimson
- Prof. John Guttag
Departments
- Electrical Engineering and Computer Science
As Taught In
- Programming Languages
Introduction to Computer Science and Programming
Assignments.
You are leaving MIT OpenCourseWare
- Assignments
- Office hours
- Forum & email
- Other resources
How assignments are graded
Written by Julie Zelenski
We know that you will invest a lot of time into completing the programming assignments and the results of those efforts will be your biggest source of accomplishment (and frustration :-) in this course. We will celebrate and reward your work by counting the assignments for a healthy chunk of your course grade. Therefore, we want you to understand our standards and the grading process we use, so you can be sure to capture all the points you deserve.
We view grading as an important commitment we are making to help you grow as a programmer. Our grading process is designed to thoroughly exercise your program and the grading TA will review your code to provide comprehensive and thoughtful feedback. Our grade report will highlight the strengths of your work, as well as point out the ways in which you can improve. Some might say that our grading is thorough to excess (we are known for poking our nose into every nook and cranny and torturing your code with our battery of tests :-) but the care we take shows our respect and reciprocation for the effort you put into creating it. In order to be able to provide a thorough evaluation for all submissions with a relatively small staff, we have developed automated tools to assist with the mechanical aspects (the infamous "autotester") so as to free up our human expertise for providing qualitative feedback in the code review.
We evaluate each submission in two broad categories: functionality and code quality . For functionality, we assess your program's effectiveness from an external perspective. We are not looking at code, but testing its behavior. For code quality, we apply quality metrics and do a individual review of your code to appraise its design and readability.
How we evaluate functionality
Functionality measures how successfully the program executes on a comprehensive set of test cases. We create our test suite by working from the original program specification to identify a list of expected behaviors and write a test case for each. We use the autotester to run a submission on each test and award points for each successful result. Thus, the resulting functionality score is a direct reflection of how much observably correct behavior your program exhibited. This process is completely automated; the grader does not search your code to find bugs and deduct for them, nor do they appraise the code and award points for tasks that are attempted or close to correct.
Our functionality test suite is a mix of:
- sanity Sanity is intended to verify basic functionality on simple inputs. These tests are published to you as sanity check.
- comprehensive This is a battery of tests, each targeted at verifying a specific functional requirement, such as case-insensitive handling or the expected response for an unsuccessful search. Taken together, the comprehensive tests touch on all required functionality. We architect these tests to be as independent and orthogonal as possible to avoid interference between features.
- robustness These tests verify the graceful handling of required error conditions and proper treatment of exceptional inputs.
- stress The stress cases push the program harder, supplying large, complex inputs and exercising program features in combination. Anything and everything is fair game for stress, but the priority is on mainstream operation with little trafficking in extreme/exceptional conditions.
A typical rubric might dedicate 50% of the functionality points for passing sanity check, 30% to the comprehensive coverage, and 10% each to the robustness and stress components.
You may ask: does this scheme double-ding some errors? Yes, a program that fails a comprehensive case often fails a stress case due to the same root cause. But this bug was prevalent in both simple and complex scenarios, which means there was more opportunity to observe it and it was more detrimental to the program's overall correctness. In other words, we are ok with applying both deductions and have configured the point values with this in mind. :-) Contrast this with a bug that only triggers in a narrow context and thus fails just one test. The smaller deduction indicates this bug was more obscure, harder to uncover, and only slightly diminished correctness. The total functionality score is not computed by counting up bugs and penalizing them; we award points for observable, correct functionality. A submission could lose a large number of points for several failures all stemming from a single, critical off-by-one error; another submission can lose the same number of points due to a plethora of underlying bugs. Both submissions received the same score because they demonstrated the same amount of "working/not working" when tested.
What about partial credit? Earning partial credit depends on having correctly implemented some observable functionality. Consider two incomplete submissions. One attempts all the required functionality but falls short (imagine it had a tiny flaw in the initial task, such as reading the input file, which causes all output to be wrong despite that the rest of the code may have been totally correct). This submission would earn few functionality points. The second attempts only some features, but correctly implements those. This submission can earn all the points for the cases that it handles correctly, despite the broken/missing code for the additional requirements. This strongly suggests a development strategy where you add functionality feature-by-feature, not attempting to implement all the required functionality in one fell swoop. I call this the "always have a working program" strategy. During development, the program will not yet include all the required features, but the code so far works correctly for the features that are attempted. From there, extend the program to handle additional cases to earn additional functionality points, taking care not to break any of the currently working features.
The mechanics of the autotester
Understanding of the process we use can help you properly prepare your project for submission and avoid surprises in grading.
Output conformance is required . The autotester is just a fancy version of our sanity check tool. It executes your program and compares its output to what is expected. It is vital that your program produce conformant output in order to be recognized as the exact match the autotester is looking for. If you change the format or leave stray debugging printfs behind, your output may be misread. For example, consider the outputs below:
Although programs A and B seem to compute the appropriate information, they don't match the output format (A adds an extra = character and B inverted the columns). The A and B programs would fail every functionality test-- yikes! To avoid this happening to you, be sure to use sanity check and follow through to resolve any discrepancies. We do not adjust scores that were mis-evaluated because the submission didn't conform to sanity check.
Pass/fail scoring . Each automated test is scored as either passed or failed, without gradations for "more" or "less wrong" as such distinctions are difficult to automate and fraught with peril. Is missing some lines of output better than having the right lines in the wrong order or producing the correct output then crashing? Both are scored by the autotester as incorrect for that test.
Timeout . The autotester employs a hard timeout to avoid stalling on potentially infinite loops. The hard timeout is generous but not unbounded (typically 10x the sample). A grossly inefficient program that executes more than an order of magnitude more slowly than the reference runs the risk of losing functionality points due to tripping the hard timeout on tests it was unable to complete in time. We do not re-run tests with ever-increasing timeouts to accommodate these programs.
Grader judgment . Most functionality cases are automatically scored without any involvement from the grader. For robustness cases and other error conditions, the autotester observes whether the program detect the problem, how it reports it to the user, and whether it appropriately handles it. The wording of your error messages is not required to match the sample program, but doing so guarantees full credit from the autotester. When the wording doesn't match, the autotester defers to the grading TA who makes the call on whether the feedback is sufficiently informative, accurate, and actionable to earn full credit. (Not to stifle your creativity, but the risk-free strategy to avoid losing points is to follow our example :-)
How we evaluate quality
In addition to the automated tests for functionality, we also evaluate how well your program meets our standards for clean, well-written, well-designed code. Although good quality code is highly correlated with correct functionality, the two can diverge, e.g. a well-written program can contain a lurking functionality flaw or a mess of spaghetti code can manage to work correctly despite its design. Make it your goal for your submission to shine in both areas!
We use automated tests for these quality metrics:
Clean compile
We expect a clean build: no warnings, no errors. Any error will block the build, meaning we won't be able to the test the program, so build errors absolutely must be addressed before submitting. Warnings are the way the compiler draws attention to a code passage that isn't an outright error but appears suspect. Some warnings are mild/harmless, but others are critically important. If you get in the habit of keeping your code compiling cleanly, you'll never miss a crucial message in a sea of warnings you are casually ignoring. We apply a small deduction if you leave behind unresolved build warnings.
Clean run under valgrind
We look for an error-free, leak-free report from Valgrind. In scoring a Valgrind report, leaks warrant only a minor deduction whereas memory errors are heavily penalized. Anytime you have an error in a Valgrind report, consider it a severe red flag and immediately prioritize investigating and resolving it. Unresolved memory errors can cause all manner of functionality errors due to unpredictable behavior and crashes. Submitting a program with a memory error will not only lose points in the Valgrind-specific test, but runs the risk of failing many other tests that stumble over the memory bug. Leaks, on the other hand, are mostly quite harmless and working to plug them can (and should) be postponed until near the end of your development. Unresolved leaks rarely cause failures outside of the Valgrind-specific test.
Reasonable efficiency
We measure submissions against the benchmark solution and observe whether it performs similarly both in terms of runtime and memory usage. Our assignment rubric typically designates a small number of points for runtime and memory efficiency. A submission earns full credit by being in the same ballpark as the sample program (i.e. "ballpark" translates to within a factor of 2-3). Our sample is written with a straightforward approach and does not pursue aggressive optimization. Your submission can achieve the same results without heroics, and that it what we want to encourage. There is no bonus for outperforming this benchmark and we especially do not want you to sacrifice elegance or complicate the design in the name of efficiency (which will displease the TA during code review). Note that gross inefficiency (beyond 10x) puts you at risk of losing much more than the designated efficiency points due to the hard timeout on the autotester. if your program is in danger of running afoul of the hard timeout, it is a clear sign you need to bring your attention to correcting the inefficiency to avoid losing points for functionality tests that exceed hard timeout in addition to the regular efficiency deductions.
For both the Valgrind and efficiency tests, we try to ignore issues of functional correctness if they don't otherwise interfere with the evaluation. For example, if the program attempts to reassemble and gets the wrong answer, its Valgrind report or runtime can still be evaluated. However, if the program is sufficiently buggy/incomplete (e.g. discards input or crashes), such inconclusive results can lead to loss of points.
Unless otherwise indicated in the problem statement, we do not require recovery, memory deallocation, or other cleanup from fatal errors, you are allowed to simply exit(1).
Code review
The most important part of the quality feedback is the TA's commentary from the code review. The TA will read your code as in the role of a team manager giving feedback before accepting the code into the team's repository. Our standards should be familiar from CS106: clear, elegant code that is readable, cleanly designed, well-decomposed, and commented appropriately. Read Nick Parlante's hilarious Landmarks in coding quality . The TA's review will identify notable issues found when your reading your code and point out the highlights and opportunities for improvement. The TA also assigns a bucket for the key tasks being evaluated. Most assignments will be to the median bucket (designed [ok]) which means the code is "reasonable". It likely has a number of small issues, but on balance is holding steady in the midst of the peer group and is not notably distinguished up or down. Code that is outstanding we will reward with the [+] bucket, while code that is more troubled will land in the [-] bucket. In rare cases where we need to send an even stronger message, there is a [--] bucket. Your most important takeaways from the code review will come in detailed feedback given in the embedded comments marking up your code, so that's where your should focus your attention. The bucket serves to confirm that you're meeting expectation [ok] or that you are over[+]/under[-] performing.
Below is a list of code quality expectations in the base rubric for the code review of all assignments. There may be additional entries in a rubric specific to a particular assignment.
Cleanliness/readability
- code is free of clutter: remove all dead code and unused vars/fns
- split long lines if necessary (screenwidth ~120 chars)
- 2-4 spaces per indent level (use spaces to indent instead of tabs to avoid editor inconsistency)
- whitespace used to visually support logical separation
- good naming conventions help avoid need for additional commentary
- use consistent scheme for capitalization/underscores
- use constants/#define'd/sizeof instead of hardcoded numbers
- overview comments (per-function, per-module) with summary highights
- inline comments used sparingly where needed to decipher dense/complex lines
- no excess verbiage that reiterates what code itself already says
Language conventions
- choose the most clean, direct, conventional syntax available to you, e.g. ptr->field instead of (*ptr).field
- functionally equivalent but more common to use subscript when accessing an individual array element, pointer arithmetic when accessing subarray
- avoid unnecessary use of obscure constructs (such as comma operator, unions)
- bool type from stdbool.h, static qualifier on private functions, const for read-only pointers
Program design
- program flow decomposed into manageable, logical pieces
- function interfaces are clean and well-encapsulated
- appropriate algorithms used, coded cleanly
- when you need same lines more the once, don't copy and paste -- unify!
- string manipulation, formatted I/O, sort/search, type conversion, etc.
Data structures
- data structures are well-chosen and appropriate
- no redundant storage/copying of data
- no global variables
Pointers/memory
- no unnecessary levels of indirection in variable/parameter declarations
- uses specific pointee type whenever possible, void* only where required
- low-level pointer manipulation/raw memory ops used only when required
- allocation uses appropriate storage (stack versus heap, based on requirements)
- allocations are of appropriate size
- use typecasts only and exactly where necessary and appropriate
Investing in testing
Succeeding on the functionality tests is a measure of your achievement in implementing the program requirements, but is also a reflection of your testing efforts. The more thorough you are in testing, the more bugs you can find and fix. High assignment scores are strongly correlated with good testing. I believe that most submissions come in with no known bugs, that is, had you observed the bug, you would have fixed it before submitting. But not everyone puts the same time into finding the bugs in the first place. Testing is an important part of the process. Your efforts to identify the inputs or code paths that need to be exercised to get full coverage and testing and re-testing throughout development can make a huge difference in results. (read our thoughts on effective software testing for advice on tactics)
When I create an assignment, I also put together extensive tests we plan to subject your submissions to. Why not give those tests to you up front? Is this stinginess just further evidence of my commitment to student cruelty? Oh, probably :-) But it is also true that your boss/advisor is not going to hand you an exhaustive test suite when assigning you a task. Along with designing and writing the code, a professional engineer is responsible for constructing test inputs, devising strategies, and/or building tools that allow them to verify their work. These skills are not trivial and require practice. Consider the CS107 assignments as chock-full of opportunities for you to gain proficiency in testing.
It is such a bummer to have worked hard on your submission only to get back our grading report with failures from bugs you would have fixed if only you had known about them! This sad outcome is entirely avoidable-- thorough testing allows you to find those bugs, which means you can fix them and earn full points on functionality. That totally rocks!
Interpreting our feedback
A grading report gives a list of the test cases and the pass/fail result from executing it against your program. Each test is identified with a short summary description of what was being tested. If you would like to know more about a particular case, you may ask in email or better, come to office hours where we can manually re-run the test and walk you through it. Note that we do not give out test cases as part of maintaining a level playing field for future students. For the code review, we return your code marked up with our comments. This individualized feedback on your code quality will highlight opportunities for future improvement and commend your successes. Please take the time to read and reflect on all of the notations made by your grading TA, and use email or office hours to resolve any questions or misunderstandings about the feedback.
Frequently asked questions about assignment grading
How does a code review bucket map to a score are assignment grades curved how do assignments figure into the course grade.
Answers to these and other burning questions about how course grades are determined .
Can I get a regrade? I think the autotester results are wrong.
We have invested much time in our tools to try to ensure they evaluate the submissions correctly and consistently and we are fairly confident in them. But given we're human and it's software, mistakes can happen and it is important to us to correct them. If you believe there is a grading error due to a bug in our tools/tests, please let us know so we will investigate further. If there is a problem, we will be eager to fix it and correct the scores for all affected submissions.
My program worked great on sanity check, but still failed many grading tests. Why?
The information from sanity check is only as good as the test cases being run. The default cases supplied with sanity check are fairly minimal. Passing them is necessary, but not sufficient, to ensure a good outcome. You gain broader coverage by creating your own custom tests. The more comprehensive your own custom tests, the more confidence you can have in the results.
I ran Valgrind myself and got a clean report but my assignment grade docked me for errors/leaks. What gives?
We run a Valgrind using one of our larger comprehensive test cases. You should do the same. Getting a clean Valgrind report on a simple test case confirms the correctness of that particular code path, but only that path. If you run Valgrind on a diverse set of code paths, you be able to additionally confirm the absence/presence of memory issues lurking in those parts and will not be caught unaware by what we find there.
How can I tell what bug caused me to fail a particular test? Can you send me the test input to reproduce it myself?
The grade report includes a summary statement of the objective of each test, but they are admittedly terse. If you're in need of further detail, catch up with us in office hours or send us an email. We can talk you through the test and its result on your submission so you better understand what went wrong. We do not publish or release our test inputs.
If I can't get my program working on the general case, can I earn sanity points by hard-coding my program to produce the expected output for the sanity inputs so that it "passes" sanity?
No. Any submission that deliberately attempts to defraud the results of automated testing will be rejected from grading and receive a 0 score for all tests.
Is it better to submit by due date and earn the on-time bonus or sacrifice the bonus to spend more time testing/polishing?
It depends. If your program has no known problem or only very minor issues, definitely make the on-time submission and enjoy the bonus! You can followup with additional testing after the fact and re-submit if you find something critical lurking. The on-time bonus is typically a 5% bump, enough to counteract a failure or two on a grading test, but not much more. Best to resolve any substantial issues before submit, using the free late days up to slip to the hard deadline.
My indentation looked fine in my editor, but misaligned when displayed for code review. What gives?
If your file has mixed tabs and spaces, the expansion of tabs into spaces can change when loaded into a editor/viewer with settings different than your own. You can configure your editor to always use only spaces for indentation as one means to avoid such surprises or use indent to post-process your final version before submission. We do note wonky indentation in code review and recommend you fix in future to improve the viewing experience for your grader, but indentation does not impact the style bucket grading unless grossly inconsistent.
Which TA grades my submissions?
We randomly shuffle grading TA per assignment. The functionality tests are all autoscored, the grading TA handles any judgment calls and the code review. The TA who reviewed your submission is shown in the header of the grade report. All TAs work from a shared rubric and the head TA does a meta-review for consistent application and calibration across graders.
I don't understand or disagree with my code review. Who can I talk to about this?
You can email the TA who graded your submission to ask for clarification or further explanation of any unclear feedback. To challenge the rubric or its application, you'll need to take it up with me (Julie) :-). Come by my office hours!
Learn Python practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, learn python interactively, python introduction.
- Get Started With Python
- Your First Python Program
- Python Comments
Python Fundamentals
- Python Variables and Literals
- Python Type Conversion
- Python Basic Input and Output
Python Operators
Python flow control.
Python if...else Statement
- Python for Loop
- Python while Loop
- Python break and continue
- Python pass Statement
Python Data types
- Python Numbers and Mathematics
- Python List
- Python Tuple
- Python String
- Python Dictionary
- Python Functions
- Python Function Arguments
- Python Variable Scope
- Python Global Keyword
- Python Recursion
- Python Modules
- Python Package
- Python Main function
Python Files
- Python Directory and Files Management
- Python CSV: Read and Write CSV files
- Reading CSV files in Python
- Writing CSV files in Python
- Python Exception Handling
- Python Exceptions
- Python Custom Exceptions
Python Object & Class
- Python Objects and Classes
- Python Inheritance
- Python Multiple Inheritance
- Polymorphism in Python
Python Operator Overloading
Python Advanced Topics
- List comprehension
- Python Lambda/Anonymous Function
- Python Iterators
- Python Generators
- Python Namespace and Scope
- Python Closures
- Python Decorators
- Python @property decorator
- Python RegEx
Python Date and Time
- Python datetime
- Python strftime()
- Python strptime()
- How to get current date and time in Python?
- Python Get Current Time
- Python timestamp to datetime and vice-versa
- Python time Module
- Python sleep()
Additional Topic
Precedence and Associativity of Operators in Python
- Python Keywords and Identifiers
- Python Asserts
- Python Json
- Python *args and **kwargs
Python Tutorials
Python 3 Tutorial
- Python Strings
- Python any()
Operators are special symbols that perform operations on variables and values. For example,
Here, + is an operator that adds two numbers: 5 and 6 .
- Types of Python Operators
Here's a list of different types of Python operators that we will learn in this tutorial.
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Special Operators
1. Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,
Here, - is an arithmetic operator that subtracts two values or variables.
Example 1: Arithmetic Operators in Python
In the above example, we have used multiple arithmetic operators,
- + to add a and b
- - to subtract b from a
- * to multiply a and b
- / to divide a by b
- // to floor divide a by b
- % to get the remainder
- ** to get a to the power b
2. Python Assignment Operators
Assignment operators are used to assign values to variables. For example,
Here, = is an assignment operator that assigns 5 to x .
Here's a list of different assignment operators available in Python.
Example 2: Assignment Operators
Here, we have used the += operator to assign the sum of a and b to a .
Similarly, we can use any other assignment operators as per our needs.
3. Python Comparison Operators
Comparison operators compare two values/variables and return a boolean result: True or False . For example,
Here, the > comparison operator is used to compare whether a is greater than b or not.
Example 3: Comparison Operators
Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.
4. Python Logical Operators
Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,
Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .
Example 4: Logical Operators
Note : Here is the truth table for these logical operators.
5. Python Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary, and 7 is 111 .
In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)
6. Python Special operators
Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.
- Identity operators
In Python, is and is not are used to check if two values are located at the same memory location.
It's important to note that having two variables with equal values doesn't necessarily mean they are identical.
Example 4: Identity operators in Python
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.
- Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).
In a dictionary, we can only test for the presence of a key, not the value.
Example 5: Membership operators in Python
Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).
Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .
- Precedence and Associativity of operators in Python
Table of Contents
- Introduction
- Python Arithmetic Operators
- Python Assignment Operators
- Python Comparison Operators
- Python Logical Operators
- Python Bitwise operators
- Python Special operators
Before we wrap up, let’s put your knowledge of Python operators to the test! Can you solve the following challenge?
Write a function to split the restaurant bill among friends.
- Take the subtotal of the bill and the number of friends as inputs.
- Calculate the total bill by adding 20% tax to the subtotal and then divide it by the number of friends.
- Return the amount each friend has to pay, rounded off to two decimal places.
Video: Operators in Python
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
- Interactive Courses
- Certificates
- 2000+ Challenges
Related Tutorials
Python Tutorial
Programming Assignments
As teachers, we've found that programming assignments are often a great way for students to cement their understanding of the principles and practice of networking. Students can "get their hands dirty," "learn by doing" and derive great satisfaction (and sometimes relief!) by building something that works.
This page contains programming assignment descriptions, and supplementary code fragments (when needed) do the programming assignments in our book. Most assignments are available in multiple languages, we recommend Python (which is the mostly used/taught) and C (which lets a student program closest to the underlying socket abstraction). Solutions to these assignments are available to instructors (only) here . If you're a faculty member who would like to access the solutions, contact one of the authors at [email protected] .
- A simple client/server simple socket program ( Python,Java,C )
- Webserver ( Python )
- UDP Pinger Lab ( Python , Java )
- SMTP Lab ( Python,Java )
- HTTP Web Proxy Server Lab ( Python , Java )
- ICMP Pinger Lab ( Python )
- Traceroute Lab ( Python )
- Video Streaming with RTSP and RTP Lab ( Python , Java )
- Reliable data transfer protocol (RDT) Lab ( Python,C )
- Distance Vector Algorithm ( C,Java )
We gratefully acknowledge the programming and problem design work of John Broderick (UMass '21), which has really helped to substantially improve this site.
Copyright © 2010-2024 J.F. Kurose, K.W. Ross Comments welcome and appreciated: [email protected]
- C++ Data Types
- C++ Input/Output
- C++ Pointers
- C++ Interview Questions
- C++ Programs
- C++ Cheatsheet
- C++ Projects
- C++ Exception Handling
- C++ Memory Management
Assignment Operators In C++
In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some kind of information.
The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the same data type.
The value can be a literal or another variable of the same data type.
Compound Assignment Operators
In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++:
- Addition Assignment Operator ( += )
- Subtraction Assignment Operator ( -= )
- Multiplication Assignment Operator ( *= )
- Division Assignment Operator ( /= )
- Modulus Assignment Operator ( %= )
- Bitwise AND Assignment Operator ( &= )
- Bitwise OR Assignment Operator ( |= )
- Bitwise XOR Assignment Operator ( ^= )
- Left Shift Assignment Operator ( <<= )
- Right Shift Assignment Operator ( >>= )
Lets see each of them in detail.
1. Addition Assignment Operator (+=)
In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way.
This above expression is equivalent to the expression:
2. Subtraction Assignment Operator (-=)
The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value from it. This operator is especially useful when you need to perform subtraction and store the result back in the same variable.
3. Multiplication Assignment Operator (*=)
In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.
4. Division Assignment Operator (/=)
The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.
5. Modulus Assignment Operator (%=)
The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and assigns the result to the variable on the left.
6. Bitwise AND Assignment Operator (&=)
This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the variable on the left.
7. Bitwise OR Assignment Operator (|=)
The bitwise OR assignment operator performs a bitwise OR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.
8. Bitwise XOR Assignment Operator (^=)
The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.
9. Left Shift Assignment Operator (<<=)
The left shift assignment operator shifts the bits of the variable on the left to left by the number of positions specified on the right and assigns the result to the variable on the left.
10. Right Shift Assignment Operator (>>=)
The right shift assignment operator shifts the bits of the variable on the left to the right by a number of positions specified on the right and assigns the result to the variable on the left.
Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data types to perform the operations we want.
Similar Reads
- Geeks Premier League
- Geeks Premier League 2023
Please Login to comment...
Improve your coding skills with practice.
IMAGES
VIDEO
COMMENTS
Learn the difference between = (assignment) and == (equal to) operators in C programming language. See examples, syntax, and explanations of how to use them correctly.
Learn how to code by creating 10 coding projects for beginners, such as a chess game, a mobile app, or a web scraper. Codecademy offers online courses and career paths to help you master various programming languages and tools.
Learn C programming language by solving 30 online exercises with solutions. Topics include arrays, pointers, loops, recursion, and more.
Operators in programming are symbols or keywords that perform operations on variables and values, such as arithmetic, logical, assignment, and bitwise. Learn about the different types of operators, their symbols, names, descriptions, and examples in this article.
Practice Python programming skills with free coding exercises for beginners and intermediate developers. Learn and solve questions on topics such as data structures, data analysis, OOP, JSON, NumPy, Pandas, Matplotlib, and more.
In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable.In most imperative programming languages, the assignment statement (or expression) is a fundamental construct.. Today, the most commonly used notation for this operation is x = expr (originally Superplan ...
The best way to learn C programming is by practicing examples. The page contains examples on basic concepts of C programming. You are advised to take the references from these examples and try them on your own. All the programs on this page are tested and should work on all platforms. Want to learn C Programming by writing code yourself? ...
Declaration: int a; Assignment: a = 3; Declaration and assignment in one statement: int a = 3; Declaration says, "I'm going to use a variable named "a" to store an integer value."Assignment says, "Put the value 3 into the variable a." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.
Learn the basics of computer science and programming in Python with this online course from MIT. The course covers topics such as algorithms, data structures, and problem solving, and provides lecture notes, videos, and assignments.
This section provides the course assignments, supporting files, and solutions. Browse Course Material Syllabus Calendar Lecture Notes Labs ... assignment_turned_in Programming Assignments with Examples. Download Course. Over 2,500 courses & materials Freely sharing knowledge with learners and educators around the world.
Programming by Doing is a website that offers a series of assignments to teach the basics of Java programming. You can practice various topics such as variables, loops, GUIs, random numbers, and projects, and check your answers online.
Learn how to use different types of assignment operators in C programming language, such as +=, -=, *=, /=, etc. See examples, explanations and a C program to demonstrate the working of assignment operators.
Introductory Programming Courses. Archived DSpace Course. Assignments. pdf. 98 kB Getting Started: Python and IDLE. file. 193 B shapes. file. 3 kB subjects. file. 634 kB words. pdf. 52 kB Problem Set 0. pdf. 66 kB Problem Set 1. pdf. 55 kB ...
How assignments are graded . Written by Julie Zelenski. We know that you will invest a lot of time into completing the programming assignments and the results of those efforts will be your biggest source of accomplishment (and frustration :-) in this course. We will celebrate and reward your work by counting the assignments for a healthy chunk ...
Learn how to use different types of operators in Python, such as arithmetic, assignment, comparison, logical, bitwise and special operators. See examples of how to perform operations on variables and values with +, -, *, /, %, ** and other symbols.
Explore a variety of programming assignments that use C or Java to solve scientific, commercial, and recreational problems. The assignments cover topics such as simulation, graphics, image processing, combinatorial optimization, text processing, and more.
Assignment 3: Problem 1: C++ Linked List Library (PDF) Sample Solution to Assignment 3, Problem 1. Solution and test data: cpplist (ZIP) (This ZIP file contains: 3 .h files, 4 .cpp files, 1 .make file and 1 .txt file.) Assignment 4 (Final Project) Problem: N-Body Gravity Simulation (problem statement available in Lecture Notes for Lecture 8)
This page contains programming assignment descriptions, and supplementary code fragments (when needed) do the programming assignments in our book. Most assignments are available in multiple languages, we recommend Python (which is the mostly used/taught) and C (which lets a student program closest to the underlying socket abstraction).
Learn how to use assignment operators to assign values to variables and perform arithmetic operations in different programming languages. See examples of simple, addition, subtraction, multiplication, division, modulus assignment operators in C, C++, Java, Python and JavaScript.
The one-year anniversary of the refined Assignment of Judges program marks a significant milestone in the journey toward a more efficient, transparent, and cost-effective judicial system. With continued innovation and collaboration, the program is poised to deliver even greater benefits in the years to come.
Learn how to use assignment operators in C++ to perform various operations on variables, such as addition, subtraction, multiplication, division, bitwise and shift. See syntax, examples and overloading of assignment operators.