what happens when there are two continuous breaks in a switch statement? - c

#include <stdio.h>
int main()
{
int i = 0;
char c = 'a';
while (i < 2){
i++;
switch (c) {
case 'a':
printf("%c ", c);
break;
break;
}
}
printf("after loop\n");
}
What will be the output of the above code?
Does the second break mean anything?

break is a jump statement in C. It unconditionally transfers control to a different location in the code. Which means that any code between that break and the target point of the jump is unreachable, unless there's a label that allows one to reach it.
In your case there's no such label. The second break is unreachable and has no effect.

There is no use for a second break statement.
The break statement has the following two usages:
When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
In this case it terminates the case statement. So the second break doesn't get called. It is a useless statement.

Related

what's the use of keeping ";" after if conditional in C?

Yesterday I was asked a question in an exam, the code is as follows:
#include <stdio.h>
int main()
{
int i=5;
if(i==5);
printf("I am printing\n");
return 0;
}
with and without ";" after if conditional I am getting the same result can anyone help me what's the use of keeping the ";" after an if conditional?
Here semicolon after if condition says there is NULL Statement to execute. It has no impact on next statements. It is rarely used. You can understand more with some changes in code. Try printf statement within if condition and change the value of i. Then see output changes;
int i=10;
if(i==5)
printf("I am printing\n");
When you put the semicolon after the if() it gets ignored and it prints the next statement like below
int i=5;
if(i==5);{
printf("I am Printing");
}
but if you try to run it with else statement it will show you an error that there is no if statement like below
int i=5;
if(i==5);{
printf("I am Printing");
}else{
printf("I am Not Printing)
}
So the main concept is when you put a semicolon at the end of any line it terminates that sentence and in your case when you're putting a semicolon after if it terminates the working of if statement

Can anyone explain the interaction of switch, while and continue?

How is the switch statement executed here?
I am especially interested in the use of continue.
#include <stdio.h>
int main()
{
char ch = 'A';
while (ch <= 'D')
{
switch (ch)
{
case 'A':
case 'B':
ch++;
continue;
case 'C':
case 'D':
ch++;
}
printf("%c", ch);
}
}
This outputs DE, as you can see live on coliru.
Short answer: Continue corresponds to the while loop in the code.
Initially, value of ch is A and it matches the first case and since your cases don't have break, once a case is triggered, switch will go through all cases (until break, exit, continue, end of cases etc...). As a result it also enters case B and increments the ch to B. Since it encounters the continue it skips the rest of the instructions and begins the next iteration of the while loop.
You can run it in debugger to understand these things. You can also use the old-school printfs if needed.
There is also SO thread which discuss in detail about continue in switch
Here in char variable ' A' is 65 and 'D' is 68 .If the char value less then or equal in the condition the while loop will run. then in switch condition ch is the value which you defined earlier then the variable value match with the condition of case and increase the value of ch

Getting zero answer while using DO-WHILE loop

I tried to calculate the tot(total fee) in the do-while loop, but all I get is tot=0.00?! Why is this happening? And after that I get a message: it said the variable fee is not being initialised?
#include<stdio.h>
int main(void)
{
int cofno;
float tot=0.0;
float fee;
char option;
do{
printf("Enter cofno: ");
scanf("%d",&cofno);
if(cofno>0)
{
printf("Key in (h/c): ");
scanf("%c",&option);
getchar();
switch(option)
{case 'h':fee=cofno*1.80;
break;
case 'c': fee=cofno*2.50;
break;
}
tot=tot+fee;
//the program will repeat until the user key in negative value or zero
}
}while(cofno>0);
printf("\ntot=RM%.2f \n\n",tot);
return 0;
}
scanf(" %c",&option); This will solve the problem for you. The reason the ' ' is provided in the scanf so that it can consume the white space characters.
What happened earlier was that your character input got the \n from previous input.
To check the thing that it inputted \n try outputting the option like this
printf("[%c]",option); you will see output
[
]
Also the break statement you provide is breaking for the case staement. Not the while loop. You have infinite loop now. You can solve this with a added condition.
...
tot=tot+fee;
if(option == 'c' || option =='h')
break;
...
Even more simply, you could have changed the while condition overall and make it like this
while(cofno<=0);
this conforms to your idea the program will repeat until the user key in negative value or zero more suitably.

Error in C with word counting program using switch statement

I am having trouble counting the number of words that the user enters using a switch statement. I want to ensure that multiple presses of the keyboard (ASCII,32) do not count for multiple words. As you can see, I have a memory variable that stores the previous keyboard press, and I want to only count a word when the current keyboard press is a space, and the previous press (i.e. the memory variable is not a space). The logic makes perfect sense to me; however, the code does not seem to work. Could someone please explain where my flaw in logic is? Thanks.
// 1.4 Exercise 1: output the amount of characters, number of words and number of newlines typed by the user
// Note that the escape command on my mac is ENTER then COMMAND Z
#include <stdio.h>
int main()
{
long characters = -1; // to exit program on my mac you must press COMMAND+Z
long newlines = 0;
long words = 1; // assume the document starts with a word
printf("Type stuff! To exit type CTRL+D (some computers use CTRL+Z then space)\n");
int i = 0;
int memory = 32; //stores the previous keyboard press
while (i != EOF) // characters will continue counting as long as the escape sequence is not entered
{
i = getchar(); //Assign the integer output of the buffered getchar() function to i
if (i != 10)
{
characters++;
}
switch (i)
{
case 10: // for enter key press
{
newlines++;
break; // exit switch (each character is unique)
}
case 32: // for space
{
if (memory != 32) // if the previous character press was not a space, then words++
{
words++;
}
memory = i; // stores the previous keyboard press
break; // exit switch (each character is unique)
}
default: break; //exit switch is the default action if the previous switches are not true
}
}
printf("%d characters were typed\n", characters);
printf("%d words were typed\n", words);
printf("%d lines were typed\n", newlines);
return 0;
}
You are only updating the value of memory when inside of your case statement when i = 32. With this, the value of memory will always be 32. Instead, you should update the value of memory after the switch statement is closed. i.e.
switch(i)
{
/* code here */
}
memory = i
As a side note, it will make your code more readable and aid portability if you don't hard-code the ascii values of characters into your switch statement. You can instead write them using the character.
switch(i)
{
case '\n':
/* code */
break;
case ' ':
/* code */
break;
}
You unconditionally have to store the previous character:
memory = i;
Also, think about the corner-cases, e.g. what happens when there's only a single word (without spaces) in a line. As you can see, not only spaces can separate words.

how the break command acts in my test code

my test code is as follows:
#include <stdio.h>
int main(){
char c;
while ((c=getchar())!=EOF){
if(c>='A'&& c<='Z'){
c=c-'A'+'a';
putchar(c);
}
//else break;
}
return 0;
}
without the else break command, the while loop went forever, but when I added the "else" command line, the loop only executed for once, I typed "A" it displayed "a" on the monitor and then stopped. But I thought it should be like this: if A~Z is input, then it produces the lower case letter, if the input character is not within the range, eg. a number of something, it would break the loop and execution would stop. Where am I made the mistake? I have tried to add curly brackets after "else" around "break", but the result remained.
The getchar function will read EVERY char from stdin, even the newline character from the "Enter/Return" key.
When you enable your else part, your code also reacts to the '\n', which causes the break.
You may try to change the
else break;
by
else if (c != '\n') break;
in your code.
If you enter only A and nothing else, your program sees A and the newline character \n. The newline character doesn't match the pattern A...Z, so the break statement is executed.
You can see this by printing the code of the character:
while ((c=getchar())!=EOF){
printf("Character code: %d\n", c);
...
}
You can enter something like ABACABB to see your desired behavior.
char c;
while ((c=getchar())!=EOF){
needs to be
int c;
while ((c=getchar())!=EOF){
see http://www.tutorialspoint.com/c_standard_library/c_function_getchar.htm
IN addition your code does not say 'stop if they enter a char thats not A-Z', it says' ask them for input till they type EOF - echoing back to them when they type A-Z'. EOF is types as ctrl-D on UNix

Resources