Question bank
Question Bank - Internal Assignment 2
| SL. No | Question |
|---|---|
| 1 | Explain the types of arrays in C (one-dimensional & two-dimensional)? |
| 2 | Explain how a single-dimension array is passed to a function in C |
| 3 | Define a pointer. Illustrate declaration and initialization of a pointer and explain how array elements can be accessed using pointers in C?. |
| 4 | A college library has a digital bookshelf system where each book is assigned a unique Book ID. The bookshelf is organized in ascending order of Book IDs. Develop a C Program to quickly find whether a book with a specific Book ID is available in the shelf? |
| 5 | What is a function? Explain three elements of a user-defined function in C with examples?. |
| 6 | Describe how to compare two structure variables of the same type. |
| 7 | What is a structure? Explain syntax and initialization with example. |
| 8 | Differentiate between structure and union |
| 9 | Write a C program using structure to read the marks of N students, compute average marks, and list students scoring above and below the average. |
| 10 | Define union with syntax and initialization example. |
| 11 | Give a simple example and define bit-fields with an example |
| 12 | Write a program to find factorial of a number |
| 13 | Write a C program to swap two numbers using variables. |
| 14 | With suitable programs, compare call by value and call by reference. |
1. Types of Arrays in C (One-Dimensional & Two-Dimensional)
What is an Array?
An array in C is a collection of elements of the
same data type stored in
contiguous memory locations.
Each element can be accessed using an
index (subscript), which starts from 0.
- Arrays help store large amounts of related data efficiently.
- All elements share the same data type.
- Accessing elements is fast using indices.
Example: Storing marks of 10 subjects using an array instead of 10 separate variables.
1. One-Dimensional Array (1D Array)
A one-dimensional array stores data in a linear form. It is used to represent a list or sequence of elements such as marks, scores, prices, or temperatures.
Declaration Syntax:
data_type array_name[size];
Example:
int marks[5] = {80, 75, 90, 85, 70};
Here, marks is a one-dimensional integer array that can store
5 values.
marks[0]→ 80marks[1]→ 75marks[4]→ 70
Use case: One-dimensional arrays are commonly used when data can be represented in a single row or list.
2. Two-Dimensional Array (2D Array)
A two-dimensional array stores data in the form of rows and columns, similar to a table or matrix. It is often used for storing data like matrices, tables, and grids.
Declaration Syntax:
data_type array_name[rows][columns];
Example:
int marks[3][4] = {
{80, 75, 90, 85},
{70, 65, 88, 92},
{78, 82, 84, 89}
};
This array stores marks of 3 students in 4 subjects.
marks[0][0]→ 80 (1st student, 1st subject)marks[1][2]→ 88 (2nd student, 3rd subject)marks[2][3]→ 89 (3rd student, 4th subject)
Use case: Two-dimensional arrays are ideal for handling data in tabular or matrix form.
Difference Between 1D and 2D Arrays
| One-Dimensional Array | Two-Dimensional Array |
|---|---|
| Stores data in a single list | Stores data in rows and columns |
| Uses one index | Uses two indices (row and column) |
| Example: marks[5] | Example: marks[3][4] |
| Simple and memory efficient | Used for complex data representation |
Note: In C, array indices always start from
0, and proper initialization helps avoid garbage values.
2. Passing a Single-Dimensional Array to a Function in C
Definition
In C, a single-dimensional array cannot be passed to a function as a complete copy (call by value). Instead, when an array is passed to a function, the base address (address of the first element) of the array is passed. The array name itself acts as a pointer to the first element.
Key Concept
When an array is passed to a function, both the calling function and the called function share the same memory location. Therefore, any changes made to the array inside the function will directly affect the original array.
Syntax
functionName(arrayName);
// Function definition can be written in any of the following ways:
returnType functionName(dataType arrayName[]);
returnType functionName(dataType *arrayName);
Explanation
- The array name represents the address of the first element.
- The function receives a pointer to the array, not a copy of all elements.
- Array size is not automatically known inside the function.
- The size of the array is usually passed as a separate argument.
- Any modification inside the function affects the original array.
- C does not perform automatic bounds checking on arrays.
Example Program
#include <stdio.h>
void display(int arr[], int n);
int main() {
int marks[5] = {80, 75, 90, 85, 70};
display(marks, 5);
return 0;
}
void display(int arr[], int n) {
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
Output
Note: Even though arrays are passed to functions using the array name, they are internally treated as pointers. Hence, passing arrays to functions in C follows the concept of call by reference.
3. Pointers in C - Definition, Declaration, Initialization, and Array Access
Definition of a Pointer
A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, a pointer points to the location in memory where the value is stored.
Key Points about Pointers
- Pointers provide direct access to memory locations.
- They are widely used with arrays, functions, and dynamic memory allocation.
- A pointer always has a data type that indicates the type of data it points to.
- Efficient memory manipulation is possible using pointers.
Declaration and Initialization of a Pointer
A pointer is declared using the * symbol. It is initialized by
assigning it the address of a variable using the & (address-of) operator.
int a = 10;
int *p; // pointer declaration
p = &a; // pointer initialization
int *indicates thatpis a pointer to an integer.&agives the memory address of variablea.*pis used to access the value stored at that address.
Example: Pointer Usage
#include <stdio.h>
int main() {
int a = 10;
int *p = &a;
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", &a);
printf("Value stored in pointer p: %p\n", p);
printf("Value at address pointed by p: %d\n", *p);
return 0;
}
Accessing Array Elements Using Pointers
In C, the name of an array itself acts as a pointer to the first element of the array. Therefore, array elements can be accessed using pointer arithmetic.
Concept
- The array name points to the base address of the array.
arr[i]is equivalent to*(arr + i).- Pointer arithmetic automatically considers the size of the data type.
Example: Accessing Array Elements Using Pointer
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // points to first element
for(int i = 0; i < 5; i++) {
printf("Element %d = %d\n", i, *(p + i));
}
return 0;
}
Explanation
p = arrassigns the base address of the array to pointerp.(p + i)points to the address of theith element.*(p + i)accesses the value of theith array element.
Conclusion
Pointers are powerful features of C that allow direct memory access. They are essential for working efficiently with arrays, enabling array traversal and manipulation using pointer arithmetic.
4. binary search program from lab
Lab part B -> 1st5. What is a Function? Explain Three Elements of a User-Defined Function in C
What is a Function?
A function is a self-contained block of code that performs a specific task. Functions help break a large program into smaller, manageable, and reusable units. Each function performs a well-defined operation and can be called whenever required.
Why Functions are Used
- Divide a large program into smaller logical parts.
- Improve readability and program structure.
- Promote code reusability.
- Simplify debugging and maintenance.
General Form of a User-Defined Function
return_type function_name(parameter_list)
{
// function body
}
Three Elements of a User-Defined Function
1. Function Declaration (Prototype)
A function declaration tells the compiler about the function’s name, return type, and parameters before it is used. It helps the compiler check for correct function calls.
int add(int a, int b);
- Specifies return type and parameter list.
- Ends with a semicolon.
- Usually written before
main().
2. Function Definition
A function definition contains the actual code that performs the task. It defines how the function works.
int add(int a, int b)
{
return a + b;
}
- Includes return type, function name, and parameters.
- Contains executable statements.
- May return a value using the
returnstatement.
3. Function Call
A function call is used to invoke or execute the function. Control is transferred to the function, and after execution, it returns back to the calling statement.
int result = add(5, 3);
- Passes actual values (arguments) to the function.
- Receives the returned value, if any.
- Can be called multiple times.
Complete Example
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int sum;
sum = add(10, 20); // function call
printf("Sum = %d", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Key Points
- A function performs a specific task.
- User-defined functions are written by the programmer.
- Three main elements are: declaration, definition, and function call.
- Functions improve modularity, readability, and reusability of code.
Note: The main() function is also a user-defined
function and acts as the entry point of a C program.
6. Comparing Two Structure Variables of the Same Type
Concept
In C, entire structures cannot be compared directly using
relational
operators such as ==, !=, <, or >.
Instead, comparison must be done by checking their individual members one by one. unlike basic data types
Important Rules
- Structures of the same type can be copied directly using the assignment operator.
- C does not allow direct structure comparison using
==or!=. - Each member of the structure must be compared separately.
Why Direct Comparison is Not Allowed?
- A structure may contain multiple members of different data types.
- C does not define how to compare all members automatically.
- Hence, programmers must decide which members are relevant for comparison.
Comparing Individual Members
To compare two structure variables, access their members using the
. operator and apply comparison operators on those members.
if (stud1.fees > stud2.fees)
printf("Student 1 has higher fees.");
Example Program
#include <stdio.h>
struct student {
int r_no;
float fees;
};
int main() {
struct student stud1 = {1, 45000};
struct student stud2;
// Copying structure
stud2 = stud1;
// Comparing structure members
if (stud1.fees == stud2.fees)
printf("Fees are same.\n");
if (stud1.fees > stud2.fees)
printf("stud1 has higher fees.");
else
printf("stud2 has higher or equal fees.");
return 0;
}
Key Points
- Structures of the same type can be copied using the assignment operator.
- Entire structures cannot be compared directly in C.
- Comparison must be done by checking each member individually.
- This gives better control over what “comparison” actually means.
Note: If a structure contains string members, use functions like
strcmp() instead of relational operators for comparison.
7. >What is a structure? Explain syntax and initialization with example
find the answer in Module 5
Module 58. > Differentiate between structure and union
find the answer in Module 5
difference between structure and unionQuestion 9: C Program Using Structure to Analyze Student Marks
Problem Statement
Write a C program using structure to read the marks of N students, compute the average marks, and list students scoring above and below the average.
Concept Used
- Structures to store student details
- Arrays of structures
- Looping and conditional statements
- Average calculation
Structure Definition
A structure is used to store the student name and marks together.
struct student {
char name[30];
float marks;
};
C Program
#include <stdio.h>
struct student {
char name[30];
float marks;
};
int main() {
int n, i;
float sum = 0, avg;
struct student s[50];
printf("Enter number of students: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
printf("Enter name of student %d: ", i + 1);
scanf("%s", s[i].name);
printf("Enter marks of student %d: ", i + 1);
scanf("%f", &s[i].marks);
sum = sum + s[i].marks;
}
avg = sum / n;
printf("\\nAverage Marks = %.2f\\n", avg);
printf("\\nStudents scoring ABOVE average:\\n");
for(i = 0; i < n; i++) {
if(s[i].marks > avg)
printf("%s : %.2f\\n", s[i].name, s[i].marks);
}
printf("\\nStudents scoring BELOW average:\\n");
for(i = 0; i < n; i++) {
if(s[i].marks < avg)
printf("%s : %.2f\\n", s[i].name, s[i].marks);
}
return 0;
}
Explanation
- An array of structures stores details of multiple students.
- Marks are summed to compute the average.
- Each student's marks are compared with the average.
- Students are categorized as above or below average.
Key Points
- Structures group related data (name and marks).
- Arrays of structures handle multiple records.
- Logical comparison helps classify students based on performance.
10. >Define union with syntax and initialization example
find the answer in Module 5
11. > Give a simple example and define bit-fields with an example
find the answer in Module 5
12. Program to Find the Factorial of a Number
What is Factorial?
The factorial of a number n is the product of
all positive integers from 1 to n. It is denoted by
n!.
- Factorial of 0 is defined as 1.
- Factorial is commonly used in permutations and combinations.
- It grows very fast, so a larger data type is required.
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Program
#include <stdio.h>
unsigned long long calculateFactorial(int number) {
unsigned long long factorial = 1;
int i;
for (i = 2; i <= number; i++) {
factorial = factorial * i;
}
return factorial;
}
void main() {
int n;
printf("Enter a number:\n");
scanf("%d", &n);
printf("The factorial is = %llu", calculateFactorial(n));
}
Example Output
5
The factorial is = 120
Note: The data type
unsigned long long is used to store large factorial values
safely. Factorial is calculated using an iterative approach
with a for loop.
13. Swap Two Numbers Using Variables
Introduction
Swapping two numbers means exchanging their values. In this program, swapping is done using a temporary variable. This is the simplest and most commonly used method, where values are exchanged without using pointers or functions.
- Uses a third (temporary) variable.
- Simple and easy to understand.
- Original values are swapped inside the same function.
C Program
#include <stdio.h>
int main() {
int num1, num2, temp;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("\nBefore swapping:\n");
printf("First number = %d\n", num1);
printf("Second number = %d\n", num2);
// Swapping using temporary variable
temp = num1;
num1 = num2;
num2 = temp;
printf("\nAfter swapping:\n");
printf("First number = %d\n", num1);
printf("Second number = %d\n", num2);
return 0;
}
Output
Enter first number: 10
Enter second number: 20
Before swapping:
First number = 10
Second number = 20
After swapping:
First number = 20
Second number = 10
Note: The temporary variable stores one value during the swap, ensuring that no data is lost during the exchange process.
14. Call by Value and Call by Reference in C
Introduction
In C, when a function is called, arguments can be passed in two common ways: Call by Value and Call by Reference. These methods determine whether changes made inside a function affect the original variables or not.
1. Call by Value
In call by value, a copy of the actual variable is passed to the function. Any changes made inside the function do not affect the original variable.
- Only a copy of data is passed.
- Original variable remains unchanged.
- More memory is used due to copying.
- Safer, as original data is protected.
Program: Call by Value
#include <stdio.h>
void changeValue(int x) {
x = x + 10;
printf("Inside function: x = %d\n", x);
}
int main() {
int a = 5;
printf("Before function call: a = %d\n", a);
changeValue(a);
printf("After function call: a = %d\n", a);
return 0;
}
Output
Inside function: x = 15
After function call: a = 5
Observation: The value of a does not change
because only a copy was passed to the function.
2. Call by Reference
In call by reference, the address of the variable is passed to the function using pointers. Changes made inside the function directly affect the original variable.
- Address of variable is passed.
- Original variable is modified.
- More efficient for large data.
- Uses pointers.
Program: Call by Reference
#include <stdio.h>
void changeValue(int *x) {
*x = *x + 10;
printf("Inside function: x = %d\n", *x);
}
int main() {
int a = 5;
printf("Before function call: a = %d\n", a);
changeValue(&a);
printf("After function call: a = %d\n", a);
return 0;
}
Output
Inside function: x = 15
After function call: a = 15
Observation: The value of a changes because
its address was passed to the function.
Comparison Table
| Call by Value | Call by Reference |
|---|---|
| Passes copy of variable | Passes address of variable |
| Original value is not changed | Original value is modified |
| Does not use pointers | Uses pointers |
| Safer but less efficient | Efficient but needs care |
Conclusion: Use call by value when data should not be modified, and call by reference when changes to original data are required.