Module 3: User-Defined Functions in C
Module 3: User-Defined Functions in C
ere are the answers to the questions found in[Link],utilizing the provided
H
notes.
1. F
unction Declaration (Prototype):This statement tellsthe compiler about the function
name, return type, and parameters before it is used. It is usually placed before themain()
function2222.
+1
Syntax:return_type function_name(parameter_list);
○
2. Function Call:This is the act of using the functionat the required place in the program.
It transfers control to the function definition3.
Syntax:function_name(actual_parameters);
○
3. Function Definition:This is the actual block of codethat performs the specific task. It
contains the function header and the function body4444.
+1
○ S
yntax:
C
return_typefunction_name(formal_parameters){
// body
}
Example:
C
#include<stdio.h>
voidmain(){
inta =10, b =20;
add(a, b); // 2. Function Call
}
/ / 3. Function Definition
voidadd(intx,inty){
intsum = x + y;
printf("Sum is %d", sum);
}
5
ote: While the provided text classifies functions broadly as Library and User-Defined6, in an
N
exam context regarding "categories of user-defined functions," this typically refers to the four
types based on arguments and return values.
C
#include<stdio.h>
voidswap(inta,intb);
voidmain(){
intx, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("Before swap: x=%d, y=%d\n", x, y);
swap(x, y);
}
voidswap(inta,intb){
// Using XOR (^) operator to swap without a temporaryvariable
= a ^ b;
a
b = a ^ b;
a = a ^ b;
printf("After swap: x=%d, y=%d\n", a, b);
}
C
#include<stdio.h>
intcalculateSum(intn);
voidmain(){
intn, sum;
printf("Enter value of n: ");
scanf("%d", &n);
sum = calculateSum(n);
printf("Sum of first %d natural numbers is: %d",n, sum);
}
intcalculateSum(intn){
intsum =0;
for(inti =1; i <= n; i++) {
sum = sum + i;
}
returnsum;
}
C
#include<stdio.h>
intfibonacci(intn);
voidmain(){
intn, i;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for(i =0; i < n; i++) {
printf("%d ", fibonacci(i));
}
}
intfibonacci(intn){
if(n ==0)
return0;
elseif(n ==1)
return1;
else
returnfibonacci(n -1) + fibonacci(n -2);
}
7
C
#include<stdio.h>
intsumOfDigits(intn);
voidmain(){
intnum, sum;
printf("Enter a number: ");
scanf("%d", &num);
sum = sumOfDigits(num);
printf("Sum of digits: %d", sum);
}
intsumOfDigits(intn){
if(n ==0)
return0;
else
return(n %10) + sumOfDigits(n /10);
}
Example:
C
#include<stdio.h>
/ / Function definition
voidprintArray(intarr[],intsize){
for(inti =0; i < size; i++) {
printf("%d ", arr[i]);
}
}
intmain(){
intnumbers[] = {10,20,30,40,50};
// Passing array 'numbers' and its size
printArray(numbers,5);
return0;
}
9
( Note: The provided notes utilize Bubble Sort10. However,since the question asks explicitly for
Selection Sort, here is the standard implementation.)
C
#include<stdio.h>
voidselectionSort(intarr[],intn){
inti, j, min_idx, temp;
for(i =0; i < n-1; i++) {
min_idx = i;
for( j = i+1; j < n; j++)
if(arr[j] < arr[min_idx])
min_idx = j;
voidmain(){
intarr[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter integers: ");
for(i=0; i<n; i++)scanf("%d", &arr[i]);
selectionSort(arr, n);
#include<stdio.h>
voidfindMaxMin(intarr[],intn){
intmin = arr[0];
intmax = arr[0];
voidmain(){
intnums[50], n;
printf("Enter size: ");
scanf("%d", &n);
printf("Enter elements: ");
for(inti =0; i < n; i++) {
scanf("%d", &nums[i]);
}
findMaxMin(nums, n);
}
● S
tatic:Retains value between function calls. Lifetimeis the entire program execution.
Default value is zero121212.
+1
E
○ xample Auto:void func() { auto int x=10; }
○ Example Static:void func() { static int count=0;count++; }
● G
lobal (Extern):Declared outside all functions. Scopeis the entire program (or file).
Lifetime is program duration151515.
+2
● F
ormal:The variables defined in the function headerto receive values. (e.g., void add(int
a, int b))17.
● S
cope (Visibility):Determines where in the programthe variable can be accessed.
○ Auto/Register:Block scope (only inside the function/block)19.
+1
Initialization:
1. C
ompile Time:Values are assigned during declaration.
○ Example:int a[4] = {10, 20, 30, 40};25
2. R
un Time:Values are entered by the user or calculatedduring execution.
○ Example:
C
for(inti=0; i<4; i++) {
scanf("%d", &a[i]);
}
26262626
+1
Example:
C
include<stdio.h>
#
voidmain(){
inta[3] = {10,20,30};
inti;
// Traversing the array to print elements
for(i =0; i <3; i++) {
printf("%d\n", a[i]);
}
}
28
he following are the exam-style answers for theModule 4 Question Bank, utilizing the
T
provided notes ([Link] and [Link]).
STRINGS
1 . Define a string. List all string manipulation functions. Explain any 4 with syntax and
examples.
efinition:
D
A string in C is a sequence of characters terminated by a special null character '\0'. It is
essentially a one-dimensional array of characters. 1111+1
.
4 s trlen()
5. strcpy()
6. strcmp()
7. strcat()
8. strrev() (and others like strlwr, strupr).
Explanation of 4 Functions:
2. strlen(): This function calculates the length of astring (excluding the null terminator).3
○ E
xample:
C
charstr[] ="Hello";
intlen =strlen(str);// len becomes 5
3. strcpy(): Copies the content of the source stringinto the destination string variable.5
○ E
xample:
C
charsrc[] ="CopyMe", dest[20];
strcpy(dest, src);// dest now contains "CopyMe"
4. strcmp(): Compares two strings. It returns0if theyare equal, a positive value if the first
is lexicographically greater, and a negative value if smaller.7777
+1
S
○ yntax:int result = strcmp(str1, str2);
○ Example:
C
intres =strcmp("Apple","Banana");// res will benegative ('A' < 'B')
5. strcat(): Concatenates (joins) the second string ontothe end of the first string.8
○ E
xample:
C
chars1[20] ="Hi ", s2[] ="World";
strcat(s1, s2);// s1 becomes "Hi World"
eclaration:
D
Strings are declared as character arrays. You must specify a size large enough to hold the
characters plus the null terminator '\0'. 101010+1
2. Syntax:char variable_name[size];11
Initialization:
There are two main ways to initialize strings:
2. Character-by-character:You must explicitly includethe null terminator.12121212
+1
. Write a program to check whether a string is palindrome or not without using built-in
3
function.
14
C
#include<stdio.h>
voidmain(){
charstr[100];
inti, j, len =0, flag =0;
i =0;
j = len -1;
if(flag ==0)
printf("String is a palindrome.\n");
else
printf("String is not a palindrome.\n");
}
. Using suitable code, Discuss the working of the following string functions:
4
i. strcat() ii. strlen() iii. strcmp() iv. strcpy() v. strrev()
● i. strcat(): Appends the source string to the destinationstring.
C
chars1[20] ="Good", s2[] ="Morning";
strcat(s1, s2);// s1 becomes "GoodMorning"
15
16
17
18
● v
. strrev(): Reverses the given string in place.
C
chars[] ="ABC";
strrev(s);// s becomes "CBA"
5. Write a C program to find the length of string without using library function.
19
C
#include<stdio.h>
voidmain(){
charstr[100];
intlen =0, i;
6. Develop a C program to concatenate two strings without using built-in function.
20
C
#include<stdio.h>
voidmain(){
charstr1[50], str2[50];
inti =0, j =0;
7. Write a C program to copy one string to another without using strcpy().
21
C
#include<stdio.h>
voidmain(){
charsrc[100], dest[100];
inti =0;
. Write a C program to copy one string (combination of digits and alphabets) to
8
another string (only alphabets).
C
#include<stdio.h>
voidmain(){
charsrc[100], dest[100];
inti =0, j =0;
while(src[i] !='\0') {
// Check if character is alphabet (A-Z ora-z)
if((src[i] >='A'&& src[i] <='Z') || (src[i]>='a'&& src[i] <='z')) {
est[j] = src[i];
d
j++;
}
i++;
}
dest[j] ='\0';// Null terminate the new string
+1
1 0. Write a C program to read a sentence and count the number of words in the
sentence.
C
#include<stdio.h>
voidmain(){
charstr[200];
inti =0, words =0;
while(str[i] !='\0') {
// Check for space or newline to identifyword boundaries
// Only count if current is space and nextis NOT space (avoids double counting spaces)
if(str[i] ==' '&& str[i+1] !=' '&& str[i+1]!='\0') {
words++;
}
i++;
}
// Add 1 for the first word (unless string isempty)
if(i >0&& str[0] !=' ') words++;
+1
C
include<stdio.h>
#
#include<ctype.h> // Using ctype macros
voidmain(){
charch;
printf("Enter a character: ");
scanf("%c", &ch);
if(isupper(ch)) {
printf("It is Uppercase.");
}elseif(islower(ch)) {
printf("It is Lowercase.");
}elseif(isdigit(ch)) {
printf("It is a Number.");
}else{
printf("It is a Special Character.");
}
}
POINTERS
1 . What is pointer? Show how variables are declared and initialized with example. List
advantages and disadvantages of pointers.
efinition:
D
A pointer is a variable that stores the memory address of another variable. 2424+1
Declaration and Initialization:
● Declaration:data_type *pointer_name;25
● Example:
C
intnum =10;
int*ptr;
ptr = #// ptr now holds the address of num
Advantages:
● A
llows us to pass arguments by reference (modifying actual parameters from within a
function).27
S
● upports dynamic memory allocation.
● Efficient way to access and manipulate array elements and strings.
Disadvantages:
U
● ninitialized pointers can lead to system crashes or unpredictable behavior.
● Pointer arithmetic can be complex and error-prone.
28282828
+1
C
#include<stdio.h>
voidmain(){
intnum1, num2, sum;
int*ptr1, *ptr2;
tr1 = &num1;
p
ptr2 = &num2;
3. Write a C program to swap contents of two variables using pointer technique.
29
C
#include<stdio.h>
voidswap(int*a,int*b){
inttemp;
t emp = *a; // Save value at address a
*a = *b; // Put value at address b into addressa
*b = temp; // Put saved value into address b
}
voidmain(){
intm, n;
printf("Enter values for m and n: ");
scanf("%d %d", &m, &n);
4. Develop a C program to find the largest of three numbers using pointer.
30
C
#include<stdio.h>
voidfindLargest(int*a,int*b,int*c,int*largest){
if(*a > *b && *a > *c) {
*largest = *a;
}elseif(*b > *c) {
*largest = *b;
}else{
*largest = *c;
}
}
intmain(){
intx, y, z, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &x, &y, &z);
. Write a program in C to find the sum and mean of all elements in an array using
5
pointers.
C
#include<stdio.h>
voidmain(){
intarr[50], n, i, sum =0;
floatmean;
int*ptr;
. Develop a program using pointers to compute the Sum, Mean and Standard deviation
6
of all elements stored in an array of N real numbers.
C
include<stdio.h>
#
#include<math.h> // Required for pow() and sqrt()
voidmain(){
floatarr[50], sum =0, mean, variance =0, std_dev;
intn, i;
float*ptr;
printf("Enter N: ");
scanf("%d", &n);
ptr = arr;
printf("Enter elements: ");
for(i=0; i<n; i++) {
scanf("%f", ptr + i);
sum += *(ptr + i);
}
7. What is pre processor directive? Explain any two pre processor directives in C.
efinition:
D
Preprocessor directives are commands processed by the C preprocessor before the actual
compilation begins. They always start with a # symbol.
Examples:
● # include: This directive tells the preprocessor toinsert the contents of another file (like
a standard library header) into the program.
○ Example: #include <stdio.h>
● #define: This directive is used to create symbolicconstants or macros. It replaces every
occurrence of the macro name with its defined value.
○ Example: #define PI 3.14
. Using pointers perform add, subtract, multiply and divide two numbers with input
8
and output.
31
C
#include<stdio.h>
intmain(){
intnum1, num2, sum, diff, prod;
floatquot;
● D
eclaration:Normal variables are declared directly(e.g., int a;). Pointers are declared
with an asterisk (e.g.,int *p;).33
STRUCTURES
1. Define a structure. Explain the syntax of structure declaration with a example.
efinition:
D
A structure is a user-defined data type in C that allows grouping variables of different data
types under a single name1. It is used to represent a record, like a student's profile (containing
name, age, marks, etc.)2.+1
Syntax of Structure Declaration:
The struct keyword is used to declare a structure.
C
structtagname {
atatype member1;
d
datatype member2;
// ...
datatype memberN;
};
3
Example:
C
structstudent {
charname[20];
intusn;
floatmarks;
};
Here,studentis the structure tag, andname,usn, andmarksare its members4.
○ E
xample:
C
structstudent {
charname[20];
intusn;
};
structstudent s1, s2;// Variable declaration
5
○ E
xample:
C
struct{
charname[20];
intusn;
} s1, s2;
6
○ E
xample:
C
typedefstruct{
charname[20];
intusn;
} STUDENT;
STUDENT s1, s2;
7
. Write a program to implement structure to read, write and compute average the
3
students scoring above and below average marks for class N students.
( Note: The logic below reads N students, calculates the class average, then counts/displays
those above and below it.)
C
#include<stdio.h>
structStudent {
charname[20];
intusn;
floatmarks;
};
voidmain(){
structStudent s[100];
intn, i;
floattotal =0, avg;
xample:
E
We can have a Date structure nested inside a Student structure to store the Date of Birth
(DOB).
C
#include<stdio.h>
structDate {
intdd;
intmm;
intyyyy;
};
structStudent {
charname[20];
intusn;
structDate dob;// Nested structure member
};
voidmain(){
structStudent s1;
8888
+1
. Create a structure student having members name and USN. Write a program which
6
reads details of 5 students and print the same.
C
#include<stdio.h>
structstudent {
charname[20];
charusn[15];
};
voidmain(){
structstudent s[5];
inti;
here are two ways to pass structures: by value (passing the whole structure) or by reference.
T
Here is an example passing the whole structure.
C
#include<stdio.h>
structPoint {
intx;
inty;
};
voidmain(){
structPoint p1 ={10,20};
displayPoint(p1);// Passing structure variable
}
9
8. What are union? Give syntax and example for it.
efinition:
D
A union is a user-defined data type similar to a structure, but all its members share the same
emory location. This means a union can store only one member's value at a time 10.
m
Syntax:
C
uniontagname {
atatype member1;
d
datatype member2;
//...
};
Example:
C
unionData {
inti;
floatf;
charstr[20];
};
voidmain(){
unionData data;
data.i =10;
printf("data.i: %d\n", data.i);// Valid
data.f =220.5;
printf("data.f: %f\n", data.f);// Valid, butdata.i is now overwritten/garbage
}
11
9. What are Enumerated data type? Explain with syntax and example.
efinition:
D
Enumeration (or enum) is a user-defined data type that consists of a set of named integer
onstants. It improves code readability by giving meaningful names to numbers 12.
c
Syntax:
enum tagname {constant1, constant2, ... constantN};
By default, the values start at 0 and increment by 1.
Example:
C
#include<stdio.h>
voidmain(){
enumWeekday today;
today = Monday;// Monday has value 1 by default(Sunday=0)
printf("Value of Monday is: %d", today);
}
13
C
#include<stdio.h>
structTime {
inthour;
intminute;
intsecond;
};
voidmain(){
structTime t1, t2;
1 1. Implement structures to read, write and compute average marks and the students
scoring below and above average in a class of 'N' students.
(This is identical to Question 3. Please refer to the solution for Question 3 above.)
1 2. Define a structure by name DOB consisting of three members dd, mm and yy.
Develop a C program that would read values to the individual member and display the
date in the form dd/mm/yyy.
C
#include<stdio.h>
structDOB {
intdd;
intmm;
intyy;
};
voidmain(){
structDOB d;
C
#include<stdio.h>
structBook {
chartitle[50];
charauthor[50];
intid;
};
voidmain(){
structBook b[100];
intn, i;
printf("\nLibrary Collection:\n");
for(i =0; i < n; i++) {
printf("ID: %d | Title: %s | Author: %s\n",b[i].id, b[i].title, b[i].author);
}
}
14. Develop a C program to read and display a single bank Customer details using
tructure with the following attributes customer name, customer ID, Account Number,
s
Address, Mobile.
C
#include<stdio.h>
structCustomer {
charname[50];
intid;
longaccNum;
charaddress[100];
longmobile;
};
voidmain(){
structCustomer c;
1 5. Write a C program to store and print name, USN, Subject and IA marks of students
using structure.
C
#include<stdio.h>
structStudent {
charname[20];
charusn[15];
charsubject[20];
intiaMarks;
};
voidmain(){
structStudent s;
printf("\nStudent Record:\n");
printf("%s (%s) - %s: %d\n", [Link], [Link], [Link],[Link]);
}
FILES
1. Discuss the different modes of operation on files with suitable example.
3. "w" (Write Mode):Opens a file for writing. If thefile doesn't exist, it creates a new one. If
it exists, iterases(truncates) the old content.16
4. " a" (Append Mode):Opens a file to add data to theend. It preserves existing data. If the
file doesn't exist, it creates a new one.17
Example:
C
ILE *fp;
F
fp = fopen("[Link]","w");// Opens [Link] forwriting
gets() fgets()
Reads from standard input (keyboard) only. an read fromanyfile stream (including
C
keyboard/stdin).
18181818
+1
19
. Write a program in C to create and store information in a text file and print the same
3
on console.
C
include<stdio.h>
#
#include<stdlib.h>
voidmain(){
FILE *fp;
chartext[100], ch;
4. Write a program in C to count the number of words and characters in a file.
C
#include<stdio.h>
voidmain(){
FILE *fp;
charch;
intcharacters =0, words =0;
fp = fopen("[Link]","r");
if(fp ==NULL) {
printf("File not found.");
return;
}
21
5. Write a program in C to copy a file to another name.
C
include<stdio.h>
#
#include<stdlib.h>
voidmain(){
FILE *fp1, *fp2;
charch;
charsourceFile[] ="[Link]";
chardestFile[] ="[Link]";
fp1 = fopen(sourceFile,"r");
if(fp1 ==NULL) {
printf("Cannot open source file.\n");
exit(0);
}
fp2 = fopen(destFile,"w");
if(fp2 ==NULL) {
printf("Cannot create destination file.\n");
fclose(fp1);
exit(0);
}
f close(fp1);
fclose(fp2);
}
22
. Write a note on following functions:
6
i. fscanf() ii. fgets() iii. fgetc() iv. fprintf() v. fputs() vi. fputc()
4. i. fscanf(): Used to read formatted data (like ints,floats, strings) from a file. It works like
scanf but takes a file pointer.
○ Syntax:fscanf(fp, "%s %d", name, &age);23
5. ii. fgets(): Reads a line (string) from a file upto n characters. It stops at a newline or EOF.
○ Syntax:fgets(str, n, fp);24
6. iii. fgetc(): Reads a single character from the file.Returns EOF if end of file is reached.
○ Syntax:ch = fgetc(fp);25
8. v
. fputs(): Writes a string (line) to a file.
○ Syntax:fputs(str, fp);27
9. v
i. fputc(): Writes a single character to a file.
○ Syntax:fputc(ch, fp);28
. Develop a C program to count the number of lines, words and characters in a given
7
text file and write the output to a separate file.
C
include<stdio.h>
#
#include<stdlib.h>
voidmain(){
FILE *fp, *out;
charch;
intchars =0, words =0, lines =0;
fp = fopen("[Link]","r");
if(fp ==NULL) {
printf("Input file not found.");
exit(0);
}
fclose(fp);
29