[go: up one dir, main page]

0% found this document useful (0 votes)
58 views82 pages

C Answers

The document discusses various concepts in C programming, including dynamic memory allocation functions like malloc(), calloc(), realloc(), and free(), as well as pointers, arrays, structures, and file access modes. It also covers pre-processor directives, storage classes, operations, and loop structures in C. Additionally, examples are provided for better understanding of each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views82 pages

C Answers

The document discusses various concepts in C programming, including dynamic memory allocation functions like malloc(), calloc(), realloc(), and free(), as well as pointers, arrays, structures, and file access modes. It also covers pre-processor directives, storage classes, operations, and loop structures in C. Additionally, examples are provided for better understanding of each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

2023

Q5a) What are the various dynamic memory allocation functions in C?


Explain with an example.

Dynamic memory allocation in C allows the programmer to allocate memory during


runtime. This is done using the following functions available in the stdlib.h library:

1. malloc() (Memory Allocation):


o Allocates a block of memory of the specified size (in bytes).
o Returns a pointer to the beginning of the block or NULL if the allocation fails.
o Memory is not initialized.

Syntax:

ptr = (cast-type*) malloc(size);

Example:

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

int main() {
int *ptr;
int n = 5;

// Allocate memory for 5 integers


ptr = (int*) malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

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


ptr[i] = i * 2;
printf("%d ", ptr[i]);
}

free(ptr); // Free the allocated memory


return 0;
}

2. calloc() (Contiguous Allocation):


o Allocates multiple blocks of memory and initializes each block to 0.
o Syntax:
o ptr = (cast-type*) calloc(n, size);
o Example:
o int *ptr = (int*) calloc(5, sizeof(int));
3. realloc() (Reallocate Memory):
o Resizes a previously allocated memory block.
o Syntax:

1
o ptr = (cast-type*) realloc(ptr, new_size);
4. free():
o Frees dynamically allocated memory to avoid memory leaks.

Q5b) What is a pointer? Explain array of pointers to function with a suitable


example.

Pointer: A pointer is a variable that stores the address of another variable. It is used to
indirectly access and manipulate data.

Array of Pointers: An array of pointers is a collection of pointer variables that can store the
addresses of multiple variables.

Pointer to Function: A pointer that points to the address of a function and can be used to
invoke the function.

Array of Pointers to Functions:

 It is an array where each element points to a function.

Example:

#include <stdio.h>

void add(int a, int b) {


printf("Sum: %d\n", a + b);
}

void subtract(int a, int b) {


printf("Difference: %d\n", a - b);
}

int main() {
void (*func_ptr[2])(int, int); // Array of pointers to functions
func_ptr[0] = add;
func_ptr[1] = subtract;

func_ptr[0](10, 5); // Call add()


func_ptr[1](10, 5); // Call subtract()

return 0;
}

Q6a) Differentiate between formatted and unformatted input and output


functions.

Feature Formatted I/O Unformatted I/O


Functions printf, scanf, fprintf getchar, putchar, gets, puts
Data type Requires format specifiers like %d, Does not require format
specification %f specifiers

2
Feature Formatted I/O Unformatted I/O
Flexibility Highly flexible Less flexible
Example printf("%d", x); putchar(ch);

Q6b) Write short notes on:

i) Structure and Union:

 Structure:
o A user-defined data type that allows grouping of variables of different data
types.
o Memory is allocated for all members.
o Example:
o struct Student {
o int id;
o char name[20];
o };
 Union:
o Similar to structure, but memory is shared among all members.
o Only one member can hold a value at a time.
o Example:
o union Data {
o int i;
o float f;
o };

ii) Passing Structure to Functions:

Structures can be passed to functions by value or by reference.

Example:

struct Student {
int id;
};

void display(struct Student s) {


printf("ID: %d", s.id);
}

int main() {
struct Student s1 = {1};
display(s1);
return 0;
}

iii) File Access Modes:

 Modes to open files:


o r: Read only.

3
o w: Write only (creates new or truncates existing file).
o a: Append to a file.
o r+: Read and write.
o w+: Write and read.
o a+: Append and read.

Q7a) What is the use of atoi() function? Explain with an example.

atoi(): Converts a string to an integer. Defined in stdlib.h.

Syntax:

int atoi(const char *str);

Example:

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

int main() {
char str[] = "1234";
int value = atoi(str);
printf("Integer: %d\n", value);
return 0;
}

Output:

Integer: 1234

Q7b) Compare arrays and structures. Justify your comparison with an


example.

Feature Array Structure


Data type Contains only one data type Can contain different data types
Memory Allocation Contiguous memory for all elements Separate memory for each member
Access Indexed by position Accessed by member name
Use Used for lists or collections Used for grouping related data

Example:

Array:

int arr[3] = {1, 2, 3};


printf("%d", arr[0]);

Structure:

4
struct Student {
int id;
char name[20];
} s1 = {1, "Alice"};

printf("%d %s", s1.id, s1.name);

Q8a) Explain the syntax and usage of inbuilt string functions with a suitable
example.

C provides a set of inbuilt string functions in the string.h header file. These functions are
used to manipulate and process strings.

1. strlen(): Calculates the length of a string (excluding the null terminator).


o Syntax: size_t strlen(const char *str);
o Example:
o #include <stdio.h>
o #include <string.h>
o int main() {
o char str[] = "Hello";
o printf("Length of string: %zu\n", strlen(str));
o return 0;
o }
2. strcpy(): Copies one string to another.
o Syntax: char* strcpy(char *dest, const char *src);
o Example:
o char src[] = "Hello";
o char dest[10];
o strcpy(dest, src);
o printf("Copied string: %s\n", dest);
3. strcat(): Concatenates two strings.
o Syntax: char* strcat(char *dest, const char *src);
o Example:
o char str1[20] = "Hello ";
o char str2[] = "World!";
o strcat(str1, str2);
o printf("Concatenated string: %s\n", str1);
4. strcmp(): Compares two strings lexicographically.
o Syntax: int strcmp(const char *str1, const char *str2);
o Example:
o char str1[] = "Apple";
o char str2[] = "Orange";
o int result = strcmp(str1, str2);
o if (result == 0)
o printf("Strings are equal\n");
o else
o printf("Strings are not equal\n");
5. strrev() (non-standard in some compilers): Reverses a string.
o Example:
o char str[] = "Hello";
o printf("Reversed: %s\n", strrev(str));

5
Q8b) Write a program to identify the largest and smallest word in a string.

Here is a C program to identify the largest and smallest word in a string:

#include <stdio.h>
#include <string.h>
#include <limits.h>

int main() {
char str[100], word[20], maxWord[20], minWord[20];
int i = 0, j = 0, maxLen = 0, minLen = INT_MAX;

printf("Enter a string: ");


gets(str);

while (str[i] != '\0') {


if (str[i] != ' ' && str[i] != '\0') {
word[j++] = str[i];
} else {
word[j] = '\0'; // Terminate the word
if (j > 0) { // Check word length
if (j > maxLen) {
maxLen = j;
strcpy(maxWord, word);
}
if (j < minLen) {
minLen = j;
strcpy(minWord, word);
}
}
j = 0; // Reset for next word
}
i++;
}

printf("Largest word: %s (Length: %d)\n", maxWord, maxLen);


printf("Smallest word: %s (Length: %d)\n", minWord, minLen);

return 0;
}

Q9a) Explain the following header files:

i) Math.h

 The math.h header file contains mathematical functions.


 Common functions include:
o sqrt(x) → Square root.
o pow(x, y) → Power function.
o sin(x), cos(x), tan(x) → Trigonometric functions.
o fabs(x) → Absolute value.
 Example:
 #include <stdio.h>
 #include <math.h>

 int main() {

6
 printf("Square root of 16: %.2f\n", sqrt(16));
 printf("2 raised to power 3: %.2f\n", pow(2, 3));
 return 0;
 }

ii) stdlib.h

 The stdlib.h header file includes functions for general purpose utilities:
o malloc(), calloc(), realloc() → Memory management.
o atoi() → Convert string to integer.
o rand() → Generate random numbers.
 Example:
 #include <stdio.h>
 #include <stdlib.h>

 int main() {
 char str[] = "123";
 int num = atoi(str);
 printf("Integer value: %d\n", num);
 return 0;
 }

iii) time.h

 The time.h header provides functions related to time and date.


 Common functions include:
o time() → Returns current time.
o clock() → Returns processor time consumed.
o difftime() → Difference between two times.
 Example:
 #include <stdio.h>
 #include <time.h>

 int main() {
 time_t t;
 time(&t);
 printf("Current time: %s", ctime(&t));
 return 0;
 }

Q9b) Write a program in C to check whether the input word is a palindrome


or not.

Palindrome: A string that reads the same forward and backward.

Example Program:

#include <stdio.h>
#include <string.h>

int main() {

7
char str[50], rev[50];
printf("Enter a word: ");
scanf("%s", str);

strcpy(rev, str); // Copy the original string


strrev(rev); // Reverse the string

if (strcmp(str, rev) == 0)
printf("The word is a palindrome.\n");
else
printf("The word is not a palindrome.\n");

return 0;
}

Input/Output:

 Input: madam
 Output: The word is a palindrome.
 Input: hello
 Output: The word is not a palindrome.

2019

a) Discuss pre-processor directives in C.

Pre-processor directives are commands that are executed before the program compilation
begins. They are used to include files, define constants, and perform conditional
compilation.

 Pre-processor directives start with a # symbol.


 Common pre-processor directives:
1. #include: Used to include header files.
 Example: #include <stdio.h>
2. #define: Used to define constants or macros.
 Example: #define PI 3.14
3. #undef: Undefines a macro.
4. #ifdef, #ifndef: Used for conditional compilation.
 Example:
 #define DEBUG
 #ifdef DEBUG
 printf("Debug mode\n");

8
 #endif
5. #pragma: Gives specific instructions to the compiler.

b) What do you understand by dynamic memory allocation? Explain malloc(),


calloc(), realloc(), and free() functions with syntax and an example.

Dynamic Memory Allocation allows programs to allocate memory during runtime instead
of compile time. It is done using functions from stdlib.h:

1. malloc(): Allocates uninitialized memory.


o Syntax: void* malloc(size_t size);
o Example:
o int *ptr = (int*)malloc(4 * sizeof(int));
o if (ptr != NULL) {
o printf("Memory allocated using malloc.\n");
o }
2. calloc(): Allocates memory and initializes it to zero.
o Syntax: void* calloc(size_t num, size_t size);
o Example:
o int *ptr = (int*)calloc(4, sizeof(int));
o if (ptr != NULL) {
o printf("Memory allocated and initialized to zero.\n");
o }
3. realloc(): Resizes previously allocated memory.
o Syntax: void* realloc(void *ptr, size_t size);
o Example:
o ptr = realloc(ptr, 8 * sizeof(int));
o printf("Memory reallocated.\n");
4. free(): Frees allocated memory.
o Syntax: void free(void *ptr);
o Example:
o free(ptr);
o printf("Memory freed.\n");

c) Write a short note on storage classes in C.

Storage classes determine the scope, lifetime, and visibility of variables. The four storage
classes in C are:

1. auto (Automatic Storage Class):


o Default for local variables.
o Example:
o void func() {
o auto int x = 10;
o printf("%d\n", x);
o }
2. static:
o Retains the value of a variable between function calls.
o Example:

9
o void func() {
o static int x = 0;
o x++;
o printf("%d\n", x);
o }
3. extern:
o Declares a global variable without defining it.
o Example:
o extern int x;
4. register:
o Suggests storing the variable in a CPU register for fast access.
o Example:
o register int counter;

d) Discuss the various operations in C.

C provides the following types of operations:

1. Arithmetic Operators:
o +, -, *, /, %
o Example: a + b
2. Relational Operators:
o ==, !=, >, <, >=, <=
o Example: if (a > b)
3. Logical Operators:
o &&, ||, !
o Example: if (a > 0 && b > 0)
4. Bitwise Operators:
o &, |, ^, ~, <<, >>
o Example: a & b
5. Assignment Operators:
o =, +=, -=, *=, /=
o Example: a += b
6. Increment/Decrement Operators:
o ++, --
o Example: a++
7. Conditional Operator:
o ? :
o Example: int x = (a > b) ? a : b;

e) Explain the different loop structures in C through suitable examples.

C has three main loop structures:

1. for loop: Used when the number of iterations is known.


o Syntax:
o for (int i = 0; i < 5; i++) {
o printf("%d\n", i);

10
o }
2. while loop: Used when the condition is checked before execution.
o Syntax:
o int i = 0;
o while (i < 5) {
o printf("%d\n", i);
o i++;
o }
3. do-while loop: Executes at least once, and then checks the condition.
o Syntax:
o int i = 0;
o do {
o printf("%d\n", i);
o i++;
o } while (i < 5);

f) Distinguish between a structure and a union through a suitable example.

Both structures and unions are used to group variables of different data types, but they
differ in memory allocation:

Structure Union
Each member has its own memory. All members share the same memory.
Larger in size (sum of all members). Smaller in size (size of largest member).
Syntax: struct keyword. Syntax: union keyword.

Example:

#include <stdio.h>

struct ExampleStruct {
int a;
float b;
};

union ExampleUnion {
int a;
float b;
};

int main() {
struct ExampleStruct s = {10, 20.5};
union ExampleUnion u;

u.a = 10;
printf("Struct: %d, %.2f\n", s.a, s.b);

u.b = 20.5;
printf("Union: %d, %.2f\n", u.a, u.b);

return 0;
}

Output:

11
 In structure, both a and b retain their values.
 In union, changing b overwrites the value of a.

Sure! Let's break down and answer the questions one by one.

### Q2.

#### a) Explain the if..else statement with all its variations. Compare it with switch..case.
Write a C program that demonstrates the difference between the two.

**If..else Statement:**

- **Simple if:** Executes a block of code if the condition is true.

- **If-else:** Executes one block of code if the condition is true and another block if it's
false.

- **Else if ladder:** Tests multiple conditions one by one.

- **Nested if:** An if or if-else statement inside another if or if-else statement.

**Switch..case:**

- Used for multiple conditional checks based on a single variable.

- It’s more readable when dealing with multiple conditions.

**Comparison:**

- **if..else** can handle complex conditions.

- **switch..case** is more readable and efficient when dealing with a variable compared
against multiple constant values.

**C Program:**

```c

#include <stdio.h>

12
int main() {

int num = 2;

// If..else

if (num == 1) {

printf("Number is 1\n");

} else if (num == 2) {

printf("Number is 2\n");

} else {

printf("Number is not 1 or 2\n");

// Switch..case

switch (num) {

case 1:

printf("Number is 1\n");

break;

case 2:

printf("Number is 2\n");

break;

default:

printf("Number is not 1 or 2\n");

13
return 0;

```

#### b) Write a C program to test whether a given integer is a prime number or not. Display
an appropriate message in the output.

```c

#include <stdio.h>

#include <stdbool.h>

bool isPrime(int num) {

if (num <= 1) return false;

for (int i = 2; i <= num / 2; i++) {

if (num % i == 0) return false;

return true;

int main() {

int num;

printf("Enter an integer: ");

scanf("%d", &num);

if (isPrime(num)) {

printf("%d is a prime number.\n", num);

} else {

14
printf("%d is not a prime number.\n", num);

return 0;

```

### Q3.

#### a) What do you understand by type casting? Why is it required? Explain using an
example.

**Type Casting:**

- Type casting is the process of converting a variable from one data type to another.

- It is required when you want to perform operations between different types or use a specific
type for calculations.

**Example:**

```c

#include <stdio.h>

int main() {

int num = 10;

float result;

// Implicit type casting

result = num / 4;

printf("Result without type casting: %f\n", result);

15
// Explicit type casting

result = (float)num / 4;

printf("Result with type casting: %f\n", result);

return 0;

```

In this example, type casting ensures that the division operation is performed with floating-
point precision.

#### b) Write a C program to display the following pattern (for n lines):

```

12

123

1234

12345

```

**C Program:**

```c

#include <stdio.h>

int main() {

int n;

16
printf("Enter the number of lines: ");

scanf("%d", &n);

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

for (int j = 1; j <= i; j++) {

printf("%d ", j);

printf("\n");

return 0;

```

Alright, let's tackle these questions one by one:

### UNIT II

#### Q4.

**a) Write a short note on recursion. (5.5)**

Recursion is a programming technique where a function calls itself directly or indirectly. It's
used to solve problems that can be broken down into smaller, similar subproblems. Each
recursive call reduces the problem size, and the base case(s) stop the recursion. Recursion
simplifies code and is commonly used for tasks such as traversing data structures, sorting
algorithms, and solving mathematical problems (e.g., calculating factorials, Fibonacci
sequences).

17
**b) Write a complete C program that displays the first n Fibonacci numbers through a
recursive function Fibonacci. (7)**

```c

#include <stdio.h>

// Recursive function to calculate Fibonacci numbers

int fibonacci(int n) {

if (n <= 1)

return n;

return fibonacci(n - 1) + fibonacci(n - 2);

int main() {

int n, i;

printf("Enter the number of Fibonacci numbers to display: ");

scanf("%d", &n);

printf("The first %d Fibonacci numbers are:\n", n);

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

printf("%d ", fibonacci(i));

printf("\n");

return 0;

```

#### Q5.

18
**a) Differentiate between call by value and call by reference methods of passing parameters
to functions using an appropriate example. (7)**

- **Call by Value:** The actual value is passed to the function. Changes made to the
parameter inside the function do not affect the original value.

- **Call by Reference:** The address of the variable is passed to the function. Changes made
to the parameter inside the function affect the original value.

**Example:**

```c

#include <stdio.h>

// Call by value function

void callByValue(int a) {

a = a + 10;

printf("Inside callByValue: %d\n", a);

// Call by reference function

void callByReference(int *a) {

*a = *a + 10;

printf("Inside callByReference: %d\n", *a);

int main() {

int x = 20;

printf("Before callByValue: %d\n", x);

callByValue(x);

19
printf("After callByValue: %d\n", x);

printf("Before callByReference: %d\n", x);

callByReference(&x);

printf("After callByReference: %d\n", x);

return 0;

```

**b) Write a C function that searches for an element x in an array of integers. (5.5)**

```c

#include <stdio.h>

// Function to search for an element in an array

int searchElement(int arr[], int size, int x) {

for (int i = 0; i < size; i++) {

if (arr[i] == x)

return i; // Return the index of the element

return -1; // Return -1 if the element is not found

int main() {

int arr[] = {1, 2, 3, 4, 5};

int size = sizeof(arr) / sizeof(arr[0]);

20
int x = 3;

int result = searchElement(arr, size, x);

if (result != -1) {

printf("Element %d found at index %d.\n", x, result);

} else {

printf("Element %d not found.\n", x);

return 0;

```

### UNIT III

#### Q6.

**a) What are structures and what are Bit Field structures? How are they different from
Unions? (4)**

- **Structures:** Collections of variables of different types grouped together under a single


name.

- **Bit Field Structures:** Special type of structures where the width of each field is
specified in bits, used to save memory space.

- **Unions:** Similar to structures, but all members share the same memory location. Only
one member can store a value at a time.

**Example of Structures and Unions:**

```c

#include <stdio.h>

21
// Structure

struct Student {

int id;

char name[50];

float marks;

};

// Bit Field Structure

struct BitFieldExample {

unsigned int a : 1;

unsigned int b : 3;

unsigned int c : 4;

};

// Union

union Data {

int i;

float f;

char str[20];

};

int main() {

struct Student student1 = {1, "John Doe", 85.5};

printf("Student: ID=%d, Name=%s, Marks=%.2f\n", student1.id, student1.name,


student1.marks);

22
union Data data;

data.i = 10;

printf("Union Data: i=%d\n", data.i);

data.f = 220.5;

printf("Union Data: f=%.2f\n", data.f);

snprintf(data.str, sizeof(data.str), "Hello");

printf("Union Data: str=%s\n", data.str);

struct BitFieldExample example = {1, 5, 10};

printf("Bit Field: a=%d, b=%d, c=%d\n", example.a, example.b, example.c);

return 0;

```

**b) Explain how structures can be passed as parameters to functions, by value and by
reference? And how they can be returned from functions? (6)**

- **Passing by Value:** A copy of the structure is passed to the function. Changes inside the
function do not affect the original structure.

- **Passing by Reference:** The address of the structure is passed to the function. Changes
inside the function affect the original structure.

- **Returning from Functions:** Functions can return structures. Either a copy of the
structure or the address can be returned.

**Examples:**

```c

#include <stdio.h>

23
// Structure definition

struct Student {

int id;

char name[50];

};

// Function to modify structure by value

void modifyByValue(struct Student student) {

student.id = 2;

snprintf(student.name, sizeof(student.name), "Alice");

// Function to modify structure by reference

void modifyByReference(struct Student *student) {

student->id = 3;

snprintf(student->name, sizeof(student->name), "Bob");

// Function to return structure by value

struct Student createStudent() {

struct Student student = {4, "Eve"};

return student;

int main() {

24
struct Student student1 = {1, "John Doe"};

// Passing by value

modifyByValue(student1);

printf("By Value: ID=%d, Name=%s\n", student1.id, student1.name); // No change

// Passing by reference

modifyByReference(&student1);

printf("By Reference: ID=%d, Name=%s\n", student1.id, student1.name); // Modified

// Returning structure

struct Student student2 = createStudent();

printf("Returned: ID=%d, Name=%s\n", student2.id, student2.name); // New values

return 0;

```

**c) What do you understand by pointers to structures? How can we access the elements of a
structure through a pointer to the structure? (2.5)**

- **Pointers to Structures:** These are pointers that point to the address of a structure.

- **Accessing Elements:** Use the `->` operator to access elements of the structure through
the pointer.

**Example:**

```c

25
#include <stdio.h>

// Structure definition

struct Student {

int id;

char name[50];

};

int main() {

struct Student student = {1, "John Doe"};

struct Student *ptr = &student;

printf("Using Pointer: ID=%d, Name=%s\n", ptr->id, ptr->name);

return 0;

```

Alright, let's address the questions in detail one by one. Here are your questions:

### Q7

**a) Write a C program that creates and displays a text file on screen. (7.5)**

To create and display a text file, we need to use file handling functions in C such as `fopen()`,
`fprintf()`, `fclose()`, and `fread()`.

Here's a C program that accomplishes this:

26
```c

#include <stdio.h>

int main() {

FILE *file;

char filename[100] = "example.txt";

char ch;

// Create and write to the file

file = fopen(filename, "w");

if (file == NULL) {

printf("Error opening file!\n");

return 1;

fprintf(file, "Hello, this is a test file.\nIt contains multiple lines.\n");

fclose(file);

// Open and read the file

file = fopen(filename, "r");

if (file == NULL) {

printf("Error opening file!\n");

return 1;

27
// Display the contents of the file

while ((ch = fgetc(file)) != EOF) {

putchar(ch);

fclose(file);

return 0;

```

In this program:

- We first create a file named `example.txt` and write some text to it using `fprintf()`.

- We then reopen the file in read mode and read its contents using `fgetc()`, displaying each
character until the end of the file (`EOF`) is reached.

**b) Discuss the following file handling functions, through syntax and examples: (5)**

i) **`fopen()`**

```c

FILE *fopen(const char *filename, const char *mode);

```

- Opens a file with the specified mode (`"r"`, `"w"`, `"a"`, etc.).

- Example:

```c

FILE *file = fopen("example.txt", "r");

if (file == NULL) {

printf("Error opening file!\n");

28
}

```

ii) **`fclose()`**

```c

int fclose(FILE *stream);

```

- Closes an opened file.

- Example:

```c

fclose(file);

```

iii) **`fseek()`**

```c

int fseek(FILE *stream, long int offset, int whence);

```

- Sets the file position to a specific location.

- Example:

```c

fseek(file, 0, SEEK_SET); // Move to the beginning of the file

```

iv) **`fwrite()`**

```c

29
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

```

- Writes data from an array to a file.

- Example:

```c

int data[5] = {1, 2, 3, 4, 5};

fwrite(data, sizeof(int), 5, file);

```

v) **`fread()`**

```c

size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

```

- Reads data from a file into an array.

- Example:

```c

int buffer[5];

fread(buffer, sizeof(int), 5, file);

```

### UNIT IV

**Q8. a) Write a C program that counts the number of occurrences of a character in a given
string without the use of any string handling library functions. (7.5)**

Here's a C program to count the occurrences of a character in a string:

30
```c

#include <stdio.h>

int main() {

char str[100], ch;

int count = 0;

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

printf("Enter a character to count its occurrences: ");

scanf("%c", &ch);

for (int i = 0; str[i] != '\0'; i++) {

if (str[i] == ch) {

count++;

printf("The character '%c' occurs %d times in the string.\n", ch, count);

return 0;

```

31
**b) Explain any five string handling functions from string.h with syntax and example. (5)**

Here are five string handling functions from `string.h`:

1. **`strlen()`**: Returns the length of a string.

```c

size_t strlen(const char *str);

```

Example:

```c

char str[] = "Hello";

size_t len = strlen(str);

```

2. **`strcpy()`**: Copies a string to another.

```c

char *strcpy(char *dest, const char *src);

```

Example:

```c

char dest[20];

char src[] = "Hello";

strcpy(dest, src);

```

32
3. **`strcmp()`**: Compares two strings.

```c

int strcmp(const char *str1, const char *str2);

```

Example:

```c

char str1[] = "Hello";

char str2[] = "World";

int result = strcmp(str1, str2);

```

4. **`strcat()`**: Concatenates two strings.

```c

char *strcat(char *dest, const char *src);

```

Example:

```c

char dest[20] = "Hello";

char src[] = " World";

strcat(dest, src);

```

5. **`strstr()`**: Finds the first occurrence of a substring.

```c

char *strstr(const char *haystack, const char *needle);

33
```

Example:

```c

char str[] = "Hello World";

char sub[] = "World";

char *pos = strstr(str, sub);

```

### Q9

**a) Write a short note on header files. (2.5)**

Header files in C and C++ contain definitions of functions, macros, constants, and data types.
They are included in source files using the `#include` directive. Header files promote code
reusability by allowing shared declarations across multiple source files, facilitating modular
programming. Standard header files, like `stdio.h`, `math.h`, and `stdlib.h`, provide access to
standard library functions.

**b) Explain any two functions each from the following header files: (10)**

- **`stdio.h`**:

1. `printf()` - Prints formatted output to the console.

```c

int printf(const char *format, ...);

```

Example:

```c

34
printf("Hello, World!\n");

```

2. `scanf()` - Reads formatted input from the console.

```c

int scanf(const char *format, ...);

```

Example:

```c

int x;

scanf("%d", &x);

```

- **`math.h`**:

1. `sqrt()` - Computes the square root of a number.

```c

double sqrt(double x);

```

Example:

```c

double result = sqrt(16.0);

```

2. `pow()` - Computes the power of a number.

```c

double pow(double base, double exponent);

```

35
Example:

```c

double result = pow(2, 3); // 2^3 = 8

```

- **`stdlib.h`**:

1. `malloc()` - Allocates memory dynamically.

```c

void *malloc(size_t size);

```

Example:

```c

int *ptr = (int *)malloc(10 * sizeof(int));

```

2. `free()` - Frees dynamically allocated memory.

```c

void free(void *ptr);

```

Example:

```c

free(ptr);

```

- **`ctype.h`**:

1. `isdigit()` - Checks if a character is a digit.

36
```c

int isdigit(int c);

```

Example:

```c

if (isdigit('5')) {

printf("It's a digit\n");

```

2. `toupper()` - Converts a character to uppercase.

```c

int toupper(int c);

```

Example:

```c

char c = toupper('a'); // 'A'

```

- **`string.h`**:

1. `strcpy()` - Copies a string to another.

```c

char *strcpy(char *dest, const char *src);

```

Example:

```c

37
char dest[20];

char src[] = "Hello";

strcpy(dest, src);

```

2. `strlen()` - Returns the length of a string.

```c

size_t strlen(const char *str);

```

Example:

```c

size_t len = strlen("Hello");

2018
a) What do you mean by pre-increment and post-increment operator? Explain with an
example.

- **Pre-increment (`++x`):** The value of `x` is incremented by 1, and then the updated
value of `x` is used in the expression.

- **Post-increment (`x++`):** The current value of `x` is used in the expression, and then `x`
is incremented by 1.

**Example:**

```c

#include <stdio.h>

int main() {

int x = 5;

38
printf("Pre-increment: %d\n", ++x); // Output: 6

x = 5;

printf("Post-increment: %d\n", x++); // Output: 5

printf("Value after post-increment: %d\n", x); // Output: 6

return 0;

```

**b) Differentiate between structure and union. Explain the use of `extern` keyword.**

- **Structure:** Allows grouping of variables of different data types. Each member has its
own memory location.

- **Union:** Similar to a structure, but all members share the same memory location. Only
one member can hold a value at a time.

**Example:**

```c

#include <stdio.h>

struct ExampleStruct {

int a;

float b;

};

union ExampleUnion {

int a;

39
float b;

};

int main() {

struct ExampleStruct s;

union ExampleUnion u;

printf("Size of structure: %lu\n", sizeof(s)); // Sum of sizes of all members

printf("Size of union: %lu\n", sizeof(u)); // Size of the largest member

return 0;

```

**`extern` keyword:** Used to declare a global variable or function in another file. It tells the
compiler that the variable or function is defined elsewhere.

**Example:**

```c

// file1.c

#include <stdio.h>

extern int x; // Declaration of an external variable

void printX() {

printf("x = %d\n", x);

// file2.c

int x = 10; // Definition of the external variable

40
int main() {

printX();

return 0;

```

**c) Explain the concept of a pointer? Define dynamic memory allocation and its various
functions.**

- **Pointer:** A variable that stores the memory address of another variable. Pointers
provide direct access to memory and facilitate dynamic memory management.

**Example:**

```c

#include <stdio.h>

int main() {

int x = 10;

int *ptr = &x; // Pointer to x

printf("Value of x: %d\n", x); // Output: 10

printf("Address of x: %p\n", ptr); // Output: Address of x

printf("Value pointed by ptr: %d\n", *ptr); // Output: 10

return 0;

```

41
- **Dynamic Memory Allocation:**

- **`malloc()`:** Allocates memory blocks and returns a pointer to the beginning.

- **`calloc()`:** Allocates memory for an array and initializes all elements to zero.

- **`realloc()`:** Changes the size of previously allocated memory.

- **`free()`:** Deallocates previously allocated memory.

**Example:**

```c

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr;

ptr = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers

if (ptr == NULL) {

printf("Memory allocation failed\n");

return 1;

for (int i = 0; i < 5; i++) {

ptr[i] = i * 2;

for (int i = 0; i < 5; i++) {

printf("%d ", ptr[i]);

42
printf("\n");

free(ptr); // Deallocate memory

return 0;

```

**d) Differentiate between static and register storage class in C language.**

- **Static:**

- Variables retain their value between function calls.

- Scope is limited to the block where they are defined.

- Initialized only once.

**Example:**

```c

#include <stdio.h>

void func() {

static int count = 0; // Static variable

count++;

printf("Count: %d\n", count);

int main() {

for (int i = 0; i < 5; i++) {

43
func();

return 0;

```

- **Register:**

- Stored in the CPU register for faster access.

- Limited scope to the block where they are defined.

- Cannot take the address of register variables.

**Example:**

```c

#include <stdio.h>

int main() {

register int i;

for (i = 0; i < 5; i++) {

printf("%d\n", i);

return 0;

```

**e) What is a string? Write a program for the concatenation of two strings.**

44
- **String:** A sequence of characters terminated by a null character (`'\0'`).

**Example of String Concatenation:**

```c

#include <stdio.h>

int main() {

char str1[100] = "Hello, ";

char str2[] = "World!";

int i = 0, j = 0;

// Concatenate str2 to str1

while (str1[i] != '\0') {

i++;

while (str2[j] != '\0') {

str1[i] = str2[j];

i++;

j++;

str1[i] = '\0'; // Null-terminate the concatenated string

printf("Concatenated String: %s\n", str1);

return 0;

45
}

```

**f) What are preprocessor directives? From which symbol do they start?**

- **Preprocessor Directives:** Commands that are processed by the preprocessor before the
actual compilation of code begins. They provide instructions for the compiler to preprocess
the information before actual compilation starts.

**Symbol:** Preprocessor directives begin with the `#` symbol.

**Examples:**

- **`#include`**: Includes a header file.

- **`#define`**: Defines a macro.

- **`#ifndef`**: Checks if a macro is not defined.

### UNIT-I

**Q2**

**a) Explain the while loop and do-while loop with an example. Elaborate the difference
between them. (4.5)**

- **While Loop:**

- A control flow statement that repeats a block of code as long as the condition is true.

- The condition is evaluated before the execution of the loop's body.

**Example:**

46
```c

#include <stdio.h>

int main() {

int i = 0;

while (i < 5) {

printf("%d\n", i);

i++;

return 0;

```

- **Do-While Loop:**

- Similar to the while loop, but the condition is evaluated after the execution of the loop's
body.

- Ensures the loop is executed at least once.

**Example:**

```c

#include <stdio.h>

int main() {

int i = 0;

do {

printf("%d\n", i);

47
i++;

} while (i < 5);

return 0;

```

**Difference:**

- **While Loop:** Checks the condition before executing the loop body. May not execute if
the condition is false initially.

- **Do-While Loop:** Executes the loop body at least once and then checks the condition.

**b) Write a program to find the largest number among the three numbers. (8)**

```c

#include <stdio.h>

int main() {

int num1, num2, num3;

printf("Enter three numbers: ");

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

if (num1 >= num2 && num1 >= num3) {

printf("Largest number is %d\n", num1);

} else if (num2 >= num1 && num2 >= num3) {

printf("Largest number is %d\n", num2);

48
} else {

printf("Largest number is %d\n", num3);

return 0;

```

### Q3

**a) Explain the Switch statement, Break statement, and Continue statement with an
example. (6)**

- **Switch Statement:**

- A control statement that allows a variable to be tested for equality against a list of values.

- Each value is called a case, and the variable being switched on is checked for each case.

**Example:**

```c

#include <stdio.h>

int main() {

int day = 4;

switch (day) {

case 1:

printf("Monday\n");

49
break;

case 2:

printf("Tuesday\n");

break;

case 3:

printf("Wednesday\n");

break;

case 4:

printf("Thursday\n");

break;

case 5:

printf("Friday\n");

break;

default:

printf("Weekend\n");

return 0;

Here's a detailed breakdown of the answers for the questions listed in the image:

UNIT-III

(a) Explain the concept of structure. Write a C program to store the


information (name, roll, branch, dept., and marks) of 10 students using
structures. Find who has topped in the class.

Explanation of Structure

50
In C programming, a structure is a user-defined data type that allows grouping different
types of variables under one name. This is particularly useful for storing and managing
information related to complex entities like students, employees, etc.

A structure is defined using the struct keyword and can hold members of various data types.
The syntax is:

struct StructureName {
data_type member1;
data_type member2;
...
};

Program

Here is the full program to solve the problem:

#include <stdio.h>
#include <string.h>

struct Student {
char name[50];
int roll;
char branch[50];
char dept[50];
float marks;
};

int main() {
struct Student students[10];
int i, topper_index = 0;
float max_marks = 0.0;

// Input information of 10 students


printf("Enter information of 10 students:\n");
for (i = 0; i < 10; i++) {
printf("\nStudent %d\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", students[i].name);
printf("Roll number: ");
scanf("%d", &students[i].roll);
printf("Branch: ");
scanf(" %[^\n]", students[i].branch);
printf("Department: ");
scanf(" %[^\n]", students[i].dept);
printf("Marks: ");
scanf("%f", &students[i].marks);

// Finding topper
if (students[i].marks > max_marks) {
max_marks = students[i].marks;
topper_index = i;
}
}

// Output the topper's information


printf("\nThe topper is:\n");
printf("Name: %s\n", students[topper_index].name);

51
printf("Roll Number: %d\n", students[topper_index].roll);
printf("Branch: %s\n", students[topper_index].branch);
printf("Department: %s\n", students[topper_index].dept);
printf("Marks: %.2f\n", students[topper_index].marks);

return 0;
}

Explanation of Code

1. Structure Definition: The struct Student groups all student details (name, roll, branch,
dept., and marks).
2. Input Loop: The program takes inputs for 10 students using a for loop.
3. Finding Topper: The maximum marks are tracked, and the index of the student with the
highest marks is updated.
4. Output: Finally, the program displays the details of the student who topped the class.

(b) Write a short note on each

(i) How to pass a structure to a function?

Structures in C can be passed to functions in two ways:

1. Pass by Value: A copy of the structure is passed, and any changes inside the function do not
affect the original structure.
2. void display(struct Student s) {
3. printf("Name: %s", s.name);
4. }
5. Pass by Reference: The address of the structure is passed using a pointer, and changes made
inside the function reflect in the original structure.
6. void display(struct Student *s) {
7. printf("Name: %s", s->name);
8. }

(ii) Bit fields

Bit fields are used within structures to allocate a specific number of bits to a field, optimizing
memory usage.
Example:

struct Example {
unsigned int a : 2; // 'a' uses 2 bits
unsigned int b : 4; // 'b' uses 4 bits
};

Here, a can store values from 0-3, and b can store values from 0-15.

(iii) Automatic storage classes

Automatic storage classes in C are those variables declared within a function. They have:

52
 Scope: Local to the function.
 Lifetime: Created when the function is called, destroyed when the function exits.
 Keyword: auto (default for local variables).

Example:

void function() {
auto int x = 10; // Automatic variable
}

(iv) File handling

File handling in C allows data to be stored in files permanently. The common file operations
are:

1. Opening a File: Use fopen() to open files in modes like "r", "w", "a".
2. Reading/Writing: Use functions like fprintf(), fscanf(), fread(), and fwrite().
3. Closing the File: Use fclose() to release resources.
Example:

FILE *fp = fopen("data.txt", "w");


fprintf(fp, "Hello, File!");
fclose(fp);

UNIT-IV

(a) Write a program to compare two strings where they are identical or not.

Program:

#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100];

printf("Enter first string: ");


scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);

if (strcmp(str1, str2) == 0)
printf("Strings are identical.\n");
else
printf("Strings are not identical.\n");

return 0;
}

Explanation:

 The strcmp() function compares two strings. If they are equal, it returns 0.

53
(b) Explain the following inbuilt functions.

1. strlen(): Returns the length of a string.


2. int len = strlen("hello"); // len = 5

3. strcat(): Concatenates two strings.


4. char str1[20] = "hello";
5. strcat(str1, " world");
6. printf("%s", str1); // Output: "hello world"

7. strlwr(): Converts a string to lowercase.


8. char str[] = "HELLO";
9. strlwr(str); // str = "hello"

10. strupr(): Converts a string to uppercase.


11. char str[] = "hello";
12. strupr(str); // str = "HELLO"

(a) Write a program to find the largest and smallest word in a string.

Program:

#include <stdio.h>
#include <string.h>

int main() {
char str[200], word[20], smallest[20], largest[20];
int i = 0, j = 0, len;

printf("Enter a sentence: ");


gets(str);

while (str[i] != '\0') {


if (str[i] == ' ' || str[i] == '\0') {
word[j] = '\0';
len = strlen(word);
if (strlen(smallest) == 0 || len < strlen(smallest))
strcpy(smallest, word);
if (len > strlen(largest))
strcpy(largest, word);
j = 0;
} else {
word[j++] = str[i];
}
i++;
}

printf("Smallest word: %s\n", smallest);


printf("Largest word: %s\n", largest);

return 0;
}

54
(b) Explain the following header files.

1. stdlib.h: Contains functions like malloc, calloc, free, atoi, and exit.
2. ctype.h: Contains character handling functions like isalpha(), isdigit().
3. math.h: Contains mathematical functions like sqrt(), pow(), ceil(), floor().
4. process.h: Contains functions for process management like exit() and system().

2017
Here are detailed answers for each question in the provided image:

Q1: Short Questions (2.5 × 10 = 25)

(a) What are the keywords in C? Give examples.

Keywords are reserved words in C programming that have special meanings. They cannot be
used as identifiers (variable names, function names, etc.).
Examples: int, float, return, if, else, while, for, break, void, sizeof, etc.

(b) Explain various bitwise operators available in C.

Bitwise operators work on individual bits of integer values. The following are the bitwise
operators:

1. AND (&): Performs bitwise AND.


Example: 5 & 3 → 0101 & 0011 → 0001 (Result = 1).
2. OR (|): Performs bitwise OR.
Example: 5 | 3 → 0101 | 0011 → 0111 (Result = 7).
3. XOR (^): Performs bitwise exclusive OR.
Example: 5 ^ 3 → 0101 ^ 0011 → 0110 (Result = 6).
4. NOT (~): Performs bitwise NOT (complement).
Example: ~5 → ~0101 → 1010 (Result = -6).
5. Left Shift (<<): Shifts bits to the left.
Example: 5 << 1 → 0101 << 1 → 1010 (Result = 10).
6. Right Shift (>>): Shifts bits to the right.
Example: 5 >> 1 → 0101 >> 1 → 0010 (Result = 2).

(c) What is the function of break and continue statement in C?

55
1. break: Terminates the nearest loop or switch statement and transfers control outside.
Example:
2. for (int i = 0; i < 5; i++) {
3. if (i == 3) break;
4. printf("%d ", i);
5. } // Output: 0 1 2
6. continue: Skips the remaining part of the loop for the current iteration and proceeds to
the next iteration.
Example:
7. for (int i = 0; i < 5; i++) {
8. if (i == 2) continue;
9. printf("%d ", i);
10. } // Output: 0 1 3 4

(d) Briefly explain the concept of recursion.

Recursion is a process where a function calls itself directly or indirectly. It is used to solve
problems that can be broken into smaller, similar subproblems.
Example (Factorial of a number):

int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}

(e) What are macros in C?

Macros are preprocessor directives in C used to define constant values or replace code
fragments. They are defined using the #define directive.
Example:

#define PI 3.14
#define SQUARE(x) ((x) * (x))
printf("Area: %.2f", PI * SQUARE(5)); // Output: Area: 78.50

(f) Differentiate between function declaration and function definition.

 Function Declaration: Tells the compiler about the function name, return type, and
parameters. It ends with a semicolon.
Example: int add(int, int);
 Function Definition: Contains the actual body of the function.
Example:
 int add(int a, int b) {
 return a + b;
 }

(g) Name functions of standard library ctype.h.

56
Functions in ctype.h are used for character handling.
Examples:

1. isalpha(): Checks if a character is an alphabet.


2. isdigit(): Checks if a character is a digit.
3. isalnum(): Checks if a character is alphanumeric.
4. toupper(): Converts a character to uppercase.
5. tolower(): Converts a character to lowercase.

(h) What are nested control statements? Give examples.

Nested control statements are control structures (if, while, for) placed inside other control
structures.
Example:

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 2; j++) {
printf("%d %d\n", i, j);
}
}

(i) What is the need of pre-processor directives in C?

Pre-processor directives are used for:

1. Including header files (#include).


2. Defining macros (#define).
3. Conditional compilation (#ifdef).
4. Improving code readability and reusability.

(j) Differentiate between post-increment and pre-increment operator with


example.

1. Pre-increment (++i): Increments the value first, then uses it.


2. int i = 5;
3. printf("%d", ++i); // Output: 6
4. Post-increment (i++): Uses the value first, then increments it.
5. int i = 5;
6. printf("%d", i++); // Output: 5

Q2: (a) Explain loop statements in C.

C supports three types of loops:

1. For Loop:

57
2. for (int i = 0; i < 5; i++) { printf("%d ", i); }
3. While Loop:
4. int i = 0;
5. while (i < 5) { printf("%d ", i); i++; }
6. Do-While Loop: Executes at least once.
7. int i = 0;
8. do { printf("%d ", i); i++; } while (i < 5);

Q2(b): What are different types of operators in C?

1. Arithmetic Operators (+, -, *, /, %).


2. Relational Operators (==, !=, >, <, >=, <=).
3. Logical Operators (&&, ||, !).
4. Bitwise Operators (&, |, ^, ~, <<, >>).
5. Assignment Operators (=, +=, -=, etc.).
6. Increment/Decrement (++, --).
7. Ternary Operator (? :).

Q3 (a): What is an array? Write a program to print the average of all


elements of an array.

An array is a collection of elements of the same data type stored in contiguous memory.

Program:

#include <stdio.h>
int main() {
int arr[5], i, sum = 0;
float avg;
printf("Enter 5 elements: ");
for (i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
avg = sum / 5.0;
printf("Average = %.2f", avg);
return 0;

Q4 (a): With the help of a program, explain the concept of call by value and
call by reference.

Call by Value: A copy of the variable is passed to the function. Changes made in the
function do not affect the original variable.
Call by Reference: The address of the variable is passed, and changes made in the function
affect the original variable.

58
Program:
#include <stdio.h>

// Call by value
void callByValue(int a) {
a = a + 10;
printf("Inside Call by Value: %d\n", a);
}

// Call by reference
void callByReference(int *a) {
*a = *a + 10;
printf("Inside Call by Reference: %d\n", *a);
}

int main() {
int x = 20;
printf("Original Value: %d\n", x);

// Call by value
callByValue(x);
printf("After Call by Value: %d\n", x);

// Call by reference
callByReference(&x);
printf("After Call by Reference: %d\n", x);

return 0;
}

Output:
Original Value: 20
Inside Call by Value: 30
After Call by Value: 20
Inside Call by Reference: 30
After Call by Reference: 30

Q4 (b): Define the following terms:

1. Static Variables:
Static variables retain their value between function calls. They are initialized only
once.
Example:
2. void demo() {
3. static int count = 0;
4. count++;
5. printf("%d ", count);
6. }
7. int main() {
8. demo(); demo(); demo();
9. return 0;
10. }
11. // Output: 1 2 3

59
12. Pointers:
Pointers store the address of another variable.
Example:
13. int x = 10;
14. int *ptr = &x;
15. printf("Value: %d, Address: %p", *ptr, ptr);

16. Dynamic Memory Allocation:


Allocating memory during runtime using functions like malloc(), calloc(), and
free().

Q5 (a): Explain the concept of recursion by writing a program to find


factorial of any given number.

Program:

#include <stdio.h>

int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}

Output:
For input 5:

Factorial of 5 is 120

Q5 (b): How array of pointers are passed as arguments in a function. Give


an example.

Arrays of pointers can be passed to a function as arguments by passing their address.

Program:

#include <stdio.h>

void printStrings(char *arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%s\n", arr[i]);
}
}

60
int main() {
char *arr[] = {"Hello", "World", "C Programming"};
int size = 3;
printStrings(arr, size);
return 0;
}

Output:

Hello
World
C Programming

Q6 (a): Explain the concept and need of structures in C. How is union


different from structure?

Structures:

Structures in C are used to group variables of different data types under one name.
Example:

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

Need of Structures:

 To organize complex data logically.


 To handle real-world data like student records, employee details, etc.

Difference between Structure and Union:

Structure Union

Allocates memory for all members separately. Allocates memory shared by all members.

All members can be accessed simultaneously. Only one member can be accessed at a time.

Example: struct Student. Example: union Data.

Q6 (b): What is file handling? What are various functions used in file
handling? Briefly explain.

File Handling: File handling allows programs to store and retrieve data to/from files.

Functions in File Handling:

61
1. fopen(): Opens a file.
Syntax: FILE *fopen(const char *filename, const char *mode);
2. fprintf()/fscanf(): Writes/Reads formatted data.
3. fread()/fwrite(): Reads/Writes binary data.
4. fclose(): Closes an open file.
5. fseek(): Moves the file pointer to a specific position.

Q7: What is file pointer? Write a program to create a file, write string data
into it, and count number of characters in that file.

File Pointer: A pointer of type FILE * that is used to handle files.

Program:

#include <stdio.h>
#include <string.h>

int main() {
FILE *fp;
char str[100];
int count = 0;

fp = fopen("test.txt", "w");
if (fp == NULL) {
printf("File cannot be opened.\n");
return 1;
}

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);
fputs(str, fp);
fclose(fp);

fp = fopen("test.txt", "r");
while (fgetc(fp) != EOF) count++;
fclose(fp);

printf("Number of characters in the file: %d", count);


return 0;
}

Q8 (a): What is array of strings? Describe various string manipulation


functions with example.

Array of Strings:

An array where each element is a string.


Example:

char *arr[] = {"C", "Programming", "Language"};

62
String Manipulation Functions:

1. strlen(): Returns string length.


2. strcpy(): Copies one string to another.
3. strcat(): Concatenates two strings.
4. strcmp(): Compares two strings.

Q8 (b): What are standard libraries in C? Give examples of functions in


libraries stdio.h, math.h, and string.h.

1. stdio.h: Standard Input/Output library.


o printf(), scanf(), fgets(), fputs().

2. math.h: Mathematical functions.


o sqrt(), pow(), fabs().

3. string.h: String handling functions.


o strlen(), strcpy(), strcat(), strcmp().

Q9: Write a program to first compare and then concatenate two strings
entered by user.

Program:

#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100];

printf("Enter first string: ");


gets(str1);
printf("Enter second string: ");
gets(str2);

if (strcmp(str1, str2) == 0)
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");

strcat(str1, str2);
printf("Concatenated string: %s", str1);

return 0;
}

Output:

Enter first string: Hello

63
Enter second string: World
Strings are not equal.
Concatenated string: HelloWorld

Let me know if you need further clarification! 😊

2016
Here are detailed answers for all the questions from the provided image:

Q1 (a): What is ternary operator? Write a program to find smallest among 3


numbers using ternary operator.

Ternary Operator:

The ternary operator is a shorthand for the if-else statement. Its syntax is:

(condition) ? expression_if_true : expression_if_false;

Program to find the smallest of 3 numbers:


#include <stdio.h>

int main() {
int a, b, c, smallest;

printf("Enter three numbers: ");


scanf("%d %d %d", &a, &b, &c);

smallest = (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);

printf("The smallest number is: %d", smallest);


return 0;
}

Output Example:

Enter three numbers: 5 8 2


The smallest number is: 2

64
Q1 (b): What are Bitwise operators?

Bitwise operators perform operations on individual bits of integers.

 & (AND): Bitwise AND


 | (OR): Bitwise OR
 ^ (XOR): Bitwise XOR
 ~ (NOT): Bitwise NOT
 << (Left Shift): Shifts bits to the left
 >> (Right Shift): Shifts bits to the right

Example:

#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("a & b = %d\n", a & b); // AND
printf("a | b = %d\n", a | b); // OR
printf("a ^ b = %d\n", a ^ b); // XOR
printf("~a = %d\n", ~a); // NOT
printf("a << 1 = %d\n", a << 1); // Left shift
printf("a >> 1 = %d\n", a >> 1); // Right shift
return 0;
}

Q1 (c): What are the basic data types and their associated range?

The basic data types in C are:

Data Type Size (bytes) Range

char 1 -128 to 127

int 4 -2,147,483,648 to 2,147,483,647

float 4 1.2E-38 to 3.4E+38

double 8 2.3E-308 to 1.7E+308

short 2 -32,768 to 32,767

long 4 or 8 -2,147,483,648 to 2,147,483,647

unsigned int 4 0 to 4,294,967,295

65
Q1 (d): Differentiate between exit controlled loop and entry controlled
loop.
Entry Controlled Loop Exit Controlled Loop

Condition is checked before the loop begins. Condition is checked after one iteration.

Example: for, while loops. Example: do-while loop.

If condition is false initially, the loop will not Executes at least once regardless of the
execute. condition.

Q1 (e): Differentiate between break and continue.


Break Continue

Terminates the loop entirely. Skips the current iteration and continues the loop.

Example: break; exits the loop. Example: continue; skips to next iteration.

Example:

#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // Terminates loop
printf("%d ", i);
}

for (int i = 1; i <= 5; i++) {


if (i == 3) continue; // Skips iteration
printf("%d ", i);
}
return 0;
}

Q2 (a): List the different types of loop control statements and explain them
with examples.

1. For loop:
Syntax: for (initialization; condition; increment/decrement) { ... }
Example:
2. for (int i = 1; i <= 5; i++) {
3. printf("%d ", i);
4. }

5. While loop:
Syntax: while (condition) { ... }
Example:
6. int i = 1;

66
7. while (i <= 5) {
8. printf("%d ", i);
9. i++;
10. }

11. Do-while loop:


Syntax:
12. do {
13. ...
14. } while (condition);

Example:

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);

Q2 (b): Write a program to display the following pattern as output.

Pattern:

a
a b
a b c
a b c d
a b c d e

Program:
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
for (char ch = 'a'; ch < 'a' + i; ch++) {
printf("%c ", ch);
}
printf("\n");
}
return 0;
}

Q3 (a): Write a program to reverse a given integer number.

Program:

#include <stdio.h>

int main() {
int num, reversed = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &num);

67
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}

printf("Reversed number: %d", reversed);


return 0;
}

Q3 (b): What is the difference between pass by reference and pass by value?
Pass by Value Pass by Reference

Copies the value of the variable. Passes the address of the variable.

Changes do not affect original. Changes affect the original.

Example:

#include <stdio.h>

// Pass by value
void valueExample(int a) { a = a + 5; }

// Pass by reference
void referenceExample(int *a) { *a = *a + 5; }

int main() {
int x = 10;

valueExample(x);
printf("After pass by value: %d\n", x);

referenceExample(&x);
printf("After pass by reference: %d\n", x);
return 0;
}

Here are the answers to the remaining questions (Q4 to Q6):

Q4 (a): Explain the concept of static variable with the help of a suitable
example.

Static Variable:

A static variable in C retains its value between function calls. It is initialized only once and
maintains its state.

Example:

68
#include <stdio.h>

void demo() {
static int count = 0; // Static variable
count++;
printf("Count = %d\n", count);
}

int main() {
demo();
demo();
demo();
return 0;
}

Output:

Count = 1
Count = 2
Count = 3

Explanation:

 The variable count retains its value across multiple calls to the demo function.

Q4 (b): Differentiate between getc(), getch(), getche(), and gets().


Function Description Example

getc() Reads a single character from a file or input stream. getc(stdin)

getch() Reads a character without echoing it to the console. char c = getch();

getche() Reads a character and echoes it to the console. char c = getche();

gets() Reads an entire string until a newline is encountered. char str[20]; gets(str);

Example Program:
#include <stdio.h>
#include <conio.h>

int main() {
char c1, c2, c3;

printf("Enter character using getc: ");


c1 = getc(stdin);

printf("Enter character using getch: ");


c2 = getch(); // does not display input
printf("\n");

printf("Enter character using getche: ");


c3 = getche(); // displays input

69
printf("\n");

printf("getc: %c, getch: %c, getche: %c\n", c1, c2, c3);

return 0;
}

Q4 (c): Write a program to copy one string into another string without
using inbuilt function.

Program:
#include <stdio.h>

void copyString(char *source, char *destination) {


while (*source != '\0') {
*destination = *source;
source++;
destination++;
}
*destination = '\0'; // Add null terminator
}

int main() {
char source[100], destination[100];

printf("Enter the source string: ");


gets(source); // Input string

copyString(source, destination);

printf("Copied string: %s\n", destination);


return 0;
}

Q5 (a): Explain all storage classes in C with suitable examples.

Storage Classes in C:

1. Automatic (auto): Default storage class for local variables.


2. void demo() {
3. auto int x = 10; // auto keyword (optional)
4. printf("x = %d", x);
5. }

6. Register: Stores variables in CPU registers for faster access.


7. void demo() {
8. register int i = 0;
9. printf("Register variable: %d", i);
10. }

11. Static: Retains the value of a variable between function calls.


12. void demo() {
13. static int count = 0;

70
14. count++;
15. printf("Count = %d\n", count);
16. }

17. Extern: Declares a global variable defined in another file.


18. extern int x; // Declared in another file

Q5 (b): Differentiate between pointer to an array and array of pointers with


suitable examples.

Pointer to an Array:

 A pointer that points to an entire array.

#include <stdio.h>

int main() {
int arr[3] = {1, 2, 3};
int (*p)[3] = &arr; // Pointer to array

printf("First element: %d\n", (*p)[0]);


return 0;
}

Array of Pointers:

 An array where each element is a pointer to another variable.

#include <stdio.h>

int main() {
int a = 1, b = 2, c = 3;
int *arr[3] = {&a, &b, &c}; // Array of pointers

printf("First element: %d\n", *arr[0]);


return 0;
}

Q6 (a): What is recursion? Write a program to calculate XY using recursion


(where X and Y are entered by the user).

Recursion:

Recursion is a function calling itself to solve smaller instances of a problem.

Program to calculate XY using recursion:


#include <stdio.h>

int power(int x, int y) {


if (y == 0)

71
return 1; // Base case
return x * power(x, y - 1); // Recursive case
}

int main() {
int x, y;

printf("Enter base (X): ");


scanf("%d", &x);

printf("Enter exponent (Y): ");


scanf("%d", &y);

printf("%d^%d = %d\n", x, y, power(x, y));


return 0;
}

Output Example:
Enter base (X): 2
Enter exponent (Y): 3
2^3 = 8

Alright, let's break down and answer each question in detail based on the transcription of the
image you provided.

### Q6

#### a) What is pointer arithmetic? Explain with suitable examples. (6.5)

**Pointer arithmetic** refers to the operations that can be performed on pointers. These
operations include addition, subtraction, and comparison. Pointer arithmetic is useful for
accessing array elements and traversing memory locations.

1. **Pointer Addition:**

When you add an integer to a pointer, you are actually moving the pointer by a number of
elements, not bytes. The size of the elements depends on the data type the pointer is pointing
to.

**Example:**

72
```c

#include <stdio.h>

int main() {

int arr[] = {10, 20, 30, 40, 50};

int *ptr = arr;

for (int i = 0; i < 5; i++) {

printf("Value at arr[%d] = %d\n", i, *(ptr + i));

return 0;

```

2. **Pointer Subtraction:**

When you subtract an integer from a pointer, you move the pointer backwards by a number
of elements.

**Example:**

```c

#include <stdio.h>

int main() {

int arr[] = {10, 20, 30, 40, 50};

int *ptr = &arr[4];

73
for (int i = 4; i >= 0; i--) {

printf("Value at arr[%d] = %d\n", i, *(ptr - i));

return 0;

```

3. **Pointer Difference:**

You can subtract two pointers to find the number of elements between them.

**Example:**

```c

#include <stdio.h>

int main() {

int arr[] = {10, 20, 30, 40, 50};

int *ptr1 = &arr[0];

int *ptr2 = &arr[4];

printf("Number of elements between ptr1 and ptr2 = %ld\n", ptr2 - ptr1);

return 0;

```

### Q7

74
Explain the following with suitable examples:

#### a) Nested Structure

A nested structure is a structure that contains another structure as a member.

**Example:**

```c

#include <stdio.h>

struct Address {

char city[30];

int pin;

};

struct Employee {

char name[30];

struct Address address;

};

int main() {

struct Employee emp = {"John Doe", {"New York", 10001}};

printf("Name: %s\nCity: %s\nPIN: %d\n", emp.name, emp.address.city, emp.address.pin);

return 0;

75
```

#### b) Arrays within Structure

Structures can have arrays as their members.

**Example:**

```c

#include <stdio.h>

struct Student {

char name[30];

int marks[5];

};

int main() {

struct Student student = {"Alice", {85, 90, 78, 92, 88}};

printf("Name: %s\n", student.name);

printf("Marks: ");

for (int i = 0; i < 5; i++) {

printf("%d ", student.marks[i]);

printf("\n");

return 0;

76
```

#### c) Structure as function parameter

Structures can be passed to functions by value or by reference.

**Example:**

```c

#include <stdio.h>

struct Point {

int x;

int y;

};

void printPoint(struct Point p) {

printf("Point: (%d, %d)\n", p.x, p.y);

int main() {

struct Point pt = {10, 20};

printPoint(pt);

return 0;

```

77
### Q8

#### a) What are header files? Give the format of any three library functions for each of
these header files: ctype.h, stdio.h, math.h (6)

**Header files** contain definitions of functions and macros that can be shared among
multiple source files. They allow for modular programming by separating declarations from
implementations.

**Examples:**

- `ctype.h` (Character handling functions):

- `int isalpha(int c);` - Checks if a character is alphabetic.

- `int isdigit(int c);` - Checks if a character is a digit.

- `int toupper(int c);` - Converts a character to uppercase.

- `stdio.h` (Standard input/output functions):

- `int printf(const char *format, ...);` - Prints formatted output to stdout.

- `int scanf(const char *format, ...);` - Reads formatted input from stdin.

- `FILE *fopen(const char *filename, const char *mode);` - Opens a file.

- `math.h` (Mathematical functions):

- `double sqrt(double x);` - Computes the square root of x.

- `double pow(double base, double exp);` - Computes the power of base raised to exp.

- `double sin(double x);` - Computes the sine of x.

b) What is preprocessor directive? Explain different preprocessor directives with examples.


(6.5)

78
Preprocessor directives are instructions that are processed by the preprocessor before the
actual compilation begins. They provide macros, include files, and conditional compilation.

Examples:

- `#include` - Includes the contents of a file.

```c

#include <stdio.h>

```

- `#define` - Defines a macro.

```c

#define PI 3.14159

```

- `#ifdef` and `#ifndef` - Conditional compilation.

```c

#ifdef DEBUG

printf("Debug mode\n");

#endif

```

- `#undef` - Undefines a macro.

```c

#undef PI

```

79
- `#pragma` - Provides special commands to the compiler.

```c

#pragma pack(1)

```

### Q9

**a) What is file pointer? Write a program in C that writes 10 integers in `data.txt` file and
copies them into `duplicate.txt` file. (12.5)**

A **file pointer** is a pointer to a structure of type `FILE` that is used to control file
operations. It is obtained by opening a file using functions like `fopen()`.

**Example Program:**

```c

#include <stdio.h>

int main() {

FILE *dataFile, *duplicateFile;

int numbers[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Writing to data.txt

dataFile = fopen("data.txt", "w");

if (dataFile == NULL) {

printf("Error opening data.txt\n");

return 1;

80
}

for (int i = 0; i < 10; i++) {

fprintf(dataFile, "%d\n", numbers[i]);

fclose(dataFile);

// Copying to duplicate.txt

dataFile = fopen("data.txt", "r");

if (dataFile == NULL) {

printf("Error opening data.txt\n");

return 1;

duplicateFile = fopen("duplicate.txt", "w");

if (duplicateFile == NULL) {

printf("Error opening duplicate.txt\n");

fclose(dataFile);

return 1;

int number;

while (fscanf(dataFile, "%d", &number) != EOF) {

fprintf(duplicateFile, "%d\n", number);

fclose(dataFile);

81
fclose(duplicateFile);

printf("Data successfully copied to duplicate.txt\n");

return 0;

82

You might also like