All the statements will end with semicolon (;), Number of statements can be grouped by placing them with in curly braces. { };
{
Statement1;
Statement2;
Statement3;
}
The if keyword is used to execute the statement or group of statements based on the condition’s.Below are the few examples,
//if, execution of one statement on condition satisfied
if ( condition ) statement;
//if, execution of block/statement's on condition satisfied
if ( condition ) {
Statement1;
Statement2;
}
//if along with else part
if(condition) {
Statement1;
}
else {
stetement2;
}
//if, with nested if in else part
if(condition2) {
Statement1;
}
else if (condition2) {
if(condition3) stetement2;
else statement3;
}
Example:
#include "systemc.h"
int sc_main (int argc, char* argv[]) {
//declaration and initialization
int a = 10;
int b = 30;
//if-else
if( a > b )
cout <<" a is greater than b "< a)
cout <<" b-a is greater than a"<
Simulation Output:
b is greater than a
b-a is greater than a
for (initialization; condition; increment/decrement) statement;
for loop works as below,
#include "systemc.h"
int sc_main (int argc, char* argv[]) {
//for-loop
for(int i=0; i<4; i++)
{
cout <<" Value of i = "<
SIMULATOR OUTPUT:
Value of i = 0
Value of i = 1
Value of i = 2
Value of i = 3
The while loop will repeats the execution of statement/block until the condition is true.
#include "systemc.h"
int sc_main (int argc, char* argv[]) {
//declaration and initialization
int a = 15;
int b = 10;
//while-loop
while( a > b ) {
cout <<" a is greater than b a = "<
SIMULATOR OUTPUT:
a is greater than b a = 15 b = 10
a is greater than b a = 14 b = 10
a is greater than b a = 13 b = 10
a is greater than b a = 12 b = 10
a is greater than b a = 11 b = 10
b is greater than a
The do-while loop will execute the statement/block and then checks for condition.The difference between do-while and while is, irrespective of the condition the statement/block will be executed at least once in do-while.
#include "systemc.h"
int sc_main (int argc, char* argv[]) {
//declaration and initialization
int a = 9;
int b = 10;
//while-loop
do{
cout <<" a is greater than b a = "<
SIMULATOR OUTPUT:
a is greater than b a = 9 b = 10
b is greater than a