UNIT IV CSC
UNIT IV CSC
Q14. Write a C++ program to print the first n Fibonacci numbers using a loop.
A14.
cpp
CopyEdit
#include <iostream>
int main() {
int n;
cin >> n;
if (i <= 1)
else {
first = second;
second = next;
return 0;
}
Explanation:
The program initializes the first two Fibonacci numbers and then uses a for loop to calculate and
print each subsequent number until it has printed n numbers.
Q15. Write a C++ function that takes an array of integers and returns the maximum element.
A15.
cpp
CopyEdit
#include <iostream>
maxVal = arr[i];
return maxVal;
int main() {
cout << "The maximum element is: " << findMax(numbers, size) << endl;
return 0;
Explanation:
The function findMax iterates through the array, comparing each element to the current maximum,
and finally returns the highest value found.
Q16. How do user-defined functions improve code readability and maintenance? Provide an
example.
A16.
User-defined functions allow you to:
Example:
Imagine you need to calculate the area of a circle several times. Instead of writing the formula each
time, you define a function:
cpp
CopyEdit
#include <iostream>
int main() {
double r = 5.0;
cout << "Area of the circle is: " << calculateArea(r) << endl;
return 0;
This function makes your code shorter and easier to update if the formula or constant changes.
Q17. Describe how string manipulation functions such as strcpy, strcat, and strlen work in C++ with
examples.
A17.
strlen:
Returns the length of a string (number of characters before the null terminator).
Example:
cpp
CopyEdit
strcpy:
Copies one string to another.
Example:
cpp
CopyEdit
char destination[20];
strcpy(destination, source);
cout << "Copied string: " << destination << endl; // Outputs "World"
strcat:
Concatenates (joins) two strings together.
Example:
cpp
CopyEdit
strcat(greeting, name);
These functions help perform common text operations, making string handling easier in C++.
Below is a comprehensive set of exam questions and answers for UNIT 4: PROGRAMMING IN C++.
The answers are written in simple language with extended explanations and code examples where
needed. You can use these to study and review key concepts in flow control, inbuilt functions, user-
defined functions, arrays, and user-defined data types.
A. Flow of Control
1. Conditional Statements
Q1. What are the different types of conditional statements in C++? Explain if-else, nested if, switch-
case (with default), and the conditional (ternary) operator with simple examples.
A1.
if-else Statement:
Checks a condition and executes one block if true and another if false.
Example:
int x = 10;
if(x > 5)
else
Nested if Statement:
Uses one if inside another to check multiple conditions.
Example:
int x = 10;
if(x > 0) {
if(x > 5)
else
}
switch-case Statement:
Compares a single variable against multiple constant values. The default case is executed if
none match. Example:
int choice = 2;
switch(choice) {
case 1:
break;
case 2:
break;
default:
}
Conditional (Ternary) Operator:
Provides a compact form of an if-else statement. Example:
int a = 5, b = 3;
A2.
The break statement stops the execution of the switch-case block. Without it, execution “falls
through” to the next case—even if that case's condition isn’t met. This can lead to unintended
behavior. Always use break unless you specifically need fall-through.
A3.
Nested switch-case statements are used when you need to evaluate more than one condition in a
hierarchical manner.
Example:
#include <iostream>
int main() {
switch(grade) {
case 1:
break;
case 2:
switch(subject) {
case 1:
break;
case 2:
break;
default:
break;
default:
return 0;
2. Loops
Q4. Compare the while loop, do-while loop, and for loop. When would you use each?
A4.
while Loop:
Runs as long as a condition is true. Use it when you do not know the number of iterations in
advance. Example:
int i = 1;
while(i <= 5) {
i++;
}
do-while Loop:
Executes the loop body at least once before checking the condition. Use when you need the
code to run at least once. Example:
int i = 1;
do {
i++;
}
Q5. Write a simple C++ program using a nested loop to print a multiplication table (from 1 to 5).
A5.
#include <iostream>
int main() {
return 0;
Explanation:
The outer loop controls the row, while the inner loop calculates and prints the product for each
column.
Q6. What is the role of header files in C++? List some common header files and what functions
they provide.
A6.
Header files contain declarations of functions, classes, and macros. They allow you to use pre-written
functions without coding them yourself.
<ctype.h>: Offers character handling functions like isalnum(), isalpha(), isdigit(), islower(),
isupper(), tolower(), and toupper().
<string.h>: Contains functions for string handling such as strcpy(), strcat(), strlen(), strcmp(),
strrev(), strupr(), and strlwr().
<math.h>: Provides mathematical functions like fabs(), pow(), sqrt(), sin(), cos(), and abs().
<stdlib.h>: Contains utility functions like randomize(), random(), itoa(), and atoi().
Q7. What are the functions gets() and puts() used for?
A7.
gets():
Reads a string (including spaces) from the standard input until a newline is encountered.
(Note: It is unsafe and often replaced by safer alternatives like fgets().)
puts():
Writes a string to the standard output and appends a newline automatically.
Example:
#include <stdio.h>
int main() {
char str[100];
return 0;
Q8. List some character functions provided by ctype.h and give an example using isalpha(),
isdigit(), tolower(), and toupper().
A8.
Example:
#include <iostream>
#include <ctype.h>
int main() {
char ch = 'A';
if(isalpha(ch))
if(isdigit('5'))
cout << "Lowercase of " << ch << " is " << (char)tolower(ch) << endl;
cout << "Uppercase of " << 'b' << " is " << (char)toupper('b') << endl;
return 0;
Q9. Explain the purpose of string functions like strcpy(), strcat(), strlen(), and strcmp() with simple
examples.
A9.
strcpy(destination, source):
Copies the source string to the destination.
char destination[20];
strcat(destination, source):
Concatenates the source string to the end of the destination.
strlen(string):
Returns the length of the string (excluding the null character).
strcmp(str1, str2):
Compares two strings. Returns 0 if they are equal.
if(strcmp("abc", "abc") == 0)
Q10. What are some common mathematical functions in C++? Give examples using fabs(), pow(),
sqrt(), sin(), and cos().
A10.
sin(x) and cos(x): Compute the sine and cosine of an angle (in radians).
cout << "sin(0) = " << sin(0) << ", cos(0) = " << cos(0);
Q11. Briefly describe the use of functions such as randomize(), random(), itoa(), and atoi() found in
stdlib.h.
A11.
atoi(string):
Converts a string to an integer.
Example:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
char str[10];
return 0;
C. User-Defined Functions
Q12. What is a user-defined function in C++? Explain its components and benefits with a simple
example.
A12.
A user-defined function is one created by the programmer to perform a specific task. It typically
consists of:
Function Prototype: Declaration of the function (its return type, name, and parameters).
#include <iostream>
// Function prototype
int main() {
return 0;
}
// Function definition
return a + b;
Benefits:
Q13. Explain the difference between call by value and call by reference. Provide code examples for
both.
A13.
Call by Value:
The function receives a copy of the variable. Changes in the function do not affect the
original.
num++;
}
int main() {
int x = 5;
increment(x);
// x remains 5
}
Call by Reference:
The function receives the actual variable (using a reference), so changes affect the original.
num++;
}
int main() {
int x = 5;
increment(x);
// x becomes 6
}
Q14. What are default arguments in functions? Provide an example where a function uses a
default argument.
A14.
Default arguments allow a function to be called with fewer parameters by providing default values
for some parameters.
#include <iostream>
int main() {
return 0;
Q15. How do scope rules affect variables in functions? Explain the difference between local and
global variables.
A15.
Local Variables:
Declared inside a function or block. They are only accessible within that function or block
and are destroyed once the block ends.
Global Variables:
Declared outside all functions. They are accessible from any function in the program
throughout its execution.
Scope rules help avoid naming conflicts and control the lifetime of data.
1. Arrays
Q16. What is an array in C++ and what are its advantages? Explain one-dimensional arrays with
examples of declaration, initialization, and a simple operation (e.g., calculating the sum of
elements).
A16.
An array is a collection of elements of the same type stored in contiguous memory.
Advantages:
Example:
#include <iostream>
int main() {
int sum = 0;
sum += numbers[i];
cout << "Sum of array elements: " << sum << endl;
return 0;
Q17. How are strings represented as arrays in C++? Provide an example that performs a simple
string manipulation, such as counting the number of vowels.
A17.
Strings are stored as arrays of characters ending with a null character ('\0').
Example:
#include <iostream>
int main() {
int vowelCount = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
vowelCount++;
return 0;
Q18. Explain two-dimensional arrays. Write an example program that calculates the sum of each
row in a 3x3 matrix.
A18.
#include <iostream>
int main() {
{4, 5, 6},
{7, 8, 9} };
int rowSum = 0;
rowSum += matrix[i][j];
cout << "Sum of row " << i + 1 << " is " << rowSum << endl;
return 0;
Explanation:
The outer loop iterates through each row while the inner loop sums the values in that row.
A19.
#include <iostream>
#include <cstring>
struct Student {
char name[50];
int age;
float grade;
};
int main() {
Student s1;
s1.age = 20;
s1.grade = 88.5;
cout << "Name: " << s1.name << ", Age: " << s1.age << ", Grade: " << s1.grade << endl;
return 0;
Explanation:
A structure groups related data together. You can access its members using the dot (.) operator.
Q20. How can you pass a structure to a function by value and by reference? Provide examples.
A20.
Pass by Value:
void displayStudent(Student s) {
cout << s.name << " " << s.age << " " << s.grade << endl;
}
Pass by Reference:
}
int main() {
updateGrade(s1);
displayStudent(s1);
return 0;
}
Q21. What are typedef and #define used for in C++? Provide examples demonstrating how to
create an alias for a data type and a macro.
A21.
typedef:
Creates an alias for an existing data type.
#define:
Defines a macro or constant value.
#define PI 3.14159
Explanation:
These help make code more readable and easier to maintain by using meaningful names for data
types and constants.
This set of questions and answers covers the key concepts from flow control through inbuilt
functions, user-defined functions, arrays, and structures. Reviewing these should help reinforce your
understanding of UNIT 4 in C++ programming.