0% found this document useful (0 votes)
7 views

C Programing Solution

The document provides an overview of programming in C, covering language translators, the basic structure of a C program, variables, data types, operators, and control structures. It includes examples of C programs for calculating grades, multiplying matrices, and finding the largest of three numbers. Additionally, it explains concepts such as call by value vs. call by reference, and the declaration and initialization of arrays.

Uploaded by

gobardhanrout96
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C Programing Solution

The document provides an overview of programming in C, covering language translators, the basic structure of a C program, variables, data types, operators, and control structures. It includes examples of C programs for calculating grades, multiplying matrices, and finding the largest of three numbers. Additionally, it explains concepts such as call by value vs. call by reference, and the declaration and initialization of arrays.

Uploaded by

gobardhanrout96
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

PHY – C – 414: COMPUTER PROGRAMMING

UNIT WISE SOLUTION OF PYQS MPQS (UNIT – 1 TO UNIT – 3)


UNIT – 1: ITRODUCTION TO PROGRAM AND C LANGUAGE
1. Explain about different types Language translators of programming language.
Ans.
Language translators are software tools used in the software development process to convert code written in
high-level programming languages into machine-readable format. There are mainly three types of language
translators:

a) Compiler:
- Converts entire source code written in a high-level programming language into machine code or lower-
level code all at once.
- The compilation process involves several stages such as lexical analysis, syntax analysis, semantic
analysis, optimization, and code generation.
- Once compiled, the resulting machine code can be executed multiple times without the need for re-
translation unless the source code is modified.
- Examples: GCC (GNU Compiler Collection), Microsoft Visual C++, Clang.

b) Interpreter:
- Executes source code written in a high-level programming language line by line, without prior conversion
into machine code.
- Interpreters translate and execute each line of code separately during runtime.
- Interpreters do not produce executable files or intermediate machine code; they directly execute the source
code.
- Commonly used in scripting languages like Python, Perl, JavaScript.

c) Assembler:
- Translates assembly language code into machine code.
- Assembly language is a low-level programming language that is a symbolic representation of machine
code instructions.
- Assemblers convert assembly language instructions (mnemonics) into binary machine code instructions
that the computer's CPU can understand and execute.
- Assembled code is specific to the target processor architecture and requires reassembly if ported to a
different architecture.
- Examples: NASM (Netwide Assembler), MASM (Microsoft Macro Assembler), GAS (GNU Assembler).

2. Explain the basic structure of a C program with an example.


Ans.
The basic structure of a C program typically consists of several components. Here's an explanation in points
along with a simple example:
a) Preprocessor Directives:
- Preprocessor directives are lines in the program that start with a hash symbol (#) and are processed before
compilation.
- They include header files, macro definitions, and conditional compilation instructions.
- Example: #include <stdio.h>
b) Main Function:
- Every C program must have a main function, which serves as the entry point of the program.
- The execution of the program begins from the first statement inside the main function.
- Example:
int main() {
// Statements
return 0;
}
c) Variables and Data Types:
- Variables are used to store data temporarily during program execution.
- Data types specify the type of data that a variable can hold.
- Example:
int age = 25;
float height = 5.8;
char grade = 'A';
d) Statements and Expressions:
- Statements are instructions that perform specific actions when executed.
- Expressions are combinations of variables, constants, and operators that produce a value.
- Example:
int sum = 5 + 3;
printf("The sum is: %d\n", sum);

e) Control Structures:
- Control structures determine the flow of execution in a program based on conditions.
- Common control structures include if-else statements, loops (for, while, do-while), and switch-case
statements.
- Example:
if (age >= 18) {
printf("You are an adult.\n");
} else {
printf("You are a minor.\n");
}
f) Function:
- Functions are blocks of code that perform specific tasks and can be called from other parts of the program.
- They help in organizing and modularizing the code.
- Example:
int add(int a, int b) {
return a + b;
}
g) Comments:
- Comments are used to provide additional information about the code for better understanding.
- They are ignored by the compiler during compilation.
- Example:
// This is a single-line comment

/*
This is a
multi-line comment
*/

h) Return Statement:
- The return statement is used to exit a function and optionally return a value to the calling function.
- In the main function, it indicates the successful completion of the program.
- Example: return 0;
3. What is variable? How is it different from constant? How do you write comment in C?
Ans.
Variable:
- A variable in C is a named storage location in the computer's memory.
- It holds a value that can be changed during program execution.
- Variables have a specific data type that determines the type of data they can store.
- They are declared using a valid identifier and may be initialized with an initial value.
- Variable names must adhere to certain naming conventions and cannot start with a digit.
- Examples of variable declarations: `int age;`, `float height = 5.8;`, `char grade = 'A';`.

How is Variable different from constant:


- Variables in C are named storage locations whose values can change during program execution, whereas
constants are values that remain fixed throughout the program and cannot be altered.
- Variables are declared using a valid identifier and may be initialized with an initial value, while constants
are typically declared using the `const` keyword and assigned a fixed value at the time of declaration, which
cannot be modified later.

Writing Comment in C:
In C programming, comments can be written in two ways:

i) Single-line comments:
- Single-line comments start with `//` and continue until the end of the line.
- Example: `// This is a single-line comment`

ii) Multi-line comments:


- Multi-line comments start with `/*` and end with `*/`.
- Everything between `/*` and `*/` is considered a comment, including line breaks.
- Example:
/* This is a
multi-line comment */

4. List all the operators used in C with examples.


Ans.
Arithmetic Operators:
- Definition: Perform arithmetic operations such as addition, subtraction, multiplication, division, and
modulus.
- Examples:
o Addition: `a + b`
o Subtraction: `a - b`
o Multiplication: `a * b`
o Division: `a / b`
o Modulus: `a % b`
Relational Operators:
- Definition: Compare the relationship between two operands and return a boolean result (true or false).
- Examples:
o Equal to: `a == b`
o Not equal to: `a != b`
o Greater than: `a > b`
o Less than: `a < b`
o Greater than or equal to: `a >= b`
o Less than or equal to: `a <= b`
Logical Operators:
- Definition: Perform logical operations on boolean operands and return a boolean result.
- Examples:
o Logical AND: `a && b`
o Logical OR: `a || b`
o Logical NOT: `!a`
Assignment Operators:
- Definition: Assign a value to a variable.
- Examples:
o Assign: `a = 5`
o Add and assign: `a += 3`
o Subtract and assign: `a -= 2`
o Multiply and assign: `a *= 4`
o Divide and assign: `a /= 2`
o Modulus and assign: `a %= 3`
Increment and Decrement Operators:
- Definition: Increase or decrease the value of a variable by one.
- Examples:
o Increment: `a++` or `++a`
o Decrement: `a--` or `--a`

Bitwise Operators:
- Definition: Perform bitwise operations on binary representations of operands.
- Examples:
o Bitwise AND: `a & b`
o Bitwise OR: `a | b`
o Bitwise XOR: `a ^ b`
o Bitwise NOT: `~a`
o Left shift: `a << n`
o Right shift: `a >> n`

Conditional Operator (Ternary Operator):


- Definition: A ternary operator that evaluates a condition and returns one of two values based on whether the
condition is true or false.
- Example: `result = (a > b) ? a : b;`

Comma Operator:
- Definition: Evaluates multiple expressions and returns the value of the last expression.
- Example: `x = (y = 3, y + 5);`

5. What are different data types available in “C”? Write the significance of each data type with example.

Data
Size Description Example
Type

int 2 or 4 Stores whole numbers, without decimals 1


bytes
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient 1.99
for storing 6-7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient 1.99
for storing 15 decimal digits

char 1 byte Stores a single character/letter/number, or ASCII values 'A'

6. Write down the difference between compiler, Interpreter and assembler.


Ans.
Aspect Compiler Interpreter Assembler
Takes one line or
Takes the entire source Takes assembly
Input statement at a time as
code as input. language code as input.
input.
Does not generate an
Generates machine code Generates machine code
Output intermediate file; directly
or executable file. or object file.
executes code.
Interprets and executes
Converts the entire Translates assembly
code line by line during
Execution source code to machine language code to
runtime.
code before execution. machine code.
Generally produces
Generally produces May have slower
faster execution
Performance faster execution due to execution due to
compared to high-level
precompiled code. interpretation overhead.
languages.
Detects errors when
Detects errors during the Detects errors during
Error Detection interpreting each line or
compilation process. assembly process.
statement.
Can perform Limited optimization Limited optimization,
Optimization optimization techniques opportunities due to primarily focuses on
during compilation. runtime execution. translating instructions.
GCC (GNU Compiler
Python interpreter,
Examples Collection), Microsoft NASM, MASM
JAVA Script interpreter
Visual C++

UNIT – 2: PROGRAMING WITH C


1. Write a C program to find grade of a student. The user needs to enter the subject number and the program must
return the grade of the subject based on the number.
Number of Marks Grade Conversion
90-100 Outstanding
80-89 Excellent
70-79 Very Good
60-69 Good
50-59 Average
40-49 Poor
Less than 40 Fail
Ans.
#include <stdio.h>
// Function to determine grade based on marks
char calculateGrade(int marks) {
if (marks >= 90 && marks <= 100) {
return 'O'; // Outstanding
} else if (marks >= 80 && marks <= 89) {
return 'E'; // Excellent
} else if (marks >= 70 && marks <= 79) {
return 'V'; // Very Good
} else if (marks >= 60 && marks <= 69) {
return 'G'; // Good
} else if (marks >= 50 && marks <= 59) {
return 'A'; // Average
} else if (marks >= 40 && marks <= 49) {
return 'P'; // Poor
} else {
return 'F'; // Fail
}
}

int main() {
int marks;

// Input marks from user


printf("Enter the marks: ");
scanf("%d", &marks);

// Check if marks are valid


if (marks < 0 || marks > 100) {
printf("Invalid marks! Marks should be between 0 and 100.\n");
return 1; // Return error status
}

// Calculate and display grade


char grade = calculateGrade(marks);
printf("Grade: ");
switch (grade) {
case 'O':
printf("Outstanding\n");
break;
case 'E':
printf("Excellent\n");
break;
case 'V':
printf("Very Good\n");
break;
case 'G':
printf("Good\n");
break;
case 'A':
printf("Average\n");
break;
case 'P':
printf("Poor\n");
break;
case 'F':
printf("Fail\n");
break;
}

return 0; // Return success status


}

2. Write the difference between call by value and call by reference.


Ans.
Aspect Call by Value Call by Reference
Parameter Passing Copies the value of actual arguments Passes the address of actual arguments into
into formal parameters. formal parameters.
Changes to Formal Changes made to formal parameters do Changes made to formal parameters affect
Parameters not affect actual arguments. actual arguments.
Efficiency Less efficient as it involves copying More efficient as it does not involve
data. copying data.
Syntax Parameters are passed directly. Parameters are passed by reference using
pointers.

3. Write a program to multiply two 𝟑 × 𝟑 matrix.


Ans.
#include <stdio.h>
// Function to multiply two matrices
void multiplyMatrices(int mat1[][3], int mat2[][3], int result[][3]) {
int i, j, k;

// Initialize result matrix with zeros


for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
result[i][j] = 0;
}
}

// Multiply matrices
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
for (k = 0; k < 3; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}

// Function to display a matrix


void displayMatrix(int matrix[][3]) {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int mat1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int mat2[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[3][3];

// Multiply matrices
multiplyMatrices(mat1, mat2, result);

// Display the multiplied matrix


printf("Resultant Matrix:\n");
displayMatrix(result);

return 0;
}
4. Write a program to print largest among three numbers entered by user.
Ans.
#include <stdio.h>
int main() {
int num1, num2, num3;

// Input three numbers from user


printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

// Check which number is the largest


if (num1 >= num2 && num1 >= num3) {
printf("Largest number: %d\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("Largest number: %d\n", num2);
} else {
printf("Largest number: %d\n", num3);
}

return 0;
}

5. What is array? Explain declaration, initialization and accessing elements of one and two dimension of
numeric array.
Ans.
- An array in C is a collection of elements of the same data type stored in contiguous memory locations.
Declaration:
- Syntax: `datatype arrayName[arraySize];`
- It specifies the data type of the elements and the number of elements the array can hold.
Initialization:
- Arrays can be initialized at the time of declaration or later using assignment statements.
- Example: `int numbers[5] = {1, 2, 3, 4, 5};`
Accessing Elements:
- Elements of an array can be accessed using the array index.
- Array indexing starts from 0 for the first element and goes up to `arraySize - 1`.
- Syntax: `arrayName[index];
Accessing Elements of a One-Dimensional Array:
- Single index is used to access elements of a one-dimensional array.
- Example: `int num = numbers[2]; // Accesses the third element of the array 'numbers'`
Declaration of Two-Dimensional Array:
- Syntax: `datatype arrayName[rowSize][columnSize];`
- It represents a table of rows and columns.
Initialization of Two-Dimensional Array:
- Arrays can be initialized row by row or by providing all elements at once using nested curly braces.
- Example: `int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Accessing Elements of a Two-Dimensional Array:
- Two indices are used to access elements of a two-dimensional array, one for the row and one for the column.
- Example: `int element = matrix[1][2]; // Accesses the element in the second row and third column of the
matrix.

6. What is recursive function?


Ans.
- A recursive function in C is a function that calls itself either directly or indirectly during its execution.
- Recursive functions are used to solve problems that can be broken down into smaller, similar
subproblems.
- Characteristics of a recursive function:
o Base case: A condition that stops the recursion and defines the termination point of the function.
o Recursive case: A condition that calls the function itself with modified parameters to solve a smaller
version of the original problem.
- Recursive functions have a stack-like behavior, where each recursive call creates a new instance of the
function on the call stack.
- Recursive functions can be less efficient in terms of memory usage and execution time compared to
iterative solutions for certain problems.
- Advantages of recursive functions:
o They provide a concise and elegant solution for problems that can be naturally solved using recursion.
o They can simplify the implementation of certain algorithms and make the code easier to understand.
- Examples of problems commonly solved using recursive functions include factorial calculation, Fibonacci
sequence generation, and tree traversal algorithms.
7. Write a program to find factorial of an integer number by using recursive function.
Ans.
#include <stdio.h>
// Recursive function to calculate factorial
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n! = n * (n-1)!
else {
return n * factorial(n - 1);
}
}
int main() {
int num;

// Input number from user


printf("Enter a non-negative integer: ");
scanf("%d", &num);

// Check if the number is non-negative


if (num < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
} else {
// Calculate and print factorial
int fact = factorial(num);
printf("Factorial of %d is: %d\n", num, fact);
}

return 0;
}

8. Write a C program to input the gender and age of a user and check whether the user is eligible to marry
or not.
Ans.
#include <stdio.h>
int main() {
char gender;
int age;

// Input gender from user


printf("Enter your gender (M/F): ");
scanf(" %c", &gender);

// Input age from user


printf("Enter your age: ");
scanf("%d", &age);

// Check eligibility for marriage


if ((gender == 'M' || gender == 'm') && age >= 21) {
printf("You are eligible for marriage.\n");
} else if ((gender == 'F' || gender == 'f') && age >= 21) {
printf("You are eligible for marriage.\n");
} else {
printf("You are not eligible for marriage.\n");
}

return 0;
}
9. Write a C program to find factorial of number and number should be provided by the user during
runtime.
Ans.
#include <stdio.h>
// Function to calculate factorial
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n! = n * (n-1)!
else {
return n * factorial(n - 1);
}
}

int main() {
int num;

// Input number from user


printf("Enter a non-negative integer: ");
scanf("%d", &num);

// Check if the number is non-negative


if (num < 0) {
printf("Error: Factorial is not defined for negative numbers.\n");
} else {
// Calculate and print factorial
int fact = factorial(num);
printf("Factorial of %d is: %d\n", num, fact);
}

return 0;
}

10. Write a C program to input a number and print reverse of that number.
Ans.
#include <stdio.h>
int main() {
int num, reversedNum = 0, remainder;

// Input number from user


printf("Enter a number: ");
scanf("%d", &num);

// Reverse the number


while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// Print the reversed number
printf("Reverse of the number: %d\n", reversedNum);

return 0;
}

11. Write a program in C to print sum and mean of an integer array.


Ans.
#include <stdio.h>
int main() {
int arr[100], n, i;
float sum = 0, mean;

// Input the number of elements in the array


printf("Enter the number of elements: ");
scanf("%d", &n);

// Input array elements


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

// Calculate mean
mean = sum / n;

// Print sum and mean


printf("Sum of array elements: %.2f\n", sum);
printf("Mean of array elements: %.2f\n", mean);

return 0;
}

12. Write a C program using a function to check whether the given number is prime or not.
Ans.
#include <stdio.h>
// Function to check prime
int isPrime(int num) {
// Corner cases
if (num <= 1) {
return 0; // Not prime
}
// Check divisibility from 2 to sqrt(num)
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // Not prime
}
}
return 1; // Prime
}
int main() {
int num;

// Input number from user


printf("Enter a positive integer: ");
scanf("%d", &num);

// Check if the number is prime


if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}

return 0;
}

13. Write a C program using a function to check whether the given number is even or odd.
Ans.
#include <stdio.h>
// Function to check even or odd
int isEvenOrOdd(int num) {
if (num % 2 == 0) {
return 1; // Even
} else {
return 0; // Odd
}
}

int main() {
int num;

// Input number from user


printf("Enter an integer: ");
scanf("%d", &num);

// Check if the number is even or odd


if (isEvenOrOdd(num)) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}

return 0;
}

14. Write a program in C to transpose a given matrix.


Ans.
#include <stdio.h>
// Function to transpose a matrix
void transposeMatrix(int mat[][3], int transpose[][3]) {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
transpose[j][i] = mat[i][j];
}
}
}

// Function to display a matrix


void displayMatrix(int matrix[][3]) {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[3][3], transpose[3][3];
int i, j;

// Input the matrix elements


printf("Enter the elements of the matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Transpose the matrix


transposeMatrix(matrix, transpose);

// Display the original matrix


printf("Original Matrix:\n");
displayMatrix(matrix);

// Display the transposed matrix


printf("Transposed Matrix:\n");
displayMatrix(transpose);

return 0;
}

15. What is a function? Explain the different classifications of user-defined functions based on parameter
passing and return type with examples.
Ans.
Function:
- A function is a self contained block of code that performs a specific task.
- Functions provide modularity and allow code reusability by breaking down a program into smaller,
manageable parts.
- Function in C have a name, return type, parameters (if any), and a body containing the statements to be
executed.
- They can be called from any part of the program to perform their defined task.
- Functions in C can have different classifications based on parameter passing and return type.
- Examples of function in C include printf() for output, `scanf()` for input and user defined functions created
by the programmer for custom tasks.
Classifications:
a) No parameters, No return value (Void):
- These functions do not take any parameters and do not return any value.
- Example:
#include <stdio.h>
// Function definition
void greet() {
printf("Hello, world!\n");
}

int main() {
// Function call
greet();
return 0;
}

b) Parameters, No Return Value (Void):


- These functions take parameters but do not return any value.
- Example:
#include <stdio.h>

// Function definition
void sum(int a, int b) {
int result = a + b;
printf("Sum: %d\n", result);
}

int main() {
int x = 5, y = 3;
// Function call
sum(x, y);
return 0;
}

c) No Parameters, Return Value:


- These functions take parameters but do not return any value.
- Example:
#include <stdio.h>
// Function definition
void sum(int a, int b) {
int result = a + b;
printf("Sum: %d\n", result);
}

int main() {
int x = 5, y = 3;
// Function call
sum(x, y);
return 0;
}

d) Parameters, Return Value:


- These functions do not take any parameters but return a value.
- Example:
#include <stdio.h>
// Function definition
int getRandomNumber() {
return rand() % 100; // Return a random number between 0 and 99
}

int main() {
// Function call
int randomNumber = getRandomNumber();
printf("Random number: %d\n", randomNumber);
return 0;
}

16. Differentiate between call by value and call by references.


Ans.
Feature Call by Value Call by Reference
Addresses of actual parameters are
Passing Parameters Values of actual parameters are copied.
passed.
Effect on Actuals Original variables remain unchanged. Original variables can be modified.
Changes made to formal parameters do Changes made to formal parameters
Scope of Changes
not affect actual parameters. affect actual parameters.
Less efficient as it involves copying More efficient as it avoids copying large
Efficiency
values. data structures.
Int x = 5; foo(&x); //x can be modified
Examples Int x = 5; foo(x); //x remains 5
within foo

17. Define String.


Ans.
- In C, a string is a sequence of characters terminated by a null character (`'\0'`).
- Strings in C are represented using arrays of characters.
- A string literal is a sequence of characters enclosed in double quotation marks (`"`).
- Example: `"Hello, world!"` is a string literal.
- Strings can be manipulated using various standard library functions such as `strlen()`, `strcpy()`,
`strcat()`, and `strcmp()`.
- Strings in C are null-terminated, meaning the null character (`'\0'`) is used to mark the end of the string.
- Strings can be declared as arrays of characters or using pointers to characters.
- Example of array declaration: `char str[20];`
- Example of pointer declaration: `char *str = "Hello";`
- String handling in C requires careful consideration of null terminators to avoid buffer overflow and
undefined behavior.
18. Explain any six-string handling library function with syntax and examples.
Ans.
a) Starlen()
- Syntax: size_t strlen(const char *str);
- Description: Calculates the length of the string excluding the null terminator.
- Example
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
size_t length = strlen(str);
printf("Length of the string: %zu\n", length);
return 0;
}
b) Strcpy()
- Syntax: char *strcpy(char *dest,const char *src);
- Description: Copies the string pointed to by `src` (including the null terminator) to the `dest` buffer.
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, world!";
char dest[20];
strcpy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}
c) strcat()
- Syntax: char *strcat(char *dest, const char *src);
- Description: Concatenates the string pointed to by `srs` (including the null terminator) to the end of the
`dest` string.
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello, ";
char src[] = "world!";
strcat(dest, src);
printf("Concatenated string: %s\n", dest);
return 0;
}
d) strcmp()
- Sntax: int strcmp(const char *str1, const char *str2);
- Description: Compares two strings
- Examples:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal.\n");
} else if (result < 0) {
printf("String 1 comes before string 2.\n");
} else {
printf("String 1 comes after string 2.\n");
}
return 0;
}
e) strstr()
- Syntax: char *strstr(const char *haystack, const char *needle);
- Description: Searches for the first occurrence of the substring `needle` in the string `haystack`.
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char haystack[] = "Hello, world!";
char needle[] = "world";
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("Substring found at position: %ld\n", result - haystack);
} else {
printf("Substring not found.\n");
}
return 0;
}
f) strtok()
- Syntax: char *strtok(char *str, const char *delim);
- Description: Breaks the string `str` into a series of tokens using the delimiter `delim`.
- Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "apple,banana,orange";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}

19. Write a program in C to copy one string to another string.


Ans.
#include <stdio.h>
// Function to copy one string to another
void stringCopy(char *dest, const char *src) {
while (*src != '\0') {
*dest = *src;
src++;
dest++;
}
*dest = '\0'; // Add null terminator to the destination string
}

int main() {
char source[] = "Hello, world!";
char destination[20]; // Destination string buffer

// Copy string
stringCopy(destination, source);

// Print the copied string


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

return 0;
}

UNIT – 3: POINTER AND FILE MANAGEMENT


1. Write difference between structure and union.
Ans.
Feature Structure Union
Declaration Declared using a`struck` keyword Declared using a `union` keyword
Allocates memory for each member
Memory Allocation Shares memory along all members
separately
Size Calculation Size is the sum of sizes of all members Size is the size of the largest member
Memory usage may be inefficient for Memory usage is more efficient as it
Memory Usage
large structures shares memory among members
Members accessed individually using Members accessed through a single
Accessing Members
dot notation. name, shares memory
struct Point {int x; int y;}; struct Point union Data {int x; float y; }; union data
Example
p1; u;

2. What is file? Explain file handling in C language.


Ans.
File:
- In C, a file is a collection of data stored on a storage device such as a hard disk, solid-state drive, or
optical disk.
- Files provide a way to store and organize data for long-term storage and retrieval.
- Files can be of different types, such as text files, binary files, or special device files.
- Files in C are accessed through file streams, which represent the connection between the program and
the physical file.
- Operations on files include opening, closing, reading, and writing data to and from files.
- File operations in C are performed using functions provided by the Standard Input/Output Library
(`stdio.h`), such as `fopen()`, `fclose()`, `fread()`, `fwrite()`, etc.

File Handling in C:
- File handling in C involves performing operations on files, such as reading from or writing to them,
using file streams.
- The `stdio.h` header file provides functions and macros for file handling in C.
- Basic file operations include opening, closing, reading, and writing data to files.
- To open a file, the `fopen()` function is used, which returns a file pointer that represents the connection
to the file.
- Files can be opened in different modes, such as read (`"r"`), write (`"w"`), append (`"a"`), or read/write
(`"r+"`, `"w+"`, `"a+"`).
- Once a file is opened, data can be read from it using functions like `fscanf()` or `fgets()`, or written to it
using functions like `fprintf()` or `fputs()`.
- After performing operations on a file, it should be closed using the `fclose()` function to release system
resources associated with it.
- File handling also involves error handling to check if file operations succeed or fail.
- Error handling in file handling typically involves checking return values of file functions and using
error-checking macros like `feof()` and `ferror()`.
- In addition to text files, C can also handle binary files, which contain data in binary format and require
different read/write operations.
- File handling in C allows working with files stored on local disks, network drives, or other storage
devices.
- Advanced file handling techniques include file positioning, buffering, and handling large files using
functions like `fseek()` and `rewind()`.
3. Write a C program to create a structure named as “Student”. The structure has three members: name,
roll and marks. Create a structure variable s is created to store information and display it on the screen.
Ans.
#include <stdio.h>
// Define structure Student
struct Student {
char name[50];
int roll;
float marks;
};

int main() {
// Declare a structure variable of type Student
struct Student s;

// Input information from user


printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);

// Display information
printf("\nStudent Information\n");
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.roll);
printf("Marks: %.2f\n", s.marks);

return 0;
}

4. What is dynamic memory allocation? Explain malloc() and calloc() function with an example.
Ans.
Dynamic Memory Allocation:
- Dynamic memory allocation in C refers to the process of allocating memory at runtime.
- It allows programs to allocate memory as needed during program execution.
- Dynamic memory allocation is done using functions such as `malloc()`, `calloc()`, and `realloc()`.
- Memory allocated dynamically is allocated from the heap, which is a region of memory separate from
the stack.
- Dynamic memory allocation provides flexibility as memory can be allocated and deallocated as needed.
- It allows programs to manage memory more efficiently, especially when the size of data is not known
at compile time.
- Proper management of dynamically allocated memory is essential to avoid memory leaks and other
memory-related issues.
malloc() function:
- `malloc()` is a standard library function in C.
- It is used for dynamic memory allocation, allowing programs to allocate memory at runtime.
- It stands for "memory allocation".
- `malloc()` takes the size of the memory block to be allocated as its parameter.
- It returns a pointer to the beginning of the allocated memory block.
- If `malloc()` fails to allocate memory, it returns a NULL pointer.
calloc() Function:
- `calloc()` is a library function in C used for dynamic memory allocation.
- It allocates memory for an array of elements and initializes all bytes to zero.
- Syntax: `void *calloc(size_t num, size_t size);`
- It takes two arguments: `num`, the number of elements to allocate, and `size`, the size of each element
in bytes.
- The total memory allocated is `num * size` bytes.
- It returns a pointer to the allocated memory block, or `NULL` if allocation fails.
5. Write a C program to open a file and print all the content of that file.
Ans.
#include <stdio.h>
int main() {
FILE *filePointer;
char fileName[50];
char ch;

// Input file name from user


printf("Enter the name of the file: ");
scanf("%s", fileName);

// Open the file in read mode


filePointer = fopen(fileName, "r");

// Check if file exists and can be opened


if (filePointer == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}

// Read and print the contents of the file


printf("Content of the file:\n");
while ((ch = fgetc(filePointer)) != EOF) {
printf("%c", ch);
}

// Close the file


fclose(filePointer);
return 0;
}

6. Explain the different types of programming languages.


Ans.
- Low-Level Languages: These languages are closer to machine code and are directly executable by the
computer's hardware. Examples include assembly languages.
- High-Level Languages: These languages are closer to human language and are easier to understand and
program. Examples include C, Java, Python, and JavaScript.
- Procedural Languages: Programs in these languages are organized around procedures or routines, which
contain a series of steps to be executed. Examples include C and Pascal.
- Object-Oriented Languages: These languages are based on the concept of objects, which encapsulate
data and behavior. Examples include Java, C++, and Python.
- Functional Languages: Programs in these languages are based on mathematical functions and treat
computation as the evaluation of mathematical expressions. Examples include Haskell and Lisp.
- Scripting Languages: These languages are designed for automating the execution of tasks and are often
used for rapid prototyping and web development. Examples include Python, Perl, and JavaScript.
- Compiled Languages: Programs written in these languages are translated into machine code before
execution. Examples include C, C++, and Rust.
- Interpreted Languages: Programs written in these languages are executed line-by-line by an interpreter.
Examples include Python, JavaScript, and Ruby.
- Static Typing Languages: These languages require variables to be explicitly declared with their data
types before they can be used. Examples include C, C++, and Java.
- Dynamic Typing Languages: These languages determine the data type of variables at runtime and do
not require explicit type declarations. Examples include Python, JavaScript, and Ruby.

7. Define Structure.
Ans.
- In C programming, a structure is a user-defined data type that allows grouping together a collection of
variables under a single name.
- It enables the creation of a composite data type that contains members of different data types.
- Structures are defined using the `struct` keyword followed by a name and a list of member variables
enclosed in curly braces.
- Each member variable within a structure can have its own data type and name.
- Structures provide a way to organize related data elements into a single unit, making it easier to manage
and manipulate complex data.
- Instances of structures, known as structure variables, can be created to store data conforming to the
structure's layout.

8. Explain how the pointer variable is declared and initialized.


Ans.
- Pointer variables in C are declared using the asterisk (*) symbol followed by the variable name.
- The asterisk (*) indicates that the variable is a pointer.
- Example: `int *ptr;` declares a pointer variable named `ptr` that can hold the address of an integer
variable.
- Pointer variables can be declared for any data type, including integers, characters, floats, structures, and
even other pointers.
- Pointer variables can also be declared as pointers to functions.
- Pointers must be initialized with the address of a variable before they can be dereferenced.
- Initialization of a pointer variable involves assigning the memory address of another variable to the
pointer variable.
- This can be done using the address-of operator (&) followed by the variable name.
- Example: `int x = 10; int *ptr = &x;` initializes the pointer variable `ptr` with the address of the integer
variable `x`.
- Pointers can also be initialized with `NULL`, which indicates that they are not pointing to any valid
memory address.
- Example: `int *ptr = NULL;` initializes the pointer variable `ptr` with a null pointer.
- Pointers can be initialized with the result of dynamic memory allocation functions like `malloc()`,
`calloc()`, or `realloc()`.
- Example: `int *ptr = malloc(sizeof(int));` initializes the pointer variable `ptr` with the memory address
returned by the `malloc()` function.
- Pointer variables can also be assigned the value of another pointer variable.
- Example: `int *ptr1 = &x; int *ptr2 = ptr1;` initializes `ptr2` with the value of `ptr1`.
- Pointer variables can be declared and initialized in a single statement.
- Example: `int *ptr = &x;` declares and initializes the pointer variable `ptr` with the address of the integer
variable `x`.
- It's important to ensure that pointer variables are properly initialized to avoid undefined behavior when
dereferencing them.
- Pointers can also be declared as constant pointers or pointers to constant data by using the `const`
keyword in the declaration.
- Example: `const int *ptr = &x;` declares `ptr` as a pointer to a constant integer.
- Pointer variables can be initialized to point to array elements by specifying the array name or using array
indexing syntax.
- Example: `int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr;` initializes `ptr` to point to the first element of the
array `arr`.
- Pointers can also be initialized with the result of arithmetic operations on other pointers.
- Example: `int arr[5]; int *ptr = arr + 3;` initializes `ptr` to point to the fourth element of the array `arr`.
- Example of a simple programming:
#include <stdio.h>
int main() {
int num = 10; // Declare and initialize an integer variable
int *ptr; // Declare a pointer variable of type int

ptr = &num; // Initialize the pointer with the address of the integer variable

// Print the value of the integer variable and the pointer's value (memory address)
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num); // Print address using '&' operator
printf("Value of ptr (memory address of num): %p\n", ptr);

return 0;
}

9. What is NULL pointer?


Ans.
- In C programming, a null pointer is a special pointer value that points to no memory location.
- It is represented by the constant value `NULL`.
- A null pointer is typically used to indicate that the pointer does not point to a valid object or memory
location.
- Attempting to dereference a null pointer (accessing the memory location it points to) results in undefined
behavior and may lead to program crashes or segmentation faults.
- Null pointers are commonly used in pointer initialization and error handling.
- They are useful for initializing pointers before they are assigned valid addresses or for checking if a
pointer has been properly initialized before dereferencing it.
- Dereferencing a null pointer is considered a programming error and should be avoided.

10. What is Double pointer explain with example.


Ans.
- In C programming, a double pointer is a pointer that points to another pointer.
- Double pointers are also known as pointer-to-pointer variables.
- They are declared by adding an additional asterisk (*) to the pointer declaration.
- Double pointers are used to store the address of another pointer variable.
- They are commonly used in situations where a function needs to modify a pointer variable declared in
the calling function.
- Double pointers are frequently used in dynamic memory allocation scenarios, where memory needs to
be allocated or deallocated dynamically and the changes need to be reflected outside the function scope.
- Double pointers are also used in multi-level data structures such as linked lists and trees, where each
node may contain a pointer to another node or pointer to a pointer pointing to another node.
- Manipulating double pointers requires careful handling of memory allocation, deallocation, and
dereferencing to avoid memory leaks or undefined behavior.
- Example:
#include <stdio.h>
#include <stdlib.h>
// Function to allocate memory for an integer and store a value
void allocateAndStore(int **ptr, int value) {
*ptr = (int *)malloc(sizeof(int)); // Allocate memory for an integer
if (*ptr != NULL) { // Check if memory allocation is successful
**ptr = value; // Store the value in the allocated memory
}
}

int main() {
int *ptr = NULL; // Declare a pointer to int and initialize it to NULL
int value = 10; // Value to be stored

// Call function to allocate memory for an integer and store the value
allocateAndStore(&ptr, value);

// Check if memory allocation and storing value were successful


if (ptr != NULL) {
printf("Value stored at pointer address %p: %d\n", (void *)ptr, *ptr);
free(ptr); // Free allocated memory
} else {
printf("Memory allocation failed.\n");
}

return 0;
}
11. What is pointer to function and pointer to array?
Ans.
Pointer:
- In C programming, a pointer to a function, often called a function pointer, is a variable that stores the
address of a function.
- Function pointers allow functions to be passed as arguments to other functions, returned from functions,
or stored in data structures.
- They provide a way to implement callbacks, where a function is called in response to an event or
condition.
- Function pointers are declared by specifying the return type and parameter types of the function they
point to, followed by `(*ptr)` syntax.
- They are initialized by assigning the address of a function to the function pointer variable.
- Function pointers can be used to create arrays of functions or to implement function tables.
- Dereferencing a function pointer invokes the function it points to, similar to calling a regular function.
- Function pointers provide flexibility and enable dynamic behavior in programs, allowing different
functions to be invoked based on runtime conditions.
- Proper usage of function pointers requires careful consideration of function signatures, including return
types and parameter types.
- Function pointers are commonly used in advanced programming techniques such as function pointers
to implement polymorphism and dynamic dispatch.
Pointer to Array:
- In C programming, a pointer to an array is a pointer variable that points to the first element of an array.
- When a pointer is declared to be a pointer to an array, it points to the memory address of the first element
of the array.
- Pointer to array declaration syntax involves specifying the data type of the elements in the array followed
by an asterisk (*) and the pointer variable name.
- Pointer to array allows accessing elements of the array using pointer arithmetic.
- Pointer to array can be incremented or decremented to navigate through the elements of the array.
- Pointer to array is often used to pass arrays to functions or to manipulate array elements dynamically.
- It can also be used to allocate memory for multi-dimensional arrays dynamically.
- Pointer to array can be declared for arrays of any data type, including primitive types like integers or
characters, as well as user-defined types like structures.
12. Write a C program to swap the values of two variables using a pointer.
Ans.
#include <stdio.h>
// Function to swap the values of two variables using pointers
void swap(int *ptr1, int *ptr2) {
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}

int main() {
int num1, num2;

// Input two numbers from user


printf("Enter value for num1: ");
scanf("%d", &num1);
printf("Enter value for num2: ");
scanf("%d", &num2);

// Print values before swapping


printf("\nBefore swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);
// Call swap function to swap values using pointers
swap(&num1, &num2);

// Print values after swapping


printf("\nAfter swapping:\n");
printf("num1 = %d\n", num1);
printf("num2 = %d\n", num2);

return 0;
}

13. Write a Program in C to read a file and write the content of the file.
Ans.
#include <stdio.h>

int main() {
FILE *filePointer;
char fileName[100];
char ch;

// Input file name from user


printf("Enter the name of the file: ");
scanf("%s", fileName);

// Open the file in read mode


filePointer = fopen(fileName, "r");

// Check if file exists and can be opened


if (filePointer == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}

// Read and print the contents of the file


printf("\nContent of the file:\n");
while ((ch = fgetc(filePointer)) != EOF) {
printf("%c", ch);

// Write the character to another file


// You can comment this part if you only want to print the content
// FILE *writeFilePointer = fopen("output.txt", "a");
// fputc(ch, writeFilePointer);
// fclose(writeFilePointer);
}

// Close the file


fclose(filePointer);

return 0;
}
14. Write a program in C to read the name and marks of the 'n' number of students and store them in a file.
Ans.
#include <stdio.h>
int main() {
FILE *filePointer;
char fileName[100];
int n, i;
char name[50];
float marks;

// Input file name from user


printf("Enter the name of the file to store student information: ");
scanf("%s", fileName);

// Open the file in write mode


filePointer = fopen(fileName, "w");

// Check if file can be opened


if (filePointer == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}

// Input the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

// Input and store information of each student


for (i = 0; i < n; i++) {
printf("\nEnter details of student %d:\n", i + 1);
printf("Name: ");
scanf("%s", name);
printf("Marks: ");
scanf("%f", &marks);

// Write student information to file


fprintf(filePointer, "Student %d: Name: %s, Marks: %.2f\n", i + 1, name, marks);
}

// Close the file


fclose(filePointer);

printf("\nStudent information stored successfully in the file '%s'.\n", fileName);

return 0;
}

You might also like