Problem Solving & Programming
Question Bank-1
1. List the basic structure of a C program.
● Pre-processor Directives: Imports necessary libraries.
● Global Variables: Declares variables that can be accessed throughout the program.
● Function Declarations/Prototypes: Declare functions before they are defined.
● main() Function: The entry point where program execution starts.
● User-defined Functions: Define additional custom functions to modularize the program.
2. Tell about pre and Post increment, decrement operators.
A. Pre-increment / Pre-decrement
Pre-increment (++var): Increments the variable first, then returns the updated value.
int a = 5;
int b = ++a; // a becomes 6, b is 6
Pre-decrement (- -var): Decrements the variable first, then returns the updated value.
int a = 5;
int b = - -a; // a becomes 4, b is 4
B. Post-increment / Post-decrement
Post-increment (var++): Returns the current value, then increments the variable.
int a = 5;
int b = a++; // b is 5, a becomes 6
Post-decrement (var--): Returns the current value, then decrements the variable.
int a = 5;
int b = a--; // b is 5, a becomes 4
Pre changes the value first, while Post uses the value first and then changes it.
3. Outline the scope rules of a variable in C.
In C, the scope of a variable determines where it can be accessed:
A. Block Scope (Local): Variables inside a function or block (e.g., loops, if
statements) are accessible only within that block.
B. File Scope (Global): Variables declared outside functions are global and
accessible throughout the file.
C. Program Scope: Global variables can be shared across multiple files using
extern.
4. Which of the following identifiers are valid? _a, __abc, --ab, #doorno, door#, $cost
i. _a: Valid (starts with an underscore and contains a letter).
ii. __abc: Valid (starts with underscores and contains letters).
5. Demonstrate multidimensional array in C with its syntax?
In C, a multidimensional array is essentially an array of arrays. The most commonly used
multidimensional array is the two-dimensional array, which can be thought of as a matrix
or table.
Syntax of a Multidimensional Array:
type arrayName[size1][size2][size3]...[sizeN];
Declaring and Initializing a 2D Array:
int matrix[3][2] = { {1, 2}, {3, 4}, {5, 6} };
Here, matrix is a 2D array with 3 rows and 2 columns.
6. Find the output of the following C program. Discuss the steps of execution
For(i=1, j=1;i<=10;++i,++j)
{
if(i= =3) { continue; }
else {
if(j= =4) { break; }
else {
Print(“I am in for loop and the values of i and j are: %d %d”,i,j);
}
}
}
ANSWER:
I am in for loop and the values of i and j are: 1 1
I am in for loop and the values of i and j are: 2 2
7. Explain matrix multiplication process and how it can be implemented in C for the given 2X2
matrices?
A = [1 2
6 5]
B=[34
2 1]
ANSWER:
Matrix Multiplication Process
Matrix multiplication involves multiplying the rows of the first matrix by the columns of
the second matrix. For two matrices A and B:
● If A is of size m × n (m rows and n columns)
● And B is of size n × p (n rows and p columns)
Then the resulting matrix C will be of size m × p.
For the given matrices:
A = [1 2
6 5]
B=[34
2 1]
● Size of A: 2 × 2
● Size of B: 2 × 2
The resulting matrix C will also be of size 2 × 2.
Implementation in C:
#include <stdio.h>
int main()
{
int A[2][2] = { {1, 2}, {6, 5} };
int B[2][2] = { {3, 4}, {2, 1} };
int C[2][2] = { {0, 0}, {0, 0} };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
C[i][j] = 0;
for (int k = 0; k < 2; k++)
{
C[i][j] = C[i][j] + (A[i][k] * B[k][j]);
}
}
}
printf("Resulting Matrix C:\n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Resulting Matrix C:
76
28 29
8. List relational and logical operators with suitable examples
Relational Operators
Relational operators are used to compare two values. The result of the comparison is
either true (1) or false (0).
Example of Relational Operators:
#include <stdio.h>
int main()
{
int a = 5, b = 10;
printf("a = = b: %d\n", a = = b); // 0 (false)
printf("a ! = b: %d\n", a ! = b); // 1 (true)
printf("a > b: %d\n", a > b); // 0 (false)
printf("a < b: %d\n", a < b); // 1 (true)
printf("a > = b: %d\n", a > = b); // 0 (false)
printf("a < = b: %d\n", a < = b); // 1 (true)
return 0;
}
Logical Operators
Logical operators are used to combine or invert boolean values (true/false).
Example of Logical Operators:
#include <stdio.h>
int main()
{
int a = 1, b = 0; // 1 is true, 0 is false
printf("a && b: %d\n", a && b); // 0 (false)
printf("a || b: %d\n", a || b); // 1 (true)
printf("!a: %d\n", !a); // 0 (false)
printf("!b: %d\n", !b); // 1 (true)
return 0;
}
9. Classify the function prototypes with suitable examples.
In C programming, function prototypes are declarations of functions that inform the compiler
about a function's name, its return type, and parameters, without providing the actual
implementation.
Function prototypes can be classified based on:
1. Number of Arguments: No arguments, one argument, or multiple arguments.
2. Return Type: Void return, non-void return.
3. Parameter Types: Passing arguments by value or by reference.
Classification:
i) Function with No Return Value and No Arguments: In this case, the function neither
returns any value nor accepts any arguments.
void displayMessage(void);
ii) Function with Return Value and No Arguments: The function returns a value but
does not take any parameters.
int getRandomNumber(void);
iii) Function with No Return Value but with Arguments: The function does not return
any value but takes one or more arguments.
void printSum(int, int);
iv) Function with Return Value and Arguments: The function takes arguments and
returns a value.
int add(int, int);
v) Function with Array Parameters: A function that takes an array as an argument.
void printArray(int[], int);
vi) Function with Pointers as Parameters: A function that accepts pointers as arguments.
void swap(int*, int*);
10. What is meant by a pre processor directive in C programming? Describe various types of pre
processor directives available in C and provide examples of how they are used in a program.
Explain the significance of each type in the overall compilation process.
Preprocessor Directives in C Programming
Preprocessor directives in C are commands that are processed by the C preprocessor before
the actual compilation of the code begins. They begin with the # symbol and do not require
a semicolon at the end. These directives are used for various purposes such as including
header files, defining constants, and conditionally compiling code.
Types of Preprocessor Directives
1. File Inclusion Directives
o Syntax: #include <filename> or #include "filename"
o Purpose: To include the contents of a file (usually a header file) into the program.
Example:
#include <stdio.h> // Standard library
#include "myheader.h" // User-defined header
Significance: Allows the use of functions and macros defined in other files, enhancing
modularity and code reuse.
2. Macro Definition Directives
o Syntax: #define
o Purpose: To define a macro that can be used throughout the code.
o Example:
#define PI 3.14
#define SQUARE(x) ((x) * (x))
Significance: Enables the use of constants and inline functions without the overhead of
function calls, making the code cleaner and more efficient.
3. Conditional Compilation Directives
o Syntax:
#ifdef
// code to include
#endif
o Purpose: To include or exclude parts of the code based on certain conditions.
o Example:
#define
#ifdef
printf("Debugging information...\n");
#endif
Significance: Facilitates debugging and testing by allowing specific code segments to be
compiled only under certain conditions.
4. Error Directive
o Syntax: #error message
o Purpose: To generate a compilation error with a specified message.
o Example:
#ifdef
#error "UNDEFINED_MACRO is not defined!"
#endif
Significance: Helps in ensuring that certain conditions are met before compilation
proceeds, thereby preventing errors at runtime.
5. Line Control Directive
o Syntax: #line number "filename"
o Purpose: To change the current line number and filename in error messages.
o Example:
#line 100 "myfile.c"
Significance: Useful for debugging, as it allows developers to specify where errors
occurred in the code.
Example Program Demonstrating Preprocessor Directives
#include <stdio.h> // Including standard I/O library
#define PI 3.14 // Defining a constant
#define SQUARE(x) ((x) * (x)) // Defining a macro
int main()
{
float radius = 5.0;
float area = PI * SQUARE(radius); // Using the defined constant and macro
printf("Area of the circle: %.2f\n", area);
#ifdef
printf("Debugging mode is ON\n");
#endif
return 0;
}
11. Demonstrate with the help of a program to count the number of vowels in the string
“MASTER” using a character array.
#include <stdio.h>
int main() {
char str[] = "MASTER"; // Define the string
int vowelCount = 0; // Initialize the vowel counter
int i;
// Loop through each character in the string
for (i = 0; str[i] != '\0'; i++)
{
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch ==
'I' || ch == 'O' || ch == 'U')
{
vowelCount++;
}
}
// Output the result
printf("Number of vowels in the string \"%s\": %d\n", str, vowelCount);
return 0;
}
12. Compare and contrast user-defined functions and library functions in C with relevant examples.
In C programming, functions can be classified into two main categories: user-defined
functions and library functions. Below is a comparison of these two types of functions,
highlighting their characteristics, differences, and relevant examples.
User-Defined Functions
Definition: User-defined functions are functions that programmers create to perform specific
tasks within their programs. These functions allow for modular programming, making code
more organized and reusable.
Example:
#include <stdio.h>
// User-defined function to calculate the square of a number
int square(int num)
{
return num * num; // Returns the square of the input number
}
int main() {
int number = 5;
// Calling the user-defined function
printf("The square of %d is %d\n", number, square(number));
return 0;
}
Library Functions
Definition: Library functions are pre-defined functions provided by C standard libraries. These
functions are already compiled and ready to use, allowing programmers to perform common
tasks without having to implement them from scratch.
Characteristics:
● Provided by the C standard library (e.g., <stdio.h>, <math.h>, etc.).
● Have fixed names and functionalities.
● Require the appropriate header files to be included in the program.
● Usually well-documented, ensuring reliable usage.
Example:
#include <stdio.h>
#include <math.h> // Including math library
int main() {
double number = 25.0;
// Calling a library function to calculate the square root
printf("The square root of %.2f is %.2f\n", number, sqrt(number));
return 0;
}
Contrast:
1. Creation: User-defined functions are created by the programmer to meet specific
needs, while library functions are predefined in the standard libraries and can be used as
needed.
2. Flexibility: User-defined functions can be tailored to specific tasks, whereas library
functions have fixed functionalities that cannot be changed.
3. Implementation: User-defined functions can be implemented in the same source
file or in separate files, while library functions require the inclusion of appropriate header
files to use them.
4. Documentation: Library functions are well-documented, making it easy for
programmers to understand their usage, while user-defined functions need proper
documentation by the programmer to aid in clarity and maintainability.
13. Explain the various string handling functions available in C. Demonstrate their use by writing a
program that performs a series of string manipulations and summarizes the results.
In C programming, strings are treated as arrays of characters terminated by a null character ('\0').
The C Standard Library provides several functions for string handling, primarily defined in the
<string.h> header. Here’s a summary of some common string handling functions along with a
demonstration program.
Common String Handling Functions
1.strlen( )
o Description: Returns the length of the string (excluding the null character).
2.strcpy( )
o Description: Copies the string
3.strcat( )
o Description: Concatenates the string.
4.strcmp( )
o Description: Compares two strings. Returns 0 if they are equal, a negative value
if str1 is less than str2, and a positive value if str1 is greater than str2.
5.strchr( )
o Description: Returns a pointer to the first occurrence of the character in the
string str. Returns NULL if the character is not found.
6.strrev( ) (not standard in all C implementations)
o Description: Reverses the string in place.
EXAMPLE:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[50], combined[150];
// Input string
printf("Enter a string: ");
fgets(str1);
// Calculate length
printf("Length of the string: %zu\n", strlen(str1));
// Copy string
strcpy(str2, str1);
printf("Copied string: %s\n", str2);
// Concatenate another string
strcat(str2, " - copied");
printf("Concatenated string: %s\n", str2);
return 0;
}
Output:
Enter a string: Hello, World!
Length of the string: 13
Copied string: Hello, World!
Concatenated string: Hello, World! - copied
14. Demonstrate a C program to generate the fibonacci series upto n number using recursive
function.
#include <stdio.h>
int Fibonacci (int n)
{
if (n < = 0)
{
return 0;
}
else if (n = = 1)
{
return 1;
}
else
{
return Fibonacci (n - 1) + Fibonacci (n - 2);
}
}
int main()
{
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci series up to %d terms:\n", n);
for (i = 0; i < n; i++)
{
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}