1.4.1 The while Statement
1.A while statement provides for iterative execution. example:
#include <iostream>
int main()
{
int sum=0,val=1;
while(val<=10){
sum+=val;
++val;
}
std::cout<<"sum of 1 to 10 inclusive is"
<<sum<<std::endl;
return 0;
}
2. a while executes by(repeatedly)testing the condition and excuting the associated while_body_statement until the condition is false;
3.if the condition value is nonzero,then the condition is true;if the value is zero then the condition is fale;
4.The first statemnet in the block uses the compound assignment operatior,(th += operator).This operator adds its righthand operand to its left-hand operand.it'a the same as sum=sum+val;
5.In the while_body_statement ++val uses the prefix increment operator(the ++ operator).The increament operator adds one to its operand.Writing ++val is ths same as writing val=val+1;
1.4.2 The for statement
rewrite the program to sum the numbers from 1 through 10 using a for loop .example:
#include<iostream>
int main()
{
int sum=0;
//sum values from 1 up to 10 inclusive
for(int val=1;val<=10;++val)
sum+=val;//equivalent to sum=sum+val
std::cout<<"sum of 1 to 10 inclusive is"
<<sum<<std::endl;
return 0;
}
1.The for statement has two parts:the for header and the for body.The heander controls how often the body is executed.The header itself consists of three parts:an init-statement,a condition,and an expression.
2.When we exit the for loop,the variable val is no longer accessible.It is not possible to use val after this loop terminates.However,not all compilers enforce this requirement..
3.A compiler cannot detect whether the meaning of a program is correct,but is can detect errors in the form of program.The following are the most common kinds of errors a compiler will detect.
3.1 systax errors.
3.2 Type errors.
3.3 Declaration errors.
1.4.3 The if statement
1.Like most languages,C++ provides an if statement that supports conditional execution.example:
#include<iostream>
int main()
{
std::cout<<"Enter two numbers:"<<std::endl;
int v1,v2;
std::cin>>v1>>v2;//read input
//use smaller number as lower bound for summation
// and larger number as upper bound
int lower,upper;
if(v1<=v2)
{ lower=v1;
upper=v2;
}
else{
lower=v2;
`upper=v1;
}
int sum=0;
//sum values from lower up to and includeing upper
for(int val=lower;val<=upper;++val)
sum+=val;//sum=sum+val
std::cout<<"Sum of "<<lower
<<" to "<<upper
<<"inclusive is "
<<sum<<std::endl;
return 0;
}