0% found this document useful (0 votes)
9 views16 pages

Unit 4 Note and Question Bank

The document provides a comprehensive overview of functions in C programming, covering topics such as function prototypes, declarations, definitions, recursion, and storage classes. It includes examples of various function categories, call by value vs. call by reference, and string handling functions, along with detailed explanations and code snippets. Additionally, it discusses the scope of variables and how strings can be accessed using pointers.

Uploaded by

kyashu071
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

Unit 4 Note and Question Bank

The document provides a comprehensive overview of functions in C programming, covering topics such as function prototypes, declarations, definitions, recursion, and storage classes. It includes examples of various function categories, call by value vs. call by reference, and string handling functions, along with detailed explanations and code snippets. Additionally, it discusses the scope of variables and how strings can be accessed using pointers.

Uploaded by

kyashu071
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Part 1: 2 Marks Questions (Short Answers)

1. What is a function prototype? Differentiate between function declaration


and function definition.

 Function Prototype: It is a declaration that tells the compiler about the


function's name, return type, and parameters before it is used. It ensures
type checking.
o Syntax: return_type function_name(parameter_list);

Function Declaration (Prototype) Function Definition

Tells the compiler what the function is Tells the compiler how the function
(name, args, return type). works (the actual code).

Does not end with a semicolon; uses a


Ends with a semicolon (;).
body { ... }.

Allocates no memory. Allocates memory for the code.

2. List the categories of functions.

Functions in C are categorized based on arguments and return values:

1. Function with no arguments and no return value.


2. Function with no arguments and a return value.
3. Function with arguments and no return value.
4. Function with arguments and a return value.

3. What is recursion and its types?


Recursion is a process where a function calls itself directly or indirectly to
solve a problem. The function is called a recursive function. It must have a base
case to stop infinite looping.

Types:

 Direct Recursion: Function A calls Function A.


 Indirect Recursion: Function A calls Function B, and Function B calls
Function A.

4. Differentiate between formal and actual arguments.

Formal Arguments (Parameters) Actual Arguments

Variables declared in the function Values or variables passed during the


definition header. function call.

They act as placeholders to receive data. They are the actual data source.

Example: void add(int a, int b) (a, b are Example: add(10, 20); (10, 20 are
formal). actual).

5. Write a short note on storage classes.

Storage classes define the scope (visibility), lifetime, and initial value of a
variable. There are four types in C:

1. auto: Local scope, garbage value by default (default for local variables).
2. register: Stored in CPU registers for faster access, local scope.
3. static: Preserves value between function calls, default value 0.
4. extern: Global scope, visible across different files.

6. Write a short note on scope of variables.

Scope refers to the region of the program where a variable is accessible.

 Local Scope: Variables declared inside a function/block are accessible


only within that block.
 Global Scope: Variables declared outside all functions are accessible
throughout the entire program.

7. What is a static variable?

A static variable is a variable that retains its value even after the function
execution is completed. It is initialized only once (to 0 by default) and exists
until the program ends, unlike auto variables which are destroyed when the
function exits.

8. Differentiate between call by value and call by reference.

Call by Value Call by Reference

A copy of the value is passed to the The address (pointer) of the variable
function. is passed.

Changes in the function do not affect Changes in the function do affect the
the original variable. original variable.

Uses less memory (no copying of


Uses more memory (due to copying).
large data).
9. What is the purpose of the return statement?

The return statement serves two purposes:

1. It immediately terminates the execution of the function.


2. It returns a value (result) from the called function to the calling function
(if the return type is not void).

10. Explain how strings are stored in memory and importance of ‘\0’.

 Storage: A string is stored as a contiguous array of characters.


 Importance of \0: C does not have a distinct string data type; it uses char
arrays. The null character \0 marks the end of the string. Without it, the
computer wouldn't know where the string stops, leading to garbage
output.

11. What are the various string handling functions in C-language?

(Requires <string.h> header)

 strlen(s): Returns the length of the string.


 strcpy(dest, src): Copies source string to destination.
 strcat(dest, src): Concatenates (joins) source to the end of destination.
 strcmp(s1, s2): Compares two strings (Returns 0 if equal).
 strrev(s): Reverses the string.

Part 2: 6 Marks Questions (Detailed Answers)

1. Explain Function Declaration, Definition, and Call with examples.


A function is a block of code designed to perform a specific task. Using it
involves three steps:

a. Function Declaration (Prototype):

Announces the function properties to the compiler (Name, Arguments, Return


Type) before main().

b. Function Definition:

Contains the actual logic/code. It consists of the function header and the
function body.

c. Function Call:

The point where the function is actually invoked. Control jumps from the main
(or caller) to the function definition.

Example Program:

C
#include <stdio.h>

// 1. Function Declaration
int add(int, int);

int main() {
int sum;
// 3. Function Call (Passing 5 and 10)
sum = add(5, 10);
printf("Sum is: %d", sum);
return 0;
}

// 2. Function Definition
int add(int a, int b) {
int result = a + b;
return result;
}

2. Discuss Call by Value and Call by Reference with a C program (Swap


two numbers).

A. Call by Value:

Values are copied. Swapping happens in temporary variables inside the


function, leaving the original variables in main unchanged.

C
void swapValue(int x, int y) {
int temp = x;
x = y;
y = temp;
// x and y are swapped here, but actual variables in main are NOT.
}

B. Call by Reference:

Addresses are passed. The function accesses the original memory locations
using pointers, so the swap is permanent.

Complete Program (Swapping):


C
#include <stdio.h>

void swapRef(int *x, int *y) {


int temp = *x; // Get value at address x
*x = *y; // Put value at y into address x
*y = temp; // Put temp into address y
}

int main() {
int a = 10, b = 20;

printf("Before Swap: a=%d, b=%d\n", a, b);

// Pass addresses using '&'


swapRef(&a, &b);

printf("After Swap: a=%d, b=%d\n", a, b);


return 0;
}

3. Explain the categories of functions with examples.

1. No Arguments, No Return Value:

Usually used for printing menus or messages.

C
void printMsg() {
printf("Hello World");
}

2. No Arguments, With Return Value:

Used when the function generates data (like getting user input) but needs no
input itself.

C
int getNumber() {
int n = 5;
return n;
}

3. With Arguments, No Return Value:

Used to process data without giving back a result (e.g., printing formatted data).

C
void printSquare(int n) {
printf("%d", n*n);
}

4. With Arguments, With Return Value:

The most common type; takes input, processes it, and returns a result.

C
int add(int a, int b) {
return a + b;
}
4. Explain recursion in detail. Program for Fibonacci series.

Recursion occurs when a function calls itself.

 Base Case: The condition to stop recursion (e.g., if (n == 0) return;).


 Recursive Step: The logic where the function calls itself with a smaller
input.

Fibonacci Logic: The sequence is 0, 1, 1, 2, 3, 5, 8...

Mathematically: $F(n) = F(n-1) + F(n-2)$

Program:

C
#include <stdio.h>

int fibonacci(int n) {
// Base cases
if (n == 0) return 0;
if (n == 1) return 1;

// Recursive step
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n = 10, i;
printf("Fibonacci Series: ");
for(i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}

5. Structured program using user-defined functions for Array Operations.

C
#include <stdio.h>

// Function Declarations
void readArray(int arr[], int n);
int findLargest(int arr[], int n);
int findSmallest(int arr[], int n);
int findSum(int arr[], int n);

int main() {
int n, arr[100];

printf("Enter number of elements: ");


scanf("%d", &n);

readArray(arr, n);

printf("Largest: %d\n", findLargest(arr, n));


printf("Smallest: %d\n", findSmallest(arr, n));
printf("Sum: %d\n", findSum(arr, n));

return 0;
}
// a. Read an array
void readArray(int arr[], int n) {
printf("Enter %d elements:\n", n);
for(int i=0; i<n; i++) {
scanf("%d", &arr[i]);
}
}

// b. Find Largest
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;
}

// c. Find Smallest
int findSmallest(int arr[], int n) {
int min = arr[0];
for(int i=1; i<n; i++) {
if(arr[i] < min) min = arr[i];
}
return min;
}

// d. Find Sum
int findSum(int arr[], int n) {
int sum = 0;
for(int i=0; i<n; i++) {
sum += arr[i];
}
return sum;
}

6. Explain storage classes (auto, register, static, extern).

1. Auto (Automatic):
o Scope: Local (inside function).
o Lifetime: Function execution.
o Default: Garbage value.
o Usage: Standard local variables.
2. Register:
o Scope: Local.
o Storage: CPU Registers (not RAM) for speed.
o Usage: Loop counters (register int i;). Note: Cannot use & operator
on them.
3. Static:
o Scope: Local (but retains value).
o Lifetime: Entire program execution.
o Default: Zero.
o Usage: Counting how many times a function is called.
4. Extern:
o Scope: Global (visible to all files).
o Lifetime: Entire program.
o Usage: Sharing variables between multiple .c files.
7. & 8. String operations without library functions.

Here is a single program that performs Length, Copy, Concatenate, and


Compare manually.

C
#include <stdio.h>

// a. String Length
int xstrlen(char *s) {
int len = 0;
while(s[len] != '\0') {
len++;
}
return len;
}

// b. String Copy
void xstrcpy(char *dest, char *src) {
int i = 0;
while(src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0'; // Add null terminator
}

// c. Concatenate
void xstrcat(char *dest, char *src) {
int i = 0, j = 0;
// Move to end of dest
while(dest[i] != '\0') i++;

// Append src
while(src[j] != '\0') {
dest[i] = src[j];
i++; j++;
}
dest[i] = '\0';
}

// d. Compare
int xstrcmp(char *s1, char *s2) {
int i = 0;
while(s1[i] == s2[i]) {
if(s1[i] == '\0') return 0; // Strings are equal
i++;
}
return s1[i] - s2[i]; // Return difference
}

int main() {
char s1[50] = "Hello";
char s2[50] = "World";
char temp[50];

printf("Length of s1: %d\n", xstrlen(s1));


xstrcpy(temp, s1);
printf("Copy s1 to temp: %s\n", temp);

xstrcat(s1, s2);
printf("Concatenated: %s\n", s1);

int cmp = xstrcmp("Apple", "Banana");


if(cmp == 0) printf("Strings are equal");
else printf("Strings are different");

return 0;
}

9. Explain how strings can be accessed using pointers.

In C, the name of a character array acts as a pointer to the first character. We


can iterate through a string by incrementing a pointer rather than using array
indexing [].

Key Concepts:

1. char *ptr = str; initializes a pointer to the start of the string.


2. *ptr gives the character at the current position.
3. ptr++ moves the pointer to the next memory address (next character).

Example:

C
#include <stdio.h>
int main() {
char str[] = "Pointer";
char *ptr;

ptr = str; // Point to start of string

printf("Accessing string using pointer:\n");


while(*ptr != '\0') {
printf("%c ", *ptr); // Print current char
ptr++; // Move to next char address
}
return 0;
}

Output: P o i n t e r

You might also like