Arijit Das
Arijit Das

Reputation: 55

Switch Case Producing Wrong Ouput

The output is supposed to be 5 10 14 18. But even tough default case is executed it outputs 5 10 15 20.

#include<stdio.h>

void main(void)
{
   int i=0;
   for(i=0;i<20;i++){
   switch(i){
       case 0: i+=5;  break;
       case 1: i+=2;  break;
       case 5: i+=5;  break;
       default: i+=4;   
   }
   printf("%d \n",i);
   }
}

Output - 
5 
10 
15 
20

Shouldnt the output be 5 10 14 18 ?

Upvotes: 0

Views: 108

Answers (5)

Haidar Haidar
Haidar Haidar

Reputation: 25

it's correct ... as u see u are incrementing "i" by (5) if the case is (0) so {i --> 5} then after the "i++" in the loop it becames (6). so, then the switch case will switch to the default on the other cases of "i" because "i" became (6) then "i" will increment by (4) in the default case and by (1) in the loop (i++) ;

so the output is correct !!!!!!

Upvotes: -1

prashantas
prashantas

Reputation: 455

after 5 in printed, i becomes 6 , and then it goes to default where i becomes 10 and 10 is preinted. After this the for loop increases it by 1 and i becomes 11. Again goes to default which makes i =15 and hence 15 is printed. Again it increases by 1 , by for, and becomes 19 and goes to default again and i becomes 20. Please put a line, before the switch starts

     printf("value of i before switch:%d\n",i);  

This will make u clear. Plz keep in mind that for loop is also increamenting the value of i. Dont increament the value of i in for loop to get the desired result.

Upvotes: 0

Stolas
Stolas

Reputation: 289

Lets see:

i =  0, case + 5 = i=5
i =  6, case + 4 = i=10
i = 11, case + 4 = i=15
i = 16, case + 4 = i=20

The CPU is right

Upvotes: 3

Yu Hao
Yu Hao

Reputation: 122373

Don't forget i increments 1 in every for loop. Add another debugging print before switch, you can see it:

for(i = 0; i < 20; i++){
   printf("before %d \n",i);
   switch (i){
       case 0: i+=5;  break;
       case 1: i+=2;  break;
       case 5: i+=5;  break;
       default: i+=4;   
   }
   printf("after %d \n",i);
}

Output:

before 0 
after 5 
before 6 
after 10 
before 11 
after 15 
before 16 
after 20 

Upvotes: 6

Sander De Dycker
Sander De Dycker

Reputation: 16243

You should get the output you expect if you remove the i++ from the for loop :

for(i=0;i<20;){

For every iteration, you're both incrementing i in the switch statement, as well as the increment part of the for loop.

Upvotes: 1

Related Questions