0% found this document useful (0 votes)
7 views47 pages

Module 3: User-Defined Functions in C

The document provides a comprehensive overview of user-defined functions in C programming, including their elements, categories, and examples. It also addresses common errors in function definitions and offers solutions, along with various programming exercises such as swapping numbers, calculating sums, and generating Fibonacci series. Additionally, it explains storage classes and their impact on variable scope, visibility, and lifetime.
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)
7 views47 pages

Module 3: User-Defined Functions in C

The document provides a comprehensive overview of user-defined functions in C programming, including their elements, categories, and examples. It also addresses common errors in function definitions and offers solutions, along with various programming exercises such as swapping numbers, calculating sums, and generating Fibonacci series. Additionally, it explains storage classes and their impact on variable scope, visibility, and lifetime.
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

​ ased on the files provided, the Question Bank (cModule3QBank.

pdf) is labeled​​Module 3​​,​


B
​although your prompt mentions Module 2. Since the content covers Functions, Arrays, and​
​Storage Classes (which matches the Module 3 notes), I have provided the exam-style answers​
​for the​​Module 3 Question Bank​​below.​

​ ere are the answers to the questions found in​​[Link]​​,​​utilizing the provided​
H
​notes.​

1​ . Explain the elements of a user-defined function with suitable​


​example.​
​There are three main elements of a user-defined function​​1​​:​

​1.​ F
​ unction Declaration (Prototype):​​This statement tells​​the compiler about the function​
​name, return type, and parameters before it is used. It is usually placed before the​​main()​
​function​​2222​​.​
​+1​

​ ​ ​Syntax:​​return_type function_name(parameter_list);​

​2.​ ​Function Call:​​This is the act of using the function​​at the required place in the program.​
​It transfers control to the function definition​​3​​.​

​ ​ ​Syntax:​​function_name(actual_parameters);​

​3.​ ​Function Definition:​​This is the actual block of code​​that performs the specific task. It​
​contains the function header and the function body​​4444​​.​
​+1​

​○​ S
​ yntax:​
​C​
​return_type​​function_name​​(formal_parameters)​​{​
​// body​
​}​

​Example:​

​C​
​#​include​​<stdio.h>​

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

​void​​main​​()​​{​
​int​​a =​​10​​, b =​​20​​;​
​add(a, b);​ ​// 2. Function Call​
​}​

/​ / 3. Function Definition​
​void​​add​​(​int​​x,​​int​​y)​​{​
​int​​sum = x + y;​
​printf​​(​"Sum is %d"​​, sum);​
​}​

​5​

​ . List the categories of user-defined function and explain them with​


2
​suitable examples.​

​ ote: While the provided text classifies functions broadly as Library and User-Defined​​6​,​ in an​
N
​exam context regarding "categories of user-defined functions," this typically refers to the four​
​types based on arguments and return values.​

​1.​ F ​ unction with no arguments and no return value:​


​The function takes no data from the calling function and returns no value.​
​○​ ​Example:​​void printMessage(void) { printf("Hello");​​}​
​2.​ ​Function with arguments but no return value:​
​Data is passed to the function, but it prints the result or performs an action without​
​returning data.​
​○​ ​Example:​​void sum(int a, int b) { printf("%d", a+b);​​}​
​3.​ ​Function with no arguments but returns a value:​
​The function generates data (e.g., reading input) and sends it back to the calling​
​function.​
​○​ ​Example:​​int getNumber() { return 5; }​
​4.​ ​Function with arguments and returns a value:​
​Data is passed to the function, processed, and the result is returned.​
​○​ ​Example:​​int multiply(int a, int b) { return a * b;​​}​
​ . Find the errors, if any, in the following function definitions and​
3
​correct them.​
​a)​​void main(int a, int b) {​
​●​ E ​ rror:​​The standard main function does not take arbitrary​​integer arguments like a and b.​
​It generally takes void or argc, argv.​
​●​ ​Correction:​​void main() or int main()​

​b)​​int abc(int a, int b) { int c; return (c); }​


​●​ E ​ rror:​​The variable c is declared but never initialized​​or calculated. It will return a garbage​
​value.​
​●​ ​Correction:​
​C​
​int​​abc​​(​int​​a,​​int​​b)​​{​
​int​​c = a + b;​​// Assign a value​
​return​​c;​
​}​

​c)​​int abc(int a, int b) } {​


​●​ E ​ rror:​​The syntax for the function body is incorrect.​​The opening brace { must come​
​before the closing brace }.​
​●​ ​Correction:​​int abc(int a, int b) { ... }​

​d)​​void abc(void) { double c=a+b return (c); }​


​​
● ​ rror 1:​​The return type is void, but the function​​attempts to return (c).​
E
​●​ ​Error 2:​​Missing semicolon after c=a+b.​
​●​ ​Error 3:​​Variables a and b are not defined.​
​●​ ​Correction:​
​C​
​double​​abc​​(​double​​a,​​double​​b)​​{​​// Change type to​​double to return c​
​double​​c = a + b;​
​return​​c;​
​}​

​e)​​int abc(void) { return; }​


​​ E
● ​ rror:​​The function is declared to return an int,​​but the return statement returns nothing.​
​●​ ​Correction:​​void abc(void) { return; } OR int abc(void)​​{ return 0; }​
​ . Write a user-defined function to swap two numbers using bitwise​
4
​operators.​

​C​

​#​include​​<stdio.h>​

​void​​swap​​(​int​​a,​​int​​b)​​;​

​void​​main​​()​​{​
​int​​x, y;​
​printf​​(​"Enter two numbers: "​​);​
​scanf​​(​"%d %d"​​, &x, &y);​
​printf​​(​"Before swap: x=%d, y=%d\n"​​, x, y);​
​swap(x, y);​
​}​

​void​​swap​​(​int​​a,​​int​​b)​​{​
​// Using XOR (^) operator to swap without a temporary​​variable​
​ = a ^ b;​
a
​b = a ^ b;​
​a = a ^ b;​
​printf​​(​"After swap: x=%d, y=%d\n"​​, a, b);​
​}​

​ . Write a user-defined function to find sum of 1st n natural​


5
​numbers.​

​C​

​#​include​​<stdio.h>​

​int​​calculateSum​​(​int​​n)​​;​
​void​​main​​()​​{​
​int​​n, sum;​
​printf​​(​"Enter value of n: "​​);​
​scanf​​(​"%d"​​, &n);​
​sum = calculateSum(n);​
​printf​​(​"Sum of first %d natural numbers is: %d"​​,​​n, sum);​
​}​

​int​​calculateSum​​(​int​​n)​​{​
​int​​sum =​​0​;​
​for​​(​int​​i =​​1​; i <= n; i++) {​
​sum = sum + i;​
​}​
​return​​sum;​
​}​

​ . Write a recursive function to generate Fibonacci series for n no. of​


6
​terms.​

​C​

​#​include​​<stdio.h>​

​int​​fibonacci​​(​int​​n)​​;​

​void​​main​​()​​{​
​int​​n, i;​
​printf​​(​"Enter number of terms: "​​);​
​scanf​​(​"%d"​​, &n);​
​printf​​(​"Fibonacci Series: "​​);​
​for​​(i =​​0​; i < n; i++) {​
​printf​​(​"%d "​​, fibonacci(i));​
​}​
​}​

​int​​fibonacci​​(​int​​n)​​{​
​if​​(n ==​​0​)​
​return​​0​;​
​else​​if​​(n ==​​1​)​
​return​​1​;​
​else​
​return​​fibonacci(n -​​1​) + fibonacci(n -​​2​);​
​}​

​7​

​7. Write a C program to find sum of digits using recursion.​

​C​

​#​include​​<stdio.h>​

​int​​sumOfDigits​​(​int​​n)​​;​

​void​​main​​()​​{​
​int​​num, sum;​
​printf​​(​"Enter a number: "​​);​
​scanf​​(​"%d"​​, &num);​
​sum = sumOfDigits(num);​
​printf​​(​"Sum of digits: %d"​​, sum);​
​}​

​int​​sumOfDigits​​(​int​​n)​​{​
​if​​(n ==​​0​)​
​return​​0​;​
​else​
​return​​(n %​​10​​) + sumOfDigits(n /​​10​​);​
​}​

​ . Explain the concept of passing of 1-d array as function argument​


8
​with suitable example.​
​In C, an entire array cannot be passed as an argument by value. Instead, we pass the array by​
r​ eference​​(by address). When we pass an array name to a function, it decays into a pointer to​
​the first element of the array​​8​​.​

​Syntax:​​return_type function_name(data_type array_name[],​​int size);​

​Example:​

​C​

​#​include​​<stdio.h>​

/​ / Function definition​
​void​​printArray​​(​int​​arr[],​​int​​size)​​{​
​for​​(​int​​i =​​0​; i < size; i++) {​
​printf​​(​"%d "​​, arr[i]);​
​}​
​}​

​int​​main​​()​​{​
​int​​numbers[] = {​​10​​,​​20​​,​​30​​,​​40​​,​​50​​};​
​// Passing array 'numbers' and its size​
​printArray(numbers,​​5​);​
​return​​0​;​
​}​

​9​

​ . Write a user-defined function to sort n numbers in ascending​


9
​order using selection sort.​

(​ Note: The provided notes utilize Bubble Sort​​10​​. However,​​since the question asks explicitly for​
​Selection Sort, here is the standard implementation.)​
​C​

​#​include​​<stdio.h>​

​void​​selectionSort​​(​int​​arr[],​​int​​n)​​{​
​int​​i, 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;​

​// Swap the found minimum element with the​​first element​


t​ emp = arr[min_idx];​
​arr[min_idx] = arr[i];​
​arr[i] = temp;​
​}​
​}​

​void​​main​​()​​{​
​int​​arr[​​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);​

​printf​​(​"Sorted array: "​​);​


​for​​(i=​​0​; i<n; i++)​​printf​​(​"%d "​​, arr[i]);​
​}​

1​ 0. Write a C program to find the maximum and minimum values​


​using the concept of passing 1-d array as an argument to function.​
​C​

​#​include​​<stdio.h>​

​void​​findMaxMin​​(​int​​arr[],​​int​​n)​​{​
​int​​min = arr[​​0​];​
​int​​max = arr[​​0​];​

​for​​(​int​​i =​​1​; i < n; i++) {​


​if​​(arr[i] > max)​
​ ax = arr[i];​
m
​if​​(arr[i] < min)​
​min = arr[i];​
​}​
​printf​​(​"Maximum value: %d\n"​​, max);​
​printf​​(​"Minimum value: %d\n"​​, min);​
​}​

​void​​main​​()​​{​
​int​​nums[​​50​​], n;​
​printf​​(​"Enter size: "​​);​
​scanf​​(​"%d"​​, &n);​
​printf​​(​"Enter elements: "​​);​
​for​​(​int​​i =​​0​; i < n; i++) {​
​scanf​​(​"%d"​​, &nums[i]);​
}​ ​
​findMaxMin(nums, n);​
​}​

1​ 1. Distinguish between the following storage classes. Give example​


​for each.​
​a) Automatic and Static variables​
​●​ A
​ uto:​​Created when the block is entered, destroyed​​when exited. Default value is​
​garbage. Accessible only within the block​​111111​​.​
​+1​

​●​ S
​ tatic:​​Retains value between function calls. Lifetime​​is the entire program execution.​
​Default value is zero​​121212​​.​
​+1​

​​ E
○ ​ xample Auto:​​void func() { auto int x=10; }​
​○​ ​Example Static:​​void func() { static int count=0;​​count++; }​

​b) Automatic and Register variables​


​​ A
● ​ uto:​​Stored in main memory (RAM).​
​●​ ​Register:​​Stored in CPU registers for faster access.​​You cannot use the address operator​
​(​&​) on them​​13131313131313​​.​
​+2​

​○​ ​Example:​​register int i; (Used for loop counters).​

​c) Global and Local variables​


​●​ ​Local (Auto):​​Declared inside a function. Scope is​​limited to that function​​14​​.​

​●​ G
​ lobal (Extern):​​Declared outside all functions. Scope​​is the entire program (or file).​
​Lifetime is program duration​​151515​​.​
​+2​

​d) Actual and Formal arguments​


​●​ ​Actual:​​The variables/values used in the function​​call. (e.g., add(m, n))​​16​​.​

​●​ F
​ ormal:​​The variables defined in the function header​​to receive values. (e.g., void add(int​
​a, int b))​​17​​.​

1​ 2. Explain the relevance of storage classes on scope, visibility and​


​lifetime of variables.​
​ torage classes determine where a variable is stored, its initial value, its scope (visibility), and​
S
​its lifetime​​18​​.​

​●​ S
​ cope (Visibility):​​Determines where in the program​​the variable can be accessed.​
​○​ ​Auto/Register:​​Block scope (only inside the function/block)​​19​​.​

​ lobal/Static:​​Program or File scope (visible across​​functions or file)​​20202020​​.​


​○​ G
​+1​

​●​ ​Lifetime:​​Determines how long the variable stays in​​memory.​


​○​ ​Auto:​​Destroyed when the function finishes​​21​​.​

​○​ ​Static/Global:​​Exists for the entire duration of the​​program execution​​22​​.​

​13. Define array.​


​ n array is a collection of similar data items (same data type) stored in consecutive memory​
A
​locations. All elements share a common name and are accessed using an index​
​(subscript)​​23232323​​.​

​+1​

1​ 4. Explain the declaration and initialization of single dimensional​


​array with example.​
​ eclaration:​
D
​Syntax: datatype array_name[size];​
​It specifies the type of data, the name, and the maximum number of elements24.​
​●​ ​Example:​​int marks[5];​

​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 calculated​​during execution.​
​○​ ​Example:​
​C​
​for​​(​int​​i=​​0​; i<​​4​; i++) {​
​scanf​​(​"%d"​​, &a[i]);​
​}​
​26262626​
​+1​

​15. Explain the Traversing of an array with an example.​


​ raversal is the process of visiting every element in the array exactly once, usually to print or​
T
​process the data. We typically use a​​for​​loop​​27​​.​

​Example:​
​C​

​ ​include​​<stdio.h>​
#
​void​​main​​()​​{​
​int​​a[​​3​] = {​​10​​,​​20​​,​​30​​};​
​int​​i;​
​// 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 the​​Module 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​

​String Manipulation Functions (found in​​<string.h>​​):​​2​

​ .​
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 a​​string (excluding the null terminator).​​3​

​○​ ​Syntax:​​int len = strlen(string_name);​​4​

​○​ E
​ xample:​
​C​
​char​​str[] =​​"Hello"​​;​
​int​​len =​​strlen​​(str);​​// len becomes 5​

​3.​ ​strcpy()​​: Copies the content of the source string​​into the destination string variable.​​5​

​○​ ​Syntax:​​strcpy(destination, source);​​6​

​○​ E
​ xample:​
​C​
​char​​src[] =​​"CopyMe"​​, dest[​​20​​];​
​strcpy​​(dest, src);​​// dest now contains "CopyMe"​

​4.​ ​strcmp()​​: Compares two strings. It returns​​0​​if they​​are equal, a positive value if the first​
i​s lexicographically greater, and a negative value if smaller.​​7777​
​+1​

​​ S
○ ​ yntax:​​int result = strcmp(str1, str2);​
​○​ ​Example:​
​C​
​int​​res =​​strcmp​​(​"Apple"​​,​​"Banana"​​);​​// res will be​​negative ('A' < 'B')​

​5.​ ​strcat()​​: Concatenates (joins) the second string onto​​the end of the first string.​​8​

​○​ ​Syntax:​​strcat(destination, source);​​9​

​○​ E
​ xample:​
​C​
​char​​s1[​​20​​] =​​"Hi "​​, s2[] =​​"World"​​;​
​strcat​​(s1, s2);​​// s1 becomes "Hi World"​

​2. Explain the declaration and initialization of string variables.​

​ 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​

​3.​ ​Example:​​char name[20];​

I​nitialization:​
​There are two main ways to initialize strings:​
​2.​ ​Character-by-character:​​You must explicitly include​​the null terminator.​​12121212​
​+1​

​ ​ ​Example:​​char ch[6] = {'H', 'e', 'l', 'l', 'o', '\0'};​



​3.​ ​Using string literals:​​You use double quotes. The​​compiler automatically appends the​
​null terminator.​​13131313​
​+1​

​○​ ​Example:​​char ch[] = "Hello"; OR char ch[6] = "Hello";​

​ . Write a program to check whether a string is palindrome or not without using built-in​
3
​function.​
​14​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​char​​str[​​100​​];​
​int​​i, j, len =​​0​, flag =​​0​;​

​printf​​(​"Enter a string: "​​);​


​gets(str);​

​// Calculate length manually​


​for​​(i =​​0​; str[i] !=​​'\0'​​; i++) {​
​len++;​
​}​

i​ =​​0​;​
​j = len -​​1​;​

​// Compare characters from start and end moving​​inwards​


​while​​(i < j) {​
​if​​(str[i] != str[j]) {​
​flag =​​1​;​​// Mismatch found​
​break​​;​
}​ ​
​i++;​
​j--;​
​}​

​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 destination​​string.​
​C​
​char​​s1[​​20​​] =​​"Good"​​, s2[] =​​"Morning"​​;​
​strcat​​(s1, s2);​​// s1 becomes "GoodMorning"​

​15​

​●​ i​i. strlen()​​: Counts the number of characters before​​\0.​


​C​
​char​​s[] =​​"Code"​​;​
​int​​n =​​strlen​​(s);​​// n is 4​

​16​

​●​ i​ii. strcmp()​​: Compares strings based on ASCII values.​


​C​
​char​​s1[] =​​"A"​​, s2[] =​​"B"​​;​
​int​​n =​​strcmp​​(s1, s2);​​// n is negative​

​17​

​●​ i​v. strcpy()​​: Copies the source string to the destination​​array.​


​C​
​char​​s1[​​10​​], s2[] =​​"Test"​​;​
​strcpy​​(s1, s2);​​// s1 becomes "Test"​

​18​

​●​ v
​ . strrev()​​: Reverses the given string in place.​
​C​
​char​​s[] =​​"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>​

​void​​main​​()​​{​
​char​​str[​​100​​];​
​int​​len =​​0​, i;​

​printf​​(​"Enter a string: "​​);​


​gets(str);​

​// Iterate until null terminator is found​


​for​​(i =​​0​; str[i] !=​​'\0'​​; i++) {​
​len++;​
​}​

​printf​​(​"The length of the string is: %d"​​, len);​


​}​

​6. Develop a C program to concatenate two strings without using built-in function.​

​20​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​char​​str1[​​50​​], str2[​​50​​];​
​int​​i =​​0​, j =​​0​;​

​printf​​(​"Enter First String: "​​);​


​gets(str1);​
​printf​​(​"Enter Second String: "​​);​
​gets(str2);​

​// Move i to the end of str1​


​while​​(str1[i] !=​​'\0'​​) {​
​i++;​
​}​

​// Copy str2 to the end of str1​


​while​​(str2[j] !=​​'\0'​​) {​
s​ tr1[i] = str2[j];​
​i++;​
​j++;​
}​ ​
​str1[i] =​​'\0'​​;​​// Add null terminator manually​

​printf​​(​"Concatenated String is: "​​);​


​puts​​(str1);​
​}​

​7. Write a C program to copy one string to another without using strcpy().​

​21​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​char​​src[​​100​​], dest[​​100​​];​
​int​​i =​​0​;​

​printf​​(​"Enter string: "​​);​


​gets(src);​

​// Copy character by character​


​while​​(src[i] !=​​'\0'​​) {​
​dest[i] = src[i];​
​i++;​
}​ ​
​dest[i] =​​'\0'​​;​​// Add null terminator​

​printf​​(​"Copied String: %s"​​, dest);​


​}​

​ . Write a C program to copy one string (combination of digits and alphabets) to​
8
​another string (only alphabets).​

​(Logic derived from source 2553)​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​char​​src[​​100​​], dest[​​100​​];​
​int​​i =​​0​, j =​​0​;​

​printf​​(​"Enter a string with digits and alphabets:​​"​);​


​gets(src);​

​while​​(src[i] !=​​'\0'​​) {​
​// Check if character is alphabet (A-Z or​​a-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​

​printf​​(​"String with only alphabets: %s"​​, dest);​


​}​
​9. Mention the purpose of a Null Character in C strings.​

​ he null character​​'\0'​​serves as a​​delimiter​​or terminator​​for strings in C. Since strings are​


T
​arrays of characters without an inherent length stored in the variable, the null character marks​
​where the string ends in memory.​​22222222​

​+1​

1​ 0. Write a C program to read a sentence and count the number of words in the​
​sentence.​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​char​​str[​​200​​];​
​int​​i =​​0​, words =​​0​;​

​printf​​(​"Enter a sentence: "​​);​


​gets(str);​

​while​​(str[i] !=​​'\0'​​) {​
​// Check for space or newline to identify​​word boundaries​
​// Only count if current is space and next​​is 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 is​​empty)​
​if​​(i >​​0​​&& str[​​0​] !=​​' '​​) words++;​

​printf​​(​"Number of words: %d"​​, words);​


​}​

1​ 1. Write a C Program to check the given character is Lowercase or Uppercase or​


​number or Special Character.​
​23232323​

​+1​

​C​

​ ​include​​<stdio.h>​
#
​#​include​​<ctype.h> // Using ctype macros​

​void​​main​​()​​{​
​char​​ch;​
​printf​​(​"Enter a character: "​​);​
​scanf​​(​"%c"​​, &ch);​

​if​​(​isupper​​(ch)) {​
​printf​​(​"It is Uppercase."​​);​
​}​​else​​if​​(​islower​​(ch)) {​
​printf​​(​"It is Lowercase."​​);​
​}​​else​​if​​(​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​

​●​ ​Initialization:​​pointer_name = &variable_name;​​26​

​●​ ​Example:​
​C​
​int​​num =​​10​​;​
​int​​*ptr;​
​ptr = &num;​​// 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.​

​2. Write a C program to add two numbers using pointers.​

​28282828​

​+1​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​int​​num1, num2, sum;​
​int​​*ptr1, *ptr2;​

​printf​​(​"Enter two numbers: "​​);​


​scanf​​(​"%d %d"​​, &num1, &num2);​

​ tr1 = &num1;​
p
​ptr2 = &num2;​

​sum = *ptr1 + *ptr2;​​// Dereference pointers to​​get values and add​


​printf​​(​"Sum = %d"​​, sum);​
​}​

​3. Write a C program to swap contents of two variables using pointer technique.​

​29​

​C​

​#​include​​<stdio.h>​

​void​​swap​​(​int​​*a,​​int​​*b)​​{​
​int​​temp;​
t​ emp = *a;​ ​// Save value at address a​
​*a = *b;​ ​// Put value at address b into address​​a​
​*b = temp;​ ​// Put saved value into address b​
​}​

​void​​main​​()​​{​
​int​​m, n;​
​printf​​(​"Enter values for m and n: "​​);​
​scanf​​(​"%d %d"​​, &m, &n);​

​printf​​(​"Before swapping: m=%d n=%d\n"​​, m, n);​


​swap(&m, &n);​​// Pass addresses​
​printf​​(​"After swapping: m=%d n=%d\n"​​, m, n);​
​}​

​4. Develop a C program to find the largest of three numbers using pointer.​

​30​

​C​
​#​include​​<stdio.h>​

​void​​findLargest​​(​int​​*a,​​int​​*b,​​int​​*c,​​int​​*largest)​​{​
​if​​(*a > *b && *a > *c) {​
​*largest = *a;​
​}​​else​​if​​(*b > *c) {​
​*largest = *b;​
​}​​else​​{​
​*largest = *c;​
​}​
​}​

​int​​main​​()​​{​
​int​​x, y, z, largest;​
​printf​​(​"Enter three numbers: "​​);​
​scanf​​(​"%d %d %d"​​, &x, &y, &z);​

​findLargest(&x, &y, &z, &largest);​

​printf​​(​"The largest number is: %d\n"​​, largest);​


​return​​0​;​
​}​

​ . Write a program in C to find the sum and mean of all elements in an array using​
5
​pointers.​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​int​​arr[​​50​​], n, i, sum =​​0​;​
​float​​mean;​
​int​​*ptr;​

​printf​​(​"Enter number of elements: "​​);​


​scanf​​(​"%d"​​, &n);​
​printf​​(​"Enter elements: "​​);​
​for​​(i=​​0​; i<n; i++) {​
​scanf​​(​"%d"​​, &arr[i]);​
​}​

​ptr = arr;​​// Initialize pointer to the start​​of the array​

​for​​(i =​​0​; i < n; i++) {​


s​ um = sum + *ptr;​​// Add the value pointed​​to by ptr​
​ptr++;​​// Move pointer to the next integer​​position​
​}​

​mean = (​​float​​)sum / n;​


​printf​​(​"Sum = %d\n"​​, sum);​
​printf​​(​"Mean = %.2f\n"​​, mean);​
​}​

​ . 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()​

​void​​main​​()​​{​
​float​​arr[​​50​​], sum =​​0​, mean, variance =​​0​, std_dev;​
​int​​n, 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);​
​}​

​mean = sum / n;​

​// Calculate Variance​


​for​​(i=​​0​; i<n; i++) {​
​variance +=​​pow​​((*(ptr + i) - mean),​​2​);​
}​ ​
​variance = variance / n;​

​// Calculate Standard Deviation​


​std_dev =​​sqrt​​(variance);​

​printf​​(​"Sum = %.2f\n"​​, sum);​


​printf​​(​"Mean = %.2f\n"​​, mean);​
​printf​​(​"Standard Deviation = %.2f\n"​​, std_dev);​
​}​

​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 to​​insert the contents of another file (like​
​a standard library header) into the program.​
​○​ ​Example: #include <stdio.h>​
​●​ ​#define​​: This directive is used to create symbolic​​constants 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>​

​void​​add​​(​int​​*a,​​int​​*b,​​int​​*result)​​{ *result =​​*a + *b; }​


​void​​subtract​​(​int​​*a,​​int​​*b,​​int​​*result)​​{ *result​​= *a - *b; }​
​void​​multiply​​(​int​​*a,​​int​​*b,​​int​​*result)​​{ *result​​= *a * *b; }​
​void​​divide​​(​int​​*a,​​int​​*b,​​float​​*result)​​{ *result​​= (​​float​​)*a / *b; }​

​int​​main​​()​​{​
​int​​num1, num2, sum, diff, prod;​
​float​​quot;​

​printf​​(​"Enter two numbers: "​​);​


​scanf​​(​"%d %d"​​, &num1, &num2);​

​ dd(&num1, &num2, &sum);​


a
​subtract(&num1, &num2, &diff);​
​multiply(&num1, &num2, &prod);​
​divide(&num1, &num2, &quot);​

​printf​​(​"Sum: %d\n"​​, sum);​


​printf​​(​"Difference: %d\n"​​, diff);​
​printf​​(​"Product: %d\n"​​, prod);​
​printf​​(​"Quotient: %.2f\n"​​, quot);​
​return​​0​;​
​}​

​ . Mention any two differences between:​


9
​(a) pointer variable and a normal variable​
​(b) a null pointer and a void pointer​
​(a) Pointer vs Normal Variable:​
​●​ C
​ ontent:​​A normal variable stores a data value (like​​10 or 'a'). A pointer variable stores​
​the​​address​​of another variable.​​32323232​
​+1​

​●​ D
​ eclaration:​​Normal variables are declared directly​​(e.g., int a;). Pointers are declared​
​with an asterisk (e.g.,​​int *p;​​).​​33​

​(b) Null Pointer vs Void Pointer:​


​●​ N
​ ull Pointer:​​A pointer initialized to NULL (or 0). It points to nothing and signifies that the​
​pointer is not currently valid or assigned.​​34​

​ ​ ​Example: int *p = NULL;​



​ ​ ​Void Pointer (Generic Pointer):​​A pointer with the​​type void. It can point to data of​​any​

​type (​​int​​,​​char​​, etc.), but cannot be dereferenced​​directly without casting.​​35​

​○​ ​Example: void *p;​


​ ere are the exam-style answers for the​​Module 5 Question Bank​​, utilizing the provided​
H
​resources ([Link] and [Link]).​

​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​

​struct​​tagname {​
​ atatype member1;​
d
​datatype member2;​
​// ...​
​datatype memberN;​
​};​

​3​

​Example:​

​C​

​struct​​student {​
​char​​name[​​20​​];​
​int​​usn;​
​float​​marks;​
​};​
​Here,​​student​​is the structure tag, and​​name​​,​​usn​​, and​​marks​​are its members​​4​​.​

​2. List and explain types of structures with examples​

​There are three main ways to declare structures in C:​


​9.​ T
​ agged Structure:​
​This method names the structure (tag), allowing it to be used later to declare variables.​
​○​ ​Syntax:​
​C​
​struct​​tag_name {​
​datatype member1;​
​//...​
​};​
​struct​​tag_name v1, v2;​

​○​ E
​ xample:​
​C​
​struct​​student {​
​char​​name[​​20​​];​
​int​​usn;​
​};​
​struct​​student s1, s2;​​// Variable declaration​

​5​

​10.​​Structure without Tag (Anonymous Structure):​


​The structure is defined and variables are declared immediately. It cannot be reused​
​elsewhere because it has no tag name.​
​○​ ​Syntax:​
​C​
​struct​​{​
​datatype member1;​
​//...​
​} v1, v2;​

​○​ E
​ xample:​
​C​
​struct​​{​
​char​​name[​​20​​];​
​int​​usn;​
​} s1, s2;​
​6​

​11.​​Type-Defined Structure (typedef):​


​This creates a new type alias for the structure, making variable declaration simpler (no​
​need to write struct every time).​
​○​ ​Syntax:​
​C​
​typedef​​struct​​{​
​datatype member1;​
​//...​
}​ TYPE_ID;​
​TYPE_ID v1;​

​○​ E
​ xample:​
​C​
​typedef​​struct​​{​
​char​​name[​​20​​];​
​int​​usn;​
}​ 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>​

​struct​​Student {​
​char​​name[​​20​​];​
​int​​usn;​
​float​​marks;​
​};​

​void​​main​​()​​{​
​struct​​Student s[100];​
​int​​n, i;​
​float​​total =​​0​, avg;​

​printf​​(​"Enter number of students: "​​);​


​scanf​​(​"%d"​​, &n);​

​// Read details​


​for​​(i =​​0​; i < n; i++) {​
​printf​​(​"Enter details for student %d (Name​​USN Marks): "​​, i +​​1​);​
​scanf​​(​"%s %d %f"​​, s[i].name, &s[i].usn, &s[i].marks);​
​total += s[i].marks;​
​}​

​avg = total / n;​


​printf​​(​"\nClass Average: %.2f\n"​​, avg);​

​printf​​(​"\nStudents scoring Above Average:\n"​​);​


​for​​(i =​​0​; i < n; i++) {​
​if​​(s[i].marks >= avg) {​
​printf​​(​"%s (Marks: %.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 (Marks: %.2f)\n"​​, s[i].name,​​s[i].marks);​
​}​
​}​
​}​

​4. Explain structure within a structure with an example.​

​ structure within a structure is known as a​​nested​​structure​​. This means a member of a​


A
​structure is itself another structure variable. It is used to represent hierarchical data.​

​ xample:​
E
​We can have a Date structure nested inside a Student structure to store the Date of Birth​
​(DOB).​

​C​

​#​include​​<stdio.h>​

​struct​​Date {​
​int​​dd;​
​int​​mm;​
​int​​yyyy;​
​};​

​struct​​Student {​
​char​​name[​​20​​];​
​int​​usn;​
​struct​​Date dob;​​// Nested structure member​
​};​

​void​​main​​()​​{​
​struct​​Student s1;​

​// Assigning values​


s​ [Link] =​​101​​;​
​[Link] =​​15​​;​
​[Link] =​​8​;​
​[Link] =​​2000​​;​

​printf​​(​"DOB: %d-%d-%d"​​, [Link], [Link],​​[Link]);​


​}​

​5. Differentiate between structure and union.​

​Feature​ ​Structure​ ​Union​

​Keyword​ ​Defined using struct.​ ​Defined using union.​

​Memory Allocation​ ​ llocates memory for​​all​


A ​ llocates memory for only​
A
​members. Total size is the​ ​the​​largest​​member. Total​
s​ um of sizes of all​ s​ ize is the size of the​
​members.​ ​largest member.​

​Data Storage​ ​ ll members can store​


A ​ nly one member can hold​
O
​distinct values​ ​a value at any given time.​
​simultaneously.​

​Usage​ ​ sed when all data items​


U ​ sed when only one of the​
U
​need to be used at once.​ ​data items is used at a time​
​to save memory.​

​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>​

​struct​​student {​
​char​​name[​​20​​];​
​char​​usn[​​15​​];​
​};​

​void​​main​​()​​{​
​struct​​student s[5];​
​int​​i;​

​printf​​(​"Enter details of 5 students:\n"​​);​


​for​​(i =​​0​; i <​​5​; i++) {​
​printf​​(​"Student %d (Name USN): "​​, i+​​1​);​
​scanf​​(​"%s %s"​​, s[i].name, s[i].usn);​
​}​
​printf​​(​"\nStudent Details:\n"​​);​
​for​​(i =​​0​; i <​​5​; i++) {​
​printf​​(​"Name: %s, USN: %s\n"​​, s[i].name, s[i].usn);​
​}​
​}​

​ . Write a C program that accepts a structure variable as a parameters to a function​


7
​from a function call.​

​ 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>​

​struct​​Point {​
​int​​x;​
​int​​y;​
​};​

/​ / Function accepting structure parameter​


​void​​displayPoint​​(struct Point p)​​{​
​printf​​(​"Point coordinates: (%d, %d)\n"​​, p.x, p.y);​
​}​

​void​​main​​()​​{​
​struct​​Point 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​

​union​​tagname {​
​ atatype member1;​
d
​datatype member2;​
​//...​
​};​

​Example:​

​C​

​union​​Data {​
​int​​i;​
​float​​f;​
​char​​str[​​20​​];​
​};​

​void​​main​​()​​{​
​union​​Data data;​
​data.i =​​10​​;​
​printf​​(​"data.i: %d\n"​​, data.i);​​// Valid​
​data.f =​​220.5​​;​
​printf​​(​"data.f: %f\n"​​, data.f);​​// Valid, but​​data.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>​

​enum​​Weekday {​​Sunday, Monday, Tuesday, Wednesday};​

​void​​main​​()​​{​
​enum​​Weekday today;​
​today = Monday;​​// Monday has value 1 by default​​(Sunday=0)​
​printf​​(​"Value of Monday is: %d"​​, today);​
​}​

​13​

1​ 0. Develop a C program by defining a structure named time containing three integer​


​members hour, minute and second. Create two structure variables, input the values​
​and print them in the format hh:mm:ss.​

​C​

​#​include​​<stdio.h>​

​struct​​Time {​
​int​​hour;​
​int​​minute;​
​int​​second;​
​};​
​void​​main​​()​​{​
​struct​​Time t1, t2;​

​printf​​(​"Enter time 1 (hh mm ss): "​​);​


​scanf​​(​"%d %d %d"​​, &[Link], &[Link], &[Link]);​

​printf​​(​"Enter time 2 (hh mm ss): "​​);​


​scanf​​(​"%d %d %d"​​, &[Link], &[Link], &[Link]);​

​printf​​(​"\nTime 1: %02d:%02d:%02d\n"​​, [Link],​​[Link], [Link]);​


​printf​​(​"Time 2: %02d:%02d:%02d\n"​​, [Link], [Link],​​[Link]);​
​}​

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>​

​struct​​DOB {​
​int​​dd;​
​int​​mm;​
​int​​yy;​
​};​

​void​​main​​()​​{​
​struct​​DOB d;​

​printf​​(​"Enter Date of Birth (dd mm yyyy): "​​);​


​scanf​​(​"%d %d %d"​​, &[Link], &[Link], &[Link]);​
​printf​​(​"Date of Birth: %02d/%02d/%d"​​, [Link], [Link], [Link]);​
​}​

1​ 3. Write a C program to implement structures to read and write Book-Title,​


​Book-Author and Book-id of n books.​

​C​

​#​include​​<stdio.h>​

​struct​​Book {​
​char​​title[​​50​​];​
​char​​author[​​50​​];​
​int​​id;​
​};​

​void​​main​​()​​{​
​struct​​Book b[100];​
​int​​n, i;​

​printf​​(​"Enter number of books: "​​);​


​scanf​​(​"%d"​​, &n);​

​for​​(i =​​0​; i < n; i++) {​


​printf​​(​"Enter details for Book %d\n"​​, i+​​1​);​
​printf​​(​"Title: "​​);​​scanf​​(​"%s"​​, b[i].title);​
​printf​​(​"Author: "​​);​​scanf​​(​"%s"​​, b[i].author);​
​printf​​(​"ID: "​​);​​scanf​​(​"%d"​​, &b[i].id);​
​}​

​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>​

​struct​​Customer {​
​char​​name[​​50​​];​
​int​​id;​
​long​​accNum;​
​char​​address[​​100​​];​
​long​​mobile;​
​};​

​void​​main​​()​​{​
​struct​​Customer c;​

​printf​​(​"Enter Customer Name: "​​);​​scanf​​(​"%s"​​, [Link]);​


​printf​​(​"Enter Customer ID: "​​);​​scanf​​(​"%d"​​, &[Link]);​
​printf​​(​"Enter Account Number: "​​);​​scanf​​(​"%ld"​​,​​&[Link]);​
​printf​​(​"Enter Address: "​​);​​scanf​​(​"%s"​​, [Link]);​
​printf​​(​"Enter Mobile: "​​);​​scanf​​(​"%ld"​​, &[Link]);​

​printf​​(​"\n--- Customer Details ---\n"​​);​


​printf​​(​"Name: %s\nID: %d\nAccount: %ld\nAddress:​​%s\nMobile: %ld\n"​​,​
​[Link], [Link], [Link], [Link], [Link]);​
​}​

1​ 5. Write a C program to store and print name, USN, Subject and IA marks of students​
​using structure.​

​C​

​#​include​​<stdio.h>​
​struct​​Student {​
​char​​name[​​20​​];​
​char​​usn[​​15​​];​
​char​​subject[​​20​​];​
​int​​iaMarks;​
​};​

​void​​main​​()​​{​
​struct​​Student s;​

​printf​​(​"Enter Name: "​​);​​scanf​​(​"%s"​​, [Link]);​


​printf​​(​"Enter USN: "​​);​​scanf​​(​"%s"​​, [Link]);​
​printf​​(​"Enter Subject: "​​);​​scanf​​(​"%s"​​, [Link]);​
​printf​​(​"Enter IA Marks: "​​);​​scanf​​(​"%d"​​, &[Link]);​

​printf​​(​"\nStudent Record:\n"​​);​
​printf​​(​"%s (%s) - %s: %d\n"​​, [Link], [Link], [Link],​​[Link]);​
​}​

​16. Write a note on enumerated data type.​

​(See answer to Question 9. Key points:)​


​ .​
5 I​t is a user-defined data type named enum.​
​6.​ ​It consists of named integer constants called enumerators.​
​7.​ ​By default, the first constant is 0, the next is 1, etc.​
​8.​ ​It makes code more readable (e.g., using Monday instead of 1).​
​9.​ ​Example: enum boolean {NO, YES}; (NO=0, YES=1).​
​14​

​FILES​
​1. Discuss the different modes of operation on files with suitable example.​

​When opening a file using fopen(), we must specify the mode.​


​2.​ "​ r" (Read Mode):​​Opens an existing file for reading.​​If the file doesn't exist, it returns​
​NULL. The pointer is at the beginning.​​15​

​3.​ ​"w" (Write Mode):​​Opens a file for writing. If the​​file doesn't exist, it creates a new one. If​
​it exists, it​​erases​​(truncates) the old content.​​16​

​4.​ "​ a" (Append Mode):​​Opens a file to add data to the​​end. 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] for​​writing​

​2. a. Differentiate between gets() and fgets().​

​gets()​ ​fgets()​

​Reads from standard input (keyboard) only.​ ​ an read from​​any​​file stream (including​
C
​keyboard/stdin).​

​ oes​​not​​check buffer size (unsafe, can​


D ​ hecks buffer size (n parameter), making it​
C
​cause overflow).​ ​safer.​

​Syntax: gets(str);​ ​Syntax: fgets(str, size, file_pointer);​

​18181818​

​+1​

​2. b. Differentiate between gets and scanf functions.​

​scanf("%s", ...)​ ​gets()​

​ tops reading at the first whitespace​


S ​ eads until a newline character (Enter key).​
R
​(space, tab, newline). Cannot read​ ​Can read full sentences with spaces.​
​multi-word strings.​

​Syntax: scanf("%s", str);​ ​Syntax: gets(str);​

​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>​

​void​​main​​()​​{​
​FILE *fp;​
​char​​text[​​100​​], ch;​

​// Writing to file​


​fp = fopen(​​"[Link]"​​,​​"w"​​);​
​if​​(fp ==​​NULL​​)​​exit​​(​0​);​

​printf​​(​"Enter text to store in file: "​​);​


​gets(text);​
​fprintf​​(fp,​​"%s"​​, text);​
​fclose(fp);​

​// Reading from file​


​fp = fopen(​​"[Link]"​​,​​"r"​​);​
​printf​​(​"\nData from file:\n"​​);​
​while​​((ch = fgetc(fp)) != EOF) {​
​printf​​(​"%c"​​, ch);​
​}​
​fclose(fp);​
​}​
​20​

​4. Write a program in C to count the number of words and characters in a file.​

​C​

​#​include​​<stdio.h>​

​void​​main​​()​​{​
​FILE *fp;​
​char​​ch;​
​int​​characters =​​0​, words =​​0​;​

​fp = fopen(​​"[Link]"​​,​​"r"​​);​
​if​​(fp ==​​NULL​​) {​
​printf​​(​"File not found."​​);​
​return​​;​
​}​

​while​​((ch = fgetc(fp)) != EOF) {​


​characters++;​
​if​​(ch ==​​' '​​|| ch ==​​'\n'​​|| ch ==​​'\t'​​)​​{​
​words++;​
​}​
​}​
​// Correction for the last word if file doesn't​​end with space/newline​
​if​​(characters >​​0​) words++;​

​printf​​(​"Characters: %d\nWords: %d"​​, characters,​​words);​


​fclose(fp);​
​}​

​21​
​5. Write a program in C to copy a file to another name.​

​C​

​ ​include​​<stdio.h>​
#
​#​include​​<stdlib.h>​

​void​​main​​()​​{​
​FILE *fp1, *fp2;​
​char​​ch;​
​char​​sourceFile[] =​​"[Link]"​​;​
​char​​destFile[] =​​"[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​);​
​}​

​while​​((ch = fgetc(fp1)) != EOF) {​


​fputc(ch, fp2);​
​}​

​printf​​(​"File copied successfully.\n"​​);​

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.​ i​i. fgets()​​: Reads a line (string) from a file up​​to n characters. It stops at a newline or EOF.​
​○​ ​Syntax:​​fgets(str, n, fp);​​24​

​6.​ i​ii. fgetc()​​: Reads a single character from the file.​​Returns EOF if end of file is reached.​
​○​ ​Syntax:​​ch = fgetc(fp);​​25​

​7.​ i​v. fprintf()​​: Writes formatted data to a file. Works​​like printf.​


​○​ ​Syntax:​​fprintf(fp, "Result: %d", res);​​26​

​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>​

​void​​main​​()​​{​
​FILE *fp, *out;​
​char​​ch;​
​int​​chars =​​0​, words =​​0​, lines =​​0​;​

​fp = fopen(​​"[Link]"​​,​​"r"​​);​
​if​​(fp ==​​NULL​​) {​
​printf​​(​"Input file not found."​​);​
​exit​​(​0​);​
​}​

​while​​((ch = fgetc(fp)) != EOF) {​


​chars++;​
​if​​(ch ==​​'\n'​​) lines++;​
​if​​(ch ==​​' '​​|| ch ==​​'\t'​​|| ch ==​​'\n'​​)​​words++;​
​}​
​if​​(chars >​​0​) {​
​words++;​​// Count last word​
​lines++;​​// Count last line​
​}​

​fclose(fp);​

​// Writing output to separate file​


​out = fopen(​​"output_stats.txt"​​,​​"w"​​);​
​fprintf​​(out,​​"Characters: %d\nWords: %d\nLines:​​%d\n"​​, chars, words, lines);​
​fclose(out);​

​printf​​(​"Statistics written to output_stats.txt\n"​​);​


​}​

​29​

You might also like