Output of C++ programs | Set 42
Last Updated :
30 Aug, 2017
Prerequisite : Pointers and References
Q.1 What Is The Output Of this program?
#include <iostream>
using namespace std;
void fun( int & a, int b)
{
a += 2;
b += 1;
}
int main()
{
int x = 10, y = 2;
fun(x, y);
cout << x << " " << y << " " ;
fun(x, y);
cout << x << " " << y;
return 0;
}
|
Option
a) 10 2 10 2
b) 12 2 14 2
c) 12 3 14 3
d) 12 2 14 3
Answer : b
Explanation : In this program, in main() we pass two values x or y in fun() and fun() received the reference of x so increment it’s value but y have incremented but not a reference so y is same in main block.
Q.2 What Is The Output Of this program?
#include <iostream>
using namespace std;
void f2( int p = 30)
{
for ( int i = 20; i <= p; i += 5)
cout << i << " " ;
}
void f1( int & m)
{
m += 10;
f2(m);
}
int main()
{
int n = 20;
f1(n);
cout << n << " " ;
return 0;
}
|
Option
a) 25 30 35 20
b) 20 25 30 20
c) 25 30 25 30
d) 20 25 30 30
Answer : d
Explanation : In this program, main() call the f1() and pass the value of n in f1() and f1() is received the reference of n and increments 10 of it’s value now n is 30. Again call f2() and pass the value of m in f2(), f2() receive the value of m and check the condition and print the value.
Q.3 What Is The Output Of this program?
#include <iostream>
using namespace std;
void fun( char s[], int n)
{
for ( int i = 0; s[i] != '\0' ; i++)
if (i % 2 == 0)
s[i] = s[i] - n;
else
s[i] = s[i] + n;
}
int main()
{
char str[] = "Hello_World" ;
fun(str, 2);
cout << str << endl;
return 0;
}
|
Option
a) EgjnmaTqpnb
b) FgjnmaUqpnb
c) Fgjnm_Uqpnb
d) EgjnmaTqpnb
Answer : b
Explanation : In main(), call a fun() and pass string and one integer is 2. In fun(), loop i is iterated and check the condition if i is Even then decrease index value by 2 and if i is odd then increase by 2.
Q.4 What Is The Output Of this program?
#include <iostream>
using namespace std;
int main()
{
int x[] = { 12, 25, 30, 55, 110 };
int * p = x;
while (*p < 110) {
if (*p % 3 != 0)
*p = *p + 1;
else
*p = *p + 2;
p++;
}
for ( int i = 4; i >= 1; i--) {
cout << x[i] << " " ;
}
return 0;
}
|
Option
a) 110 56 32 26
b) 110 57 30 27
c) 110 56 32 25
d) 100 55 30 25
Answer : a
Explanation : In this program, a pointer p contains a base address of array x so *p contain a value of x[0] and p++ is pointing address of next element.
Q.5 What Is The Output Of this program?
#include <iostream>
using namespace std;
int main()
{
char * str = "GEEKSFORGEEK" ;
int * p, arr[] = { 10, 15, 70, 19 };
p = arr;
str++;
p++;
cout << *p << " " << str << endl;
return 0;
}
|
Option
a) 10 EEKSFORGEEK
b) 15 GEEKSFORGEEK
c) 15 EEKSFORGEEK
d) 10 GEEKSFORGEEK
Answer : C
Explanation : In this, the str contain a base address of string and pointer p contain a base address of array. If string and pointer is incremented by 1 – it’s pointing the next address value of string and array.