Need a project done?

C++ Programming Developer

Search This Blog

Tricky Questions in C++

What will be its output?

#include<iostream>
using namespace std;
f();
int x = 9;
void main()
{
f();
cout << x;
}

f()
{
::x = 8;
}

Output: 8



C++ question about strlen(--).?

include <iostream>

using namespace std;

int main()
{
char s1[] = {'a','b','c','d','e'};
cout << strlen(s1);

return 0;
}

Output: 11, WHY?

char s1[] = {'a'}
cout <<strlen(s1);
Output: 7. WHY?


Answerer 1
strlen(--), is a function that counts the number of characters, starting from START OF YOUR CHAR ARRAY, till the previous character of the null pointer ... that is, '\0'

Every string you handle with c++, strings you cin, or strings you make up with strcpy, they AUTOMATICALLY put a null character as an extra character in the array. So, strlen(--) works normally, and counts all characters correctly.

Here in your code, you haven't put the null character, so strlen(--) keeps on checking for null character indefinitely, counting all the while. That's why you are getting 11 and 7.


SOLUTION

Declare arrays like the following

Method 1
abcde : (Case 1) :
char s1[] = {'a', 'b', 'c', 'd', 'e', '\0'};

a: (Case 2) :
char s1[] = {'a', '\0'};


Method 2

abcde (Case 1) :
char s1[10];
strcpy(s1, "abcde");

a (Case 2):
char s1[10];
strcpy(s1, "a");


Answer 2:
Q. Output: 11, WHY?
A. because you never ended the string, so strlen counted all the characters until it found a NULL character (char 0), which randomly happened to be at position 11
you can fix it like this:

include <iostream>
using namespace std;
int main()
{
char s1[] = {'a','b','c','d','e', '\0'};
cout << strlen(s1);
//output 5
return 0;
}


Now a Question from you:
What will be the output of Following program?

#include <iostream>
using namespace std;
m();
int i = 0;

int main()
{
m();
cout << i;

return 0;
}
m()
{
i = 2;
}


//--------------------------------------------------------------------------------------------------------------------

Guess the output:


#include <iostream>

void f1(int **p);
void f2(int **p);

int main(){
 int *p;
 f1(&p);
 std::cout<<*p<<std::endl;
 return 0;
}
void f1(int **p){
 f2(p);
}
void f2(int **p){
 int x = 4;
 *p = &x;

}

1 comment:

  1. thnxx for such questions. Please post more such questions looking for more articles from you. and I too have collected some of the tricky programming questions from my personal experience and from my friends. Please have a review on this and i hope that it will really help you to improve your logics. :) http://csetips.catchupdates.com/tricky-programming-questions-interview/

    ReplyDelete

"Don't let anyone ever make you feel like you don't deserve what you want."