while loop in C++

By: Stanley B. Emailed: 1727 times Printed: 2328 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A while statement provides for iterative execution. We could use a while to write a program to sum the numbers from 1 through 10 inclusive as follows:

#include <iostream>
int main()
{
int sum = 0, val = 1;
// keep executing the while until val is greater than 10
while (val <= 10) {
sum += val; // assigns sum + val to sum
++val; // add 1 to val
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}

This program when compiled and executed will print:

Sum of 1 to 10 inclusive is 55

As before, we begin by including the iostream header and define a main function. Inside main we define two int variables: sum, which will hold our summation, and val, which will represent each of the values from 1 through 10. We give sum an initial value of zero and start val off with the value one.

The important part is the while statement. A while has the form

while (condition) while_body_statement;

A while executes by (repeatedly) testing the condition and executing the associated while_body_statement until the condition is false.

A condition is an expression that is evaluated so that its result can be tested. If the resulting value is nonzero, then the condition is true; if the value is zero then the condition is false.

If the condition is true (the expression evaluates to a value other than zero) then while_body_statement is executed. After executing while_body_statement, the condition is tested again. If condition remains true, then the while_body_statement is again executed. The while continues, alternatively testing the condition and executing while_body_statement until the condition is false.

In this program, the while statement is:

// keep executing the while until val is greater than 10
while (val <= 10) {
sum += val; // assigns sum + val to sum
++val; // add 1 to val
}

The condition in the while uses the less-than-or-equal operator (the <= operator) to compare the current value of val and 10. As long as val is less than or equal to 10, we execute the body of the while. In this case, the body of the while is a block containing two statements:

{
sum += val; // assigns sum + val to sum
++val; // add 1 to val
}

A block is a sequence of statements enclosed by curly braces. In C++, a block may be used wherever a statement is expected. The first statement in the block uses the compound assignment operator, (the += operator). This operator adds its right-hand operand to its left-hand operand. It has the same effect as writing an addition and an assignment:

sum = sum + val; // assign sum + val to sum

Thus, the first statement adds the value of val to the current value of sum and stores the result back into sum.

The next statement

++val; // add 1 to val

uses the prefix increment operator (the ++ operator). The increment operator adds one to its operand. Writing ++val is the same as writing val = val + 1.

After executing the while body we again execute the condition in the while. If the (now incremented) value of val is still less than or equal to 10, then the body of the while is executed again. The loop continues, testing the condition and executing the body, until val is no longer less than or equal to 10.

Once val is greater than 10, we fall out of the while loop and execute the statement following the while. In this case, that statement prints our output, followed by the return, which completes our main program.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Stanley B.
Enumerations in C++
typedef in C++
Declarations and Definitions in C++
Uninitialized Variables Cause Run-Time Problems in C++
C++ keywords
Lvalues and Rvalues in C++
Multi-Line Literals in C++
Concatenated String Literals in C++
Character String Literals in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++
if in C++
Programming errors a compiler will detect in C++
for loop in C++
while loop in C++

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Difference between Procedural, Structured, and Object-Oriented Programming
Calculating total based on the given quantity and price in C++
The indirection operator (*) - dereference operator.
C++ Recursion function explained using Fibonacci series
Dot (.) vs Arrow (->) to access data members in C++
Public versus Private members in C++
Constructors and Destructors in C++
while (1) Loops in C++
Converting Pointers that Operate on Arrays in C++ to Java
Operator Precedence in C++
strlen() sample program in C++
assert() example program in C++
cin.ignore() in C++
Lvalues and Rvalues in C++
Uninitialized Variables Cause Run-Time Problems in C++
Most Emailed Articles (in C++)
Multiple statements in for loops in C++
Getting User Input Using cin in C++
Difference between Procedural, Structured, and Object-Oriented Programming
Interface Versus Implementation in C++
Tutorial on Inline Implementation in C++
Looping with the keyword goto in C++
Converting C++ Abstract Classes into Java Interfaces
Call by reference in C++ Functions
Checking Prime Number in C++
if in C++
Multi-Line Literals in C++
Using cout in C++
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
The if Statement in C++