1. Define a structure in C. Write the syntax for structure declaration with an example.
In C, a structure is a user-defined data type that can hold different types of data. A structure is defined using the struct
keyword.
Syntax for structure declaration:
struct structure_name {
data_type member1;
data_type member2;
// More members
};
Example:
#include <stdio.h>
// Defining a structure to store student details
struct Student {
int roll_no;
char name[50];
float marks;
};
int main() {
// Declaring and initializing a structure variable
struct Student student1 = {101, "John Doe", 85.5};
// Displaying the student's details
printf("Roll Number: %d\n", student1.roll_no);
printf("Name: %s\n", student1.name);
printf("Marks: %.2f\n", student1.marks);
return 0;
}
2. Declare the C structures for the following scenario:
(i) College contains the following fields: College code (2 characters), College Name, year of establishment, number of courses. (ii) Each course is associated with course name (String), duration, number of students.
C Structure Declaration:
#include <stdio.h>
struct Course {
char course_name[50];
int duration; // Duration in months
int num_students;
};
struct College {
char college_code[3]; // 2 characters + null terminator
char college_name[100];
int year_of_establishment;
int num_courses;
struct Course courses[50]; // A college can offer up to 50 courses
};
3. Define a structure type personal
, that would contain person name, date of joining, and salary. Write a program to initialize one person's data and display the same.
#include <stdio.h>
struct personal {
char name[50];
char date_of_joining[20];
float salary;
};
int main() {
struct personal p1 = {"John Doe", "01-01-2020", 75000.50};
// Displaying the person's details
printf("Name: %s\n", p1.name);
printf("Date of Joining: %s\n", p1.date_of_joining);
printf("Salary: %.2f\n", p1.salary);
return 0;
}
4. Differentiate between structure and union in C with examples. Write a program in C to maintain a record of N employee detail using an array of structures with three fields (id, name, salary) and print the details of employees whose salary is above 60000.
Structure vs Union in C:
- Structure: In a structure, each member has its own memory location. The size of the structure is the sum of the sizes of its members.
- Union: In a union, all members share the same memory location, and only one member can hold a value at any given time. The size of the union is the size of the largest member.
Example of structure:
struct Employee {
int id;
char name[50];
float salary;
};
Example of union:
union Data {
int i;
float f;
char str[20];
};
Program to maintain a record of N employee detail:
#include <stdio.h>
struct Employee {
int id;
char name[50];
float salary;
};
int main() {
int n;
printf("Enter number of employees: ");
scanf("%d", &n);
struct Employee employees[n];
// Input employee details
for (int i = 0; i < n; i++) {
printf("Enter details for employee %d\n", i + 1);
printf("ID: ");
scanf("%d", &employees[i].id);
printf("Name: ");
scanf("%s", employees[i].name);
printf("Salary: ");
scanf("%f", &employees[i].salary);
}
// Print employees with salary > 60000
printf("\nEmployees with salary above 60000:\n");
for (int i = 0; i < n; i++) {
if (employees[i].salary > 60000) {
printf("ID: %d, Name: %s, Salary: %.2f\n", employees[i].id, employees[i].name, employees[i].salary);
}
}
return 0;
}
5. Define a structure type book
, that would contain book name, author, pages, and price. Write a program to read this data using member operator (‘.’) and display the same.
#include <stdio.h>
struct Book {
char name[50];
char author[50];
int pages;
float price;
};
int main() {
struct Book book1;
// Input book details
printf("Enter book name: ");
scanf("%s", book1.name);
printf("Enter author name: ");
scanf("%s", book1.author);
printf("Enter number of pages: ");
scanf("%d", &book1.pages);
printf("Enter price: ");
scanf("%f", &book1.price);
// Displaying book details
printf("\nBook Details:\n");
printf("Name: %s\n", book1.name);
printf("Author: %s\n", book1.author);
printf("Pages: %d\n", book1.pages);
printf("Price: %.2f\n", book1.price);
return 0;
}
6. How to pass a structure member as an argument of a function? Write a program to explain it.
Passing a structure member to a function:
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
float marks;
};
// Function to display student marks
void displayMarks(float marks) {
printf("Marks: %.2f\n", marks);
}
int main() {
struct Student student1 = {101, "John Doe", 85.5};
// Passing the structure member to the function
displayMarks(student1.marks);
return 0;
}
7. What is an array of structure? Declare a variable as an array of structure and initialize it.
An array of structures is an array where each element is a structure variable.
Syntax:
struct structure_name array_name[size];
Example:
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
};
int main() {
struct Student students[2] = {
{101, "John Doe"},
{102, "Jane Smith"}
};
for (int i = 0; i < 2; i++) {
printf("Roll Number: %d, Name: %s\n", students[i].roll_no, students[i].name);
}
return 0;
}
8. Write a C program to calculate student-wise total marks for three students using an array of structure.
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
float marks[3]; // Array of marks for 3 subjects
float total;
};
int main() {
struct Student students[3];
// Input details for 3 students
for (int i = 0; i < 3; i++) {
printf("Enter details for student %d\n", i + 1);
printf("Roll Number: ");
scanf("%d", &students[i].roll_no);
printf("Name: ");
scanf("%s", students[i].name);
students[i].total = 0; // Initialize total to 0
for (int j = 0; j < 3; j++) {
printf("Enter marks for subject %d: ", j + 1);
scanf("%f", &students[i].marks[j]);
students[i].total += students[i].marks[j];
}
}
// Displaying total marks for each student
for (int i = 0; i < 3; i++) {
printf("Total marks for %s (Roll No: %d) = %.2f\n", students[i].name, students[i].roll_no, students[i].total);
}
return 0;
}
9. Write a C program using an array of structure to create employee records with the following fields: emp-id, name, designation, address, salary and display it.
#include <stdio.h>
struct Employee {
int emp_id;
char name[50];
char designation[50];
char address[100];
float salary;
};
int main() {
struct Employee employees[3];
// Input employee details
for (int i = 0; i < 3; i++) {
printf("Enter details for employee %d\n", i + 1);
printf("Employee ID: ");
scanf("%d", &employees[i].emp_id);
printf("Name: ");
scanf("%s", employees[i].name);
printf("Designation: ");
scanf("%s", employees[i].designation);
printf("Address: ");
scanf(" %[^\n]%*c", employees[i].address); // To read multi-word address
printf("Salary: ");
scanf("%f", &employees[i].salary);
}
// Display employee details
printf("\nEmployee Records:\n");
for (int i = 0; i < 3; i++) {
printf("Employee ID: %d, Name: %s, Designation: %s, Address: %s, Salary: %.2f\n",
employees[i].emp_id, employees[i].name, employees[i].designation,
employees[i].address, employees[i].salary);
}
return 0;
}
10. What is structure within structure? Give an example for it.
Structure within structure (or nested structure) is when a structure contains another structure as a member.
Example:
#include <stdio.h>
struct Address {
char city[50];
char state[50];
};
struct Employee {
int emp_id;
char name[50];
struct Address addr; // Structure within structure
};
int main() {
struct Employee emp = {1, "John Doe", {"New York", "NY"}};
printf("Employee ID: %d\n", emp.emp_id);
printf("Name: %s\n", emp.name);
printf("City: %s\n", emp.addr.city);
printf("State: %s\n", emp.addr.state);
return 0;
}
11. Write a C program using nested structures to read 3 employee details with the following fields: emp-id, name, designation, address, da, hra, and calculate gross salary of each employee.
#include <stdio.h>
struct Address {
char city[50];
char state[50];
};
struct Employee {
int emp_id;
char name[50];
char designation[50];
struct Address addr; // Nested structure
float da; // Dearness Allowance
float hra; // House Rent Allowance
float gross_salary; // Gross salary
};
int main() {
struct Employee employees[3];
// Input employee details and calculate gross salary
for (int i = 0; i < 3; i++) {
printf("Enter details for employee %d\n", i + 1);
printf("Employee ID: ");
scanf("%d", &employees[i].emp_id);
printf("Name: ");
scanf("%s", employees[i].name);
printf("Designation: ");
scanf("%s", employees[i].designation);
printf("City: ");
scanf("%s", employees[i].addr.city);
printf("State: ");
scanf("%s", employees[i].addr.state);
printf("Dearness Allowance: ");
scanf("%f", &employees[i].da);
printf("House Rent Allowance: ");
scanf("%f", &employees[i].hra);
// Calculating Gross Salary
employees[i].gross_salary = employees[i].da + employees[i].hra;
}
// Display employee details with gross salary
for (int i = 0; i < 3; i++) {
printf("\nEmployee ID: %d\n", employees[i].emp_id);
printf("Name: %s\n", employees[i].name);
printf("Designation: %s\n", employees[i].designation);
printf("Address: %s, %s\n", employees[i].addr.city, employees[i].addr.state);
printf("Gross Salary: %.2f\n", employees[i].gross_salary);
}
return 0;
}
12. Distinguish between Arrays within Structures and Array of Structure with examples.
Arrays within Structures and Array of Structures are two concepts in C where arrays and structures are used together. Let's distinguish between them:
Arrays within Structures:
An array is a member of a structure. This means that the structure contains an array as one of its members.
Example:
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
float marks[5]; // Array of 5 marks
};
int main() {
struct Student student1 = {101, "John Doe", {85.5, 90.0, 88.0, 92.5, 79.0}};
printf("Student Roll No: %d\n", student1.roll_no);
printf("Student Name: %s\n", student1.name);
printf("Marks in Subject 1: %.2f\n", student1.marks[0]);
return 0;
}
Here, marks
is an array within the structure Student
. The structure holds an array of marks as one of its members.
Array of Structures:
An array of structures is an array where each element is a structure variable. Each structure in the array can have different values for its members.
Example:
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
float marks;
};
int main() {
struct Student students[3] = {
{101, "John", 85.5},
{102, "Jane", 90.0},
{103, "Alice", 88.5}
};
for (int i = 0; i < 3; i++) {
printf("Roll No: %d, Name: %s, Marks: %.2f\n", students[i].roll_no, students[i].name, students[i].marks);
}
return 0;
}
Here, students
is an array of structures. Each element of the array holds a structure representing a student's details.
13. Write a C program using structure to create a library catalog with the following fields: Access number, author’s name, Title of the book, year of publication, publisher’s name, and price.
#include <stdio.h>
struct LibraryCatalog {
int access_number;
char author_name[50];
char title[100];
int year_of_publication;
char publisher_name[50];
float price;
};
int main() {
struct LibraryCatalog book1;
// Input book details
printf("Enter Access Number: ");
scanf("%d", &book1.access_number);
printf("Enter Author's Name: ");
scanf(" %[^\n]s", book1.author_name); // To allow spaces in the name
printf("Enter Title of the Book: ");
scanf(" %[^\n]s", book1.title);
printf("Enter Year of Publication: ");
scanf("%d", &book1.year_of_publication);
printf("Enter Publisher's Name: ");
scanf(" %[^\n]s", book1.publisher_name);
printf("Enter Price: ");
scanf("%f", &book1.price);
// Display the book details
printf("\nLibrary Catalog Information:\n");
printf("Access Number: %d\n", book1.access_number);
printf("Author: %s\n", book1.author_name);
printf("Title: %s\n", book1.title);
printf("Year of Publication: %d\n", book1.year_of_publication);
printf("Publisher: %s\n", book1.publisher_name);
printf("Price: %.2f\n", book1.price);
return 0;
}
14. Explain in brief about pointers and structures. What is self-referential structure? Explain through an example.
Pointers and Structures:
- Pointers store memory addresses of variables, including structures.
- A pointer to a structure is used to access structure members via the pointer, using the
->
operator.
Example of pointer to structure:
#include <stdio.h>
struct Student {
int roll_no;
char name[50];
};
int main() {
struct Student student1 = {101, "John"};
struct Student *ptr = &student1;
// Accessing structure members using pointer
printf("Roll No: %d, Name: %s\n", ptr->roll_no, ptr->name);
return 0;
}
Self-Referential Structure:
A self-referential structure is a structure that contains a pointer to its own type.
Example of self-referential structure:
#include <stdio.h>
struct Node {
int data;
struct Node *next; // Pointer to the same structure type
};
int main() {
struct Node node1, node2;
node1.data = 10;
node1.next = &node2; // Pointing to node2
node2.data = 20;
node2.next = NULL;
// Print data from node1 and node2
printf("Node1 Data: %d, Node2 Data: %d\n", node1.data, node2.data);
return 0;
}
15. Discuss file handling in C in brief. Explain different modes of opening files with syntax and example.
File Handling in C:
File handling allows programs to read from and write to files. It uses the following functions:
fopen()
: Opens a file.
fclose()
: Closes a file.
fprintf()
: Writes formatted data to a file.
fscanf()
: Reads formatted data from a file.
fread()
and fwrite()
: Read and write binary data.
Modes of Opening Files:
- r: Open a file for reading.
- w: Open a file for writing (creates a new file or truncates an existing file).
- a: Open a file for appending (adds to the end).
- r+: Open a file for both reading and writing.
- w+: Open a file for both reading and writing (creates a new file or truncates an existing file).
- a+: Open a file for both reading and appending.
Example:
#include <stdio.h>
int main() {
FILE *file;
// Opening a file in write mode
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file); // Closing the file
return 0;
}
16. What are the file I/O functions in C? Give a brief note about the task performed by each function.
- fopen(): Opens a file.
- fclose(): Closes a file.
- fgetc(): Reads a character from a file.
- fputc(): Writes a character to a file.
- fgets(): Reads a string from a file.
- fputs(): Writes a string to a file.
- fprintf(): Writes formatted data to a file.
- fscanf(): Reads formatted data from a file.
- fread(): Reads binary data from a file.
- fwrite(): Writes binary data to a file.
- feof(): Checks if the end of the file has been reached.
17. Write a C program to copy the content of A.txt file into B.txt using file handling functions.
#include <stdio.h>
int main() {
FILE *source, *destination;
char ch;
source = fopen("A.txt", "r");
if (source == NULL) {
printf("Error opening source file.\n");
return 1;
}
destination = fopen("B.txt", "w");
if (destination == NULL) {
printf("Error opening destination file.\n");
fclose(source);
return 1;
}
// Copying content from A.txt to B.txt
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}
printf("Content copied from A.txt to B.txt\n");
fclose(source);
fclose(destination);
return 0;
}
18. What is a preprocessor directive? Explain #define
and #include
preprocessor directives. Explain any other five preprocessor directives in C.
Preprocessor Directives:
Preprocessor directives are instructions given to the preprocessor before the program is compiled. They are not executable but are processed by the preprocessor.
-
#define: Defines a macro or constant value.
- Syntax:
#define MACRO_NAME value
Example:
#define PI 3.14
-
#include: Includes the contents of a file.
- Syntax:
#include <filename>
or #include "filename"
Example:
#include <stdio.h>
Other preprocessor directives:
- #ifdef: Checks if a macro is defined.
- #ifndef: Checks if a macro is not defined.
- #endif: Ends an
#if
, #ifdef
, or #ifndef
.
- #undef: Undefines a macro.
- #pragma: Provides additional information to the compiler.
19. Write a C program for the following: there are two input files named first.dat
and second.dat
. The files are to be merged, i.e., copy the contents of first.dat
and then second.dat
to a new file named result.dat
.
#include <stdio.h>
int main() {
FILE *file1, *file2, *file3;
char ch;
file1 = fopen("first.dat", "r");
if (file1 == NULL) {
printf("Error opening first file.\n");
return 1;
}
file2 = fopen("second.dat", "r");
if (file2 == NULL) {
printf("Error opening second file.\n");
fclose(file1);
return 1;
}
file3 = fopen("result.dat", "w");
if (file3 == NULL) {
printf("Error opening result file.\n");
fclose(file1);
fclose(file2);
return 1;
}
// Copy content from first.dat
while ((ch = fgetc(file1)) != EOF) {
fputc(ch, file3);
}
// Copy content from second.dat
while ((ch = fgetc(file2)) != EOF) {
fputc(ch, file3);
}
printf("Contents merged into result.dat\n");
fclose(file1);
fclose(file2);
fclose(file3);
return 0;
}
20. Explain the command line arguments. What are the syntactic constructs followed in C?
Command Line Arguments:
Command line arguments allow users to pass parameters to the program at the time of execution. They are passed to the main()
function.
Syntax:
int main(int argc, char *argv[])
argc
: Argument count (number of arguments passed).
argv
: Argument vector (an array of strings holding the arguments).
21. Write a C program to add two numbers using command line arguments.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Please provide two numbers.\n");
return 1;
}
int num1 = atoi(argv[1]);
int num2 = atoi(argv[2]);
printf("Sum: %d\n", num1 + num2);
return 0;
}
22. What are macros in C? Write a program in C to calculate the area and perimeter of rectangle and circle using macros in C.
Macros in C:
Macros are preprocessor directives that define constant values or expressions.
Example:
#include <stdio.h>
#define PI 3.14
#define AREA_RECTANGLE(length, width) ((length) * (width))
#define PERIMETER_RECTANGLE(length, width) (2 * ((length) + (width)))
#define AREA_CIRCLE(radius) (PI * (radius) * (radius))
#define PERIMETER_CIRCLE(radius) (2 * PI * (radius))
int main() {
float length = 5, width = 3, radius = 4;
printf("Area of Rectangle: %.2f\n", AREA_RECTANGLE(length, width));
printf("Perimeter of Rectangle: %.2f\n", PERIMETER_RECTANGLE(length, width));
printf("Area of Circle: %.2f\n", AREA_CIRCLE(radius));
printf("Perimeter of Circle: %.2f\n", PERIMETER_CIRCLE(radius));
return 0;
}
Comments
Post a Comment