0% found this document useful (0 votes)
42 views19 pages

Adv.c Question Bank

The document provides definitions and explanations of various C programming concepts, including unions, pointers, macros, and file operations. It also covers the declaration and initialization of pointers, types of arrays, structures, and basic file operations. Additionally, it includes examples and comparisons of functions like fopen(), fputs(), and scanf() versus gets().

Uploaded by

samarthpise500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views19 pages

Adv.c Question Bank

The document provides definitions and explanations of various C programming concepts, including unions, pointers, macros, and file operations. It also covers the declaration and initialization of pointers, types of arrays, structures, and basic file operations. Additionally, it includes examples and comparisons of functions like fopen(), fputs(), and scanf() versus gets().

Uploaded by

samarthpise500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Define union.

A user-defined data type that allows you to store different data types in same memory location.

enlist types of preprocessor in c.

Macro manipulation , File inclusion & Conditional compilation.

What is pointer?

A variable that stores the memory address of another variable, allowing you to directly access and manipulate data
stored in that memory location.

Which function is useD to calculate length of the string?

Strlen().

list Different types of files.

Text files, Binary files, Source code files, Header files, Object files,

What is inDex of tWo Dimensional array in c?

Row_index , colum_index

Define macro.

A macro is a preprocessor directive that allows you to define a shortcut or an alias for a piece of code.

Macros are defined using the #define directive.

Which keyWorD is useD to Declare union in c?

union.

Define use of reWinD function.

Used to reset the file pointer to the beginning of a file, allowing you to read the file from the start again.

Define string.

A string is a sequence of characters terminated by a null character (\0).

Strings are used to store and manipulate text data.

What is pointer ?

A pointer is a variable that stores the memory address of another variable.


Pointers are used to indirectly access and manipulate the values stored in memory.
Define string With example.

A string is a sequence of characters terminated by a null character (\0).

Example :
#include <stdio.h>

int main() {
char myString[] = "Hello, world!"; // String literal
char anotherString[20] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Character array with null terminator
printf("%s\n", myString); // Prints "Hello, world!"
printf("%s\n", anotherString); // Prints "Hello"
return 0;
}

Define function.

A function is a block of code that performs a specific task and can be called multiple times from different parts of a
program.

hoW is pointer variable DeclareD anD initializeD ?

To declare a pointer variable, you use an asterisk (*) before the variable name, indicating it will store a memory
address. Initialization involves assigning a valid memory address to the pointer, typically using the address-of
operator (&).
Here's a breakdown:
1. Declaration:
Syntax: data_type *pointer_name;
Example: int *ptr; (declares a pointer named ptr that can store the address of an integer)
Explanation:
data_type specifies the type of data the pointer will point to (e.g., int, float, char).
* indicates that the variable is a pointer.
pointer_name is the name you choose for the pointer variable.
2. Initialization:
Syntax: pointer_name = &variable;
Example: int num = 10; int *ptr = &num; (declares an integer num, then declares a pointer ptr and initializes it with
the address of num)
Explanation:
&variable is the address-of operator, which returns the memory address of the variable.
pointer_name = &variable; assigns the address of variable to the pointer pointer_name.

What is the inDex of the first element in an array in c?

The index of the first element in an array is always 0.

What is Dynamic memory allocation?

Allows you to allocate memory during program execution, rather than at compile time.

Which function is useD to concatenate tWo strings in c?

The strcat() function is used to concatenate two string.

What is the use of fputs().


fputs() is a function used to write a string to a file stream.

hoW Do you Declare an array of 10 integers in c?

In C, you can declare an array of 10 integers using the following:


syntax: int array_name[10];
For example:
int myArray[10];
This declares an array named myArray that can hold 10 integer values.

You can also initialize the array with values when you declare it:
int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Which keyWorD is useD to Define structure?

The keyword used to define a structure is struct.

Define preprocessor.

A program that processes the source code before it’s compiled, performing tasks like including files, defining
macros, and conditionally compiling code.

hoW is memory allocateD for an array in c?

Dynamic array size allocation can be done using memory allocation functions such as malloc(), calloc(), or relloc().

list basic file operations.

fopen() - create a new file or open a existing file


fclose() - close a file
getc() - reads a character from a file
putc() - writes a character to a file
fscanf() - reads a set of data from a file
fprintf() - writes a set of data to a file
getw() - reads a integer from a file
putw() - writes a integer to a file
fseek() - set the position to desire point
ftell() - gives current position in the file
rewind() - set the position to the beginning point

Define macro substitution Directives.

Allow the preprocessor to replace identifiers(macro names)with specified text before compilation, enabling code
reusability and flexibility.

enlist file opening moDes in c.

Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).
Opening an existing file (fopen).
Reading from file (fscanf or fgets).
Writing to a file (fprintf or fputs).
Moving to a specific location in a file (fseek, rewind).
Closing a file (fclose).

give use of & anD * operator in c

& (Address-of Operator):


The & operator is used to get the memory address of a variable.
Syntax:
&variable_name.

* (Dereference Operator):
The * operator is used to access the value stored at a memory address.
Syntax:
*pointer_name.

hoW to initialize pointer variable?

Initialization:
After declaration, you need to initialize the pointer with a valid memory address.
Using the address-of operator (&): You can obtain the address of a variable using the & operator and assign it to the
pointer.
int num = 10; declares an integer variable num.
int *ptr = &num; declares a pointer ptr and initializes it to point to the memory address of num.
Using malloc (Dynamic Memory Allocation): You can allocate memory dynamically using malloc and assign the
returned address to the pointer.
int *ptr = (int *)malloc(sizeof(int)); allocates enough memory for an integer and assigns the address to ptr.
Initializing to NULL: You can also initialize a pointer to NULL, which means it doesn't point to any valid memory
location.
int *ptr = NULL;

explain types of array.

Arrays are classified primarily as one-dimensional (1D) and multi-dimensional (2D, 3D, etc.), with 1D arrays storing
elements in a linear sequence and multi-dimensional arrays representing data in tables or matrices.
Here's a more detailed explanation:
1. One-Dimensional Arrays (1D):
Definition: A 1D array is a simple collection of elements of the same data type, stored contiguously in memory,
accessed using a single index (starting from 0).
Example: int numbers[5] = {10, 20, 30, 40, 50};
Accessing elements: numbers[0] will access the first element (10), numbers[2] will access the third element (30).
2. Multi-Dimensional Arrays (2D, 3D, etc.):
Definition:
These arrays have more than one dimension, allowing for storing data in a tabular or matrix format.
2D Arrays:
Represented as rows and columns, like a table or matrix.
Example: int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
Accessing elements: matrix[0][0] will access the element in the first row and first column (1), matrix[1][2] will access
the element in the second row and third column (7).
3. 3D Arrays (and beyond):
Can be thought of as an array of 2D arrays, or an array of arrays of arrays, and so on.
Example: `int cube = {{{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}}; `
Accessing elements: cube[0][1][0] will access the element in the first cube, second row, first column (5).

enlist the aDvantages of structure.

Structures in C offer several advantages, including organizing data of different types, improving code readability
and maintainability, facilitating the creation of custom data types, and enabling efficient data manipulation and
passing to functions.
Here's a more detailed breakdown of the advantages:
Organizing Heterogeneous Data:
Structures allow you to group different data types (integers, floats, characters, etc.) under a single name, making it
easier to manage related data as a unit.
Improved Code Readability and Maintainability:
By using structures, you can create meaningful data types that represent real-world entities, making your code
easier to understand and maintain.
Custom Data Types:
Structures enable you to define your own data types, which can be used to represent complex data structures or
objects, extending the capabilities of the language.
Efficient Data Manipulation:
You can access and modify individual members of a structure using the dot operator (variable.member), making it
easy to work with the data stored within.
Simplified Parameter Passing:
Structures can be passed to functions as a single parameter, representing a group of related values, which can
simplify function design and reduce the number of arguments needed.
Arrays of Structures:
You can create arrays of structures, allowing you to store and manage multiple instances of the same data type
efficiently.
Data Abstraction:
Structures can hide the implementation details of data, allowing you to focus on the data's logical structure rather
than its physical representation.
Code Reusability:
Structures can be reused as templates for representing similar types of data, reducing redundancy in your code and
promoting a consistent data structure.

Define file inclusive Directives.

instructs the preprocessor to insert the contents of a specified file into the source code at the point where the
directive appears.

Define pointer. hoW to Declare pointer variable in c.

A pointer is a variable that stores the memory address of another variable.


Pointers are used to indirectly access and manipulate the values stored in memory.

Declaring a Pointer Variable:


The syntax to declare a pointer variable is:
data_type *pointer_name;
Here:
- data_type is the type of data that the pointer will point to (e.g., int, char, float, etc.).
- * is the pointer operator, also known as the "dereference operator".
- pointer_name is the name of the pointer variable.

Example:
int *ptr; // declares a pointer to an integer
char *name; // declares a pointer to a character
float *balance; // declares a pointer to a floating-point number

hoW Do you access structure members?

In C, you can access structure members using two operators:

1. Dot Operator (.): Used to access members of a structure variable.

```
```
struct Person {
int age;
char name[20];
};

struct Person person;


person.age = 30;
strcpy(person.name, "John Doe");

2. **Arrow Operator (->)**: Used to access members of a structure pointer.

c
struct Person {
int age;
char name[20];
};

struct Person *person = malloc(sizeof(struct Person));


person->age = 30;
strcpy(person->name, "John Doe");
explain strcmp function With example.

The strcmp() function in C compares two strings lexicographically (character by character) and returns an integer
indicating their relationship: 0 if they are equal, a negative value if the first string is lexicographically less than the
second, and a positive value otherwise.

Example:

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

int main(){
char* s1 = "Geeks";
char* s2 = "Geeks";

// Printing the return value of the strcmp()


printf("%d", strcmp(s1, s2));

return 0;
}

explain any three functions:

• fopen()

• fputs()

• fclose()

• fseek()

i) fopen():

• Purpose: The fopen() function is used to open a file for reading, writing, or both.

• Syntax: FILE *fopen(const char *filename, const char *mode);

o filename: A string containing the name of the file to be opened.

o mode: A string specifying the mode in which the file should be opened (e.g., "r" for read, "w" for
write, "a" for append, "r+" for read and write, etc.).

• Return Value: Returns a pointer of type FILE on success, or NULL on failure.


ii) fputs():

• Purpose: The fputs() function writes a string to a file.

• Syntax: int fputs(const char *str, FILE *stream);

o str: The string to be written.

o stream: A pointer to the file stream (opened by fopen()).

• Return Value: Returns EOF on error, otherwise returns a non-negative value.

iii) fclose():

• Purpose: The fclose() function closes an open file stream.

• Syntax: int fclose(FILE *stream);

o stream: A pointer to the file stream (opened by fopen()).

• Return Value: Returns 0 on success, or EOF on error.

iv) fseek():

• Purpose: The fseek() function changes the position of the file pointer (or stream) within a file.

• Syntax: int fseek(FILE *stream, long offset, int origin);

o stream: A pointer to the file stream (opened by fopen()).

o offset: The number of bytes to move the file pointer.

o origin: Specifies the starting point for the offset (e.g., SEEK_SET for the beginning, SEEK_CUR for the
current position, SEEK_END for the end).

• Return Value: Returns 0 on success, or a non-zero value on error.

give the Difference betWeen scanf() anD gets().

• scanf():

• Reads input from the standard input stream (usually the keyboard).

• Uses format specifiers (like %d, %f, %s) to determine the data type of the input and how to store it.

• Stops reading input when it encounters whitespace characters (spaces, tabs, or newlines).

• Can read multiple values of different data types in a single call.

• Example: scanf("%d %f %s", &age, &salary, name);


• gets():

• Reads a line of text from the standard input stream until a newline character is encountered.

• Stores the input (including spaces) into a character array (string).

• Important: gets() is unsafe because it doesn't check the size of the input buffer, potentially leading to
buffer overflows if the input is longer than the buffer.

• Deprecated: Due to the security risks, gets() is now discouraged and often replaced with fgets().

• Example: gets(my_string);

Write a short note on macro substitution Directives.

Macro substitution directives in C are a powerful feature of the C preprocessor, a tool that processes your source
code before it is compiled. These directives allow you to define macros, essentially shortcuts or replacements for
code snippets. When the program is compiled, all instances of the macro are replaced by its defined contents.

Write a program to accept an array anD Display it in ascenDing orDer.

#include <stdio.h>

void main ()

int num[20];

int i, j, a, n;

printf("Enter number of elements in an array");

scanf("%d", &n);

printf("Enter the elements");

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

scanf("%d", &num[i]);

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

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

if (num[i] > num[j]){

a = num[i];

num[i] = num[j];

num[j] = a;
}

printf("The numbers in ascending order is:");

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

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

getch();

create a structure of car having car_iD, car_moDel, price. anD accept the Details of
tWo car anD Display it.

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct Car{
int id:
char model [20];
int rate;
};
void main()
{
int n,i;
printf("Enter the number of cars: ");
scanf("%d",&n);

struct Car cars[n];


for(i=0;i<3;i++){
printf("Enter the details of a car: %d\n",i+1);
printf("Car id: ");
scanf("%d",&cars[i].id);
printf("Car model: ");
scanf("%s", &cars[i].model);
printf("Car rate: ");
scanf("%d",&cars[i].rate);
} for(i=0;i<3;i++){
printf("\nCar id: %d",cars[i].id);
printf("\nCar model: %s", cars[i].model);
printf("\nCar rate: %d",cars[i].rate);
}
getch();
}

explain aDvantages of structure over the union.

Advantages of Structures Over Unions:

• Simultaneous Data Storage:

Structures allow you to store multiple data types simultaneously, which is crucial for organizing complex data.

• Independent Data:

Each member in a structure has its own memory location, ensuring that changes to one member do not affect
others.

• Data Integrity:

Structures are better suited for applications where data integrity and consistency are paramount.

• Code Readability:

Structures enhance code readability by grouping related data items under a single name, making it easier to
understand and maintain.

• General Purpose:

Structures are more versatile and suitable for a wider range of applications compared to unions.

explain the Difference betWeen structure anD union

Parameter Structure Union

A structure is a user-defined data type that A union is a user-defined data type that allows
groups different data types into a single storing different data types at the same memory
Definition entity. location.

The keyword struct is used to define a


The keyword union is used to define a union
Keyword structure

The size is the sum of the sizes of all The size is equal to the size of the largest member,
Size members, with padding if necessary. with possible padding.
Memory Each member within a structure is allocated Memory allocated is shared by individual members
Allocation unique storage area of location. of union.

Data No data overlap as members are Full data overlap as members shares the same
Overlap independent. memory.

Accessing Individual member can be accessed at a


Only one member can be accessed at a time.
Members time.

Write a c program to accept the 5 elements of array anD Display it.

#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5], n, sum=0, i;
float avg=0;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements in the array: ");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nSum of the elements in the array is: ");
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
printf("%d",sum);
printf("\nAverage of the elements in the array is: ");
for(i=0;i<n;i++)
{
avg=sum/n;
}
printf("%f",avg);
getch();

}
create a structure stuDent having rno, name, aDDress. accept the Details of tWo
stuDent anD Display it.

#include <stdio.h>

// Define the structure


struct Student {
int rollNumber;
char name[50];
char address[100];
};

void main() {
// Declare two struct Student variables
struct Student student1, student2;

// Accept details for the first student


printf("Enter details for Student 1:\n");
printf("Roll Number: ");
scanf("%d", &student1.rollNumber);
printf("Name: ");
scanf("%s", student1.name);
printf("Address: ");
scanf("%s", student1.address);

// Accept details for the second student


printf("\nEnter details for Student 2:\n");
printf("Roll Number: ");
scanf("%d", &student2.rollNumber);
printf("Name: ");
scanf("%s", student2.name);
printf("Address: ");
scanf("%s", student2.address);
// Display the details of both students
printf("\nStudent Details:\n");
printf("Student 1:\n");
printf("Roll Number: %d\n", student1.rollNumber);
printf("Name: %s\n", student1.name);
printf("Address: %s\n", student1.address);

printf("\nStudent 2:\n");
printf("Roll Number: %d\n", student2.rollNumber);
printf("Name: %s\n", student2.name);
printf("Address: %s\n", student2.address);

getch();
}

Write a c program to calculate the length of string using stanDarD function.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int length;
char str[50];
printf("Enter the string: ");
scanf("%s",&str);
length=strlen(str);
printf("Length of the string is: %d",length);
getch();
}

Write a c program to calculate the area of circle .use pi as macro.

#include <stdio.h>

// Define PI as a macro
#define PI 3.14159

void main() {
float radius, area;

// Prompt the user to enter the radius of the circle


printf("Enter the radius of the circle: ");
scanf("%f", &radius);

// Calculate the area of the circle


area = PI * radius * radius;

// Display the result


printf("The area of the circle is: %.2f\n", area);

getch();
}
Write a c program to combine tWo string using stanDarD function.

#include<stdio.h>
#include<conio.h>
void main()
{
char str[50],str2[50];
printf("Enter the string 1: ");
scanf("%s",&str);
printf("Enter the string 2: ");
scanf("%s",&str2);
strcat(str,str2);
printf("Combined string is : %s",str);
getch();
}

Write a program to Display aDDition of matrix.

#include <stdio.h>

// Function to add two matrices


void addMatrices(int matrix1[10][10], int matrix2[10][10], int result[10][10], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to display a matrix


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

int main() {
int matrix1[10][10], matrix2[10][10], result[10][10];
int row, col;

// Get the dimensions of the matrices


printf("Enter the number of rows: ");
scanf("%d", &row);
printf("Enter the number of columns: ");
scanf("%d", &col);
// Get the elements of the first matrix
printf("Enter elements of Matrix 1:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &matrix1[i][j]);
}
}

// Get the elements of the second matrix


printf("Enter elements of Matrix 2:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
scanf("%d", &matrix2[i][j]);
}
}

// Add the two matrices


addMatrices(matrix1, matrix2, result, row, col);

// Display the result


printf("Matrix 1:\n");

displayMatrix(matrix1, row, col);


printf("Matrix 2:\n");
displayMatrix(matrix2, row, col);
printf("Result:\n");
displayMatrix(result, row, col);

return 0;
}
Write a c program to combine tWo string using stanDarD function.

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

Void main() {
char str1[100], str2[100], result[200];

// Get the first string


printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
str1[strcspn(str1, "\n")] = 0; // Remove the newline character

// Get the second string


printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
str2[strcspn(str2, "\n")] = 0; // Remove the newline character

// Copy the first string to the result


strcpy(result, str1);

// Append the second string to the result


strcat(result, str2);

// Display the combined string


printf("Combined string: %s\n", result);

getch();
}
Write a program to Display aDDition of matrix.

#include <stdio.h>

#define ROWS 2
#define COLS 2

// Function to add two matrices


void addMatrices(int matrix1[ROWS][COLS], int matrix2[ROWS][COLS], int result[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
}

// Function to display a matrix


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

int main() {
int matrix1[ROWS][COLS] = {{1, 2}, {3, 4}};
int matrix2[ROWS][COLS] = {{5, 6}, {7, 8}};
int result[ROWS][COLS];

printf("Matrix 1:\n");
displayMatrix(matrix1);

printf("Matrix 2:\n");
displayMatrix(matrix2);

addMatrices(matrix1, matrix2, result);

printf("Result:\n");
displayMatrix(result);

return 0;
}
explain aDvantages anD DisaDvantages of pointer.

Advantages of Pointers:

1. Dynamic Memory Allocation: Pointers allow for dynamic memory allocation, enabling efficient memory
usage and adaptability.

2. Efficient Data Structures: Pointers facilitate the creation of complex data structures like linked lists, trees,
and graphs, which can be memory-efficient and flexible.

3. Function Parameter Passing: Passing pointers to functions can be more efficient than passing large data
structures by value in terms of memory and execution speed.

4. Manipulating Hardware and System Resources: Pointers are essential for low-level system programming,
device driver development, and interacting with hardware, providing direct memory access.

5. String Manipulation: C-style strings (character arrays) rely on pointers for efficient manipulation and
processing, making them a core feature of string handling in C.

Disadvantages of Pointers:

1. Complexity: Pointers introduce complexity and can make code harder to understand and debug, especially
for novice programmers.

2. Dangling Pointers: Dangling pointers can point to deallocated or invalid memory, leading to unpredictable
behavior.

3. Memory Leaks: Improper management of dynamically allocated memory can result in memory leaks,
consuming more memory over time.

4. Security Risks: Improper pointer usage can introduce security vulnerabilities such as buffer overflows,
compromising program security.

5. Platform Dependence: Pointer behavior can vary across platforms and compilers, making code less portable.

6. Debugging Challenges: Debugging pointer-related issues can be challenging, as errors may not manifest
immediately and can lead to subtle, hard-to-track bugs.

7. Potential for Segmentation Faults: Dereferencing an invalid or null pointer can result in a segmentation
fault, causing program termination.

You might also like