C Answers
C Answers
Syntax:
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
1
o ptr = (cast-type*) realloc(ptr, new_size);
4. free():
o Frees dynamically allocated memory to avoid memory leaks.
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.
Example:
#include <stdio.h>
int main() {
void (*func_ptr[2])(int, int); // Array of pointers to functions
func_ptr[0] = add;
func_ptr[1] = subtract;
return 0;
}
2
Feature Formatted I/O Unformatted I/O
Flexibility Highly flexible Less flexible
Example printf("%d", x); putchar(ch);
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 };
Example:
struct Student {
int id;
};
int main() {
struct Student s1 = {1};
display(s1);
return 0;
}
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.
Syntax:
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
Example:
Array:
Structure:
4
struct Student {
int id;
char name[20];
} s1 = {1, "Alice"};
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.
5
Q8b) Write a 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;
return 0;
}
i) Math.h
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
Example Program:
#include <stdio.h>
#include <string.h>
int main() {
7
char str[50], rev[50];
printf("Enter a word: ");
scanf("%s", str);
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
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.
8
#endif
5. #pragma: Gives specific instructions to the compiler.
Dynamic Memory Allocation allows programs to allocate memory during runtime instead
of compile time. It is done using functions from stdlib.h:
Storage classes determine the scope, lifetime, and visibility of variables. The four storage
classes in C are:
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;
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;
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);
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:**
- **If-else:** Executes one block of code if the condition is true and another block if it's
false.
**Switch..case:**
**Comparison:**
- **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 {
// Switch..case
switch (num) {
case 1:
printf("Number is 1\n");
break;
case 2:
printf("Number is 2\n");
break;
default:
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>
return true;
int main() {
int num;
scanf("%d", &num);
if (isPrime(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() {
float result;
result = num / 4;
15
// Explicit type casting
result = (float)num / 4;
return 0;
```
In this example, type casting ensures that the division operation is performed with floating-
point precision.
```
12
123
1234
12345
```
**C Program:**
```c
#include <stdio.h>
int main() {
int n;
16
printf("Enter the number of lines: ");
scanf("%d", &n);
printf("\n");
return 0;
```
### UNIT II
#### Q4.
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>
int fibonacci(int n) {
if (n <= 1)
return n;
int main() {
int n, i;
scanf("%d", &n);
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>
void callByValue(int a) {
a = a + 10;
*a = *a + 10;
int main() {
int x = 20;
callByValue(x);
19
printf("After callByValue: %d\n", x);
callByReference(&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>
if (arr[i] == x)
int main() {
20
int x = 3;
if (result != -1) {
} else {
return 0;
```
#### Q6.
**a) What are structures and what are Bit Field structures? How are they different from
Unions? (4)**
- **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.
```c
#include <stdio.h>
21
// Structure
struct Student {
int id;
char name[50];
float marks;
};
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() {
22
union Data data;
data.i = 10;
data.f = 220.5;
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];
};
student.id = 2;
student->id = 3;
return student;
int main() {
24
struct Student student1 = {1, "John Doe"};
// Passing by value
modifyByValue(student1);
// Passing by reference
modifyByReference(&student1);
// Returning structure
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() {
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()`.
26
```c
#include <stdio.h>
int main() {
FILE *file;
char ch;
if (file == NULL) {
return 1;
fclose(file);
if (file == NULL) {
return 1;
27
// Display the contents of the file
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
```
- Opens a file with the specified mode (`"r"`, `"w"`, `"a"`, etc.).
- Example:
```c
if (file == NULL) {
28
}
```
ii) **`fclose()`**
```c
```
- Example:
```c
fclose(file);
```
iii) **`fseek()`**
```c
```
- Example:
```c
```
iv) **`fwrite()`**
```c
29
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
```
- Example:
```c
```
v) **`fread()`**
```c
```
- Example:
```c
int buffer[5];
```
### 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)**
30
```c
#include <stdio.h>
int main() {
int count = 0;
scanf("%c", &ch);
if (str[i] == ch) {
count++;
return 0;
```
31
**b) Explain any five string handling functions from string.h with syntax and example. (5)**
```c
```
Example:
```c
```
```c
```
Example:
```c
char dest[20];
strcpy(dest, src);
```
32
3. **`strcmp()`**: Compares two strings.
```c
```
Example:
```c
```
```c
```
Example:
```c
strcat(dest, src);
```
```c
33
```
Example:
```c
```
### Q9
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`**:
```c
```
Example:
```c
34
printf("Hello, World!\n");
```
```c
```
Example:
```c
int x;
scanf("%d", &x);
```
- **`math.h`**:
```c
```
Example:
```c
```
```c
```
35
Example:
```c
```
- **`stdlib.h`**:
```c
```
Example:
```c
```
```c
```
Example:
```c
free(ptr);
```
- **`ctype.h`**:
36
```c
```
Example:
```c
if (isdigit('5')) {
printf("It's a digit\n");
```
```c
```
Example:
```c
```
- **`string.h`**:
```c
```
Example:
```c
37
char dest[20];
strcpy(dest, src);
```
```c
```
Example:
```c
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;
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;
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>
void printX() {
// file2.c
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;
return 0;
```
41
- **Dynamic Memory Allocation:**
- **`calloc()`:** Allocates memory for an array and initializes all elements to zero.
**Example:**
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
if (ptr == NULL) {
return 1;
ptr[i] = i * 2;
42
printf("\n");
return 0;
```
- **Static:**
**Example:**
```c
#include <stdio.h>
void func() {
count++;
int main() {
43
func();
return 0;
```
- **Register:**
**Example:**
```c
#include <stdio.h>
int main() {
register int 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'`).
```c
#include <stdio.h>
int main() {
int i = 0, j = 0;
i++;
str1[i] = str2[j];
i++;
j++;
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.
**Examples:**
### 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.
**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.
**Example:**
```c
#include <stdio.h>
int main() {
int i = 0;
do {
printf("%d\n", i);
47
i++;
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() {
48
} else {
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
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
#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;
// Finding topper
if (students[i].marks > max_marks) {
max_marks = students[i].marks;
topper_index = i;
}
}
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.
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. }
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.
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
}
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:
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];
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.
(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;
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:
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.
Bitwise operators work on individual bits of integer values. The following are the bitwise
operators:
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
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
}
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
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;
}
56
Functions in ctype.h are used for character handling.
Examples:
Nested control statements are control structures (if, while, for) placed inside other control
structures.
Example:
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);
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
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);
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
Program:
#include <stdio.h>
60
int main() {
char *arr[] = {"Hello", "World", "C Programming"};
int size = 3;
printStrings(arr, size);
return 0;
}
Output:
Hello
World
C Programming
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:
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.
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.
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.
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;
}
fp = fopen("test.txt", "r");
while (fgetc(fp) != EOF) count++;
fclose(fp);
Array of Strings:
62
String Manipulation Functions:
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];
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:
63
Enter second string: World
Strings are not equal.
Concatenated string: HelloWorld
2016
Here are detailed answers for all the questions from the provided image:
Ternary Operator:
The ternary operator is a shorthand for the if-else statement. Its syntax is:
int main() {
int a, b, c, smallest;
Output Example:
64
Q1 (b): What are Bitwise operators?
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?
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.
If condition is false initially, the loop will not Executes at least once regardless of the
execute. condition.
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);
}
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. }
Example:
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
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;
}
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;
}
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.
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;
}
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.
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;
69
printf("\n");
return 0;
}
Q4 (c): Write a program to copy one string into another string without
using inbuilt function.
Program:
#include <stdio.h>
int main() {
char source[100], destination[100];
copyString(source, destination);
Storage Classes in C:
70
14. count++;
15. printf("Count = %d\n", count);
16. }
Pointer to an Array:
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
int (*p)[3] = &arr; // Pointer to array
Array of Pointers:
#include <stdio.h>
int main() {
int a = 1, b = 2, c = 3;
int *arr[3] = {&a, &b, &c}; // Array of pointers
Recursion:
71
return 1; // Base case
return x * power(x, y - 1); // Recursive case
}
int main() {
int x, y;
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
**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() {
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() {
73
for (int i = 4; i >= 0; 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() {
return 0;
```
### Q7
74
Explain the following with suitable examples:
**Example:**
```c
#include <stdio.h>
struct Address {
char city[30];
int pin;
};
struct Employee {
char name[30];
};
int main() {
return 0;
75
```
**Example:**
```c
#include <stdio.h>
struct Student {
char name[30];
int marks[5];
};
int main() {
printf("Marks: ");
printf("\n");
return 0;
76
```
**Example:**
```c
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
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:**
- `int scanf(const char *format, ...);` - Reads formatted input from stdin.
- `double pow(double base, double exp);` - Computes the power of base raised to exp.
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:
```c
#include <stdio.h>
```
```c
#define PI 3.14159
```
```c
#ifdef DEBUG
printf("Debug mode\n");
#endif
```
```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() {
// Writing to data.txt
if (dataFile == NULL) {
return 1;
80
}
fclose(dataFile);
// Copying to duplicate.txt
if (dataFile == NULL) {
return 1;
if (duplicateFile == NULL) {
fclose(dataFile);
return 1;
int number;
fclose(dataFile);
81
fclose(duplicateFile);
return 0;
82