Step-by-Step Textbook Solutions for Class 12 Computer Application Chapter 03 Functions
Review structured textbook solutions for Class 12 Computer Application Chapter 03 Functions. Built according to Kerala Board guidelines for the 2026-27 academic year, these downloadable answers support daily revision and problem-solving accuracy.
Download Chapter 03 Functions Textbook Solutions PDF
Navigate directly to the solved Computer Application textbook exercises using the digital viewer below. Each solution includes detailed step-by-step explanations, allowing students to instantly cross-check their work and identify areas requiring further revision.
One Mark Questions and Answers
Question 1: To read a single character for gender, that is, 'm' or 'f', the ______ function is used.
a) getch()
b) getchar()
c) gets()
d) getline()
Answer:
b) getchar()
Exam Tips:
a) getchar() reads one character at a time and needs the header file cstdio.
Question 2: Which header file is used to work with getchar(), putchar(), gets() and puts()?
a) iostream
b) cstdio
c) input
d) output
Answer:
b) cstdio
Exam Tips:
a) Remember: cstdio holds the console input and output functions of C, while iostream holds cin and cout.
Question 3: Which header file is needed to use cin and cout?
a) iostream
b) cstdio
c) input
d) output
Answer:
a) iostream
Exam Tips:
a) cin and cout are stream objects, so they need iostream.
Question 4: Predict the output of the following code snippet.
#include<cstdio>
int main()
{
char name[] = "ADELINE";
for(int i=0; name[i]!='\0'; i++)
putchar(name[i]);
}
Answer:
The output is ADELINE. The loop prints one character at a time with putchar() until it reaches the null character.
Exam Tips:
a) The loop condition name[i]!='\0' stops at the end of the string, so every character is printed once.
b) putchar() prints no space or new line by itself, so the characters appear together.
Question 5: Which of the following is equivalent to the function getc(stdin)?
a) putchar()
b) gets()
c) getchar()
d) puts()
Answer:
c) getchar()
Exam Tips:
a) getc(stdin) reads one character from the keyboard, which is exactly what getchar() does.
Question 6: Which of the following is equivalent to the function putc(ch, stdout)?
a) putchar(ch)
b) ch=gets()
c) ch=getchar()
d) puts(ch)
Answer:
a) putchar(ch)
Exam Tips:
a) putc(ch, stdout) writes one character to the screen, which is what putchar(ch) does.
Question 7: Which function is used to print a single character at a time?
a) puts()
b) putchar()
c) gets()
d) getchar()
Answer:
b) putchar()
Exam Tips:
a) Put = print: putchar() prints a character and puts() prints a string.
Question 8: To read a string, the ______ function is used.
a) puts()
b) putchar()
c) gets()
d) getchar()
Answer:
c) gets()
Exam Tips:
a) gets() reads a whole line including spaces; puts() prints a string.
Question 9: To print a string, the ______ function is used.
a) puts()
b) putchar()
c) gets()
d) getchar()
Answer:
a) puts()
Exam Tips:
a) puts() prints the string and moves the cursor to the next line automatically.
Question 10: Consider the following code snippet.
main()
{
char str[80];
gets(str);
int i, len;
for(i=0, len=0; str[i]!='\0'; i++, len++);
cout<<"The length of the string is "<<len;
getch();
}
Select the equivalent for the for-loop statement from the following:
a) int len = strlen(str);
b) int len = strcmp(str);
c) int len = strcount(str);
d) None of these
Answer:
a) int len = strlen(str);
The loop counts the characters until the null character, which is exactly what strlen() returns.
Exam Tips:
a) strlen() is in the header file cstring and does not count the null character.
b) strcmp() compares two strings, and there is no function called strcount() in C++.
Question 11: Arjun wants to read a string with spaces. Which of the following is suitable?
a) cin>>
b) cin.getline(str, 80)
c) str=getc(stdin)
d) None of these
Answer:
b) cin.getline(str, 80)
Exam Tips:
a) The extraction operator >> stops at the first space, so use getline() or gets() to read spaces.
Question 12: State whether the following statement is true or false: The extraction operator >> stops reading a string when it encounters a space.
Answer:
True.
The extraction operator >> stops reading at a space, tab or new line, so only the first word is stored.
Exam Tips:
a) Do not confuse the extraction operator >> (used with cin) with the insertion operator << (used with cout).
Question 13: The process of dividing a big program into small programs is called ______.
Answer:
Modularisation.
Exam Tips:
a) Modularisation (modular programming) is the base for functions in C++.
Question 14: The small programs obtained by dividing a big program are called ______.
Answer:
Functions (also called modules or sub-programs).
Exam Tips:
a) Give the alternative names (modules, sub-programs) along with the word functions.
Question 15: The execution of a program begins in the ______ function.
Answer:
main() function.
Exam Tips:
a) Every C++ program must have exactly one main() function, and execution starts from it.
Question 16: Which one of the following is not involved in the creation and use of a user defined function?
a) Define a function
b) Declare a function
c) Invoke a function
d) None of these
Answer:
d) None of these
Exam Tips:
a) Defining, declaring (prototype) and calling (invoking) are all involved, so the answer is "None of these".
Question 17: The default data type returned by a function is ______.
a) float
b) double
c) int
d) char
Answer:
c) int
Exam Tips:
a) Older C++ assumes int as the return type when none is written; a function that returns nothing must use void.
Question 18: After the execution of a function, control returns to the main function by executing the ______ keyword.
Answer:
return
Exam Tips:
a) return sends the control (and a value, if any) back to the calling function.
Question 19: Data is supplied from the calling function to a function by using ______.
Answer:
Parameters (arguments).
Exam Tips:
a) Arguments are written in the function call and received by parameters in the function definition.
Question 20: The ______ keyword is used to give a value back to the calling function.
Answer:
return
Exam Tips:
a) Only one value can be returned directly by a return statement.
Question 21: The ______ keyword is used to specify that a function returns nothing.
Answer:
void
Exam Tips:
a) A void function can use return; without a value, or can end without any return statement.
Question 22: Which one of the following is not necessary in a function declaration?
a) Name of the function
b) Return type
c) Number and type of arguments
d) Name of the parameters
Answer:
d) Name of the parameters
Exam Tips:
a) In a prototype only the types of the parameters are required, for example int sum(int, int);
Question 23: A function declaration is also called a ______.
Answer:
Prototype.
Exam Tips:
a) A prototype tells the compiler the function name, return type and the number and type of arguments.
Question 24: Consider the following function.
int sum(int a, int b)
{
return a+b;
}
Which of the following is a valid function call?
a) n=sum(10)
b) n=sum(10, 20)
c) n=sum(10, 20, 30)
d) n=sum()
Answer:
b) n=sum(10, 20)
The function has two parameters, so exactly two arguments must be given in the call.
Exam Tips:
a) The number of arguments in the call must match the number of parameters (unless default arguments are used).
Question 25: The ability to access a variable or a function from anywhere in a program is called ______.
Answer:
Scope.
Exam Tips:
a) Scope can be local or global.
Question 26: A variable or a function declared within a function has ______ scope.
Answer:
Local scope.
Exam Tips:
a) A local variable can be used only inside the function (block) in which it is declared.
Question 27: A variable or a function declared outside all the functions has ______ scope.
Answer:
Global scope.
Exam Tips:
a) A global variable can be used by all functions of the program.
Question 28: State True or False:
1. A local variable exists till the end of the program.
2. A global variable is destroyed when a sub-function terminates.
Answer:
1. False
2. False
A local variable exists only while its function runs, and a global variable exists till the end of the program.
Exam Tips:
a) Local variables live only during the function call; global variables live as long as the program runs. Swap these two statements and both become true.
Question 29: Consider the following declaration:
int x;
int main()
{
...
}
Here x is a ______ variable.
Answer:
Global variable.
Exam Tips:
a) It is declared outside all functions.
Question 30: Consider the following declaration:
int main()
{
int x;
...
}
Here x is a ______ variable.
Answer:
Local variable.
Exam Tips:
a) It is declared inside main(), so it is local to main().
Question 31: The ______ parameter is used when the function call does not supply a value for the parameter.
Answer:
Default parameter (default argument).
Exam Tips:
a) A default value is given in the function declaration, for example int sum(int a, int b=10);
Question 32: Consider the following function declarations with default arguments and state whether each is legal or illegal, giving the reason.
1. int sum(int x=10, int y, int z)
2. int sum(int x=10, int y=20, int z)
3. int sum(int x=10, int y=20, int z=30)
4. int sum(int x, int y=20, int z)
5. int sum(int x, int y=20, int z=30)
6. int sum(int x, int y, int z=30)
7. int sum(int x=10, int y, int z=30)
Answer:
Default values must be given from right to left: an argument can have a default value only if all the arguments on its right side also have default values.
1. Illegal, because y and z have no default values.
2. Illegal, because z has no default value.
3. Legal.
4. Illegal, because z has no default value.
5. Legal.
6. Legal.
7. Illegal, because x has a default value but y (on its right) has none.
Exam Tips:
a) Check each declaration from the rightmost parameter towards the left; the first parameter without a default stops further defaults.
b) Write "legal" or "illegal" with a one-line reason for every item.
Question 33: The parameters used to call a function are called ______.
Answer:
Actual parameters (arguments).
Exam Tips:
a) Actual parameters are in the function call; formal parameters are in the function definition.
Question 34: The parameters that appear in a function definition are ______.
Answer:
Formal parameters.
Exam Tips:
a) Formal parameters receive the values of the actual parameters.
Question 35: After the answer scripts are given back, the teacher gives a photocopy of the mark list to the students to check the marks. If a student changes the photocopy, the original mark list is not affected. A similar method is used to pass arguments to a function. What is this method?
a) Call by value
b) Call by reference
c) Call by address
d) None of these
Answer:
a) Call by value
Exam Tips:
a) In call by value a copy of the actual argument is passed, so changes made in the function do not affect the original.
Question 36: The class teacher gives you the original mark list to check the marks. If you change it, the original mark list is changed. A similar method is used to pass arguments to a function. What is this method?
a) Call by value
b) Call by reference
c) Call by function
d) None of these
Answer:
b) Call by reference
Exam Tips:
a) In call by reference the function works on the original variable, so changes are visible in the calling function.
Question 37: Consider the following function:
int sum(int a, int b)
{
Body
}
Here the arguments are passed by ______.
Answer:
Call by value method.
Exam Tips:
a) No & symbol in the parameter means the argument is passed by value.
Question 38: Consider the following function:
int sum(int &a, int &b)
{
Body
}
Here the arguments are passed by ______.
Answer:
Call by reference method.
Exam Tips:
a) The & symbol before the parameter name makes it a reference parameter.
Question 39: A function that calls itself is known as a ______.
Answer:
Recursive function.
Exam Tips:
a) A recursive function must have a stopping condition (base case), otherwise it calls itself forever.
Question 40: Varun wants to copy a string using the strcpy() function. Which header file is used for this?
a) cstdio
b) cmath
c) cstring
d) cctype
Answer:
c) cstring
Exam Tips:
a) String handling functions like strcpy(), strcat(), strlen() and strcmp() are in cstring.
Question 41: A ______ is a named group of statements that performs a job or task and may return a value.
Answer:
Function.
Exam Tips:
a) Functions avoid repetition of code and make programs easy to read.
Question 42: Which header file is used to work with the function setw()?
Answer:
iomanip
Exam Tips:
a) setw() sets the width of the output field and is a manipulator in the header file iomanip.
Question 43: In his C++ program, Ajith wants to accept a lengthy text of more than one line. Which function in C++ can be used in this situation?
Answer:
The stream function getline() with a delimiter character other than the new line, for example cin.getline(text, 500, '$'). The text is read until the delimiter is typed, so it can run over several lines.
Exam Tips:
a) gets() and the default getline() stop at the end of the first line, so a multi-line text needs a delimiter character.
b) Name the function, give the syntax and mention the delimiter.
Question 44: Choose the C++ function which can print a string.
a) getche()
b) putchar()
c) getline()
d) puts()
Answer:
d) puts()
Exam Tips:
a) puts() prints a string; putchar() prints only one character.
Question 45: Which of the following is a console function?
a) getline()
b) write()
c) put()
d) getchar()
Answer:
d) getchar()
Exam Tips:
a) getline(), write() and put() are stream functions; getchar() is a console function from cstdio.
Question 46: Pick the odd one out and give the reason.
a) abs()
b) strlen()
c) strcmp()
d) strcpy()
Answer:
a) abs()
abs() is a mathematical function, whereas all the others are string functions.
Exam Tips:
a) Group the functions by header file: abs() is in cmath/cstdlib, the others are in cstring.
Question 47: Consider the C++ statement and answer the question:
char Word[10]="GOOD DAY";
Identify the correct output statement to display the string.
a) write(word);
b) cout.write(word);
c) cout(word);
d) cout.write(word, 10);
Answer:
d) cout.write(word, 10);
The write() function needs two arguments: the string and the number of characters to display.
Exam Tips:
a) write() is a member function of cout, so it is called as cout.write(...).
b) C++ is case sensitive: Word and word are different names.
Question 48: When the number -7 is given as the argument of a predefined function in C++, it returns the value 7. Identify the function.
Answer:
abs(). It returns the absolute value of a number.
Exam Tips:
a) abs() is in cstdlib (and cmath), and the result is always non-negative.
Question 49: Pick out the correct statement for a prototype declaration from the following and also explain the information it contains.
a) product(int a, int b);
b) int product(a, b);
c) int product(int, int);
d) product(int, int);
Answer:
c) int product(int, int);
This prototype specifies the return type, the name of the function, and the number and type of the arguments.
Exam Tips:
a) A prototype needs a return type, a name and the argument types; it ends with a semicolon.
Question 50: One of the following function prototypes is wrongly written. Identify it and give the reason.
a) float test(float);
b) float test(float, int);
c) test(float);
d) int test(int);
Answer:
c) test(float);
The prototype has no return type.
Exam Tips:
a) Check every prototype for the return type, function name and argument types.
Question 51: A user defined function is given below. Choose the most appropriate function call from the options.
float calc(int x, float y)
{
return (x+y) / 2.0;
}
a) calc(2, 4)
b) calc(2.5, 4)
c) calc(2.5, 4.5)
d) calc(2, 4.5)
Answer:
d) calc(2, 4.5);
The first argument must be an int and the second a float, and 2 is an int and 4.5 is a float.
Exam Tips:
a) Match the argument types with the parameter types in order: int first, float second.
Question 52: Which of the following statements are FALSE about a local function?
a) Declared inside a function
b) Accessible only within the function in which it is declared
c) Accessible from anywhere in the program
d) Declared outside all other functions
Answer:
Statements (c) and (d) are false for a local function.
A local function is declared inside a function and can be used only inside it.
Exam Tips:
a) Contrast with a global function, which is declared outside all functions and can be used anywhere.
Two Mark Questions and Answers
Question 53: In a C++ program you forgot to include the header file iostream. What errors will occur in the program? Explain.
Answer:
The compiler reports an error that cin and cout are not declared (a prototype or declaration error). To use cin and cout, the header file iostream must be included.
Exam Tips:
a) Link the error to the missing header: cin and cout are declared in iostream.
b) Mention the correct fix: #include<iostream> and using namespace std;
Question 54: Pick the odd one out from the following and give the reason.
gets()
getline()
getch()
getchar()
Answer:
getline()
It is a stream function, whereas the others are console functions.
Exam Tips:
a) Group them by type: console functions (gets, getch, getchar) and stream functions (getline, write, put, get).
Question 55: Consider the following code snippet.
using namespace std;
int main()
{
int n;
cout<<"Enter a number";
cin>>n;
cout<<"The number is "<<n;
}
Write down the name of the header file that must be included in this program.
Answer:
The header file iostream must be included, because cin and cout are used.
Exam Tips:
a) Look at the functions or objects used in the program (cin, cout) and name the header that declares them.
Question 56: How does C++ support modularity in programming?
Answer:
The process of dividing a big program into smaller programs is known as modularisation. These small programs are called modules, sub-programs or functions. C++ supports modularity through functions.
Exam Tips:
a) Give the definition of modularisation and name functions as the C++ feature.
Question 57: The following assignment statement will generate a compilation error.
char str[20];
str = "Computer";
Write a correct C++ statement to perform the same task.
Answer:
char str[20] = "Computer";
OR
char str[20];
strcpy(str, "Computer");
(For strcpy(), the header file cstring must be included.)
Exam Tips:
a) An array name cannot be assigned a string with =; initialise it at declaration or copy with strcpy().
Question 58: Consider the following function:
float area(const float pi=3.1415, const float r)
{
r=10;
return pi*r;
}
Is there any problem? If yes, what is it?
Answer:
Yes, there are errors.
1. r is a constant (const) parameter, so its value cannot be changed inside the function; the statement r=10; is an error.
2. pi has a default value but r, which is on its right side, has none; default values must be given from right to left.
Exam Tips:
a) A const argument can be read but never modified within the function.
b) Also check the right-to-left rule for default arguments.
Question 59: What are the jobs of a return statement in a program?
Answer:
In a sub-function, the return statement terminates the function and sends the control back to the main function or the calling function (with a value, if needed). In the main function, it terminates the program.
Exam Tips:
a) Mention both uses: ending the function and returning a value to the caller.
Question 60: Match the following.
| Function | Header file |
|---|---|
| (a) strcmp() | (1) cctype |
| (b) tolower() | (2) cstring |
| (c) sqrt() | (3) cstdlib |
| (d) abort() | (4) cmath |
Answer:
(a) - 2 (cstring)
(b) - 1 (cctype)
(c) - 4 (cmath)
(d) - 3 (cstdlib)
Exam Tips:
a) Learn the header files by group: cctype for character functions, cstring for string functions, cmath for mathematical functions and cstdlib for general utilities.
Question 61: How do you invoke (call) a function in a C++ program?
Answer:
A function is called by writing its name followed by the arguments in parentheses, for example sum(m, n);
Exam Tips:
a) Give an example call with arguments, for instance n = sum(m, n);
Question 62: Briefly explain constant arguments.
Answer:
A parameter of a function can be made a constant argument by using the keyword const. The value of a const argument cannot be modified within the function.
Exam Tips:
a) Give an example such as float area(const float r); and say that assigning to r inside the function is an error.
Question 63: Consider the following program:
void initialise()
{
int k = 10;
}
int main()
{
int a, b;
float marks;
a = 20;
cout<<"First value ="<<a;
initialise();
b = k + a;
cout<<"New value ="<<b;
}
1. Identify the error in the above code and explain the reason.
2. Correct the error.
Answer:
1. k is a local variable of the function initialise(), so it cannot be accessed in main().
2. The error is corrected by declaring k as a global variable, that is, declaring it outside all the functions:
int k;
void initialise()
{
k = 10;
}
Exam Tips:
a) A local variable is available only inside the function in which it is declared.
b) Mention that the global variable must be set (here by calling initialise()) before it is used in main().
Question 64: List the advantages of modular programming.
Answer:
1. It reduces the size of the program.
2. There is less chance of errors.
3. It reduces programming complexity.
4. It improves reusability.
Exam Tips:
a) Write at least four points; reusability and easy debugging are the most important ones.
Question 65: Analyse the following statements and predict the output:
char str1[15] = " DATA", str2[15] = " STORAGE";
strcat(str2, str1);
cout<<str2;
Answer:
The output is " STORAGE DATA". The string str1 is joined to the end of str2.
Exam Tips:
a) strcat(a, b) appends b to the end of a, so the order of the arguments decides the result.
b) The destination array must be large enough to hold both strings.
Question 66: If char name[] = "Rajeev Kumar"; what will be the output of the following statement?
cout<<strlen(name);
Answer:
The output is 12. strlen() counts all the characters, including the space, and does not count the null character.
Exam Tips:
a) Count carefully: Rajeev (6) + space (1) + Kumar (5) = 12.
Question 67: Choose the value of n after executing the following statements in C++.
char s1[] = "KIRAN";
char s2[] = "kiran";
int n = strcmp(s1, s2);
cout<<n;
a) 0
b) >0
c) <0
d) None of these
Answer:
c) <0
The capital letters have smaller ASCII values than the small letters, so s2 is greater than s1.
strcmp() compares two strings and returns an integer: 0 if both strings are equal, a positive value if string1 is greater than string2, and a negative value if string2 is greater than string1.
Exam Tips:
a) strcmp() is case sensitive: "K" (ASCII 75) is smaller than "k" (ASCII 107).
b) Remember the three possible results: zero, positive and negative.
Question 68: C++ has a built-in function with which we get the result of 4 raised to the power 2 (that is, 16).
1. Identify the name of the function.
2. Identify the header file for the function.
Answer:
1. pow(4, 2)
2. The header file used is cmath.
Exam Tips:
a) pow(x, y) returns x raised to the power y.
Question 69: Consider the following C++ statements and predict the output.
int p = isalpha('5');
cout<<p;
Answer:
0
isalpha() checks whether a character is an alphabet. It returns a non-zero value if it is an alphabet, otherwise 0. Here '5' is a digit, so the result is 0.
Exam Tips:
a) isalpha() returns 0 for digits and special characters.
b) It needs the header file cctype.
Question 70: Predict the output of the following C++ statements:
1. cout<<toupper('a');
2. cout<<(char) toupper('a');
Answer:
1. It prints 65, because toupper() returns the ASCII value (an int) of A.
2. It prints A, because the value is converted to char before printing.
Exam Tips:
a) toupper() returns an int, so a type cast to char is needed to print the letter.
Question 71: Differentiate formal arguments and actual arguments.
Answer:
The parameters used to call a function are called actual parameters (arguments). The parameters that appear in a function definition are called formal parameters.
Exam Tips:
a) Give a small example: in sum(m, n); m and n are actual arguments, and in int sum(int a, int b) a and b are formal arguments.
Three Mark Questions and Answers
Question 72: Suresh wants to print his name and native place using a C++ program. The program should accept the name and native place first and then display:
Name is: Suresh Kumar
Address is: Alappuzha
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char name[20], place[20];
cout<<"Enter your name";
cin.getline(name, 20);
cout<<"Enter your place";
cin.getline(place, 20);
cout<<"Your name is :";
puts(name);
cout<<"Your place is :";
puts(place);
}
Exam Tips:
a) A name with spaces is read with cin.getline() or gets(), not with cin>>.
b) The size given in getline() must not be larger than the size of the array.
Question 73: "Programming is Fun". Write a C++ program to read a string like this in lower case and print it in UPPER CASE without using the toupper() library function.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char line[80];
int i;
puts("Enter the string to convert");
gets(line);
for(i=0; line[i]!='\0'; i++)
if(line[i]>=97 && line[i]<=122)
line[i] = line[i] - 32;
puts(line);
}
Exam Tips:
a) The ASCII value of a lower case letter is 32 more than that of the corresponding upper case letter, so subtracting 32 converts it.
b) Only the letters from a (97) to z (122) are changed; spaces and other characters stay as they are.
Question 74: Kumar has written a C++ program as an assignment, which reads a line of text and prints the number of vowels in it. What will his program code be?
Answer:
#include<iostream>
#include<cstdio>
#include<cctype>
using namespace std;
int main()
{
char line[80];
int i, vowel=0;
puts("Enter a string");
gets(line);
for(i=0; line[i]!='\0'; i++)
switch(tolower(line[i]))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vowel++;
}
cout<<"The number of vowels is "<<vowel;
}
Exam Tips:
a) tolower() converts each character to lower case so that both A and a are counted as vowels.
b) The cases a, e, i, o, u share the same statement because there is no break between them.
Question 75: Write a program to display the following output.
A
BB
CCC
Answer:
#include<iostream>
using namespace std;
int main()
{
char str[] = "ABC";
int i, j;
for(i=0; i<3; i++)
{
for(j=0; j<=i; j++)
cout<<str[i];
cout<<endl;
}
}
Exam Tips:
a) The outer loop selects the row (and the letter) and the inner loop prints that letter i+1 times.
Question 76: Distinguish between getchar() and gets().
Answer:
getchar() is a character function, whereas gets() is a string function. For both, the header file cstdio must be included.
getchar() reads a single character from the keyboard.
char ch;
ch = getchar();
cout<<ch;
gets() reads a string from the keyboard; it reads the characters up to the Enter key, including spaces.
char str[80];
cout<<"Enter a string";
gets(str);
Exam Tips:
a) Compare them on three points: what they read, where the result is stored (a char or a char array), and the header file.
Question 77: Write a program to check whether a string is a palindrome or not. (A string is a palindrome if it is the same as the string formed by reversing its characters. Eg. "MALAYALAM", "MADAM", "ARORA", "DAD".)
Answer:
#include<iostream>
using namespace std;
int main()
{
char str[40];
int len, i, j;
cout<<"Enter a string:";
cin>>str;
for(len=0; str[len]!='\0'; len++);
for(i=0, j=len-1; i<len/2; i++, j--)
if(str[i]!=str[j])
break;
if(i==len/2)
cout<<str<<" is palindrome";
else
cout<<str<<" is not palindrome";
}
The program compares the first character with the last, the second with the second last, and so on. If all the pairs match (the loop reaches len/2), the string is a palindrome.
Exam Tips:
a) Only half of the string needs to be compared.
b) The loop ends early with break when a mismatch is found, so i is then less than len/2.
Question 78: Explain multi-character functions.
Answer:
getline() and write() are multi-character functions.
1. getline(): It reads a line of text that ends with a new line character. It reads white spaces also.
char line[80];
cin.getline(line, 80);
2. write(): It is used to display a string.
char line[80];
cin.getline(line, 80);
cout.write(line, 80);
Exam Tips:
a) Both are stream functions and need the header file iostream.
b) In write(line, 80) the second argument is the number of characters to display.
Question 79: Distinguish between the get() and put() functions.
Answer:
1. get() function: get() is an input function. It reads a single character and does not ignore white spaces and the new line character.
Syntax: cin.get(variable);
char ch;
cin.get(ch);
2. put() function: put() is an output function. It prints a single character.
Syntax: cout.put(variable);
char ch;
cin.get(ch);
cout.put(ch);
Exam Tips:
a) get() is used with cin and put() with cout.
b) Mention that, unlike cin>>, get() also reads spaces.
Question 80: Write a program to read a string and print the number of consonants.
Answer:
#include<iostream>
#include<cstdio>
#include<cctype>
using namespace std;
int main()
{
char str[40], ch;
int consonant=0, i;
cout<<"Enter a string:";
gets(str);
for(i=0; str[i]!='\0'; i++)
{
ch = toupper(str[i]);
if(ch>='B' && ch<='Z')
if(ch!='E' && ch!='I' && ch!='O' && ch!='U')
consonant++;
}
cout<<"The number of consonants is "<<consonant;
}
Exam Tips:
a) The letters from B to Z other than E, I, O and U are consonants (A is excluded by starting the range at B).
Question 81: Write a program to read a string and print the number of spaces.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char str[40];
int space=0, i;
cout<<"Enter a string:";
gets(str);
for(i=0; str[i]!='\0'; i++)
if(str[i]==32)
space++;
cout<<"The number of spaces is "<<space;
}
Exam Tips:
a) The ASCII value of the space character is 32.
b) Use gets() or getline(), because cin>> cannot read a string that contains spaces.
Question 82: Write a program to count the number of words in a sentence.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int i, words=1;
char str[80];
cout<<"Enter a string\n";
gets(str);
for(i=0; str[i]!='\0'; i++)
if(str[i]==32)
words++;
cout<<"The number of words is "<<words;
}
The words are separated by single spaces, so the number of words is one more than the number of spaces.
Exam Tips:
a) This method assumes exactly one space between the words and no space at the start or the end.
Question 83: Write a program to input a string and display its reversed string using console I/O functions only. For example, if the input is "AND" the output should be "DNA".
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char str[40], rev[40];
int len, i, j;
cout<<"Enter a string:";
gets(str);
for(len=0; str[len]!='\0'; len++);
for(i=0, j=len-1; i<len; i++, j--)
rev[i] = str[j];
rev[i] = '\0';
cout<<"The reversed string is ";
puts(rev);
}
Exam Tips:
a) Do not forget to put the null character at the end of the new string.
b) Copy from the last character of the original (index len-1) to the first.
Question 84: Write a program to input a word (say COMPUTER) and create a triangle as follows.
C
C O
C O M
C O M P
C O M P U
C O M P U T
C O M P U T E
C O M P U T E R
Answer:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[20];
cout<<"Enter a word (eg. COMPUTER):";
cin>>str;
int i, j;
for(i=0; i<strlen(str); i++)
{
for(j=0; j<=i; j++)
cout<<str[j]<<"\t";
cout<<endl;
}
}
Exam Tips:
a) In row i, the first i+1 characters of the word are printed with a tab between them.
b) strlen() needs the header file cstring.
Question 85: Write a program to input a line of text and display the first character of each word. Use only console I/O functions. For example, if the input is "Save Water, Save Nature", the output should be "SWSN".
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int i;
char str[80];
cout<<"Enter a string\n";
gets(str);
if(str[0]!=32)
cout<<str[0];
for(i=0; str[i]!='\0'; i++)
if(str[i]==32 && str[i+1]!=32)
cout<<str[i+1];
}
The first character is printed (if it is not a space), and then every character that comes just after a space is printed.
Exam Tips:
a) A word starts either at the beginning of the string or after a space.
b) Check str[i+1]!=32 so that extra spaces do not print a space.
Question 86: Consider the following code snippet:
char ch;
cout<<"Enter an alphabet";
cin>>ch;
cout<<toupper(ch);
What is the output of the above code? Give a sample output. If the above code is used on a computer that has no cctype header file, how will you modify the code to get the same output?
Answer:
The code reads a character and converts it to upper case. Because toupper() returns an int, the ASCII value is printed (for example 65 for a) unless the result is cast to char.
Sample output:
Enter an alphabet: a
The output is A (when the result is converted to char).
If the computer has no cctype header file, the code can be written as follows:
char ch;
cout<<"Enter an alphabet";
cin>>ch;
if(ch>=97 && ch<=122)
cout<<(char)(ch-32);
else
cout<<ch;
Exam Tips:
a) A lower case letter is 32 more than its upper case in ASCII, so subtract 32 to convert.
b) Only apply the subtraction when the character is between a (97) and z (122).
Question 87: Read the following program:
#include<iostream.h>
int main()
{
cout<<sum(2, 3);
}
int sum(int x, int y)
{
return (x + y);
}
On compilation of the program, an error is displayed. Identify and explain the reason. How can you rectify the problem?
Answer:
The compiler reads the program line by line. While compiling the line cout<<sum(2, 3); the compiler does not know sum(2, 3), because the function is not declared yet; hence the error "prototype required". There are two ways to rectify this problem.
First method: give the function definition before the main function.
#include<iostream>
using namespace std;
int sum(int x, int y)
{
return (x+y);
}
int main()
{
cout<<sum(2, 3);
}
Second method: give the function declaration (prototype) in the main function.
#include<iostream>
using namespace std;
int main()
{
int sum(int, int);
cout<<sum(2, 3);
}
int sum(int x, int y)
{
return (x+y);
}
Exam Tips:
a) State the reason (the function is used before it is declared) and then give both remedies.
b) The prototype can also be given before main() instead of inside it.
Question 88: Consider the following function definition:
int fact(int &n)
{
int f;
for(f=1; n>0; n--)
f = f*n;
return f;
}
int main()
{
int a=5, ans;
ans = fact(a);
cout<<a<<"! = "<<ans;
}
The expected output is 5! = 120. What will be the actual output of the program? It is not the same as above, why? What modification is required in the program to get the desired output?
Answer:
The output is 0! = 120.
The address (reference) of the variable a is given to the parameter n of the function fact() (call by reference). So the function changes the original variable by n-- until it becomes 0. Hence a is 0 when it is printed.
To get the desired result, use the call by value method, in which a copy of the value of a is passed, so the value of a does not change. So instead of int fact(int &n), just write int fact(int n); that is, remove the & symbol.
Exam Tips:
a) In call by reference, any change to the parameter also changes the original argument.
b) Explain what happens to a, not only the result.
Question 89: A function is defined as follows:
int sum(int a, int b=2)
{
return (a+b);
}
Check whether each of the following function calls is correct or wrong. Justify your answer.
1. cout<<sum(2, 3);
2. cout<<sum(2);
3. cout<<sum();
Answer:
The function is declared with one optional (default) argument, so a call with at least one argument is compulsory.
1. Valid. Here a becomes 2 and b becomes 3 (output 5).
2. Valid. Here a becomes 2 and b takes the default value 2 (output 4).
3. Not valid. At least one argument is compulsory because a has no default value.
Exam Tips:
a) Only the arguments that have default values can be left out of the call.
Question 90: How do two functions exchange data between them? Compare the two methods of data transfer from the calling function to the called function.
Answer:
There are two methods: call by value and call by reference.
1. Call by value: A copy of the actual parameters is passed to the formal parameters. If the function makes any change, it does not affect the original value.
2. Call by reference: The reference (address) of the actual parameters is passed to the formal parameters. If the function makes any change, it affects the original value.
Exam Tips:
a) Make a two-column comparison: what is passed, and whether the original value changes.
b) A short example such as void change(int &y) helps to show the difference.
Question 91: Write down the operation performed by the following statements:
1. int l = strlen("Computer Program");
2. char ch[] = tolower("My School");
3. cout<<(strcmp("High", "Low")>0 ? toupper("High") : tolower("Low"));
Answer:
1. The built-in function strlen() finds the length of the string, which is 16, and assigns it to the variable l.
2. This is an error, because tolower() is a character function; it converts a single character, not a string.
3. This is also an error, because toupper() and tolower() are character functions and cannot take strings as arguments.
Exam Tips:
a) Count the space in "Computer Program" (8 + 1 + 7 = 16).
b) Character functions (tolower, toupper) accept one character; string functions (strlen, strcmp) accept strings.
Question 92: A line of a given length with a particular character is to be displayed. For example, ********** is a line with ten asterisks (*). Define a function to achieve this output.
Answer:
#include<iostream>
using namespace std;
void line(char ch, int n)
{
int i;
for(i=0; i<n; i++)
cout<<ch;
}
int main()
{
char ch;
int n;
cout<<"Enter a character ";
cin>>ch;
cout<<"Enter how many number of times";
cin>>n;
line(ch, n);
}
Exam Tips:
a) The function receives the character and the count as parameters and prints the character n times.
b) Because the function returns nothing, its return type is void.
Question 93: Read the following function:
int fib(int n)
{
if(n<3)
return 1;
else
return (fib(n-1) + fib(n-2));
}
1. What is the speciality of this function?
2. How does it work?
3. What will be the output of the following code?
for(int i=1; i<5; i++)
cout<<fib(i)<<'\t';
Answer:
1. This function is a recursive function; that means the function calls itself.
2. It works as follows:
If i = 1, fib(1) returns 1.
If i = 2, fib(2) returns 1.
If i = 3, fib(3) returns fib(2) + fib(1), that is 1 + 1 = 2.
If i = 4, fib(4) returns fib(3) + fib(2), that is 2 + 1 = 3.
3. The output is: 1 1 2 3 (separated by tabs).
Exam Tips:
a) The condition n<3 is the base case that stops the recursion.
b) The function generates the Fibonacci series 1, 1, 2, 3, 5, ...
Question 94: Explain the scope rules of functions and variables in a C++ program.
Answer:
1. Local variable or function: A variable or function declared inside a function is called a local variable or function. It cannot be accessed from outside the function.
main()
{
int k; // local variable
cout<<sum(a, b);
}
2. Global variable or function: A variable or function declared outside all functions is called a global variable or function. It can be accessed by any statement of the program.
int k; // global variable
int sum(int a, int b); // global function
main()
{
}
Exam Tips:
a) Give a small example of each kind.
b) Scope means where in the program a name can be used.
Question 95: Briefly explain default arguments.
Answer:
A default value can be set for a parameter (argument) of a function. When the user does not give a value, the function takes the default value. An argument cannot have a default value unless all the arguments on its right side also have default values.
Functions with valid default arguments:
float area(int x, int y, int z=30);
float area(int x, int y=20, int z=30);
float area(int x=10, int y=20, int z=30);
Functions with invalid default arguments:
float area(int x=10, int y, int z);
float area(int x, int y=20, int z);
float area(int x=10, int y=20, int z);
Exam Tips:
a) State the right-to-left rule and give both valid and invalid examples.
Question 96: Write a program to read a character and check whether it is an alphabet or not. If it is an alphabet, check whether it is upper case or lower case.
Answer:
#include<iostream>
using namespace std;
int main()
{
char ch;
cout<<"Enter a character";
cin>>ch;
if(ch>=65 && ch<=90)
cout<<"It is an upper case alphabet";
else if(ch>=97 && ch<=122)
cout<<"It is a lower case alphabet";
else
cout<<"It is not an alphabet";
}
Exam Tips:
a) The ASCII codes of A to Z are 65 to 90 and those of a to z are 97 to 122.
Question 97: Write a program to read two strings and join them.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char str1[50], str2[50], str[100];
int i, len1=0, len2=0;
cout<<"Enter a string:";
gets(str1);
cout<<"Enter another string:";
gets(str2);
for(i=0; str1[i]!='\0'; i++, len1++);
for(i=0; str2[i]!='\0'; i++, len2++);
for(i=0; i<len1; i++)
str[i] = str1[i];
for(i=0; i<len2; i++)
str[len1+i] = str2[i];
str[len1+len2] = '\0';
cout<<"The concatenated string is "<<str;
}
Exam Tips:
a) Copy the first string, then copy the second string after it, and finally add the null character.
b) The result array must be at least as long as both strings together plus one.
Question 98: Write a program to read two strings and compare them.
Answer:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int m;
char str1[100], str2[100];
cout<<"Enter first string";
gets(str1);
cout<<"Enter second string";
gets(str2);
m = strcmp(str1, str2);
if(m<0)
cout<<str1<<" is less than "<<str2;
else if(m>0)
cout<<str1<<" is greater than "<<str2;
else
cout<<str1<<" is equal to "<<str2;
}
Exam Tips:
a) strcmp() returns a negative value, zero or a positive value; use these three cases in the if statements.
Question 99: Write a program to read a string and display the number of alphabets, digits and special characters.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char str[100];
int i, digit=0, alpha=0, special=0;
cout<<"Enter a string:";
gets(str);
for(i=0; str[i]!='\0'; i++)
if(str[i]>=48 && str[i]<=57)
digit++;
else if((str[i]>=65 && str[i]<=90) || (str[i]>=97 && str[i]<=122))
alpha++;
else
special++;
cout<<"The number of alphabets is "<<alpha;
cout<<" the number of digits is "<<digit;
cout<<" and the number of special characters is "<<special;
}
Exam Tips:
a) ASCII ranges: digits 48 to 57, upper case 65 to 90 and lower case 97 to 122; everything else is a special character.
b) Use brackets around the two alphabet ranges to make the condition clear.
Question 100: Consider the following two programs.
A.
void change(int&);
int main()
{
int x = 0;
change(x);
cout<<"value ="<<x;
}
void change(int &y)
{
y = 40;
cout<<"value="<<y;
}
B.
void change(int);
int main()
{
int x = 0;
change(x);
cout<<"value ="<<x;
}
void change(int y)
{
y = 40;
cout<<"value="<<y;
}
1. Predict the output of both programs.
2. Justify your predictions.
Answer:
1. Program A prints "value=40" (from change()) and then "value =40" (from main()).
Program B prints "value=40" (from change()) and then "value =0" (from main()).
2. In the first case (A), the argument x is passed by reference, so the changes made in the function are reflected in main().
In the second case (B), the argument x is passed by value, so the changes made in the function do not reflect in main().
Exam Tips:
a) Note that both programs print twice: once inside change() and once in main().
b) The only difference between the programs is the & symbol in the parameter.
Question 101: Write a program to read two strings and join them using string functions.
Answer:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
char str1[50], str2[50], str[100];
cout<<"Enter a string:";
gets(str1);
cout<<"Enter another string:";
gets(str2);
strcpy(str, str1);
strcat(str, str2);
cout<<"The concatenated string is "<<str;
}
Exam Tips:
a) strcpy() copies the first string into the empty result string, and strcat() adds the second string to the end of it.
b) Do not use strcat() on an array that has not been initialised.
Question 102: Differentiate the outputs of the following C++ statements and also give the reason.
1. cout<<strcmp("world", "WORLD");
2. cout<<strcmpi("world", "WORLD");
Answer:
1. The output is a value greater than 0, because the first string "world" is greater than "WORLD" (the ASCII value of w is greater than that of W).
2. It prints 0, because strcmpi() is the same as strcmp() but it is not case sensitive; upper case and lower case letters are treated as the same.
Exam Tips:
a) strcmp() is case sensitive and strcmpi() is not.
b) The exact positive value depends on the compiler, so write "greater than 0".
Question 103: Match the following.
| Function | Use |
|---|---|
| 1. strcmp() | a. To combine two strings |
| 2. strcpy() | b. To get 5 from 25 |
| 3. strcat() | c. To get 10 from -10 |
| 4. sqrt() | d. To change a to A |
| 5. abs() | e. To compare two strings |
| 6. toupper() | f. To copy one string to another |
Answer:
1 - e, 2 - f, 3 - a, 4 - b, 5 - c, 6 - d
Exam Tips:
a) Learn the function groups: string (strcmp, strcpy, strcat), mathematical (sqrt, abs) and character (toupper).
Question 104: Write a C++ program to find the sum of the first N natural numbers using a user defined function.
Answer:
#include<iostream>
using namespace std;
int sum(int n)
{
int i, sum=0;
for(i=1; i<=n; i++)
sum += i;
return sum;
}
int main()
{
int n;
cout<<"Enter the number of numbers to find the sum:";
cin>>n;
cout<<"The sum of first "<<n<<" natural numbers is "<<sum(n);
}
Exam Tips:
a) The function receives n, adds 1 to n in a loop and returns the sum.
b) Using the same name for the function and a local variable works here, but different names are clearer.
Question 105: Write the need for a function prototype in a C++ program.
Answer:
When a function is defined after the main function, the compiler gives an error that the function should have a prototype, because the function is used before it is defined. To avoid this, a prototype (declaration) of the function is given before it is used, for example inside the main function or before main().
Exam Tips:
a) Say what the prototype tells the compiler: the return type, the name and the argument types.
Question 106: Write a suitable function prototype for each of the following cases.
Case I: The function Volume() takes two arguments, one float and the other int, and returns its volume.
Case II: A function Big() has no arguments and no return value.
Case III: A function Print() takes two floating point arguments and returns nothing.
Answer:
Case I: float Volume(float, int);
Case II: void Big(); or void Big(void);
Case III: void Print(float, float); or void Print(double, double);
Exam Tips:
a) Write the return type first, then the name, then the argument types in brackets, and end with a semicolon.
Question 107: Find the error in the following C++ program and rectify it.
#include<iostream>
using namespace std;
int main()
{
int x, y, z;
cin>>x>>y;
z = x * y;
cout<<multi(x, y);
}
int multi(int a, int b)
{
return a*b;
}
Answer:
Error 1: The function prototype is missing, because multi() is used before it is defined.
Error 2: The variable z is not needed.
Error 3: The statement z = x*y; is not needed.
The corrected program:
#include<iostream>
using namespace std;
int multi(int, int);
int main()
{
int x, y;
cin>>x>>y;
cout<<multi(x, y);
}
int multi(int a, int b)
{
return a*b;
}
Exam Tips:
a) The real compile error is the missing prototype; the extra variable z only wastes memory.
Question 108: Consider the following function definition:
int add(int a, int b=2, int c=5)
{
int s = a + b + c;
cout<<"Sum is :"<<s;
}
Predict the output of the above code for the following function calls:
1. add(5, 8, 10);
2. add(5, 8);
3. add(5);
Answer:
1. add(5, 8, 10): a = 5, b = 8 and c = 10, so it prints "Sum is :23" (5 + 8 + 10).
2. add(5, 8): a = 5, b = 8 and c takes the default value 5, so it prints "Sum is :18" (5 + 8 + 5).
3. add(5): a = 5, and b and c take the default values 2 and 5, so it prints "Sum is :12" (5 + 2 + 5).
Exam Tips:
a) Replace any missing argument with its default value and then add.
b) The output includes the text "Sum is :" before the number.
Question 109: Consider the following C++ program, predict the output and justify it.
#include<iostream>
using namespace std;
int sqr(int&);
int main()
{
int a=5;
cout<<sqr(a);
cout<<a;
return 0;
}
int sqr(int &b)
{
int ans;
ans = b*b;
b++;
return ans;
}
Answer:
The output is 25 followed by 6 (that is, 256 on the screen).
The function uses the call by reference method. The call sqr(a) passes the variable a itself to the function, so b and a are the same variable. The function returns 5 x 5 = 25 and then changes b to 6, which means a also becomes 6.
Exam Tips:
a) Because there is no space between the two cout statements, the digits 25 and 6 appear together as 256.
b) The & in the parameter is the key to the answer.
Question 110: Differentiate local variables and global variables in a C++ program.
Answer:
1. Local scope: A variable declared inside a block can be used only in that block; it cannot be used in any other block.
int sum(int n1, int n2)
{
int s;
s = n1 + n2;
return(s);
}
Here the variable s is declared inside the function sum and has local scope.
2. Global scope: A variable declared outside all blocks can be used anywhere in the program.
int s;
int sum(int n1, int n2)
{
s = n1 + n2;
return(s);
}
Here the variable s is declared outside all the functions, so it can be used anywhere in the program.
Exam Tips:
a) Give one example for each scope, as above.
Question 111: Consider the following C++ code fragment and identify the local function and the global function. Also justify your selection.
int main()
{
int a=2, b=3;
cout<<sum(a, b);
return 0;
}
int sum(int p, int q)
{
int ans;
ans = p*q;
void print()
{
cout<<"The Sum is :"<<ans;
}
return ans;
}
Answer:
The function print() is declared inside another function (sum), so it is a local function. The function sum() is declared outside all the functions, so it is a global function.
Exam Tips:
a) This question is based on the scope rules of the syllabus: a name declared inside a function is local; one declared outside all functions is global.
b) Standard C++ does not allow a function to be defined inside another function; the example is used only to explain local scope.
Question 112: Read the following C++ program and identify the error and give the reason.
#include<iostream>
using namespace std;
void disp(int);
int main()
{
int x=10;
disp(x);
return 0;
}
void disp(int y)
{
cout<<x;
cout<<y;
return;
}
Answer:
The variable x cannot be used in disp(), so the statement cout<<x; is an error. The variable x is declared in the main() function, that is, x is a local variable of main() and is not accessible in disp().
Exam Tips:
a) Passing x to disp() makes its value available as y, so print y (or make x global) instead.
Five Mark Questions and Answers
Question 113: What will be the output of each of the following code segments if the user enters "GOOD MORNING"?
1.
char string[80];
gets(string);
cout<<string;
2.
char string[80];
cin>>string;
cout<<string;
3.
char ch;
ch = getchar();
cout<<ch;
4.
char string[80];
cin.getline(string, 9);
cout<<string;
Answer:
1. GOOD MORNING (gets() reads the whole line including the space).
2. GOOD (cin>> stops reading at the first space).
3. G (getchar() reads only one character).
4. GOOD MOR (getline(string, 9) reads at most 8 characters, because the last place is kept for the null character).
Exam Tips:
a) Check how each input method treats the space: gets() and getline() read it, cin>> stops at it.
b) For cin.getline(str, n), only n-1 characters are stored.
c) C++ is case sensitive, so the array name must be written the same way everywhere.
Question 114: Read a string and print the number of vowels.
Answer:
#include<iostream>
#include<cstdio>
#include<cctype>
using namespace std;
int main()
{
char line[80];
int i, vowel=0;
puts("Enter a string");
gets(line);
for(i=0; line[i]!='\0'; i++)
switch(tolower(line[i]))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': vowel++;
}
cout<<"The number of vowels in the string is "<<vowel;
}
The loop runs through every character; tolower() makes the comparison independent of the letter case, and vowel is increased for each of a, e, i, o and u.
Exam Tips:
a) Read the whole line with gets() so that spaces are accepted.
b) Include cctype (for tolower) and cstdio (for gets and puts).
c) Because several cases share one statement, no break statements are needed between them.
Question 115: Describe in detail the unformatted console I/O functions.
Answer:
Unformatted console I/O functions are in the header file cstdio.
1. Single character functions: These functions read or print one character at a time.
getchar(): It reads a character from the keyboard and stores it in a character variable.
char ch;
ch = getchar();
putchar(): It prints a character on the screen.
char ch;
ch = getchar();
putchar(ch);
2. String functions: These functions read or print a string.
gets(): It reads a string from the keyboard and stores it in a character array.
char str[80];
gets(str);
puts(): It displays a string on the screen and moves to the next line.
char str[80];
gets(str);
puts(str);
Exam Tips:
a) Divide your answer into single character functions and string functions, and give an example for each.
b) Mention the header file cstdio.
c) Also note that getch() and getche() are other single character functions available with some compilers.
Question 116: Write a program to input a string and find the number of uppercase letters, lowercase letters, digits, special characters and white spaces.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char str[100];
int i, digit=0, Ualpha=0, Lalpha=0, special=0, wspace=0;
cout<<"Enter a string:";
gets(str);
for(i=0; str[i]!='\0'; i++)
if(str[i]>=48 && str[i]<=57)
digit++;
else if(str[i]>=65 && str[i]<=90)
Ualpha++;
else if(str[i]>=97 && str[i]<=122)
Lalpha++;
else if(str[i]==' ' || str[i]=='\t')
wspace++;
else
special++;
cout<<"The number of alphabets is "<<Ualpha+Lalpha;
cout<<" the number of Uppercase letters is "<<Ualpha;
cout<<" the number of Lowercase letters is "<<Lalpha;
cout<<" the number of digits is "<<digit;
cout<<" the special characters is "<<special;
cout<<" and the number of white spaces is "<<wspace;
}
Exam Tips:
a) Use an if - else if ladder so that each character is counted in exactly one category.
b) Test the white space before the special characters, because a space is also not a letter or digit.
Question 117: Write a program to input a string and replace all lowercase vowels by the corresponding uppercase letters.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
char str[100];
int i;
cout<<"Enter a string:";
gets(str);
for(i=0; str[i]!='\0'; i++)
switch(str[i])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': str[i] = str[i] - 32;
}
cout<<str;
}
Each lower case vowel is converted to upper case by subtracting 32 from its ASCII value; all other characters are left unchanged.
Exam Tips:
a) Check only the five lower case vowels; capital vowels and consonants should not change.
b) Print the modified string after the loop ends.
Question 118: A list of C++ built-in functions is given. Classify them based on their usage and prepare a table with proper group names.
strcmp(), sin(), getch(), isalpha(), pow(), puts(), strcat(), tolower(), getchar(), isalnum(), sqrt(), exp(), write()
Answer:
| String functions | Mathematical functions | Character functions | I/O functions |
|---|---|---|---|
| strcmp() | sin() | isalpha() | getch() |
| strcat() | pow() | isalnum() | puts() |
| sqrt() | tolower() | getchar() | |
| exp() | write() |
Exam Tips:
a) Group the functions by header file: cstring, cmath, cctype and cstdio/iostream.
b) Check that all 13 functions appear in the table.
Question 119: The factorial of a number, say N, is the product of the first N natural numbers. Thus the factorial of 5 can be obtained by taking the product of 5 and the factorial of 4. Similarly, the factorial of 4 can be found by taking the product of 4 and the factorial of 3. At last, the factorial of 1 is 1 itself. Which technique is applicable to find the factorial of a number in this fashion? Write a C++ function to implement this technique. Also explain the working of the function by giving the number 5 as input.
Answer:
The technique is recursion: a function that calls itself is known as a recursive function.
#include<iostream>
using namespace std;
int fac(int);
int main()
{
int n;
cout<<"enter a number";
cin>>n;
cout<<fac(n);
}
int fac(int n)
{
if(n==1)
return 1;
else
return (n*fac(n-1));
}
Working: If the value of n is 5, the function is called as fac(5). It returns 5*fac(4), which calls the function again and returns 5*4*fac(3). This process continues until the value of n becomes 1. So the result is 5*4*3*2*1 = 120.
Exam Tips:
a) Every recursive function needs a stopping condition (here n==1).
b) Show the chain of calls fac(5), fac(4), fac(3), fac(2), fac(1) while explaining the working.
Question 120: Read the following program:
#include<iostream>
using namespace std;
int a = 0;
int main()
{
int showval(int);
cout<<a;
a++;
cout<<showval(a);
cout<<a;
}
int showval(int x)
{
int a = 5;
return (a + x);
}
Write down the value displayed by the output of the above program with a suitable explanation. What inferences are drawn regarding the scope of variables?
Answer:
The output is 061.
Global variable: A variable declared outside all functions is known as a global variable.
Local variable: A variable declared inside a function is known as a local variable.
If a variable declared inside a function has the same name as a global variable, the function uses the local variable and not the global one.
Here int a = 0 is a global variable. In the main function there is no local variable a, so the global a is used and 0 is displayed. The statement a++ makes the value of a 1. It calls the function showval() with the argument a = 1, so x gets the value 1. But in the function showval() there is a local variable a with the value 5, which is used, so the function returns 5 + 1 = 6 and 6 is displayed. After this, the value 1 of the global variable a is displayed. Hence the result is 061.
Exam Tips:
a) Trace the program in order: print a (0), increase a (1), print showval(a) (6), print a (1).
b) State the inference: a local variable hides a global variable of the same name inside its function.
Question 121: The following are function calling statements. Some of them will be executed, while some others generate a compilation error. Write down your opinion on each of them with proper justification.
1. char ch = getch();
2. sqrt(25);
3. strcat("Computer", "Program");
4. double num = pow(2, 3, 5);
5. putchar(getchar());
Answer:
1. getch() reads a character from the keyboard but does not echo it on the screen. The statement is valid if the header file conio.h is available and ch gets the character that was typed.
2. It returns the square root of 25, that is 5 (the header file cmath is needed). The returned value is not used or displayed here.
3. This is an error. The first argument of strcat() must be a character array that is large enough to hold the result, but "Computer" is a constant string. To get the string "ComputerProgram" use a character array, for example char s[30]="Computer"; strcat(s, "Program");
4. This is an error, because the function pow() takes only two arguments, but here it has three. It can be written as double num = pow(2, 3);
5. It reads a character from the keyboard and displays it on the screen.
Exam Tips:
a) Check the number and kind of arguments for each call.
b) For strcat(), the destination must be a modifiable array; a string constant cannot be used.
Question 122: Write short notes on character functions and string functions.
Answer:
a. Character functions (header file cctype):
1. isalnum(): checks whether a character is an alphabet or a digit. It returns a non-zero value if it is, otherwise it returns zero.
2. isalpha(): checks whether a character is an alphabet. It returns a non-zero value if it is, otherwise zero.
3. isdigit(): checks whether a character is a digit. It returns a non-zero value if it is, otherwise zero.
4. islower(): checks whether a character is a lower case alphabet. It returns a non-zero value if it is, otherwise zero.
5. isupper(): checks whether a character is an upper case alphabet. It returns a non-zero value if it is, otherwise zero.
6. tolower(): converts an alphabet into lower case.
7. toupper(): converts an alphabet into upper case.
b. String functions (header file cstring):
1. strcpy(): copies one string into another.
2. strcat(): joins (concatenates) the second string to the end of the first string.
3. strlen(): finds the length of a string.
4. strcmp(): compares two strings. If the first string is less than the second string, it returns a negative value; if both strings are equal, it returns zero; and if the first string is greater than the second, it returns a positive value.
Exam Tips:
a) Write the header file for each group.
b) Give the return value of each function in a few words, as above.
Question 123: Write a program to perform the following operations on a string: 1. Find the length of a string, 2. Search for a character, 3. Display the string.
Answer:
#include<iostream>
#include<cstdio>
using namespace std;
void len()
{
char str[100];
int i, len;
cout<<"Enter a string:";
gets(str);
for(i=0, len=0; str[i]!='\0'; i++, len++);
cout<<"The length of the string is "<<len;
}
void search()
{
char str[100], s;
int f=0, i;
cout<<"Enter a string:";
gets(str);
cout<<"Enter the character to be searched";
cin>>s;
for(i=0; str[i]!='\0'; i++)
if(str[i]==s)
f=1;
if(f)
cout<<"The character is present in the string";
else
cout<<"The character is not present in the string";
}
void display()
{
char str[100];
cout<<"Enter a string:";
gets(str);
cout<<"The string you entered is "<<str;
}
int main()
{
int ch;
do
{
cout<<"\n1. Length of a string.\n2. Search a character.\n3. Display the string\nEnter the choice (zero for exit):";
cin>>ch;
cin.ignore();
switch(ch)
{
case 1: len(); break;
case 2: search(); break;
case 3: display(); break;
default: cout<<"Thank you";
}
} while(ch!=0);
}
Exam Tips:
a) Write one function for each operation and call them from a menu in main() with a switch statement.
b) The do-while loop repeats the menu until the user enters 0.
Question 124: Write functions to perform the following operations: 1. sqrt(), 2. power of two numbers, 3. sin, 4. cos.
Answer:
#include<iostream>
#include<cmath>
using namespace std;
void sqroot()
{
int n;
cout<<"Enter the number to find square root";
cin>>n;
cout<<"The square root of "<<n<<" is "<<sqrt(n);
}
void Power()
{
int m, n;
cout<<"Enter a number and power";
cin>>m>>n;
cout<<"The result of "<<m<<" power "<<n<<" is "<<pow(m, n);
}
void sine()
{
int n;
cout<<"Enter a number";
cin>>n;
cout<<"sin("<<n<<") is "<<sin(n);
}
void cosine()
{
int n;
cout<<"Enter a number";
cin>>n;
cout<<"cos("<<n<<") is "<<cos(n);
}
int main()
{
int ch;
do
{
cout<<"\n1.Square root\n2.Power of 2 nos\n3.sin\n4.cos\nEnter the choice (zero for exit):";
cin>>ch;
switch(ch)
{
case 1: sqroot(); break;
case 2: Power(); break;
case 3: sine(); break;
case 4: cosine(); break;
}
} while(ch!=0);
}
Exam Tips:
a) All four functions are in the header file cmath.
b) The angle for sin() and cos() is given in radians, not in degrees.
Question 125: Read the following C++ programs and answer the questions:
Case I
#include<iostream>
using namespace std;
int cube(int);
int main()
{
int a=5;
cout<<"Cube of the number is :"<<cube(a);
return 0;
}
int cube(int b)
{
return b*b*b;
}
Case II
#include<iostream>
using namespace std;
int cube(int &);
int main()
{
int a=5;
cout<<"Cube of the number is :"<<cube(a);
return 0;
}
int cube(int &b)
{
return b*b*b;
}
1. Identify the type of function call in each case.
2. How do they differ?
Answer:
1. In Case I the method used is call by value, and in Case II it is call by reference.
2. They differ as follows:
Call by value: A copy of the actual parameters is passed to the formal parameters. If the function makes any change, it does not affect the original value.
Call by reference: The reference of the actual parameters is passed to the formal parameters. If the function makes any change, it affects the original value.
Exam Tips:
a) Look for the & symbol in the parameter to identify call by reference.
b) Both programs print 125, because cube() does not change its parameter; the difference matters only when the function modifies it.
Free study material for Computer Application
Step-by-Step Textbook Answers: Class 12 Computer Application Chapter 03 Functions
Chapter Exercise Answers for Class 12 Computer Application
Access structured Kerala Board textbook solutions for Chapter 03 Functions. Designed in alignment with the latest academic curriculum for Class 12 Computer Application, these answers cover all end-of-chapter exercises to support daily learning and homework completion.
Detailed Answer Guides for Chapter 03 Functions
Beyond providing final answers, these guides offer step-by-step breakdowns for complex queries in the Class 12 Computer Application module. This approach helps students balance theoretical depth with practical problem-solving skills required for Kerala Board exams.
Complete Preparation Kit for Class 12 Exams
Frequent review of these structured answers builds strong analytical capabilities and response efficiency. Maximize your academic readiness by combining these textbook solutions with our curated study materials and mock evaluations for Class 12 Computer Application.
FAQs
The complete and updated Kerala Plus Two Computer Application Chapter 3 Functions Questions and Answers is available for free on StudiesToday.com. These solutions for Class 12 Computer Application are as per latest Kerala Board curriculum.
Yes, our experts have revised the Kerala Plus Two Computer Application Chapter 3 Functions Questions and Answers as per 2026 exam pattern. All textbook exercises have been solved and have added explanation about how the Computer Application concepts are applied in case-study and assertion-reasoning questions.
Toppers recommend using Kerala Board language because Kerala Board marking schemes are strictly based on textbook definitions. Our Kerala Plus Two Computer Application Chapter 3 Functions Questions and Answers will help students to get full marks in the theory paper.
Yes, we provide bilingual support for Class 12 Computer Application. You can access Kerala Plus Two Computer Application Chapter 3 Functions Questions and Answers in both English and Hindi medium.
Yes, you can download the entire Kerala Plus Two Computer Application Chapter 3 Functions Questions and Answers in printable PDF format for offline study on any device.