C++ Module 1
C++ Module 1
7. Wrapping data and its related functionality into a single entity is known as _____________
a) Abstraction b) Encapsulation c) Polymorphism d) Modularity
Answer: B
Explanation: In OOPs, the property of enclosing data and its related functions into a single entity(in C++ we call them
classes) is called encapsulation
8. How structures and classes in C++ differ?
a) In Structures, members are public by default whereas, in Classes, they are private by default
b) In Structures, members are private by default whereas, in Classes, they are public by default
c) Structures by default hide every member whereas classes do not
d) Structures cannot have private members whereas classes can have
Answer: A
Explanation: Structure members are public by default whereas, class members are private by default. Both of them can
have private and public members.
4. Which of the following is the correct syntax of including a user defined header files in C++?
a) #include <userdefined.h>
b) #include <userdefined>
c) #include “userdefined”
d) #include [userdefined]
Answer: C
Explanation: C++ uses double quotes to include a user-defined header file. The correct syntax of including user-defined is
#include “userdefinedname”.
10. Which of the following is the correct difference between cin and scanf()?
a) both are the same
b) cin is a stream object whereas scanf() is a function
c) scanf() is a stream object whereas cin is a function
d) cin is used for printing whereas scanf() is used for reading input
Answer: B
Explanation: cin is a stream object available in C++ whereas scanf() is a function available in both C and C++. both are
used for reading input from users.
11. Which of the following is the scope resolution operator?
a) .
b) *
c) ::
d) ~
Answer: C
Explanation: :: operator is called scope resolution operator used for accessing a global variable from a function which is
having the same name as the variable declared in the function.
Sample programs:
1. Adding two numbers in C++.
Ans. Take two variables and take user input and add them.
#include <iostream>
int main() {
int a ;
int b ;
cin>>a>>b;
cout<<a+b;
return 0;
}
Input: 2 5
Output: 7
#include <iostream>
int main() {
int a ;
cin>>a;
int b = 2;
//start from b as 1 can divide any number
bool prime = true;
while(b!=a){
if(a%b == 0)
{
prime = false;
break;
}
b++;
}
if(prime)
cout<<"prime";
else cout<<"not prime";
return 0;
}
#include <iostream>
int main()
{
string str;
cin>>str;
int count = 0;
for(int i = 0;str[i];i++) // till the string character is null
count++;
cout<<count;
}
Input: abcde
Output: 5