I/O Questions #3

This is going to be a very short post, with just 1 question I thought I should address. Arrays and their initializations have long been a source for confusion. One important thing to know is –

1. Determine the o/p-

int main{
    int a[5]={2,3};
    cout<<a[2]<<a[3]<<a[4];
    return 0;
}

o/p: 000

Explaination: When an array is partially initialized, the rest of its elements are automtically initialized to 0.

I/O QUestions #2

I came across an interesting question today, and realized a lot of people make mistakes in switch statements. So here are 2 variations of a normal switch i/o question –

1. Determine the o/p:

#include<iostream>
using namespace std;

int main(){
     int i=3;
     switch(i){
        cout<<i<<endl;
case 1: cout<<"one\n"; break;
case 2: cout<<"two\n"; break;
case 3: cout<<"three\n"; break;
}
return 0;
}

o/p: three

Explaination: The switch statements does not execute any statements outside the ‘case’ and ‘default’ blocks. Hence, the statement cout<<i<<endl; will not be executed. Also, note that the default block is optional.

2. Determine the o/p:

#include<iostream>
using namespace std;

int main(){
    int i=1;
    switch(i){
        default: cout<<", Harry!\n";
        case 1: cout<<"Yer ";
        case 2: cout<<"a ";
        case 3: cout<<"wizard ";
    }
    return 0;
}

o/p: Yer a wizard

Explaination: On fall through (execution of subsequent statements on absence of a break), the default statement is not executed. It is only executed when the all of the other cases fail to match. Also, placing the default statement at the beginning, or any other place in the block will not make a difference. Default will not be executed before the other cases are checked.