C Programing Solution
C Programing Solution
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).
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';`.
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`
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`
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
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient 1.99
for storing 15 decimal digits
int main() {
int marks;
// 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];
}
}
}
}
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);
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;
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.
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;
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;
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;
return 0;
}
// Calculate mean
mean = sum / n;
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;
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;
return 0;
}
int main() {
int matrix[3][3], transpose[3][3];
int i, j;
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;
}
// 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;
}
int main() {
int x = 5, y = 3;
// Function call
sum(x, y);
return 0;
}
int main() {
// Function call
int randomNumber = getRandomNumber();
printf("Random number: %d\n", randomNumber);
return 0;
}
int main() {
char source[] = "Hello, world!";
char destination[20]; // Destination string buffer
// Copy string
stringCopy(destination, source);
return 0;
}
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;
// 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;
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.
ptr = # // 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;
}
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);
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;
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;
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;
return 0;
}