Next: Execution Control Expressions , Previous: Arithmetic , Up: Top   [ Contents ][ Index ]

7 Assignment Expressions

As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues ) because they are locations that hold a value.

An assignment in C is an expression because it has a value; we call it an assignment expression . A simple assignment looks like

We say it assigns the value of the expression value-to-store to the location lvalue , or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable . In C, that means it was not declared with the type qualifier const (see const ).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

is equivalent to

This is the only useful way for them to associate; the other way,

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

7.5: While Loop

  • Last updated
  • Save as PDF
  • Page ID 29073

  • Patrick McClanahan
  • San Joaquin Delta College

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

Introduction to while Loops

There are two commonly used loops where the condition is tested before entering loop. These loops have the posibility of NEVER entering the body of the loop, depending on the condition. They are: while loop and for loop. This lesson covers the: while.

Understanding Iteration in General - while

The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures we ask a question to control the execution of the loop. The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the while loop is as follows:

In almost all languages the condition is a Boolean expression . The Boolean data type has two values – true and false. Let's rewrite the structure to consider this:

Within the while control structure there are four attributes to a properly working loop. They are:

  • Initializing the flag -  this is important , with while loops you must initialize the flag (some people call this  priming the loop ).
  • Test expression
  • Action or actions
  • Update of the flag -  this also is important  - if we never update the flag we have no way to exit the loop.

The initialization of the flag is not technically part of the control structure, but a necessary item to occur before the loop is started. The English phrasing is, "While the expression is true, do the following actions". This is looping on the true. When the test expression is false, you stop the loop and go on with the next item in the program. Notice, because this is a test before loop the action might not happen . It is called a test before loop because the test comes before the action. It is also sometimes called a pre-test loop, meaning the test is pre (or Latin for before) the action and update.

Human Example of the while Loop

Consider the following one-way conversation from a mother to her child.

Child: The child says nothing, but mother knows the child had Cheerios for breakfast and history tells us that the child most likely spilled some Cheerios on the floor.

Mother says: "While it is true that you see (As long as you can see) a Cheerio on floor, pick it up and put it in the garbage."

Note: All of the elements are present to determine the action (or flow) that the child will be doing (in this case repeating). Because the question (can you see a Cheerios) has only two possible answers (true or false) the action will continue while there are Cheerios on the floor. Either the child 1) never picks up a Cheerio because they never spilled any or 2) picks up a Cheerio and keeps picking up Cheerios one at a time while he can see a Cheerio on the floor (that is until they are all picked up).

The while Structure within C++

The syntax for the while control structure within the C++ programming language is:

The test expression is within the parentheses, but this is not a function call. The parentheses are part of the control structure. Additionally, there is not a semicolon after the parenthesis following the expression.

The four attributes of a test before loop are present. The initialization of the flag. The test is the equality relational comparison of the value in the flag variable to the lower case character of y. The action part consists of the 6 lines that prompt for data and then displays the total of the two ages. The update of the flag is the displaying the question and getting the answer for the variable loop_response.

This type of loop control is called an event controlled loop. The flag updating is an event where someone decides if they want the loop to execute again.

Using indentation with the alignment of the loop actions and flag update is normal industry practice within the C++ community.

Infinite Loops

At this point it's worth mentioning that good programming always provides for a method to insure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code. However, if this does not happen then the program is in an infinite loop. Infinite loops are a bad thing. Consider the following code:

The programmer assigned a value to the flag before the loop which is correct. However, he forgot to update the flag. Every time the test expression is asked it will always be true. Thus, an infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the flag). Consider the following code:

No matter what the user replies during the flag update, the test expression does not do a relational comparison but does an assignment. It assigns 'y' to the variable and asks if 'y' is true? Since all non-zero values are treated as representing true within the Boolean concepts of the C++ programming language, the answer to the test expression is true. Viola, you have an infinite loop.

The undesirable semi-colon on the end of while line causes the action of the while loop to be the "nothingness" between the closing parenthesis and the semi-colon. The program will infinitely loop because there is no action (that is no action and no update). If this is the first item in your program it will appear to start but there will be no output.

Counting Loops

The examples above are for an event controlled loop. The flag updating is an event where someone decides if they want the loop to execute again. Often the initialization sets the flag so that the loop will execute at least once.

Another common usage of the while loop is as a counting loop. Consider:

The variable counter is said to be controlling the loop. It is set to zero (called initialization) before entering the while loop structure and as long as it is less than 5 (five); the loop action will be executed. But part of the loop action uses the increment operator to increase counter's value by one. After executing the loop five times (once for counter's values of: 0, 1, 2, 3 and 4) the expression will be false and the next line of code in the program will execute. A counting loop is designed to execute the action (which could be more than one statement) a set of given number of times. In our example, the message is displayed five times on the monitor. It is accomplished my making sure all four attributes of the while control structure are present and working properly. The attributes are:

  • Initializing the flag
  • Update of the flag

Missing an attribute might cause an infinite loop or give undesired results (does not work properly).

Missing the flag update usually causes an infinite loop.

Variations on Counting

In the following example, the integer variable age is said to be controlling the loop (that is the flag). We can assume that age has a value provided earlier in the program. Because the while structure is a test before loop; it is possible that the person’s age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

Consider the following variation assuming that age and counter are both integer data type and that age has a value:

This loop is a counting loop similar to our first counting loop example. The only difference is instead of using a literal constant (in other words 5) in our expression, we used the variable age (and thus the value stored in age) to determine how many times to execute the loop. However, unlike our first counting loop example which will always execute exactly 5 times; it is possible that the person’s age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

Definitions

 Adapted from: "While Loop"  by  Kenneth Busbee , Download for free at http://cnx.org/contents/[email protected]  is licensed under  CC BY 4.0

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, introduction.

  • Getting Started with C
  • Your First C Program
  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

Flow Control

C if...else Statement

C while and do...while Loop

C break and continue

  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

Programming Arrays

C Multidimensional Arrays

  • Pass arrays to a function in C

Programming Pointers

  • Relationship Between Arrays and Pointers
  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples

Programming Strings

  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

Structure and Union

  • C structs and Pointers
  • C Structure and Function

Programming Files

  • C File Handling
  • C Files Examples

Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Count Number of Digits in an Integer
  • Reverse a Number
  • Find GCD of two Numbers
  • Check Whether a Number can be Expressed as Sum of Two Prime Numbers

In programming, loops are used to repeat a block of code until a specified condition is met.

C programming has three types of loops.

do...while loop

In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and do..while loop.

The syntax of the while loop is:

How while loop works?

  • The while loop evaluates the testExpression inside the parentheses () .
  • If  testExpression is true , statements inside the body of while loop are executed. Then, testExpression is evaluated again.
  • The process goes on until testExpression is evaluated to false .
  • If  testExpression is false , the loop terminates (ends).

To learn more about test expressions (when  testExpression is evaluated to true and false ), check out relational and logical operators .

Flowchart of while loop

flowchart of while loop in C programming

Example 1: while loop

Here, we have initialized i to 1.

  • When i = 1 , the test expression i <= 5 is true . Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2 .
  • Now, i = 2 , the test expression i <= 5 is again true . The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3 .
  • This process goes on until i becomes 6. Then, the test expression i <= 5 will be false and the loop terminates.

The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.

The syntax of the do...while loop is:

How do...while loop works?

  • The body of do...while loop is executed once. Only then, the testExpression is evaluated.
  • If testExpression is true , the body of the loop is executed again and testExpression is evaluated once more.
  • This process goes on until testExpression becomes false .
  • If testExpression is false , the loop ends.

Flowchart of do...while Loop

do while loop flowchart in C programming

Example 2: do...while loop

Here, we have used a do...while loop to prompt the user to enter a number. The loop works as long as the input number is not 0 .

The  do...while loop executes at least once i.e. the first iteration runs without checking the condition. The condition is checked only after the first iteration has been executed.

So, if the first input is a non-zero number, that number is added to the sum variable and the loop continues to the next iteration. This process is repeated until the user enters  0 .

But if the first input is 0, there will be no second iteration of the loop and  sum  becomes 0.0 .

Outside the loop, we print the value of sum .

Table of Contents

  • Example: while Loop
  • do...while Loop
  • Example: do...while Loop

Video: C while Loop

Sorry about that.

Related Tutorials

C Programming Tutorial

  • The while loop in C

Last updated on July 27, 2020

Loops are used to execute statements or block of statements repeatedly. For example, suppose we want to write a program to print "Hello" 5 times. One way to achieve this is to write the following statement 5 times.

But what if we want to print it 100 or 1000 times. Of course, writing the same statement 100 times or 1000 times would be insane. Using loops we can solve this kind of problem easily. C provides three types of loops.

  • do while loop

The while loop #

Just like the if-else statement , the while loop starts with a condition. First, the condition is evaluated, if it is true then the statements in the body of the while are executed. After executing the body of the while loop, the condition is checked again, if it is still true then once again statements in the body of the while are executed. This process keeps repeating until the condition becomes false. Therefore, you must always include a statement which alters the value of the condition so that it ultimately becomes false at some point. Each execution of the loop body is known as iteration.

The following program uses while loop to prints all even numbers between 1 to 100 :

Expected Output:

How it works:

In line 5, we have declared a variable i and initialized it to 1 . First, the condition (i < 100) is checked, if it is true. Control is transferred inside the body of the while loop. Inside the body of the loop, if condition ( i % 2 == 0 ) is checked, if it is true then the statement inside the if block is executed. Then the value of i is incremented using expression i++ . As there are no more statements left to execute inside the body of the while loop, this completes the first iteration. Again the condition ( i < 100 ) is checked, if it is still true then once again the body of the loop is executed. This process repeats as long as the value of i is less than 100 . When i reaches 100 , the loop terminates and control comes out of the while loop.

Consider one more example:

The following program calculates the sum of digits of a number entered by the user.

Expected Output: 1st run:

Let's say the user entered 123 , then here are the steps to find the sum of digits.

1st iteration #

1st step: #.

Take out the last digit of 123 by evaluating 123 % 10 and store the result in the variable remainder .

2nd step: #

Add the number obtained in the last step to the variable sum .

3rd step: #

Now we don't need the last digit of 123 , so remove it by evaluating 123 / 10 .

2nd iteration #

3rd iteration #.

When n reaches 0 while condition becomes false and control comes out of the while loop. Hence the sum of digits of 123 is 6 .

Load Comments

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

Recent Posts

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

cppreference.com

Assignment operators.

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

[ edit ] Simple assignment

The simple assignment operator expressions have the form

Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs .

Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic (since C11)
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict (since C99) -qualified or atomic (since C11) .
  • lhs is a (possibly qualified or atomic (since C11) ) pointer and rhs is a null pointer constant such as NULL or a nullptr_t value (since C23)

[ edit ] Notes

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C.

[ edit ] Compound assignment

The compound assignment operator expressions have the form

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

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.16 Assignment operators (p: 72-73)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

[ edit ] See Also

Operator precedence

[ edit ] See also

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 19 August 2022, at 08:36.
  • This page has been accessed 54,567 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

CProgramming Tutorial

  • C Programming Tutorial
  • 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 - Booleans
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • 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
  • 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
  • C - Functions
  • C - Main Functions
  • 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
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • 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 −

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 −

To Continue Learning Please Login

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

c while assignment

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?

C++ Tutorial

C++ functions, c++ classes, c++ reference, c++ examples, c++ while loop.

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

The while loop loops through a block of code as long as a specified condition is true :

In the example below, the code in the loop will run, over and over again, as long as a variable ( i ) is less than 5:

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C++ Exercises

Test yourself with exercises.

Print i as long as i is less than 6.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Codeforwin

Loop programming exercises and solutions in C

In programming, there exists situations when you need to repeat single or a group of statements till some condition is met. Such as – read all files of a directory, send mail to all employees one after another etc. These task in C programming is handled by looping statements .

Looping statement defines a set of repetitive statements. These statements are repeated with same or different parameters for a number of times. Looping statement is also known as iterative or repetitive statement .

C supports three looping statements.

  • do…while loop

In this exercise we will practice lots of looping problems to get a strong grip on loop. This is most recommended C programming exercise for beginners.

Always feel free to drop your queries, suggestions, hugs or bugs down below in the comments section . I always look forward to hear from you.

Required knowledge

Basic C programming , Relational operators , Logical operators , If else , For loop

List of loop programming exercises

  • Write a C program to print all natural numbers from 1 to n.  – using  while loop
  • Write a C program to print all natural numbers in reverse (from n to 1) . – using  while loop
  • Write a C program to print all alphabets from a to z.  – using  while loop
  • Write a C program to print all even numbers between 1 to 100.  – using  while loop
  • Write a C program to print all odd number between 1 to 100.
  • Write a C program to find sum of all natural numbers between 1 to n.
  • Write a C program to find sum of all even numbers between 1 to n .
  • Write a C program to find sum of all odd numbers between 1 to n .
  • Write a C program to print multiplication table of any number .
  • Write a C program to count number of digits in a number .
  • Write a C program to find first and last digit of a number .
  • Write a C program to find sum of first and last digit of a number.
  • Write a C program to swap first and last digits of a number .
  • Write a C program to calculate sum of digits of a number .
  • Write a C program to calculate product of digits of a number .
  • Write a C program to enter a number and print its reverse .
  • Write a C program to check whether a number is palindrome or not.
  • Write a C program to find frequency of each digit in a given integer .
  • Write a C program to enter a number and print it in words.
  • Write a C program to print all ASCII character with their values .
  • Write a C program to find power of a number using for loop .
  • Write a C program to find all factors of a number .
  • Write a C program to calculate factorial of a number .
  • Write a C program to find HCF (GCD) of two numbers .
  • Write a C program to find LCM of two numbers .
  • Write a C program to check whether a number is Prime number or not.
  • Write a C program to print all Prime numbers between 1 to n.
  • Write a C program to find sum of all prime numbers between 1 to n .
  • Write a C program to find all prime factors of a number .
  • Write a C program to check whether a number is Armstrong number or not.
  • Write a C program to print all Armstrong numbers between 1 to n.
  • Write a C program to check whether a number is Perfect number or not .
  • Write a C program to print all Perfect numbers between 1 to n .
  • Write a C program to check whether a number is Strong number or not .
  • Write a C program to print all Strong numbers between 1 to n .
  • Write a C program to print Fibonacci series up to n terms .
  • Write a C program to find one’s complement of a binary number .
  • Write a C program to find two’s complement of a binary number .
  • Write a C program to convert Binary to Octal number system .
  • Write a C program to convert Binary to Decimal number system .
  • Write a C program to convert Binary to Hexadecimal number system .
  • Write a C program to convert Octal to Binary number system .
  • Write a C program to convert Octal to Decimal number system .
  • Write a C program to convert Octal to Hexadecimal number system .
  • Write a C program to convert Decimal to Binary number system .
  • Write a C program to convert Decimal to Octal number system .
  • Write a C program to convert Decimal to Hexadecimal number system .
  • Write a C program to convert Hexadecimal to Binary number system .
  • Write a C program to convert Hexadecimal to Octal number system .
  • Write a C program to convert Hexadecimal to Decimal number system .
  • Write a C program to print Pascal triangle upto n rows .
  • Star pattern programs – Write a C program to print the given star patterns.
  • Number pattern programs – Write a C program to print the given number patterns .

IMAGES

  1. The 'while' Statement in C++

    c while assignment

  2. C programming +=

    c while assignment

  3. Assignment Operators in C Example

    c while assignment

  4. Assignment Operators in C++

    c while assignment

  5. While & DO while loop in c++ with examples (video#07)

    c while assignment

  6. Assignment Operators in C

    c while assignment

VIDEO

  1. C while loops ♾️

  2. #12: while Loop in C Programming

  3. C_37 While Loop in C (part-1)

  4. C_38 While Loop in C (part-2)

  5. While loop in C Programming with examples

  6. C_44 Nested while loop in C

COMMENTS

  1. c

    C Programming While Loop Assignment. 2. Variable assignment in conditional statement. 0. While Loop Variable Initialization and Variable Types(C) 3. Using the assignment operator in a while loop condition in C. 0. While loop doesn't execute statements at each iteration. 0.

  2. Why would you use an assignment in a condition?

    The reason is: Performance improvement (sometimes) Less code (always) Take an example: There is a method someMethod() and in an if condition you want to check whether the return value of the method is null. If not, you are going to use the return value again. If(null != someMethod()){. String s = someMethod();

  3. Is doing an assignment inside a condition considered a code smell?

    I also agree with Rob Y's answer that in the very first glance you might think it should be an equation == rather than an assignment, however if you actually read the while statement to the end you will realize it's not a typo or mistake, however the problem is that you can't clearly understand Why there is an assignment within the while ...

  4. while Statement (GNU C Language Manual)

    19.6.1 while Statement. The while statement is the simplest loop construct. It looks like this: Here, body is a statement (often a nested block) to repeat, and test is the test expression that controls whether to repeat it again. Each iteration of the loop starts by computing test and, if it is true (nonzero), that means the loop should execute ...

  5. Assignment Expressions (GNU C Language Manual)

    An assignment in C is an expression because it has a value; we call it an assignment expression. A simple assignment looks like. lvalue = value-to-store. We say it assigns the value of the expression value-to-store to the location lvalue, or that it stores value-to-store there. You can think of the "l" in "lvalue" as standing for ...

  6. 7.5: While Loop

    Like all control structures we ask a question to control the execution of the loop. The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the while loop is as follows: initialization of the flag. while the answer to the question is true then do. some statements or action.

  7. while loop in C

    Working of while Loop. We can understand the working of the while loop by looking at the above flowchart: STEP 1: When the program first comes to the loop, the test condition will be evaluated. STEP 2A: If the test condition is false, the body of the loop will be skipped program will continue. STEP 2B: If the expression evaluates to true, the ...

  8. C while and do...while Loop

    The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated. The syntax of the do...while loop is: do {. // the body of the loop.

  9. while loop

    Explanation. A while statement causes the statement (also called the loop body) to be executed repeatedly until the expression (also called controlling expression) compares equal to zero.The repetition occurs regardless of whether the loop body is entered normally or by a goto into the middle of statement.. The evaluation of expression takes place before each execution of statement (unless ...

  10. The while loop in C

    The while loop. Syntax: // body of while loop. statement 1; statement 2; Just like the if-else statement, the while loop starts with a condition. First, the condition is evaluated, if it is true then the statements in the body of the while are executed. After executing the body of the while loop, the condition is checked again, if it is still ...

  11. While loop in C programming

    while loop is an entry controlled looping construct. We use while loop to repeat set of statements when number of iterations are not known prior to its execution. It provides flexibility to define loop without initialization and update parts (present in for loop). Looping statements whose condition is checked prior to the execution of its body ...

  12. while loop

    Explanation. Whether statement is a compound statement or not, it always introduces a block scope. Variables declared in it are only visible in the loop body, in other words, while(-- x >=0)int i;// i goes out of scope. is the same as. while(-- x >=0){int i;}// i goes out of scope. If condition is a declaration such as T t = x, the declared ...

  13. C

    In this guide we will learn while loop in C. C - while loop. Syntax of while loop: while (condition test) { //Statements to be executed repeatedly // Increment (++) or Decrement (--) Operation } ... Unary Operator in C with Examples; Assignment Operators in Java with Examples; About the Author. I have 15 years of experience in the IT industry ...

  14. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  15. C Operators

    C Switch C While Loop. While Loop Do/While Loop Real-Life Examples. C For Loop. For Loop Nested Loops Real-Life Examples. C Break/Continue C Arrays. ... In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example. int x = 10;

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

  17. C Programming While Loop Assignment

    1. Question: Take n as input. Then take n numbers as input and print the summation of those n numbers. But this time output as the format below. Example: Input: output 1 + 5 + 3 - 4 = 5. I got the output value correctly, but I do not know how am I going to show the actual summation sequence, especially in one line....

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

  19. C++ While Loop

    Arithmetic Assignment Comparison Logical. C++ Strings. ... C++ While Loop Previous Next C++ Loops. Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable.

  20. Loop programming exercises and solutions in C

    List of loop programming exercises. Write a C program to print all natural numbers from 1 to n. - using while loop. Write a C program to print all natural numbers in reverse (from n to 1). - using while loop. Write a C program to print all alphabets from a to z. - using while loop.

  21. Combined assignment operator in a while loop condition in C

    The test is purposely obfuscated. Here are the steps: --x > -10 always decrements x and compares the resulting value to -10, breaking from the loop if x reaches -10 or below. if x >= -10 from the previous test, (x -= 2) further decreases the value of x by 2 and tests whether the resulting value is non zero.

  22. 𝘔𝘪.𝘨𝘢𝘤𝘺_𝘢𝘳𝘵

    37 likes, 4 comments - mi.san_arts on May 12, 2024: "A quick sketch while doing assignment (can't focus嵐) . #quicksketch #sketch #pencildrawing #pencilsketch". 𝘔𝘪.𝘨𝘢𝘤𝘺_𝘢𝘳𝘵 | A quick sketch while doing assignment (can't focus🤡) .