Lesson 12: Switch-Case, Break; and Continue;


E-mail this post



Remember me (?)



All personal information that you provide here will be governed by the Privacy Policy of Blogger.com. More...



New lesson is up. I’ve composed this one, based on common examples where controls: break; and continue; are used. Another explanation on branching - using “switch – case” order is provided. Enjoy it! Hope you’ve noticed by now I also added some appendixes (more to be added soon); and for some time now, I post regular News regarding C++ Maniac homepage development. You can find these links in my sidebar.



Loop flow controls: break; and continue;



C uses two different orders to control loop’s flow

  • break – escapes from the nearest outer loop

  • continue – inside “while” and “do” loop: switches program execution to test condition, inside “for” loop: switches program execution to “for” loop step and then to condition test (also applies for nearest outer loop) - this can sound little messy, so better check the examples




Example:


Write your own program that tests if the given number is prime number.


#include <stdio.h>
#include <math.h>

void main() {

int i, n, prime=1; // prime is true

printf("Input natural number :");
scanf("%d", &n);

for( i=2; i<= n-1; i++) {

if( n % i == 0 ) { // also possible to state if(!(n % i))

prime =0; // prime is now false

break;

}
}

if( prime )

printf("%d is prime number !\n", n);

else

printf("%d isn’t prime number!\n", n);

}




Possible algorithm enhancements (decreasing number of loop’s iterations/repeats):

  • It is enough to loop n/2 times, better, only till square root(n) (C function sqrt(n))

  • Test if the number is dividable with 2, and if it isn’t, test inside loop if the number is dividable with odd numbers bigger than 2




Example:


Write your own program that reads integers given by keyboard and applies following rule above them: if the given number is smaller than zero, program should print error message and stop reading numbers. If the given number is bigger than 100, it should be skipped and program should read another number. All other numbers should be red and printed. Program must stop reading numbers when 0 or error shows up.


#include <stdio.h>

void main() {


int x;


do {

printf ("Input number :\n");

scanf("%d", &x );
if (x < 0) {

printf("Not allowed value\n");

break;
/* escapes the loop */
}

if (x > 100) {

printf("Skipping the value\n");

continue;
/* jumps to second iteration */

}

printf ("Given number is : %d", x);

} while (x != 0);
}




Branching condition order switch – case



Syntax:


switch( expression ){

case const_expression1: orders1;

[case const_expression2: orders2;]
.
.
.
[default : oredersN;]

}


  • used instead of multisided if selection

  • pay attention: if the keyword break isn’t stated inside case block; program continues to next case block in the list!





Example


Program reads student’s grade given from keyboard (from 1 to 5) and prints it’s description.


#include <stdio.h>

void main() {


int grade;
printf ("Input grade :");
scanf("%d", & grade);

switch (grade) {

case 1:
printf("Fall (F)\n");break;
case 2:
printf("Bad (D)\n");break;
case 3:
printf("Good (C)\n");break;
case 4:
printf("Very Good (B)\n");break;
case 5:
printf("Excellent (A)\n");break;
default:
printf("You have inputted false grade\n");
break; // break isn’t necessary here
}
}



Pay Attention:

If break; was to be left-out from every case block, for given grade 3 (example), the result would be false and following:

Good
Very Good
Excellent
You have inputted false grade



Pay Attention:

If the “default” block is last block in your switch order, then it isn’t necessary to state break next to it.


Pay Attention:

Consequence of falling through case labels in lack of break order is that the same collection of orders is executed for more different case labels. Better explained, this allows the following code


switch (letter) {

case 'a': NrOfVowels++; break;

case 'e': NrOfVowels ++; break;
case 'i' : NrOfVowels ++; break;
case 'o': NrOfVowels ++; break;
case 'u': NrOfVowels ++; break;
default : NrOfOthers++; break;
}




also to be written more shortly, in this way:


switch (letter) {

case 'a':

case 'e':
case 'i' :
case 'o':
case 'u': NrOfVowels ++; break;
default : NrOfOthers++; break;
}








Technorati Tags:
, , , , , ,



8 Responses to “Lesson 12: Switch-Case, Break; and Continue;”

  1. Anonymous Anonymous 

    I realise English is not your native language, or it could be a typo, anyway I believe you mean "Fail" as opposed to "Fall". Otherwise this is a excellent tutorial.

  2. Anonymous Anonymous 

    thank you for your reply.

    acctually I ment "falling" as "going through the steps, falling from one to another" but I realise it is pretty clumbsy sentence I composed... I will fix that

  3. Anonymous Anonymous 

    you made a very helpful tutorial, thankyou :) appreciat eit. its helped me in my assignment #1 for uni.

    btw, i think if english isnt your native language, you seem to speak it very well in code imho :)

  4. Anonymous Anonymous 

    Where can I get lessons 1-11?

  5. Anonymous Anonymous 

    Hehe, just use the sidebar links are there.. If you are using firefox it's simple, but if you use Internet Explorer sidebar might be down nelow this comment box (screwed up?)

  6. Anonymous Anonymous 

    why there is nothing related c?

  7. Anonymous Anonymous 

    Hello

    I'm looking for the syntax in C that allows me to enter a range in the case-expression.
    Like in:
    switch (i) {
    case #i going from 0 to 9#
    statements;break;
    case #i=10 OR i=20#
    statements;break;
    }

    Thanks!
    John

  8. Anonymous Anonymous 

    John, this is a crude method but this might work for you


    switch (i) {
    case 1:
    case 2:
    case 3:
    ....
    case 9:
    case 0: do something ; break;
    case 10:
    case 20:do something ; break;
    }

Leave a Reply

      Convert to boldConvert to italicConvert to link

 


German Flag Spanish Flag French Flag Italian Flag Portuguese Flag Japanese Flag Korean Flag Chinese Flag British Flag


This Website is optimized for Firefox. Users browsing with Internet Explorer may encounter problems while viewing pages.


C++ Maniac



Learn C



Additional



#include



Learn Converting



Appendix


Links


Previous posts




Daily Lessons for programming in Visual Studio, using C code.