Programming in C
QB - Module 3
Q1. What is a function prototype? Why is it required in programming?
Demonstrate with an example program. (9 marks)
✅ Answer:
A function prototype is a declaration of a function that tells the compiler about
the function name, return type, and parameters before its actual definition. It
helps the compiler ensure that function calls are made with correct arguments
and return types.
🔍 Why is it required?
● Ensures type checking at compile time.
● Allows the function to be defined after main() or any function using it.
● Helps in modular programming.
✅ Example Program:
#include <stdio.h>
// Function prototype
int add(int, int);
int main() {
int result = add(5, 3); // Function call
printf("Sum is: %d", result);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
🔁 Explanation:
● Prototype: int add(int, int); tells the compiler about the function add.
● Call: add(5, 3); uses the function.
● Definition: Actual logic of the function.
2. Program to demonstrate function prototype, call, and definition. Explain
flow of execution. (9 marks)
✅ Program:
#include <stdio.h>
// Function prototype
float multiply(float, float);
int main() {
float a = 5.5, b = 4.0;
float result = multiply(a, b); // Function call
printf("Product = %.2f\n", result);
return 0;
}
// Function definition
float multiply(float x, float y) {
return x * y;
}
🔁 Flow of Execution:
1. main() is executed first.
2. multiply(a, b) is called with arguments.
3. Control jumps to multiply function.
4. Product is returned to main.
5. Result is printed.
Q3. Explain function definition, syntax, components with a factorial
example. (9 marks)
✅ Function Definition:
It provides the actual body or implementation of the function.
📌 Syntax:
return_type function_name(parameter_list) {
// body of function
}
🔑 Key Components:
● Return type: Type of value function returns.
● Function name: Identifier.
● Parameter list: Inputs.
● Body: Code that executes.
✅ Factorial Example:
#include <stdio.h>
int factorial(int n) { // Function definition
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int num = 5;
printf("Factorial of %d = %d", num, factorial(num));
return 0;
}
Q4. Write a function prototype for a function that takes two integers and
returns a float. Explain with an example. (3 marks)
Function Prototype :
float divide(int, int);
Example
#include <stdio.h>
// Prototype
float divide(int, int);
int main() {
printf("Division: %.2f", divide(10, 4));
return 0;
}
float divide(int a, int b) {
return (float)a / b;
}
Q5. What is a function prototype? Why is it important? (3 marks)
✅ Answer:
A function prototype is a declaration that specifies the function's name, return
type, and parameters before it is defined.
Importance:
● Enables type checking.
● Allows flexibility in function placement.
● Prevents errors during compilation.
Q6. Difference between function definition and function declaration. (3
marks)
7. a) Explain parameter passing by reference in C with an example. (5
marks)
✅ Answer:
In parameter passing by reference, we pass the address (reference) of
variables to a function. This allows the function to modify the original values.
In C, true pass-by-reference is done using pointers.
🔍 Example:
#include <stdio.h>
void update(int *x) {
*x = *x + 10;
}
int main() {
int num = 5;
update(&num); // Passing address
printf("Updated value: %d", num); // Output: 15
return 0;
}
7. b) Program to demonstrate swapping using pass by reference. (4 marks)
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
swap(&x, &y);
printf("After swapping: x = %d, y = %d", x, y);
return 0;
}
8. a) Explain parameter passing by value in C with an example. (5 marks)
✅ Answer:
In pass by value, a copy of the variable is passed to the function. Changes
inside the function do not affect the original variable.
#include <stdio.h>
void addTen(int x) {
x = x + 10;
}
int main() {
int num = 5;
addTen(num);
printf("Value of num: %d", num); // Output: 5
return 0;
}
8. b) Program to demonstrate swapping using pass by value. (4 marks)
#include <stdio.h>
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
swap(x, y);
printf("After swapping: x = %d, y = %d", x, y); // Output: x = 10, y = 20
return 0;
}
9. Difference between call by value and call by reference with examples. (9
marks)
🔍 Call by Value Example:
void add(int a) {
a += 10;
}
🔍 Call by Reference Example:
void add(int *a) {
*a += 10;
}
In main:
int x = 5;
add(x); // Call by value
add(&x); // Call by reference
10. C program to find the largest of two numbers
#include <stdio.h>
int findMax(int a, int b) {
if (a > b)
return a;
else
return b;
}
int main() {
int x = 8, y = 15;
printf("Largest number is: %d", findMax(x, y));
return 0;
}
11. Define formal parameters and actual parameters with an example
● Formal Parameters: Parameters listed in the function definition.
● Actual Parameters: Values/variables passed to the function call.
● Example:
void greet(char name[]) { // Formal parameter
printf("Hello, %s", name);
}
int main() {
greet("Alice"); // "Alice" is the actual parameter
return 0;
}
12. Types of parameter passing with examples
✅ Types:
1. Call by Value
2. Call by Reference (using pointers in C)
13. Define recursion with an example. Differentiate between iteration and
recursion.
Recursion:
Recursion is a process in which a function calls itself directly or indirectly to
solve a problem.
Example: Factorial of a number using recursion
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
14. What is recursion? Write a C program to display the Fibonacci series
using a recursive function.
Recursion: A function that calls itself to solve smaller instances of the same
problem.
Program:
#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: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
15. What is recursion? Write a C program to find the factorial of a given
number using recursion.
Recursion: A function calling itself for smaller inputs until a base condition is
met.
Program:
#include <stdio.h>
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
16. Write a C program to find the sum of the first n natural numbers using
recursion.
#include <stdio.h>
int sumNatural(int n) {
if (n == 1)
return 1;
else
return n + sumNatural(n - 1);
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Sum of first %d natural numbers is %d\n", n, sumNatural(n));
return 0;
}
17. What is recursion? Give an example.
Recursion: Function calls itself to solve smaller subproblems.
Example: Finding factorial (same as above).
18. Write a C program to find the sum of digits of a number using
recursion.
#include <stdio.h>
int sumOfDigits(int n) {
if (n == 0)
return 0;
else
return (n % 10) + sumOfDigits(n / 10);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Sum of digits of %d is %d\n", num, sumOfDigits(num));
return 0;
}
19. Write a program to demonstrate passing a one-dimensional array to a
function. The function should return the largest element in the array.
#include <stdio.h>
int findLargest(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Largest element is %d\n", findLargest(arr, n));
return 0;
}
20. Write a C program to sort N numbers using functions.
#include <stdio.h>
void sortArray(int arr[], int n) {
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
// Swap
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
sortArray(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
21. Write a C program to find the second largest element of an array using
user defined functions.
#include <stdio.h>
int secondLargest(int arr[], int n) {
int first, second;
if (arr[0] > arr[1]) {
first = arr[0];
second = arr[1];
} else {
first = arr[1];
second = arr[0];
}
for (int i = 2; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
return second;
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Second largest element is %d\n", secondLargest(arr, n));
return 0;
}
22. Write a program to find the average of n elements of an array using a
function.
#include <stdio.h>
float average(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return (float)sum / n;
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Average is %.2f\n", average(arr, n));
return 0;
}
23. Write a simple program that passes an array to a function to calculate
its sum.
#include <stdio.h>
int sumArray(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return sum;
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Sum of array elements is %d\n", sumArray(arr, n));
return 0;
}
24. How do you pass an array to a function in C? Write an example.
Answer:
In C, you pass an array to a function by passing the base address of the array.
The function receives it as a pointer.
Example:
#include <stdio.h>
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
return 0;
}
25. Write a program that takes three command-line arguments (length,
breadth, and height) and uses a macro to calculate and print the volume of
a rectangular box.
#include <stdio.h>
#include <stdlib.h>
#define VOLUME(l, b, h) ((l) * (b) * (h))
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Usage: %s length breadth height\n", argv[0]);
return 1;
}
int length = atoi(argv[1]);
int breadth = atoi(argv[2]);
int height = atoi(argv[3]);
printf("Volume of the rectangular box is %d\n", VOLUME(length, breadth,
height));
return 0;
}
26.a) What are command-line arguments in C? Discuss their syntax and
usage.
Answer:
Command-line arguments are inputs passed to the program at the time of
execution from the command prompt or terminal. They allow the user to specify
parameters or options when running a program.
Syntax:
int main(int argc, char *argv[])
argc: Argument count - number of command-line arguments including program
name.
argv: Argument vector - array of strings containing each argument.
b) Write a program to accept two numbers as command-line arguments
and calculate their sum and product.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s num1 num2\n", argv[0]);
return 1;
}
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
printf("Sum = %d\n", num1 + num2);
printf("Product = %d\n", num1 * num2);
return 0;
}
27.
a) Explain the advantages and disadvantages of macros in C with examples.
Advantages:
Macros are expanded inline, which may improve performance by avoiding
function call overhead.
Useful for defining constants and simple code snippets.
Disadvantages:
No type checking, which may cause unexpected behavior.
Difficult to debug because they are expanded before compilation.
Can lead to code bloat if overused.
Example:
#define PI 3.1416
#define SQUARE(x) ((x) * (x))
b) Write a program that uses a macro to calculate the area of a rectangle
and demonstrate its use.
#include <stdio.h>
#define AREA(length, breadth) ((length) * (breadth))
int main() {
int length = 5, breadth = 10;
printf("Area of rectangle: %d\n", AREA(length, breadth));
return 0;
}
28. Differentiate between macros and functions in C. Illustrate with an
example of a macro that calculates the cube of a number.
Macro for cube:
#define CUBE(x) ((x) * (x) * (x))
29. Explain command-line arguments in C and write a program to print all
command-line arguments passed to the program.
Answer:
Command-line arguments are parameters passed to a program when it is
invoked.
Program:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
30. What are macros in C? Write a program that defines a macro to
calculate the square of a number.
Answer:
Macros are preprocessor directives that define constants or expressions.
Program:
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
int num = 5;
printf("Square of %d is %d\n", num, SQUARE(num));
return 0;
}
31. Write a C program to:
a) Create a structure with fields: Name, Address, Date of birth.
b) Read the above details for five students from the user and display the details.
#include <stdio.h>
struct Date {
int day, month, year;
};
struct Student {
char name[50];
char address[100];
struct Date dob;
};
int main() {
struct Student students[5];
for (int i = 0; i < 5; i++) {
printf("Enter details for student %d\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", students[i].name);
printf("Address: ");
scanf(" %[^\n]", students[i].address);
printf("Date of Birth (dd mm yyyy): ");
scanf("%d %d %d", &students[i].dob.day, &students[i].dob.month,
&students[i].dob.year);
}
printf("\nStudent Details:\n");
for (int i = 0; i < 5; i++) {
printf("Name: %s\n", students[i].name);
printf("Address: %s\n", students[i].address);
printf("DOB: %d-%d-%d\n", students[i].dob.day, students[i].dob.month,
students[i].dob.year);
printf("-------------------------\n");
}
return 0;
}
32. Read two inputs each representing the distances between two points in
the Euclidean space, store these in structure variables and add the two
distance values.
#include <stdio.h>
struct Distance {
float dist;
};
int main() {
struct Distance d1, d2;
printf("Enter first distance: ");
scanf("%f", &d1.dist);
printf("Enter second distance: ");
scanf("%f", &d2.dist);
float sum = d1.dist + d2.dist;
printf("Sum of distances = %.2f\n", sum);
return 0;
}
33. Write a C program to:
a) Create a structure containing the fields: Name, Price, Quantity, Total Amount.
b) Use separate functions to read and print the data.
#include <stdio.h>
struct Item {
char name[50];
float price;
int quantity;
float totalAmount;
};
void readData(struct Item *item) {
printf("Enter name: ");
scanf(" %[^\n]", item->name);
printf("Enter price: ");
scanf("%f", &item->price);
printf("Enter quantity: ");
scanf("%d", &item->quantity);
item->totalAmount = item->price * item->quantity;
}
void printData(struct Item item) {
printf("Name: %s\n", item.name);
printf("Price: %.2f\n", item.price);
printf("Quantity: %d\n", item.quantity);
printf("Total Amount: %.2f\n", item.totalAmount);
}
int main() {
struct Item item;
readData(&item);
printData(item);
return 0;
}
Q34. Define a structure Book with members title, author, and price. Write
a program to define a structure variable, assign values to its members, and
display the information.
#include <stdio.h>
struct Book {
char title[100];
char author[50];
float price;
};
int main() {
struct Book b = {"The Alchemist", "Paulo Coelho", 299.99};
printf("Book Details:\n");
printf("Title: %s\n", b.title);
printf("Author: %s\n", b.author);
printf("Price: %.2f\n", b.price);
return 0;
}
✅ Q35. What is a structure in C? Define a structure Student with
members name, roll_no, and marks, and demonstrate how to access its
members.
Answer:
A structure in C is a user-defined data type that groups different types of
variables under one name.
Program:
#include <stdio.h>
struct Student {
char name[50];
int roll_no;
float marks;
};
int main() {
struct Student s = {"Anu", 101, 89.5};
printf("Student Details:\n");
printf("Name: %s\n", s.name);
printf("Roll No: %d\n", s.roll_no);
printf("Marks: %.2f\n", s.marks);
return 0;
}
✅ Q36. How does an array differ from a structure?
Q37. Union for address details using strings
#include <stdio.h>
#include <string.h>
#define C_SIZE 50
union Address {
char name[C_SIZE];
char houseName[C_SIZE];
char cityName[C_SIZE];
char state[C_SIZE];
char pinCode[C_SIZE];
};
int main() {
union Address addr;
printf("Note: Only one value can be stored at a time in a union.\n");
printf("\nEnter Name: ");
scanf(" %[^\n]", addr.name);
printf("Name: %s\n", addr.name);
printf("\nEnter House Name: ");
scanf(" %[^\n]", addr.houseName);
printf("House Name: %s\n", addr.houseName);
printf("\nEnter City Name: ");
scanf(" %[^\n]", addr.cityName);
printf("City Name: %s\n", addr.cityName);
printf("\nEnter State: ");
scanf(" %[^\n]", addr.state);
printf("State: %s\n", addr.state);
printf("\nEnter Pin Code: ");
scanf(" %[^\n]", addr.pinCode);
printf("Pin Code: %s\n", addr.pinCode);
printf("\nNote: Only the last stored value is retained in a union.\n");
return 0;
}
Q38. Structure to read and print data of n employees
#include <stdio.h>
struct Employee {
char name[50];
int id;
float salary;
};
int main() {
int n;
printf("Enter number of employees: ");
scanf("%d", &n);
struct Employee e[n];
for(int i = 0; i < n; i++) {
printf("\nEnter details for Employee %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", e[i].name);
printf("ID: ");
scanf("%d", &e[i].id);
printf("Salary: ");
scanf("%f", &e[i].salary);
}
printf("\nEmployee Details:\n");
for(int i = 0; i < n; i++) {
printf("\nEmployee %d:\n", i + 1);
printf("Name: %s\n", e[i].name);
printf("ID: %d\n", e[i].id);
printf("Salary: %.2f\n", e[i].salary);
}
return 0;
}
Q39. Average mark using array of structures
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
float mark_for_C;
};
int main() {
int n;
float sum = 0.0;
printf("Enter number of students: ");
scanf("%d", &n);
struct Student s[n];
for(int i = 0; i < n; i++) {
printf("\nEnter details for Student %d:\n", i + 1);
printf("Roll No: ");
scanf("%d", &s[i].roll_no);
printf("Name: ");
scanf(" %[^\n]", s[i].name);
printf("Mark for C: ");
scanf("%f", &s[i].mark_for_C);
sum += s[i].mark_for_C;
}
float average = sum / n;
printf("\nAverage mark for Programming in C: %.2f\n", average);
return 0;
}
✅ Q40. What is an array of structures? Demonstration with 5 students
Definition:
An array of structures allows storing multiple records (each with multiple
fields) together. Useful when you need to handle data of multiple entities of the
same type (e.g., students, employees).
Example:
#include <stdio.h>
struct Student {
char name[50];
int roll_no;
float marks;
};
int main() {
struct Student s[5];
printf("Enter details for 5 students:\n");
for(int i = 0; i < 5; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", s[i].name);
printf("Roll No: ");
scanf("%d", &s[i].roll_no);
printf("Marks: ");
scanf("%f", &s[i].marks);
}
printf("\nStudent Details:\n");
for(int i = 0; i < 5; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: %s\n", s[i].name);
printf("Roll No: %d\n", s[i].roll_no);
printf("Marks: %.2f\n", s[i].marks);
}
return 0;
}
✅ Q41. Advantages and Disadvantages of Union Over Structure in C
Advantages of Union:
● Efficient memory usage — all members share the same memory location.
● Useful when only one variable is needed at a time (e.g., variant types,
interpreting memory).
Disadvantages of Union:
● Only one member can hold a valid value at a time.
● Cannot store multiple values simultaneously like a structure.
● Risk of overwriting data if not managed carefully.
#include <stdio.h>
struct MyStruct {
int a;
float b;
};
union MyUnion {
int a;
float b;
};
int main() {
struct MyStruct s = {10, 20.5};
union MyUnion u;
u.a = 10;
u.b = 20.5;
printf("Structure: a = %d, b = %.2f\n", s.a, s.b);
printf("Union: a = %d (may be corrupted), b = %.2f\n", u.a, u.b);
return 0;
}
Q43. Write a note on storage classes in C
Storage classes in C define the scope, visibility, lifetime, and default initial
value of variables. The four types of storage classes in C are:
1. auto
2. register
3. static
4. extern
✅ Q44a. Explain automatic and static storage classes with examples
🔹 auto (Automatic):
● Default for all local variables.
● Memory is allocated at runtime and deallocated when function ends.
#include <stdio.h>
void autoExample() {
auto int x = 5;
printf("auto x = %d\n", x);
}
static:
● Retains its value across function calls.
● Initialized only once.
#include <stdio.h>
void staticExample() {
static int count = 0;
count++;
printf("static count = %d\n", count);
Q44b. Program to demonstrate static by tracking function calls
#include <stdio.h>
void countCalls() {
static int count = 0; // Retains value between calls
count++;
printf("Function called %d time(s)\n", count);
}
int main() {
for (int i = 0; i < 5; i++) {
countCalls();
}
return 0;
}
Q45. Explain various C storage classes with examples
1. auto
#include <stdio.h>
void demoAuto() {
auto int a = 10; // auto is default for local variables
printf("auto variable: %d\n", a);
}
2. Register
#include <stdio.h>
void demoRegister() {
register int i = 5; // stored in CPU register (if possible)
printf("register variable: %d\n", i);
}
3. Static
#include <stdio.h>
void demoStatic() {
static int x = 0;
x++;
printf("static variable: %d\n", x);
}
4. Extern
#include <stdio.h>
int a = 100; // Global variable
void demoExtern();
int main() {
demoExtern();
return 0;
}
void demoExtern() {
extern int a; // declaration
printf("extern variable: %d\n", a);
}
Q46. What is the register storage class in C? Explain with example
● register suggests storing the variable in a CPU register for faster access.
● Can't take the address using &.
#include <stdio.h>
void demoRegister() {
register int speed = 90;
❌
printf("Speed: %d km/h\n", speed);
// printf("%p", &speed); // Error: cannot take address
}
Q47. What is the external storage class in C? Example
● extern refers to global variables defined elsewhere (outside the current
file or function).
● Used to share global variables across files or functions.
#include <stdio.h>
int number = 50; // Global variable
void printExtern();
int main() {
printExtern();
return 0;
}
void printExtern() {
extern int number;
printf("Extern variable: %d\n", number);
}
Q48. What is the automatic storage class in C? Characteristics + Example
Characteristics:
● Default for local variables inside functions.
● Created on function entry, destroyed on exit.
● Uninitialized variables have garbage values.
#include <stdio.h>
void demoAuto() {
auto int x = 10;
printf("Auto variable: %d\n", x);
}
int main() {
demoAuto();
return 0;
}