next up previous
Next: else Statement Up: If Statement Previous: Activity 1

Blocks of Code

Because C++ is a structured language, it supports the creation of Blocks of code. A block is a logically connected group of program statements that is treated as a unit. In C++, a code block is created by placing a sequence of statements between opening and closing curly braces.

Example
#include <iostream.h>
main( )
{
int a, b;

cout << "Enter first number" ;
cin >> a;
cout << "Enter Second number" ;
cin >> b;

if(a<b) {

cout << "First number is less than second $\backslash$n";
cout << "Their difference is :" << b-a;
cout << "Their sum is "<< a+b;
cout << "The remainder of a/b is" << a%b;
}
return 0;
}

The four statements after the if and between the curly braces are executed only if a<b. These four statements together with the braces represent a block of code. They are a logical unit: One of the statements cannot execute without the other also executing. In C++ the target of most commands can be either a single statement or a code block. Code blokes allow many algorithms to be implemented with greater clarity and efficiency. They can also help you better conceptualize the true nature of the routine.


next up previous
Next: else Statement Up: If Statement Previous: Activity 1
Yousef Haik
2/23/1998