Ad Code

Case and While Code Structure in C & C++

Case:

In Case statement, control can take either of several branches (as opposed to only two in If statement.) First node represents the switch statement (C/C++) and nodes in middle correspond to all different cases. Program can take one branch and result into the same instruction.

Case Statement in C and C++


Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.

switch ( <variable> ) {
case this-value:
  Code to execute if <variable> == this-value
  break;
case that-value:
  Code to execute if <variable> == that-value
  break;
...
default:
  Code to execute if <variable> does not equal the value following any of the cases
  break;
}

Another case Example;
 
int a = 10;
int b = 10;
int c = 20;

switch ( a ) {
case b:
  // Code
  break;
case c:
  // Code
  break;
default:
  // Code
  break;
}

While:

A while loop structure consists of a loop guard instruction through which the iteration in the loop is controlled. The control keeps iterating in the loop as long as the loop guard condition is true. It branches to the last instruction when it becomes false.

 #include <iostream>
using namespace std; // So we can see cout and endl
int main()
{
int x = 0;  // Don't forget to declare variables
while ( x < 10 ) { // While x is less than 10
cout<< x <<endl;
x++;             // Update x so the condition can be met eventually
}
cin.get();
}
Reactions

Post a Comment

0 Comments