Languages-C & C Plus Plus [3i Infotech Placement]: Sample Questions 223 - 224 of 354

Glide to success with Doorsteptutor material for competitive exams : get questions, notes, tests, video lectures and more- for all subjects of your exam.

Question 223

C & C Plus Plus
Edit

Describe in Detail

Essay▾

What is the output of the following program?

  1. main ()
  2. {
  3.     voidswap ();
  4.     intx =10, y =8;
  5.     swap (&x, &y);
  6.     printf ( “x =%dy =%d”, x, y);
  7. }
  8. voidswap ()
  9. int ⚹a, int ⚹b
  10. {
  11.     a^=⚹b,⚹b^=⚹a,⚹a^=⚹b;
  12. }

Explanation

In the program using ^ swaps two variables without using a temporary variable and that too in a single statement.

Table Shows the Program
void swap () ;
  • Swap is a function
  • Take any number of arguments and returns nothing.
int x = 10, y = 8;
  • Define integer variable x = 10 and y = 8
swap (&x, &y) ;
  • Call swap (&x, &y) ; that has two arguments.
printf ( “x =% d y =% d” , x, y) ;
  • printf prints the swapping value of x and y
Modern style of declaration:

void swap (int ⚹ a, int ⚹ b)

{

⚹ a ^ =⚹ b, ⚹ b ^ =⚹ a, ⚹ a ^ =⚹ b;

}

void swap ()

int ⚹ a, int ⚹ b

{

⚹ a ^ =⚹ b, ⚹ b ^ =⚹ a, ⚹ a ^ =⚹ b;

}

  • This convention is historic pre-ANSI style (referred to as Kernighan and Ritchie style) style of function declaration.
  • Swap function is defined with arguments following the () .
  • So the declaration for swap looks void swap () which means the swap can take any number of arguments.

Question 224

C & C Plus Plus
Edit

Describe in Detail

Essay▾

What is the output of the following program?

  1. main ()
  2. {
  3.     inti, n;
  4.     char ⚹x =“girl”;
  5.     n =strlen(x);
  6.     x =x[n];
  7.     For( i =0; i<n;++i)
  8.     {
  9.         printf (%s, x);
  10.         x ++;
  11.     }
  12. }

Explanation

(Blank space)

irl

rl

l

In a program

Table Shows the Program
int i, n;Define integer variable I and n.
char ⚹ x = “girl” ;String (a pointer to char) is initialized with a value “girl” .
n = strlen (x) ;The strlen function returns the length of thestring, thus n has a value 4.
⚹ x = x [n] ;This statement assigns value at the nth location ( ‘⧵0’ ) to the first location. Nowthe string becomes “⧵0irl” .
For (i = 0; i < n; ++ i)

{

printf (% s, x) ;

x ++ ;

}

Printf statement printsthe string. After each iteration it increments it starting position. Loop starts from 0 to 4.
  • The first time x [0] = ‘⧵0’ hence it prints nothing and pointer value is incremented.
  • The second time it prints from x [1] i.e.. “irl”
  • The third time it prints “rl”
  • And the last time it prints “l” and the loop terminates.

Developed by: